Skip to content

fix: keep agents responsive when recovery closes temporary SQLite readers - #173482

Closed
VictorSesma wants to merge 10 commits into
openclaw:mainfrom
VictorSesma:fix/auth-refresh-reader-lifetime
Closed

VictorSesma wants to merge 10 commits into
openclaw:mainfrom
VictorSesma:fix/auth-refresh-reader-lifetime

Conversation

@VictorSesma

@VictorSesma VictorSesma commented Oct 15, 2026 •

Copy link
Copy Markdown

Related: #158592 (the same unpublished-runtime symptom; this patch addresses a different, reproduced trigger).

Prepared and submitted by Codex on behalf of Victor Sesma (@VictorSesma), with his explicit authorization. Originally submitted as a draft at his request; the PR is now ready for review. Validation below identifies the tested revisions.

What Problem This Solves

Fixes agents becoming unavailable when an authentication change queues a model refresh from temporary SQLite readers that close before the refresh finishes, as can happen during deferred database recovery.

User Impact

The refresh completes and the agent can handle its next request without restarting the Gateway. Credential invalidation and genuine publication failures continue to reject affected requests.

Why This Change Was Made

The queued refresh inherited the emitter's SQLite AsyncLocalStorage scope. Closing that scope caused real catalog reads to fail with SQLite read-only worker scope closed, leaving the reply runtime unpublished.

Schedule auth publication outside that SQLite scope. Reads continue through the existing bounded worker pool and runtime lifecycle; the spawn broker, plugin registry, publication ordering, and synchronous credential invalidation retain their existing behavior. No retry manager, new state, configuration, or schema changes are added.

Evidence

Conflict resolution against main (43ed85ea9)

Merged upstream 05ade6d2df13f660e9df17cbedaeba5eb9f93dfc to resolve the new conflict in prepared-model-runtime.ts. Both branches had added an import at the same location: the resolution keeps upstream's throwSettledAggregate and this fix's readOnlyWorkerScope. All other upstream changes merge normally.

The authored PR patch is unchanged: its stable patch ID with zero context is 0155fdf46591daf220a6768af311f2c934533eb3 both before and after integration. The diff remains three files, 45 additions and 9 deletions. The scheduling fix, directory normalization, and regression are preserved.

Validation of the merged candidate in the isolated Ubuntu VM (pnpm 12.12.1):

  • Connected-Gateway auth-refresh suite: 5/5 passed (239.61 s wall time, 228.88 s Vitest duration), including dispatch after temporary SQLite readers close. This suite uses real SQLite with mocked provider/agent execution.
  • Targeted type-aware lint: 292 rules, zero warnings and zero errors.
  • Formatting, git diff --check against the integrated main, and the official line-cap ratchet: passed; no new line-cap violations or growth.

Hosted checks for the new revision track current CI. The prior clean code review and live Gateway red/green proof below retain their original revisions; no new live-model execution is claimed for this mechanical conflict resolution. Maintainer approval is still required for the new head.

Previous integrated revision (dcc5a5f)

Merged upstream 0a0d88df543a9d36c4708f93c56d995da769050c into the PR branch. The resulting PR diff remains three files, 45 additions and 9 deletions: the reader-scope scheduling fix, existing auth-directory normalization moved into its processing owner, and the connected-Gateway regression.

Hosted CI on this exact head completed successfully on 2026-10-17 at 22:49 UTC, including lint, test type checks, changed tests, the baseline ratchets, and all three PostgreSQL conformance shards. The historical LRU failure documented below is from an earlier revision, not a failing test in this CI run. The inspected lint/ratchet annotations do not flag any of the three changed files; advisory annotations elsewhere remain visible in GitHub.

Codex code review completed on dcc5a5fced7cb41027e056e433dc772c1394ad28 with no findings. Maintainer approval remains required for the current revision because the patch touches auth-publication code; the associated approval gate is separate from the CI execution result.

The live Gateway proof and local red/green regression results below retain their original tested revisions. They have not been relabeled as new local runs on this merge commit.

Requested CI rerun (6e83931d5)

The author requested a fresh CI execution. This empty commit has exactly the same Git tree as 7328d09d3; it changes no source files, tests, or CI configuration. The validation and pinned-base failure attribution below remain attached to their recorded revisions. Checks for this rerun.

CI failure attribution: identical failure on the pinned main base

Completed the pinned-base comparison requested by ClawSweeper. Historical result on 7328d09d3: the failing LRU assertion also fails on that revision's pinned main base without this PR.

Failed CI job: checks-node-changed-compact-small-3, src/plugins/runtime/runtime-llm.prepared-owner.test.ts, keeps completion ownership coherent: lru, line 923. The global CI gate also fails as a consequence. The native failure classifier reported unknown because the scheduled-main run had no matching job; the following direct comparison supplies the missing attribution.

In the same isolated Ubuntu VM, with Node 24.21.0, pnpm 12.11.1, unchanged dependencies, and the same three plugin test files selected by the failed CI shard:

Checkout Result Failing assertion Wall / Vitest time
PR head 7328d09d3 29 pass, 1 fail line 923: expected 3 to be 2 217.64 / 208.97 s
Exact integrated main base b0ab44081ef483fcd0a86c8afae3b4eb30e9bc24, clean detached checkout, no PR changes 29 pass, 1 fail same test, line 923: expected 3 to be 2 202.84 / 195.82 s

Both runs used:

OPENCLAW_VITEST_RUNTIME=node NODE_OPTIONS=--max-old-space-size=3072 \
pnpm test \
  src/plugins/prepared-model-generation.lifecycle.test.ts \
  src/plugins/runtime/runtime-llm.prepared-owner.test.ts \
  src/plugins/runtime/runtime-llm.retained-generation.test.ts \
  --maxWorkers=1

The LRU diagnostic reports buildsBeforeSecond: 11 and secondBuilds: 11 in both runs: the owner-reuse assertion passes; the subsequent global ModelRegistry.fork count fails. Source inspection shows a possible additional catalog-projection fork: snapshot capture wraps createStores() with another fork when published models are available, after background catalog discovery. The test and these owners are unchanged by this PR.

The comparison establishes that the CI assertion is pre-existing, rather than a regression from detaching the auth-publication reader scope. No source, test expectation, baseline, or CI setting was changed during this investigation. The PR checkout was restored cleanly to 7328d09d3. That revision's failing check was retained for maintainer handling under the repository's inherited-failure policy. See the latest-revision status above for current CI and approval requirements.

Conflict resolution against current main (7328d09d3)

Merged upstream b0ab44081 to resolve the conflict introduced when #174670 refactored the connected-Gateway test helpers. Preserved the upstream test file and adapted the temporary-reader regression to refreshAuth, sendAgentRpc(agentId, runId), and expectCompleted. The runtime scheduling fix and the line-cap repair are unchanged.

Validation on the merged candidate in the isolated Ubuntu VM (Node 24.21.0, pnpm 12.11.1):

  • Full connected-Gateway auth-refresh file: 5/5 pass, including the adapted recovery regression. Wall time: 201.16 s; Vitest duration: 191.41 s, including cold compilation/Gateway startup. The regression body took 6.284 s and reuses the existing suite-level server to prove the SQLite-to-Gateway dispatch boundary.
  • Negative control: reverted only the scheduling line locally, then ran the adapted regression. It fails at the publication assertion with phase: failed and SQLite read-only worker scope closed (154.04 s wall time). Restored and verified the exact reviewed/passing source bytes before committing; the negative-control edit is not published.
  • Official line-cap ratchet against the integrated main: passes, three changed source files, no new violations or growth. Targeted type-aware lint: 292 rules, zero warnings/errors; formatting and git diff --check pass.
  • Independent autoreview of the full candidate diff against the new main: no actionable P0–P2 findings.

Hosted checks for the merge commit record the CI state for that revision. This run uses the existing connected-Gateway harness with real SQLite and mocked provider discovery/agent execution. The separate shipped-Gateway/live-model evidence below remains explicitly attributed to its original revision.

Line-cap follow-up (a85c45b)

Moved the existing auth-event directory normalization into invalidatePreparedModelRuntimeOwnersForAuthMutation, its sole processing owner. prepared-model-runtime.ts now has 697 counted lines instead of 701 (cap: 700). The scheduling fix and all regression coverage remain intact; no lint limit or baseline was relaxed.

Validation of this follow-up in the isolated Ubuntu VM:

  • Official line-cap ratchet against 6e73bd9: passes.
  • Targeted type-aware lint with config/tsconfig/oxlint.core.json: 292 rules, zero warnings/errors; formatting passes.
  • Full connected-Gateway auth-refresh test file: 5/5 pass, including temporary-reader closure, cancellation, rejected publication, and provider failures.
  • Independent autoreview of the incremental change: no actionable P0–P2 findings.

Hosted checks for this head. The shipped-Gateway red/green output below was recorded on 67eb4ad; it is retained with its original revision rather than relabeled as a new run.

Live Gateway proof (outside Vitest)

Added in response to ClawSweeper's proof request.

On 2026-10-15, built and ran head 67eb4ad0be334581d3af129b15649fd025800bb9 through the shipped pnpm openclaw gateway run entry point in a disposable Ubuntu VM. The Gateway selected the pinned Bun 1.4.3 runtime (Node compatibility version 26.3.0); build tooling used Node 24.21.0 and pnpm 12.10.1. Agent execution used the native OpenClaw agent harness and real llama.cpp inference with Qwen3-0.6B Q8_0, over loopback, without external model credentials.

Build Before the trigger After temporary readers close Subsequent real Gateway agent RPC
PR head 67eb4ad Gateway publication ready published Exit 0, status: ok, model reply returned
Same head, only the scheduling line reverted and rebuilt Real agent RPC succeeds failed: SQLite read-only worker scope closed Exit 1, UNAVAILABLE: runtime owner was not published

Within each run, the reader close and publication events below come from the same running Gateway process. The post-recovery RPC is a separate CLI process using gateway call agent --expect-final; it does not fall back to local execution. No Vitest, mocked provider discovery, mocked agent command, or fabricated model response is used. The negative control was saved as disposable local commit 637a346fb07ee5cc5e05796591d4d520ad237f3d; its diff against the PR head is exactly the one scheduling-line reversal. Configuration and preload file hashes were identical across the final red/green runs.

The deterministic input is disclosed: a disposable preload calls the existing auth-snapshot setter from a temporary SQLite reader scope, then closes the scope, using synthetic credentials and an actual persisted agent database. This isolates the publication boundary used by deferred recovery. It does not claim an end-to-end OOM/restart reproduction, an OAuth renewal test, or a production/Telegram deployment. The preload and negative-control edit are laboratory artifacts, not additions to this PR.

Recorded reader, publication and real agent RPC output
{"at": "2026-10-15T22:55:11.070Z", "pid": 31554, "event": "trigger", "run": "patched-catalog-67eb4ad", "agentDatabaseExists": true}
{"at": "2026-10-15T22:55:11.075Z", "pid": 31554, "event": "invalidated", "run": "patched-catalog-67eb4ad"}
{"at": "2026-10-15T22:55:11.095Z", "pid": 31554, "event": "readers-closed", "run": "patched-catalog-67eb4ad"}
{"at": "2026-10-15T22:55:11.198Z", "pid": 31554, "event": "published", "run": "patched-catalog-67eb4ad"}
{"at": "2026-10-15T22:54:12.601Z", "pid": 30404, "event": "trigger", "run": "negative-catalog-67eb4ad", "agentDatabaseExists": true}
{"at": "2026-10-15T22:54:12.608Z", "pid": 30404, "event": "invalidated", "run": "negative-catalog-67eb4ad"}
{"at": "2026-10-15T22:54:12.619Z", "pid": 30404, "event": "readers-closed", "run": "negative-catalog-67eb4ad"}
{"at": "2026-10-15T22:54:12.666Z", "pid": 30404, "event": "failed", "run": "negative-catalog-67eb4ad", "error": "Error: SQLite read-only worker scope closed"}

Patched Gateway, next actual agent response:

{
  "label": "patched-catalog-after",
  "started": "2026-10-15T22:55:12.059769+00:00",
  "finished": "2026-10-15T22:55:37.665736+00:00",
  "exitCode": 0,
  "runId": "53fb3df0-ee0d-4b23-8b8e-aa9703fdb095",
  "status": "ok",
  "summary": "completed",
  "payloads": [
    {
      "text": "Hello! How can I assist you today?",
      "mediaUrl": null
    }
  ],
  "provider": "llama-cpp",
  "model": "qwen3-0.6b",
  "executionTrace": {
    "winnerProvider": "llama-cpp",
    "winnerModel": "qwen3-0.6b",
    "attempts": [
      {
        "provider": "llama-cpp",
        "model": "qwen3-0.6b",
        "result": "success",
        "stage": "assistant"
      }
    ],
    "fallbackUsed": false,
    "runner": "embedded"
  }
}

Negative control, the agent works before the trigger:

{
  "label": "negative-catalog-before",
  "started": "2026-10-15T22:53:03.122586+00:00",
  "finished": "2026-10-15T22:54:03.583889+00:00",
  "exitCode": 0,
  "runId": "59a8a027-0235-4ab4-9658-67a835c8f7df",
  "status": "ok",
  "summary": "completed",
  "payloads": [
    {
      "text": "Hello! Have a great day!",
      "mediaUrl": null
    }
  ],
  "provider": "llama-cpp",
  "model": "qwen3-0.6b",
  "executionTrace": {
    "winnerProvider": "llama-cpp",
    "winnerModel": "qwen3-0.6b",
    "attempts": [
      {
        "provider": "llama-cpp",
        "model": "qwen3-0.6b",
        "result": "success",
        "stage": "assistant"
      }
    ],
    "fallbackUsed": false,
    "runner": "embedded"
  }
}

Negative control, the next request after the failed publication:

{
  "label": "negative-catalog-after",
  "started": "2026-10-15T22:54:13.500473+00:00",
  "finished": "2026-10-15T22:54:18.698332+00:00",
  "exitCode": 1,
  "runId": null,
  "status": null,
  "summary": null,
  "payloads": null,
  "provider": null,
  "model": null,
  "executionTrace": null,
  "responseError": {
    "type": "gateway_request_error",
    "code": "UNAVAILABLE",
    "message": "prepared reply dispatch runtime owner was not published for main",
    "retryable": false
  }
}
Reproduce the live Gateway check (disposable state only)

This procedure uses the normal compiled CLI, a real persisted agent database, and a real local model server. The diagnostic preload below only subscribes to existing publication events and calls the existing auth-snapshot setter inside a temporary reader scope, then closes that scope. It does not replace SQLite, discovery, scheduling, publication, Gateway admission, or agent execution. Do not install it in an operator's Gateway.

  1. Check out 67eb4ad0be334581d3af129b15649fd025800bb9, install with pnpm install --frozen-lockfile, and build through pnpm openclaw --version. The recorded toolchain was Node 24.21.0 / pnpm 12.10.1. The source launcher selected OpenClaw's pinned Bun 1.4.3 runtime for the actual Gateway. On the 4-GiB VM the documented build override was OPENCLAW_TSDOWN_MAX_OLD_SPACE_MB=4352; declarations were deferred with OPENCLAW_RUN_NODE_SKIP_DTS_BUILD=1 (hosted CI separately passed production and test type checks).

  2. Run the official llama.cpp b11669 Linux x64 server with the official Qwen/Qwen3-0.6B-GGUF Q8_0 model:

    llama-server -m Qwen3-0.6B-Q8_0.gguf --alias qwen3-0.6b \
      --host 127.0.0.1 --port 18080 -c 16384 -np 1 -t 2 -tb 2 \
      -n 96 --jinja --reasoning-budget 0

    Recorded model SHA-256: 9465e63a22add5354d9bb4b99e90117043c7124007664907259bd16d043bb031.
    Official llama.cpp archive SHA-256: cf07c1c112d709bd67e522017471de57ed0ec8bea031d732c5422351c07f65ac.
    No external model account or real API key is used.

  3. In a separate shell in the checkout, configure fresh laboratory state through the supported CLI:

    export LAB=/home/lab/recovery-live-proof
    export OPENCLAW_STATE_DIR="$LAB/state"
    export OPENCLAW_CONFIG_PATH="$LAB/state/openclaw.json"
    export OPENCLAW_SKIP_CHANNELS=1
    export OPENCLAW_RUN_NODE_SKIP_DTS_BUILD=1
    pnpm openclaw setup --non-interactive --accept-risk --mode local \
      --auth-choice custom-api-key --custom-base-url http://127.0.0.1:18080/v1 \
      --custom-model-id qwen3-0.6b --custom-api-key synthetic-local \
      --custom-provider-id recovery-proof --custom-compatibility openai --custom-text-input \
      --gateway-port 18790 --gateway-bind loopback --no-install-daemon \
      --skip-channels --skip-skills --skip-health --skip-ui --skip-hooks --skip-search \
      --skip-bootstrap --workspace "$LAB/workspace" --agent-name main \
      --suppress-gateway-token-output --json
    pnpm openclaw config patch --stdin --replace-path models.providers --replace-path agents.defaults.models <<'JSON'
    {
      "models":{"providers":{"llama-cpp":{
        "baseUrl":"http://127.0.0.1:18080/v1","api":"openai-completions","apiKey":"synthetic-local",
        "request":{"allowPrivateNetwork":true},
        "models":[{"id":"qwen3-0.6b","name":"qwen3-0.6b","contextWindow":16384,
          "maxTokens":96,"input":["text"],"reasoning":false,
          "cost":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0}}]
      }}},
      "agents":{"defaults":{"contextInjection":"never","heartbeat":{"every":"0m"},
        "model":{"primary":"llama-cpp/qwen3-0.6b"},
        "models":{"llama-cpp/qwen3-0.6b":{"agentRuntime":{"id":"openclaw"}}}}},
      "tools":{"profile":"minimal","deny":["*"],"codeMode":false},
      "plugins":{"allow":["llama-cpp","openai"],"slots":{"memory":"none"}},
      "cron":{"enabled":false}
    }
    JSON

The native llama-cpp provider is important: a generic custom provider can have no generated-catalog owner, so loadPersistedPluginModelCatalogs returns early for an empty plugin list and the closed-reader bug is not exercised.

  1. Save the diagnostic preload below as $LAB/recovery-preload.mjs. Adjust its root and dist constants if using different disposable directories. Start the shipped Gateway command in that shell:

    NODE_OPTIONS="--max-old-space-size=2048 --import=$LAB/recovery-preload.mjs" \
      pnpm openclaw gateway run --port 18790 --bind loopback --verbose
  2. Wait for gateway-publication-ready in $LAB/live-events.jsonl. In another shell with the same state environment, write {"run":"patched"} to $LAB/trigger.json. Observe invalidated, readers-closed, then published. After published, call the actual Gateway RPC (there is no CLI local-execution fallback):

    pnpm openclaw gateway call agent --expect-final --json --timeout 240000 \
      --expect-url ws://127.0.0.1:18790 \
      --params '{"agentId":"main","sessionKey":"agent:main:live-proof","idempotencyKey":"live-proof-unique-1","thinking":"off","message":"Say hello in one short sentence. Do not use any tools. /no_think"}'
  3. Negative control: stop only the disposable Gateway, replace the single scheduling line below in source, save it in a disposable local commit, and rebuild through the same CLI. The local commit keeps the source runner from rebuilding a dirty tree at every Gateway start; do not push it. Keep the configuration and preload identical. Restart, verify an ordinary agent RPC succeeds, and trigger {"run":"negative-control"}. Publication now fails with the real closed-reader exception and a subsequent Gateway RPC is rejected. Use new session and idempotency keys for each request.

    - const job = readOnlyWorkerScope.exit(() => modelRuntimeDrain.runAfter(publicationQueue, publish));
    + const job = modelRuntimeDrain.runAfter(publicationQueue, publish);

The negative control is a local experiment, not an additional PR commit. Restore the source from the pinned head afterward. This reproduces the recovery publication boundary; it does not manufacture an OOM or claim to exercise every startup-recovery branch.

Exact diagnostic preload used for the live check

This imports the existing compiled module exports without modifying them. Capturing the initial publication context preserves the Gateway's ordinary async context; the temporary reader scope is created only around the synthetic mutation. The RPC and model server run separately from this observer.

// Diagnostic-only preload for the shipped CLI Gateway, outside Vitest.
// All publication, SQLite, discovery, admission and inference code stays real.
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { AsyncLocalStorage } from "node:async_hooks";

const root = "/home/lab/recovery-live-proof";
const dist = "/home/lab/src/openclaw-proof/dist";
const agentDir = path.join(root, "state/agents/main/agent");
const record = (event, details = {}) => fs.appendFileSync(
  path.join(root, "live-events.jsonl"),
  JSON.stringify({ at: new Date().toISOString(), pid: process.pid, event, ...details }) + "\n",
);

async function compiledExport(prefix, name) {
  for (const file of fs.readdirSync(dist).filter(f => f.startsWith(prefix) && f.endsWith(".mjs"))) {
    const source = fs.readFileSync(path.join(dist, file), "utf8");
    const match = source.match(new RegExp("export \\{[^}]*\\b" + name + " as ([\\w$]+)[^}]*\\};"));
    if (match) return (await import(pathToFileURL(path.join(dist, file)).href))[match[1]];
  }
  throw new Error(`Compiled export not found: ${name}`);
}

async function install() {
  const createScope = await compiledExport("sqlite-readonly-worker-", "createSqliteReadOnlyWorkerScope");
  const setSnapshot = await compiledExport("runtime-snapshots-", "setRuntimeAuthProfileStoreSnapshot");
  const listen = await compiledExport("prepared-model-runtime.publication-events-", "registerPreparedModelRuntimePublicationListener");
  let inGatewayContext;
  let activeRun;
  let running = false;
  listen(event => {
    if (event.phase === "published" && !inGatewayContext) {
      inGatewayContext = AsyncLocalStorage.snapshot();
      record("gateway-publication-ready", { node: process.versions.node, bun: process.versions.bun });
    }
    if (activeRun && ["invalidated", "published", "failed"].includes(event.phase)) {
      record(event.phase, { run: activeRun, ...(event.error ? { error: String(event.error), stack: event.error.stack } : {}) });
    }
  });
  const timer = setInterval(() => {
    const trigger = path.join(root, "trigger.json");
    if (!inGatewayContext || running || !fs.existsSync(trigger)) return;
    const { run } = JSON.parse(fs.readFileSync(trigger, "utf8"));
    fs.unlinkSync(trigger);
    activeRun = run;
    running = true;
    inGatewayContext(async () => {
      record("trigger", { run, agentDatabaseExists: fs.existsSync(path.join(agentDir, "openclaw-agent.sqlite")) });
      const readers = createScope();
      try {
        readers.run(() => setSnapshot({ version: 1, profiles: {
          "llama-cpp:recovered": { type: "api_key", provider: "llama-cpp", key: "synthetic-recovered-key" },
        } }, agentDir));
        await readers.close();
        record("readers-closed", { run });
      } finally {
        await readers.close();
      }
    }).catch(error => record("diagnostic-error", { run, error: String(error), stack: error.stack }))
      .finally(() => { running = false; });
  }, 250);
  timer.unref();
  record("preload-installed");
}

if (process.versions.bun && process.argv[1]?.endsWith("openclaw.mjs") && process.argv.includes("gateway")) {
  await install();
}

Fast regression reproduction (Vitest)

This is a deterministic regression at the auth-publication boundary used by deferred database recovery. It uses a real persisted SQLite database and a connected Gateway, with synthetic credentials and mocked provider/agent execution. It does not require a Telegram account or a real model API key, and does not simulate the preceding out-of-memory crash or a full Gateway restart.

Use Node 24.21.0 and pnpm 12.10.1, the versions used for the recorded run. The commands below use a new disposable checkout and pin both the tested base and the PR commit.

  1. Prepare the checkout and dependencies:

    git clone --depth 1 --single-branch --branch fix/auth-refresh-reader-lifetime \
      https://github.com/VictorSesma/openclaw.git openclaw-recovery-repro
    cd openclaw-recovery-repro
    git fetch --depth 1 origin \
      6e7781b5968ff4c3b8b660bd1b6b0def24503d48 \
      ee6ef3aeede951c1070082a6482f9c1e69ac4a55
    git switch --detach ee6ef3aeede951c1070082a6482f9c1e69ac4a55
    pnpm install --frozen-lockfile
  2. Keep the new regression test, but restore the production file from the failing base:

    git restore --source=6e7781b5968ff4c3b8b660bd1b6b0def24503d48 --worktree -- \
      src/agents/prepared-model-runtime.ts
    OPENCLAW_VITEST_RUNTIME=node NODE_OPTIONS=--max-old-space-size=3072 \
      pnpm test src/gateway/server.agent.gateway-server-agent-auth-refresh.test.ts \
      --maxWorkers=1 -t 'temporary SQLite'

    Expected: exit code 1. The test dispatches after the auth mutation's temporary SQLite readers close receives publication phase failed instead of published, with SQLite read-only worker scope closed. It fails at that assertion before sending the next agent RPC. Running the base alone would not reproduce this test failure because the new regression test is absent there.

  3. Restore the fix and run the same test:

    git restore --source=ee6ef3aeede951c1070082a6482f9c1e69ac4a55 --worktree -- \
      src/agents/prepared-model-runtime.ts
    OPENCLAW_VITEST_RUNTIME=node NODE_OPTIONS=--max-old-space-size=3072 \
      pnpm test src/gateway/server.agent.gateway-server-agent-auth-refresh.test.ts \
      --maxWorkers=1 -t 'temporary SQLite'

    Expected: exit code 0. Publication reaches published, the following Gateway agent RPC returns ok with payload status ok, and the agent-command mock is invoked exactly once. Remove -t 'temporary SQLite' to run all five tests in the file. A cold compiler preparation adds roughly two minutes on the recorded VM; the individual regression timing below excludes most of that startup cost.

The test first persists the affected agent's database and prepares its runtime. It then calls setRuntimeAuthProfileStoreSnapshot(...) inside readers.run(...), immediately awaits readers.close(), and observes the asynchronously queued publication. Persisting the database is essential: an empty fixture can skip the SQLite catalog read and miss the bug. The closed-scope exception is produced by the real reader implementation.

Earlier regression evidence

  • On base 6e7781b5968ff4c3b8b660bd1b6b0def24503d48, the new regression fails with the exact closed-scope error. It emits a real auth mutation using an actual persisted agent database, then closes the temporary readers; the error is not mocked.
  • With the patch, publication succeeds and the next agent RPC completes. All 5 tests in the Gateway auth-refresh file pass, including cancellation and rejected-publication behavior.
  • 35 related tests pass across prepared-model-runtime.reload-auth, prepared-model-runtime.auth-recovery, and sqlite-readonly-worker-session.
  • Independent autoreview of the complete patch and lifecycle context: no P0-P2 findings.
  • Targeted type-aware lint (292 rules, zero warnings/errors), formatting, the deprecated-API usage guard, and git diff --check pass.

Hosted validation on 67eb4ad passed: production types, test types, lint, and changed tests. The local full typecheck had previously been stopped under the 4-GiB VM's memory pressure; no success is claimed for that interrupted run. Hosted CI supplies the completed validation on 67eb4ad.

Local proof used Node 24.21.0 on Ubuntu in an isolated 2-vCPU, 4-GiB VM. The regression took 1.37 seconds on the failing base and 6.29 seconds after the fix, including the successful RPC. The complete Gateway file took 159.29 seconds with a cold compiler preparation; the three related files took 58.09 seconds. Real SQLite plus Gateway admission is necessary to exercise the lifecycle boundary that a fixture without a persisted database misses.

The original Vitest results above use mocked provider/agent execution; the new live Gateway proof separately exercises real local-model inference. Neither is a production deployment or live Telegram test. The scope remains the reader-lifetime publication failure, not the preceding OOM or every cause of an unpublished runtime.

@clawsweeper

clawsweeper Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: S labels Oct 15, 2026
@VictorSesma
VictorSesma marked this pull request as ready for review October 15, 2026 21:25
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T20:49:28.014682Z 43ed85e New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added 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: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Schedules authentication-triggered model publication outside the temporary SQLite reader scope that emitted the change.

Example: Agent main refreshes authentication while temporary SQLite readers close.

  • Before: Publication fails with SQLite read-only worker scope closed, and subsequent agent requests return UNAVAILABLE.
  • After: Publication completes and the next Gateway agent request returns a model response.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A narrow, useful repair with shipped-entry-point red/green evidence, a distinct regression, successful current-head checks, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Supplied Ubuntu Gateway logs exercise real catalog reads and local-model inference after temporary reader closure, with a one-line negative control reproducing failure; the scheduling repair remains intact on the reviewed head.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: An authentication refresh can leave an agent permanently unavailable when temporary SQLite readers close before queued publication runs.
Reason: The patch repairs a demonstrated lifetime mismatch using existing owners, preserves security and ordering contracts, and adds a distinct regression.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a concrete publication failure still present on main, and no actionable patch defects remain.

Priority: P1
Reviewed head: dcc5a5fced7cb41027e056e433dc772c1394ad28

Before merge

None.

Findings

None.

Agent review details

How this fits together

Authentication mutations invalidate prepared model runtimes; lifecycle-owned publication rebuilds their model catalogs and makes fresh generations available to Gateway agent requests.

flowchart TD
 A[Authentication mutation] --> B[Synchronous runtime invalidation]
 B --> C[Publication outside temporary readers]
 C --> D[Existing plugin drain and publication queue]
 D --> E[SQLite worker catalog reads]
 E --> F[Published runtime generation]
 F --> G[Gateway agent request]
Loading

Technical review

Best possible solution:

Land the focused scheduling repair through the existing runtime lifecycle owner after the enforced maintainer approval.

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

Current-main scheduling inherits the temporary reader scope, whose closure rejects catalog inspections; supplied negative-control logs demonstrate the same failure through the shipped Gateway.

Is this the best way to solve the issue?

Exiting only the reader AsyncLocalStorage scope fixes resource ownership at scheduling without retries, parallel publication machinery, or changes to credential invalidation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Authentication publication scheduling keeps the original intent (a3e4005: Preserve readable model metadata during plugin drains while immediately fencing authentication changes and delaying publication until reservations settle.)
  • Authentication event directory normalization keeps the original intent (06f5f73: Lifecycle-owned model discovery normalizes directory identities before selecting affected owners; the later extraction retained that behavior.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced patch: The pinned introduced diff detaches publication scheduling from the SQLite reader scope, moves existing directory normalization into its sole processing owner, and adds a connected-Gateway regression without new production state or APIs. (src/agents/prepared-model-runtime.ts:739, dcc5a5fced7c)
  • Current main retains the failure path: Fetched main schedules auth publication directly through modelRuntimeDrain.runAfter, retaining the emitter's AsyncLocalStorage reader scope. (src/agents/prepared-model-runtime.ts:741, e39ce04c8197)
  • Reader lifetime and worker ownership: Closing a temporary scope marks it inactive and aborts its controller; inherited inspections then reject, while inspections outside a lexical scope use the existing bounded process worker pool. (src/infra/sqlite-readonly-worker.ts:136, dcc5a5fced7c)
  • Shipped Gateway proof: Victor Sesma supplied red/green logs through pnpm openclaw gateway run and a separate Gateway agent RPC using real SQLite and llama.cpp inference. The patched run publishes after readers close and returns status ok; reversing only the scheduling change produces the closed-scope error and UNAVAILABLE. The complete body was hydrated from REST; captured sourceBodySha256 is 96d1a784f0ed01e70e83be7af732da679d5984b6b374b3dd1fc8229c463141b0. This proves the synthetic publication trigger, not an entire OOM or sleep/wake recovery. (67eb4ad0be33)
  • Exact-head validation and approval gate: Workflow https://github.com/openclaw/openclaw/actions/runs/39075176358 completed successfully on the reviewed head. Paginated check runs contain no failed checks; the two failing commit statuses both explicitly require maintainer approval of this revision, rather than contributor code changes. (dcc5a5fced7c)
  • Preserved publication intent: The earlier plugin-drain change deliberately fenced authentication immediately while delaying publication until plugin reservations settled; this PR preserves that ordering and its existing owner. (src/agents/prepared-model-runtime.ts:736, a3e4005ebc5a)

Likely related people:

  • Peter Steinberger: Raw commit a3e4005 adds src/agents/prepared-model-runtime.ts:739 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a3e4005ebc5a; files: src/agents/prepared-model-runtime.ts)
  • Vincent Koc: Raw commit dd2d66c adds src/agents/prepared-model-runtime.ts:599 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dd2d66c26f16; files: src/agents/prepared-model-runtime.ts)
  • Ayaan Zaidi: Raw commit 3d7d211 adds src/agents/prepared-model-runtime.ts:731 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3d7d21166f09; files: src/agents/prepared-model-runtime.ts)

PR surface

Source +2, Tests +34. Total +36 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 11 9 +2
Tests 1 34 0 +34
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 45 9 +36

Labels

Label changes:

  • 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.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The demonstrated failure leaves an affected agent unable to answer subsequent Gateway requests until recovery or restart.
  • 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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-15T21:53:21.238Z sha 989b88d :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-15T23:02:50.799Z sha 67eb4ad :: needs maintainer review before merge. :: none
  • reviewed 2026-10-17T01:14:22.791Z sha 7328d09 :: needs changes before merge. :: none
  • reviewed 2026-10-17T01:56:55.065Z sha 6e83931 :: needs maintainer review before merge. :: none

Reviewed October 17, 2026, 6:57 PM ET / 22:57 UTC (Revision 5).

@VictorSesma

Copy link
Copy Markdown
Author

Added live Gateway evidence and reproduction steps to the PR body on behalf of @VictorSesma.

  • Head 67eb4ad: temporary readers close, publication completes, and the next real Gateway agent RPC returns a llama.cpp/Qwen response.
  • Negative control: rebuild the same head with only the scheduling line reverted. The agent works before the trigger; afterward publication fails with SQLite read-only worker scope closed and the next Gateway RPC is rejected.
  • This runs through the shipped CLI outside Vitest, with real SQLite, discovery, agent execution and local inference. The body explicitly documents the synthetic boundary trigger and the limits of the proof.
  • Current-head hosted production/test type checks, lint and changed tests pass. No additional product-code changes or merge were made.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 15, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 15, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Oct 15, 2026
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Maintainer security review required

This external contributor PR changes sensitive security components. A maintainer must review these changes before merging.

Current SHA: 43ed85ea9abc443b1b3c5b1c6fed7ceb2a0a640b

These sensitive security changes were made:

  • src/agents/prepared-model-runtime-auth-publication.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

After reviewing the changes, post a new PR comment containing only approval commands, each on its own line:

/allow-security-sensitive-change

A later push requires a fresh approval comment.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Oct 17, 2026
@VictorSesma

Copy link
Copy Markdown
Author

@clawsweeper re-review

Completed the requested pinned-base comparison on behalf of @VictorSesma; the new Evidence subsection contains the commands and results. The same three plugin test files fail at runtime-llm.prepared-owner.test.ts:923 with expected 3 to be 2 both on PR head 7328d09d3 (29 pass, 1 fail) and on a clean checkout of its exact main base b0ab44081 (29 pass, 1 fail). Owner reuse remains 11 builds before/after the second request in both runs. This establishes a pre-existing failure; no code, assertions, baselines, or CI policy were changed. The branch remains at the reviewed head, with the failed CI check and enforced maintainer approval still visible.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@VictorSesma

Copy link
Copy Markdown
Author

@clawsweeper re-review

Updated on behalf of @VictorSesma for current head dcc5a5fced7cb41027e056e433dc772c1394ad28, which merges upstream 0a0d88df543a9d36c4708f93c56d995da769050c. The PR body now distinguishes current-head validation from the historical pinned-base LRU failure and preserves the original revisions of the local/live proof.

Hosted CI for this exact head completed successfully: https://github.com/openclaw/openclaw/actions/runs/39075176358 (including lint, test type checks, changed tests, ratchets, and all three PostgreSQL shards).

Codex code review completed on this exact head without findings. The enforced maintainer approval is still required; this request does not claim or substitute for that approval.

Please also reconcile the stale review labels: the durable review on 6e83931d5 says there are no contributor-facing blockers and explicitly lists removal of status: ⏳ waiting on author and replacement of the older rating, but those older labels remain on the PR. Please assess the current revision and apply the corresponding status.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 17, 2026
steipete added a commit that referenced this pull request Oct 24, 2026
…es (#182615)

Auth publication queued during Gateway startup inherited a temporary SQLite reader scope that startup closed before the work ran, so model publication and later reads failed with 'SQLite read-only worker scope closed' until restart. The scheduling owner now exits that reader scope when queuing, preserving the caller's own startup scope. Refs #182547 (the slow startup scan is already fixed on main by #176737 and #181289). Supersedes #173482. Thanks @VictorSesma and @hoangtohl.

Co-authored-by: Victor <[email protected]>
@steipete

Copy link
Copy Markdown
Contributor

Thank you @VictorSesma. You found the real cause in #182547: startup work inheriting a temporary SQLite reader that closes before the work runs. We re-implemented it in #182615, now on main, with you credited as co-author. Closing as superseded.

@steipete steipete closed this Oct 24, 2026
@VictorSesma

Copy link
Copy Markdown
Author

awww, happy I helped fixing the issue, thanks for looking into this!

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…es (openclaw#182615)

Auth publication queued during Gateway startup inherited a temporary SQLite reader scope that startup closed before the work ran, so model publication and later reads failed with 'SQLite read-only worker scope closed' until restart. The scheduling owner now exits that reader scope when queuing, preserving the caller's own startup scope. Refs openclaw#182547 (the slow startup scan is already fixed on main by openclaw#176737 and openclaw#181289). Supersedes openclaw#173482. Thanks @VictorSesma and @hoangtohl.

Co-authored-by: Victor <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 26, 2026
…es (#182615)

Auth publication queued during Gateway startup inherited a temporary SQLite reader scope that startup closed before the work ran, so model publication and later reads failed with 'SQLite read-only worker scope closed' until restart. The scheduling owner now exits that reader scope when queuing, preserving the caller's own startup scope. Refs #182547 (the slow startup scan is already fixed on main by #176737 and #181289). Supersedes #173482. Thanks @VictorSesma and @hoangtohl.

Release adaptation: production fix (readOnlyWorkerScope.exit around the queued publication, plus the agentDir normalization moved into the invalidation owner) applied unchanged; only the conflicting main-only throwSettledAggregate import was dropped. The prepared-harness integration-test fixture change was not needed on the baseline (its main-only DB admission setup is absent) and was dropped. The Gateway regression test was ported into the baseline describe block using its sendAgentRpc and setRuntimeAuthProfileStoreSnapshot; the main-only rows-cache cold-read step was omitted. It fails without the fix with "SQLite read-only worker scope closed".

Co-authored-by: Victor <[email protected]>
(cherry picked from commit 411bac2)
RomneyDa pushed a commit that referenced this pull request Oct 26, 2026
…es (#182615)

Auth publication queued during Gateway startup inherited a temporary SQLite reader scope that startup closed before the work ran, so model publication and later reads failed with 'SQLite read-only worker scope closed' until restart. The scheduling owner now exits that reader scope when queuing, preserving the caller's own startup scope. Refs #182547 (the slow startup scan is already fixed on main by #176737 and #181289). Supersedes #173482. Thanks @VictorSesma and @hoangtohl.

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

(cherry picked from commit 411bac2)

Adapted for 2026.9.x: 9.x queues auth publication with publicationQueue.enqueue (main uses modelRuntimeDrain.runAfter), so the enqueue is wrapped in readOnlyWorkerScope.exit; the queue's previous.then(task) continuation otherwise captures the emitter's reader scope. Dropped main's normalizedEvent cleanup in prepared-model-runtime-auth-publication.ts and the source-delivery integration test mock change (unrelated refactors). beginPreparedModelRuntimePluginDrain does not exist on 9.x, so the regression closes the startup reader scope synchronously before the queued publication runs, then asserts publication completes, ensureOpenClawModelsJson sees no inherited reader scope, and an agent run on the affected agent completes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. security-review-required security-sensitive-changed size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants