Skip to content

fix(memory-wiki): wiki search times out while a large import compiles - #188256

Merged
obviyus merged 6 commits into
openclaw:mainfrom
Baumus:fix/wiki-search-background-refresh
Nov 27, 2026
Merged

obviyus merged 6 commits into
openclaw:mainfrom
Baumus:fix/wiki-search-background-refresh

Conversation

@Baumus

@Baumus Baumus commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Root cause: extensions/memory-wiki/src/tool.ts:174 awaits syncMemoryWikiImportedSources (import, then a full compile) inside the 30 s wiki_search deadline, and extensions/memory-wiki/src/gateway.ts:277 awaits the same sync before wiki.search with no deadline, so a large pending import fails or stalls searches for pages that are already on disk.

Related: #187429, #132296, #166329

What Problem This Solves

Fixes: wiki_search fails with "wiki_search timed out after 30s", and the wiki.search Gateway method hangs, when a large vault has source changes waiting to import and compile. The pages being searched for are already on disk.

User Impact

Searches answer from the current wiki at once while the Gateway imports and compiles in the background. Content that changed in the sources since the last refresh shows up on the next search, not this one. That one-search delay is the only staleness: pages written with wiki_apply are read live, and a vault with no compiled snapshot yet still answers through the existing full scan.

Unchanged: wiki_get, openclaw wiki search, imports, compile, lint, apply and status still wait for the sync. ingest.autoCompile: false still never compiles. A caller with no running wiki service (one-shot hosts) still waits as before.

Why This Change Was Made

When the wiki service is running, wiki_search and wiki.search run the query first and then start the service-owned source sync that the Overview and Import Insights dashboards already use (#132296). That helper moves from gateway.ts to source-sync.ts as refreshMemoryWikiImportedSources. It still single-flights equal requests, queues on the vault mutation lock, is cancelled by the service signal and is joined at shutdown. The refresh starts after the query because a cold read owner activates through the same vault queue, so a refresh started first would block the search.

The helper runs the sync with runInDetachedAsyncContext. Without it the built Gateway aborted every refresh after the /tools/invoke response with Failed to open the plugin state database. | This operation was aborted, so nothing was ever published. The dashboard path on main has the same defect and this fixes it too.

This takes over Baumus's PR. Thanks @Baumus for finding this, carrying the fix in your own deployment since 2026.10.10 and for the real-Gateway proof (#188256 (comment)), which also found the async-scope abort. Your commits stay in the branch. The commits on top replace the refresh coordinator (60 s freshness window, 5–60 s retry backoff, retry handles), the move to the plugin service scheduler, the query hook, the README section and the test-line allocation with the existing dashboard helper. No new freshness or retry policy is needed: the next search or dashboard poll is the retry, as for dashboards today.

Evidence

The built Gateway (dist) runs in an isolated profile with a task-owned state, config and port. Requests go through /tools/invoke → wiki_search and through openclaw gateway call wiki.search. The importer and compiler are the real unsafe-local ones, with no mocks or delays. Fixture: a compiled vault with one entities/cobalt.md, then 6,000 new synthetic source files. Source 0 contains "Zirconium publication evidence." Harness and raw captures: #188256 (comment).

Run Base 6052fff This PR
wiki_search cobalt, run 1 HTTP 500 at 30.5 s, wiki_search timed out after 30s HTTP 200 at 4.9 s, entities/cobalt.md, 0 pages imported, no new publication
wiki_search cobalt, run 2 HTTP 500 at 30.4 s, wiki_search timed out after 30s HTTP 200 at 4.3 s, entities/cobalt.md
wiki_search zirconium after publication n/a HTTP 200 at 8.4 s, the newly imported source page
wiki.search RPC (openclaw gateway call), twice no answer within 600 s; all 6,000 imported, still no publication entities/cobalt.md in 8.8 s and 7.7 s; after publication zirconium returns the new page

Controls on this PR:

  • Cold vault with no compiled snapshot: answers cobalt in 4.3 s through the scan fallback.
  • Two concurrent searches plus one wiki.overview poll: all answer, and exactly one compile is published.
  • SIGTERM during the refresh: exit 0 in 2.2 s, no publication, journal unchanged after exit.
  • ingest.autoCompile: false: the search answers, all 6,000 sources import, and nothing compiles.
  • One-shot openclaw wiki search zirconium: still waits for import and compile (508 s on a loaded host) and returns the new page.
  • Without runInDetachedAsyncContext, both runs logged background source sync failed: Failed to open the plugin state database. | This operation was aborted and never published.

Unit: tool.deadline.test.ts "answers from the current index while the service refreshes" fails on base with wiki_search timed out after 30s and passes here. Focused memory-wiki suites pass: 8 files, 95 tests. Local review on the head reports no findings.

Merge Danger

Two-way door. No config, schema, protocol or stored-data change; a revert restores the awaited sync. Blast radius: memory-wiki search through the agent tool and the wiki.search Gateway method while the plugin service runs.

@clawsweeper

clawsweeper Bot commented Oct 30, 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.

@Baumus
Baumus marked this pull request as ready for review October 30, 2026 10:27
@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. P2 Normal backlog priority with limited blast radius. 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. 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 Oct 30, 2026
@clawsweeper

clawsweeper Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR lets Gateway-hosted Wiki searches read existing pages while a shared service scheduler refreshes sources and compiled indexes.

Example: Search for cobalt while 6,000 synthetic source files are being imported.

  • Before: Search waits for import and compilation, which can exhaust its 30-second deadline.
  • After: The captured Gateway returns entities/cobalt.md before publication, then finds the newly imported Zirconium evidence after publication.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong current-head production evidence and no actionable code findings; readiness remains capped by the unresolved freshness and retry policy.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The inspected current-head captures exercise shipped Gateway HTTP tool dispatch with the candidate Wiki package on the unchanged parent host: real 6,000-source import, searches before publication, durable compiler publication, updated-content search, and a separate shutdown cancellation control. Checkout tree and production hashes match the captured build identity. This satisfies the previous review's requested scenarios; the downloaded screenshots concern the earlier dashboard repair and were treated only as historical context.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: Existing Wiki pages can remain unavailable to a search while a large source refresh consumes its response deadline.
Reason: Nonblocking search has clear value, but the accompanying freshness window and autonomous retries remain an explicitly unresolved owner choice.

Merge readiness

⛔ Blocked before merge - 1 item remains

This PR addresses a current search-blocking path and has sufficient current-head Gateway proof; its freshness and automatic-retry policy still needs an owner decision.

Priority: P2
Reviewed head: 875805b71957ff7a63b193cf492da25fbdb0a2ff
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should successful source checks be reused for 60 seconds and failed checks retry automatically with 5–60-second backoff across searches and dashboards?
  • Recommendation: Approve the proposed policy: Accept the documented freshness window and service-owned retries, retaining shared maintenance and shutdown cancellation.
  • Why: These change freshness and recovery policy beyond removing the search wait, and no recorded owner approval settles that choice.

Before merge

  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not show the added background-search regression failing on the merge base.
Agent review details

How this fits together

Memory Wiki connects agent tools and Gateway RPCs to Markdown vault queries, source importers, and compiled SQLite snapshots; the plugin service owns background maintenance and shutdown.

flowchart TD
A[Agent tool or Gateway RPC] --> B[Wiki query owner]
B --> C[Markdown query reader]
B --> D[Service refresh scheduler]
D --> E[Source synchronization]
E --> F[Compiler and snapshot store]
F --> C
C --> G[Search results]
Loading

Technical review

Best possible solution:

Use the existing service scheduler and source-sync owner to keep queries independent of maintenance, with owner-approved freshness and retry behavior.

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

Current-main source places synchronization before querying within wiki_search's 30-second response budget; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The defect is the query waiting for maintenance; the invariant is independent query completion with service-owned maintenance, and the patch uses existing scheduler, synchronization, compiler, and reader owners while removing the replaced dashboard path.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Search synchronization and cancellation changes intended behavior with a stated reason (12ee7bb: Keep shared import and snapshot recovery alive after an individual search times out while retaining query cancellation.)
  • Dashboard background maintenance and plugin shutdown keeps the original intent (0e2e6c3: Serve bounded compiled dashboard projections without waiting for compilation, preserve autoCompile=false, and retire publication at service shutdown.)
  • Source synchronization coalescing keeps the original intent (f5eacac: Equivalent polls share one complete source-and-index flight while different snapshots serialize at the vault mutation owner.)
  • Query initialization and scoring keeps the original intent (a9f4080: Share query scoring while retaining distinct admission and visibility contracts; refresh admission is added after existing vault initialization.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 0e2e6c3 adds extensions/memory-wiki/src/source-sync.ts:52 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0e2e6c3f5622; files: extensions/memory-wiki/src/source-sync.ts)
  • Peter Steinberger: Raw commit a9f4080 adds extensions/memory-wiki/src/source-sync.ts:74 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a9f4080f9749; files: extensions/memory-wiki/src/source-sync.ts)
  • Vincent Koc: Raw commit 5716d83 adds extensions/memory-wiki/src/source-sync.ts:21 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 5716d83336fd; files: extensions/memory-wiki/src/source-sync.ts)

PR surface

Source +113, Tests +213, Docs +16, Other +3. Total +345 across 11 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 5 158 45 +113
Tests 4 225 12 +213
Docs 1 16 0 +16
Config 0 0 0 0
Generated 0 0 0 0
Other 1 3 0 +3
Total 11 402 57 +345

Review metrics

Metric Value Why it matters
Refresh policy defaults 60-second successful-check reuse; automatic retries from 5 to 60 seconds These user-visible freshness and recovery defaults require the explicit owner decision.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: ⏳ waiting on maintainer.

Label justifications:

  • P2: Large-vault Wiki searches can exhaust their deadline while waiting for maintenance, with impact limited to this optional memory plugin.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • 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 (1 earlier review cycle)
  • reviewed 2026-10-30T10:44:27.473Z sha 8640153 :: needs real behavior proof before merge. :: none

Reviewed November 4, 2026, 3:07 PM ET / 20:07 UTC (Revision 2).

Baumus commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Inspectable Gateway behavior proof for current head 875805b71957

This attaches the actual terminal JSONL output and selected Gateway process log lines from the isolated 2026-11-03 08:39–08:41 UTC run already summarized in the PR body. These are existing captured outputs, not a new run or release-backport evidence.

Head identity checked again on 2026-11-04: current PR head is 875805b71957ff7a63b193cf492da25fbdb0a2ff. The two changed production files in its scheduler-repair commit were fetched from GitHub at that exact SHA and their SHA-256 hashes match the source hashes captured by the canonical plugin builder before this run:

44bdbf83fec848e777c8f25222878681d0dd9aa2e88490b38bd9a95fadce0435  extensions/memory-wiki/index.ts
e739012c2115dbf76aa84f7367ac9fa97496831d469038820a9771a7c70b4b87  extensions/memory-wiki/src/source-sync.ts

The clean local tested source tree is dc7c6b5c782fd6687df5da9c54968f48d20e8337, also recorded in the PR body. The harness's historical label scheduler repair candidate is retained verbatim below; it is tied to the current head by these captured build hashes rather than treated as a commit identifier.

The Gateway host runtime was built at parent 86401535f4ef0579933241dfd82de8a980364651; only the Memory Wiki package was rebuilt from the repaired source with buildPluginNpmRuntime. Both process logs explicitly show that package overriding the bundled baseline. This is candidate plugin behavior on the unchanged parent host, with real HTTP tool dispatch, real importer, real compiler, and durable journal publication. It is not a claim that the entire host/UI was rebuilt at the new SHA.

Each scenario starts a fresh Gateway and isolated vault with one existing Cobalt entity and 6,000 synthetic Markdown inputs. The client invokes wiki_search through HTTP /tools/invoke, then independently reads importer-created source files and the vault's compile journal. No importer/compiler mocks, artificial maintenance delays, external models, or live credentials are used. The process runs in a separate network namespace and filesystem view.

  • Search during refresh: two HTTP 200 responses return entities/cobalt.md; imported files progress 96 → 296 and publication count remains zero.
  • Publication and subsequent search: the durable compile event is observed at 08:41:09.434Z; the subsequent HTTP 200 response contains Zirconium publication evidence.
  • Shutdown cancellation control: in a separate fresh scenario, imported files progress 2 → 122 while both searches finish with zero publications. SIGTERM then yields a clean exit, code 0, in 679ms. No compile publication occurs and the journal is identical after a further one-second observation. This demonstrates cancellation before completion, not completion of all 6,000 inputs.

Redaction at egress: IP addresses, endpoint URLs, host identifiers, and the synthetic authentication token are removed where present. The displayed content contains synthetic fixture data only; no API keys or phone numbers are included. Timestamps, response bodies, source hashes, and publication identifiers are preserved for correlation. Unrelated startup/model diagnostics are omitted from the selected process excerpts.

Complete captured terminal JSONL: real HTTP responses, journal publication, and shutdown assertions
{"event":"gateway-started","at":"2026-11-03T08:39:20.861Z","kind":"publication","root":"/proof/publication-TMXICh","inputCount":6000,"head":"scheduler repair candidate","pluginBuild":{"status":"built","hostHead":"86401535f4ef0579933241dfd82de8a980364651","entryCount":5,"sourceHashes":[{"path":"extensions/memory-wiki/index.ts","sha256":"44bdbf83fec848e777c8f25222878681d0dd9aa2e88490b38bd9a95fadce0435"},{"path":"extensions/memory-wiki/src/source-sync.ts","sha256":"e739012c2115dbf76aa84f7367ac9fa97496831d469038820a9771a7c70b4b87"}],"runtimeExtensions":["./dist/index.js"]}}
{"event":"search-result","at":"2026-11-03T08:39:46.921Z","kind":"publication","query":"cobalt","elapsedMs":1310,"httpStatus":200,"body":{"ok":true,"result":{"content":[{"type":"text","text":"1. Cobalt ledger (wiki/entity)\nPath: entities/cobalt.md\nSnippet: # Cobalt ledger"}],"details":{"results":[{"corpus":"wiki","path":"entities/cobalt.md","title":"Cobalt ledger","kind":"entity","score":72,"snippet":"# Cobalt ledger","searchMode":"auto","id":"entity.cobalt"}]}}}}
{"event":"search-before-publication","at":"2026-11-03T08:39:46.941Z","kind":"publication","realImportedPagesObserved":96,"publicationCount":0}
{"event":"search-result","at":"2026-11-03T08:39:47.829Z","kind":"publication","query":"cobalt","elapsedMs":887,"httpStatus":200,"body":{"ok":true,"result":{"content":[{"type":"text","text":"1. Cobalt ledger (wiki/entity)\nPath: entities/cobalt.md\nSnippet: # Cobalt ledger"}],"details":{"results":[{"corpus":"wiki","path":"entities/cobalt.md","title":"Cobalt ledger","kind":"entity","score":72,"snippet":"# Cobalt ledger","searchMode":"auto","id":"entity.cobalt"}]}}}}
{"event":"search-during-real-refresh","at":"2026-11-03T08:39:47.833Z","kind":"publication","importedPagesBefore":96,"importedPagesAfter":296,"publicationCount":0}
{"event":"snapshot-published","at":"2026-11-03T08:41:09.493Z","kind":"publication","publication":{"type":"compile","timestamp":"2026-11-03T08:41:09.434Z","details":{"compiledCachePublicationId":"05c28cfc-0542-4bee-8d6e-f1e35751aba6","compiledCacheParentPublicationId":null,"compiledCacheReservationId":"3fb71ade-ff65-4f8e-b026-a4641d1d6370","compiledCacheSourceGeneration":"ff69dad696f374e11da42d4a1f01543cf24de0f2725949fc12de59259d41115a"}}}
{"event":"search-result","at":"2026-11-03T08:41:13.203Z","kind":"publication","query":"zirconium","elapsedMs":3710,"httpStatus":200,"body":{"ok":true,"result":{"content":[{"type":"text","text":"1. Unsafe Local Import: source-00000.md (wiki/source)\nPath: sources/unsafe-local-inputs-d79fbf51-source-00000-md-c9ff3825.md\nProvenance: unsafe-local: source-00000.md\nSnippet: Zirconium publication evidence."}],"details":{"results":[{"corpus":"wiki","path":"sources/unsafe-local-inputs-d79fbf51-source-00000-md-c9ff3825.md","title":"Unsafe Local Import: source-00000.md","kind":"source","score":3,"snippet":"Zirconium publication evidence.","searchMode":"auto","id":"source.unsafe-local.inputs-d79fbf51-source-00000-md-c9ff3825","sourceType":"memory-unsafe-local","provenanceMode":"unsafe-local","sourcePath":"/proof/publication-TMXICh/inputs/source-00000.md","provenanceLabel":"unsafe-local: source-00000.md","updatedAt":"2026-11-03T08:39:20.542Z"}]}}}}
{"event":"gateway-stopped","at":"2026-11-03T08:41:13.797Z","kind":"publication","elapsedMs":592,"code":0,"signal":null}
{"event":"gateway-started","at":"2026-11-03T08:41:13.985Z","kind":"shutdown","root":"/proof/shutdown-oaKA0R","inputCount":6000,"head":"scheduler repair candidate","pluginBuild":{"status":"built","hostHead":"86401535f4ef0579933241dfd82de8a980364651","entryCount":5,"sourceHashes":[{"path":"extensions/memory-wiki/index.ts","sha256":"44bdbf83fec848e777c8f25222878681d0dd9aa2e88490b38bd9a95fadce0435"},{"path":"extensions/memory-wiki/src/source-sync.ts","sha256":"e739012c2115dbf76aa84f7367ac9fa97496831d469038820a9771a7c70b4b87"}],"runtimeExtensions":["./dist/index.js"]}}
{"event":"search-result","at":"2026-11-03T08:41:35.574Z","kind":"shutdown","query":"cobalt","elapsedMs":801,"httpStatus":200,"body":{"ok":true,"result":{"content":[{"type":"text","text":"1. Cobalt ledger (wiki/entity)\nPath: entities/cobalt.md\nSnippet: # Cobalt ledger"}],"details":{"results":[{"corpus":"wiki","path":"entities/cobalt.md","title":"Cobalt ledger","kind":"entity","score":72,"snippet":"# Cobalt ledger","searchMode":"auto","id":"entity.cobalt"}]}}}}
{"event":"search-before-publication","at":"2026-11-03T08:41:36.796Z","kind":"shutdown","realImportedPagesObserved":2,"publicationCount":0}
{"event":"search-result","at":"2026-11-03T08:41:37.227Z","kind":"shutdown","query":"cobalt","elapsedMs":431,"httpStatus":200,"body":{"ok":true,"result":{"content":[{"type":"text","text":"1. Cobalt ledger (wiki/entity)\nPath: entities/cobalt.md\nSnippet: # Cobalt ledger"}],"details":{"results":[{"corpus":"wiki","path":"entities/cobalt.md","title":"Cobalt ledger","kind":"entity","score":72,"snippet":"# Cobalt ledger","searchMode":"auto","id":"entity.cobalt"}]}}}}
{"event":"search-during-real-refresh","at":"2026-11-03T08:41:37.228Z","kind":"shutdown","importedPagesBefore":2,"importedPagesAfter":122,"publicationCount":0}
{"event":"gateway-stopped","at":"2026-11-03T08:41:37.908Z","kind":"shutdown","elapsedMs":679,"code":0,"signal":null}
{"event":"shutdown-maintenance-control","at":"2026-11-03T08:41:38.910Z","kind":"shutdown","noPublication":true,"journalStableAfterExit":true,"importedPagesBeforeStop":2}
{"event":"proof-passed","at":"2026-11-03T08:41:38.911Z","head":"scheduler repair candidate"}

publication Gateway process log (selected lines)

2026-11-03T08:39:43.892+00:00 [gateway] [plugins] duplicate plugin id resolved by explicit config-selected plugin; bundled plugin will be overridden by config plugin (/proof/plugin-package/dist/index.js) (plugin=memory-wiki, source=/work/dist/extensions/memory-wiki/index.js)
2026-11-03T08:39:45.527+00:00 [gateway] startup phase: sidecars.plugin-services starting total=24662.4ms
2026-11-03T08:39:45.575+00:00 [gateway] startup phase: sidecars.plugin-services 48.0ms total=24710.4ms rssMb=1089.6 heapUsedMb=317.1 workers=12 workerHeapSamples=10/12 workerHeapMb=385.1 workerHeapSource=cached
2026-11-03T08:39:45.892+00:00 [gateway] ready
2026-11-03T08:41:13.207+00:00 [admission] closed: restart-signal fence
2026-11-03T08:41:13.226+00:00 [admission] closed: stop (SIGTERM)
2026-11-03T08:41:13.226+00:00 [gateway] received SIGTERM; shutting down
2026-11-03T08:41:13.227+00:00 [gateway] shutdown budget at shutdown: drain=315000ms shutdown=325000ms reserve=10000ms exitMargin=5000ms; source=Gateway stop policy=330000ms
2026-11-03T08:41:13.533+00:00 [shutdown] completed cleanly in 296ms

shutdown Gateway process log (selected lines)

2026-11-03T08:41:33.687+00:00 [gateway] [plugins] duplicate plugin id resolved by explicit config-selected plugin; bundled plugin will be overridden by config plugin (/proof/plugin-package/dist/index.js) (plugin=memory-wiki, source=/work/dist/extensions/memory-wiki/index.js)
2026-11-03T08:41:34.641+00:00 [gateway] startup phase: sidecars.plugin-services starting total=20652.8ms
2026-11-03T08:41:34.682+00:00 [gateway] startup phase: sidecars.plugin-services 40.1ms total=20693.0ms rssMb=1163.3 heapUsedMb=338.0 workers=12 workerHeapSamples=9/12 workerHeapMb=310.3 workerHeapSource=cached
2026-11-03T08:41:34.999+00:00 [gateway] ready
2026-11-03T08:41:37.246+00:00 [admission] closed: restart-signal fence
2026-11-03T08:41:37.281+00:00 [admission] closed: stop (SIGTERM)
2026-11-03T08:41:37.281+00:00 [gateway] received SIGTERM; shutting down
2026-11-03T08:41:37.296+00:00 [gateway] shutdown budget at shutdown: drain=315000ms shutdown=325000ms reserve=10000ms exitMargin=5000ms; source=Gateway stop policy=330000ms
2026-11-03T08:41:37.625+00:00 [shutdown] completed cleanly in 320ms
Client harness used for these captures (credentials and network addresses redacted)

The redacted address placeholders below describe the original loopback-only requests. The poll waits observe readiness, real importer writes, or publication; they do not delay or mock maintenance. Shutdown includes a one-second observation after process exit.

import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import net from 'node:net';
import {spawn} from 'node:child_process';
import {setTimeout as delay} from 'node:timers/promises';

const head = 'scheduler repair candidate';
const pluginBuild = JSON.parse(await fs.readFile('/proof/plugin-build.json','utf8'));
const base = '/proof';
const events = [];
const log = (event, details = {}) => {
  const row = {event, at: new Date().toISOString(), ...details};
  events.push(row);
  console.log(JSON.stringify(row));
};
async function readJournal(root) {
  try {
    return (await fs.readFile(path.join(root, 'vault/.openclaw-wiki/log.jsonl'), 'utf8'))
      .split('\n').filter(Boolean).map(line => JSON.parse(line));
  } catch (error) {
    if (error.code === 'ENOENT') return [];
    throw error;
  }
}
const publications = rows => rows.filter(row => row.type === 'compile' && row.details?.compiledCachePublicationId);
async function waitFor(label, predicate, ms = 180000) {
  const until = Date.now() + ms;
  while (Date.now() < until) {
    const value = await predicate();
    if (value) return value;
    await delay(100);
  }
  throw Error(`Timed out: ${label}`);
}
async function unusedPort() {
  return await new Promise((resolve, reject) => {
    const server = net.createServer(); server.once('error', reject);
    server.listen(0, '[REDACTED_IP]', () => { const port = server.address().port; server.close(() => resolve(port)); });
  });
}
async function scenario(kind, inputCount) {
  const root = await fs.mkdtemp(path.join(base, kind + '-'));
  for (const dir of ['home', 'state', 'workspace', 'inputs', 'vault/entities']) await fs.mkdir(path.join(root, dir), {recursive:true,mode:0o700});
  await fs.writeFile(path.join(root, 'vault/entities/cobalt.md'),
    '---\npageType: entity\nid: entity.cobalt\ntitle: Cobalt ledger\nstatus: active\n---\n# Cobalt ledger\n\nExisting cobalt evidence remains searchable.\n');
  for (let start = 0; start < inputCount; start += 64) {
    await Promise.all(Array.from({length:Math.min(64, inputCount-start)}, (_, offset) => {
      const n = start + offset;
      return fs.writeFile(path.join(root, 'inputs', `source-${String(n).padStart(5,'0')}.md`),
        `# Synthetic source ${n}\n\n${n === 0 ? 'Zirconium publication evidence.' : 'Synthetic background import evidence.'}\n`);
    }));
  }
  const port = await unusedPort(); assert.notEqual(port, 18789);
  const config = {
    gateway:{mode:'local',bind:'loopback',port,auth:{mode:'token',token:'[REDACTED_SYNTHETIC_TOKEN]'},controlUi:{enabled:false},tools:{allow:['wiki_search','wiki_get']}},
    logging:{level:'debug',file:path.join(root, 'runtime.log')},
    agents:{defaults:{workspace:path.join(root,'workspace'),skipBootstrap:true},entries:{main:{tools:{allow:['wiki_search','wiki_get']}}}},
    plugins:{load:{paths:['/proof/plugin-package']},allow:['memory-wiki'],slots:{memory:'none'},entries:{'memory-wiki':{enabled:true,config:{vaultMode:'unsafe-local',vault:{path:path.join(root,'vault')},unsafeLocal:{allowPrivateMemoryCoreAccess:true,paths:[path.join(root,'inputs')]},search:{backend:'local',corpus:'wiki'},ingest:{autoCompile:true}}}}},
    discovery:{mdns:{mode:'off'}},skills:{allowBundled:[]},tools:{allow:['wiki_search','wiki_get']},
  };
  const configPath = path.join(root,'openclaw.json');
  await fs.writeFile(configPath, JSON.stringify(config,null,2));
  const output = await fs.open(path.join(root,'gateway.log'),'w');
  const env = {PATH:process.env.PATH,HOME:path.join(root,'home'),LANG:'C.UTF-8',OPENCLAW_STATE_DIR:path.join(root,'state'),OPENCLAW_CONFIG_PATH:configPath};
  if (process.argv.includes('--diagnostics')) env.NODE_OPTIONS = '--import /proof/diagnostic.mjs';
  const gateway = spawn(process.execPath,['/work/dist/index.js','gateway','--port',String(port),'--allow-unconfigured'],{cwd:root,env,stdio:['ignore',output.fd,output.fd]});
  const exit = new Promise(resolve => gateway.once('exit',(code,signal) => resolve({code,signal})));
  let stopped = false;
  async function stop() {
    if (stopped) return;
    const started = performance.now(); gateway.kill('SIGTERM');
    const result = await Promise.race([exit, delay(30000,undefined,{ref:false}).then(() => {throw Error('Gateway did not stop within 30 seconds');})]);
    stopped = true; log('gateway-stopped',{kind,elapsedMs:Math.round(performance.now()-started),...result});
    assert.equal(result.code,0);
  }
  async function search(query) {
    const start = performance.now();
    const response = await fetch(`[REDACTED_ENDPOINT]`,{
      method:'POST',headers:{authorization:'Bearer [REDACTED_SYNTHETIC_TOKEN]','content-type':'application/json'},
      body:JSON.stringify({tool:'wiki_search',args:{query,maxResults:3},agentId:'main'}),signal:AbortSignal.timeout(45000),
    });
    const body = await response.json();
    log('search-result',{kind,query,elapsedMs:Math.round(performance.now()-start),httpStatus:response.status,body});
    assert.equal(response.status,200); assert.equal(body.ok,true);
    return body;
  }
  try {
    log('gateway-started',{kind,root,inputCount,head,pluginBuild});
    await waitFor('Gateway readiness',async() => {
      if (gateway.exitCode !== null) throw Error(`Gateway exited ${gateway.exitCode}; inspect ${root}/gateway.log`);
      try {return (await fetch(`[REDACTED_ENDPOINT]`)).ok;} catch {return false;}
    },120000);
    await waitFor('plugin service startup',async()=> {
      if (gateway.exitCode !== null) throw Error(`Gateway exited ${gateway.exitCode}`);
      const output = await fs.readFile(path.join(root,'gateway.log'),'utf8');
      return /startup phase: sidecars\.plugin-services \d+(?:\.\d+)?ms/.test(output);
    },120000);
    const initial = await search('cobalt');
    assert.ok(initial.result.details.results.some(result => result.path === 'entities/cobalt.md'));
    const atResponse = await readJournal(root);
    assert.equal(publications(atResponse).length,0,'Search must complete before refresh publication');
    const imported = await waitFor('real importer writes',async()=> {
      const output = await fs.readFile(path.join(root,'gateway.log'),'utf8');
      if (output.includes('background source sync failed')) throw Error('Real importer failed; inspect isolated Gateway diagnostics');
      try {return (await fs.readdir(path.join(root,'vault/sources'))).filter(file=>file.startsWith('unsafe-local-')).length;} catch {return false;}
    });
    log('search-before-publication',{kind,realImportedPagesObserved:imported,publicationCount:0});
    assert.equal(publications(await readJournal(root)).length,0);
    const duringRefresh = await search('cobalt');
    assert.ok(duringRefresh.result.details.results.some(result => result.path === 'entities/cobalt.md'));
    const importedAfterSearch = (await fs.readdir(path.join(root,'vault/sources')))
      .filter(file=>file.startsWith('unsafe-local-')).length;
    assert.equal(publications(await readJournal(root)).length,0,
      'A search issued after real importer writes must complete before publication');
    log('search-during-real-refresh',{kind,importedPagesBefore:imported,
      importedPagesAfter:importedAfterSearch,publicationCount:0});
    if (kind === 'publication') {
      const published = await waitFor('real compiler publication',async()=>publications(await readJournal(root))[0],240000);
      log('snapshot-published',{kind,publication:published});
      const updated = await search('zirconium');
      assert.match(JSON.stringify(updated),/Zirconium publication evidence/);
      assert.equal(publications(await readJournal(root)).length,1);
      await stop();
    } else {
      const beforeStop = await readJournal(root);
      assert.equal(publications(beforeStop).length,0);
      await stop();
      const afterStop = await readJournal(root);
      assert.equal(publications(afterStop).length,0);
      await delay(1000);
      assert.deepEqual(await readJournal(root),afterStop);
      log('shutdown-maintenance-control',{kind,noPublication:true,journalStableAfterExit:true,importedPagesBeforeStop:imported});
    }
    return {kind,root,inputCount,status:'pass'};
  } finally {
    if (!stopped && gateway.exitCode === null) {gateway.kill('SIGKILL');await exit;}
    await output.close();
  }
}
try {
  const requestedKind = process.argv[2];
  const results = requestedKind === 'shutdown'
    ? [await scenario('shutdown',6000)]
    : requestedKind === 'publication'
      ? [await scenario('publication',6000)]
      : [await scenario('publication',6000),await scenario('shutdown',6000)];
  const result = {status:'pass',head,pluginBuild,node:process.version,kind:'built-Gateway-real-import-and-compile',results,events};
  await fs.writeFile(path.join(base,requestedKind ? `gateway-proof-${requestedKind}.json` : 'gateway-proof.json'),JSON.stringify(result,null,2));
  log('proof-passed',{head});
} catch(error) {
  await fs.writeFile(path.join(base,'gateway-proof-failure.json'),JSON.stringify({status:'failed',head,error:String(error),stack:error.stack,events},null,2));
  log('proof-failed',{error:String(error)});process.exitCode=1;
}

The separate maintainer decision about the 60-second freshness window and 5–60-second retries remains open. This evidence addresses the behavior-proof request only.

Baumus commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The behavior-proof request is addressed for current head 875805b71957ff7a63b193cf492da25fbdb0a2ff: #188256 (comment) attaches redacted captured Gateway terminal output, actual HTTP search responses during real refresh, the later durable publication and updated-content response, selected loader/shutdown process logs, and the client harness. Source hashes captured at build time were checked against that exact GitHub head. The PR body now links these inspectable artifacts and states the unchanged parent-host/candidate-plugin build boundary.

The separate maintainer decision on the 60-second freshness window and 5–60-second retries remains open.

@clawsweeper

clawsweeper Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 4, 2026

Baumus commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@obviyus, this builds on your service-owned Wiki dashboard maintenance in #132296. Could you review the search fix, decide on the 60-second freshness window and 5–60-second retry backoff, and, if you approve those defaults, merge it for the next release?

I have carried the combined Wiki backports across OpenClaw 2026.10.10 and 2026.11.1, and they made Wiki practical for my daily work. The current installation retains this behavior; the November 7 source comparison also confirmed that the refresh coordinator matches this PR. That is combined-backport experience, separate from the pinned candidate tests.

The candidate passed 48 focused tests covering caller-scope closure, retries, cancellation and shutdown, plus types and targeted lint. The captured real Gateway proof uses 6,000 actual synthetic inputs: existing pages remain searchable during import, newly imported content is found after publication, and shutdown cancels cleanly. ClawSweeper now reports sufficient behavior proof and no actionable code findings; the freshness/retry decision remains open.

Landing this would keep large refreshes from consuming the search deadline and remove a backport I currently maintain. Could you resolve that remaining decision for the next release?

Baumus commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

@obviyus, could you please review this fix for inclusion in the next official OpenClaw release, subject to the remaining maintainer decisions below?

Deployment update — November 18: I have carried the release-adapted fix since OpenClaw 2026.10.10 and continue to reapply it across upgrades, including 2026.11.3, 2026.11.4 and the currently deployed 2026.11.5. It has remained stable in my use, with no regression attributable to this fix observed. This keeps Wiki search available while source refresh continues. I would appreciate having it included upstream so this correction no longer needs to be reapplied for each release.

The 2026.11.5 installation passed package-byte verification, native Doctor/database migrations, restarted-Gateway health and active-plugin checks. This is operational evidence for my combined release adaptation; it does not claim a new pristine runtime proof of this PR head.

Current PR head: 875805b71957ff7a63b193cf492da25fbdb0a2ff. Its CI gate and dependency/security review statuses are successful, GitHub reports it mergeable, and there are no unresolved inline review threads. Existing behavioral proof remains tied to the revisions named in the PR description.

Please explicitly decide the documented 60-second successful-refresh window and 5–60-second retry backoff before merging. My local use does not supply upstream policy approval.

Previous follow-up and revision-specific evidence

@obviyus, could you please review this again, decide the documented freshness/retry policy, and include the fix in the next official release if you approve?

Deployment update (November 12): the release-adapted fix is included in my running combined OpenClaw 2026.11.3 build. After installation, I verified the package contents against the source-bound artifact and checked the restarted Gateway and relevant active plugins. This is operational evidence for the combined local adaptation, separate from a pristine build or fresh isolated behavior proof of this PR head. Earlier validation notes below remain tied to the revisions they name.

Earlier PR-branch evidence (historical, separate from the deployed release adaptation):

Keeping search independent of source refresh remains helpful for usable Wiki recall. GitHub currently reports head 875805b71957 mergeable, with its CI gate successful and no unresolved inline review threads. The outstanding owner decision is explicit: reuse successful checks for 60 seconds and retry failed checks with 5–60-second backoff. Please confirm those defaults or specify the policy you want; local compatibility does not substitute for that decision.

Baumus commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

2026.11.7 update: I carried forward Wiki search during background refresh. Focused tests passed for searching during maintenance with and without a published snapshot, and for the Gateway delegating refresh to the service. The official tag still waits for source synchronization on the query path.

- wiki_search and wiki.search answer from the current index, then start the existing service-owned source sync.
- Replace the refresh coordinator, scheduler move, query hook, README section and test-lines allocation with the existing dashboard helper, moved to source-sync.ts.
- One-shot callers without a running service still await the sync; wiki_get, CLI search, imports, compile, lint, apply and status are unchanged.
- Chain the refresh on the search promise so the query path keeps its shape.
- Without it the refresh opened plugin state after the /tools/invoke scope closed and failed with "This operation was aborted" on the built Gateway.
@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Built-Gateway proof for this fix (real unsafe-local importer and compiler, synthetic 6,000-source vault, isolated profile/state/port). Raw per-run events below.

PR #188256 proof (worker WikiSearchRefresh, 2026-11-27)
Tier: dist-nodts (ocx build --dist). Built Gateway, isolated --profile p188256base/p188256cand, task-owned OPENCLAW_HOME/STATE_DIR/CONFIG_PATH under a temp root, unique loopback port.
Fixture: real unsafe-local importer and compiler; compiled vault with entities/cobalt.md, then 6,000 new synthetic inputs (source 0 = "Zirconium publication evidence.").
Harness: proofs/188256/harness.mjs, run-cand.sh; raw events and gateway logs: proofs/188256/runs/
Base: merge base 6052fffac2993079e81dba7de5bfdff89eebb08b (ocx base merge-base)
Candidate: dist built from bfff5ac087aa6a0046e462d9bf2683998a9bcce3; pushed head 6ebff41249286be33d93cc4230df4073192dc7cc differs only by a `: unknown` catch annotation (lint)

BASE
base tool-warm 1: wiki_search cobalt -> HTTP 500 in 30458 ms; gateway log "tool execution failed: Error: wiki_search timed out after 30s" (904 pages imported, no new publication)
base tool-warm 2: wiki_search cobalt -> HTTP 500 in 30378 ms; same timeout
base rpc-warm 1: gateway call wiki.search cobalt -> no answer within 600000 ms (6000 imported, no new publication); Gateway then logged wiki.search 656552ms internal_error during shutdown
base rpc-warm 2: same, no answer within 600000 ms; wiki.search 656452ms

CANDIDATE WITHOUT runInDetachedAsyncContext (625af2341f, two runs)
wiki_search cobalt -> HTTP 200 in 6.8 s / 7.6 s, but every refresh failed with "memory-wiki: background source sync failed: Failed to open the plugin state database. | This operation was aborted", so nothing was published within 600 s -> the wrapper was kept

CANDIDATE
cand tool-warm 1: cobalt -> HTTP 200 in 4876 ms, entities/cobalt.md, 0 imported, 0 new publications; after publication (6000 imported) zirconium -> HTTP 200 in 8360 ms, sources/unsafe-local-inputs-...-source-00000-md-....md
cand tool-warm 2: cobalt -> HTTP 200 in 4296 ms; after publication zirconium -> HTTP 200 in 10552 ms, the new source page
cand rpc-warm 1: gateway call wiki.search cobalt -> exit 0 in 8805 ms, entities/cobalt.md; after publication zirconium -> exit 0 in 9799 ms, the new source page
cand rpc-warm 2: cobalt -> exit 0 in 7668 ms; after publication zirconium -> exit 0 in 16300 ms, the new source page
control cold vault (no snapshot): cobalt -> HTTP 200 in 4320 ms with 0 publications (scan fallback); later zirconium found after first publication
control concurrent: 2x wiki_search + wiki.overview at once -> 200/200/exit 0; exactly 1 new compile publication
control SIGTERM during refresh (48/6000 imported): exit code 0 in 2178 ms, 0 new publications, journal unchanged 3 s after exit
control autoCompile false: cobalt -> HTTP 200 in 2523 ms; all 6000 imported, 0 new publications
control CLI `openclaw wiki search zirconium` (one-shot): exit 0 after 507986 ms (waited for import+compile), found the new source page
No "background source sync failed" or "tool execution failed" lines in any candidate gateway log.

@obviyus obviyus changed the title fix(memory-wiki): avoid search timeouts during source refresh fix(memory-wiki): wiki search times out while a large import compiles Nov 27, 2026
@obviyus
obviyus merged commit f9f7bf7 into openclaw:main Nov 27, 2026
101 checks passed
@obviyus

obviyus commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

Landed in f9f7bf7. Wiki search now answers from the current index right away and refreshes imported sources in the background, so a large vault no longer fails with "wiki_search timed out after 30s" while it imports and compiles. Content imported since the last refresh shows up on the next search. Thanks @Baumus for finding this, for the real-Gateway proof and for the original fix; we replaced the refresh coordinator with the existing background helper in commits on top of yours.

tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
…#188256)

Root cause: `extensions/memory-wiki/src/tool.ts:174` awaits `syncMemoryWikiImportedSources` (import, then a full compile) inside the 30 s `wiki_search` deadline, and `extensions/memory-wiki/src/gateway.ts:277` awaits the same sync before `wiki.search` with no deadline, so a large pending import fails or stalls searches for pages that are already on disk.

Related: #187429, #132296, #166329

## What Problem This Solves

Fixes: `wiki_search` fails with "wiki_search timed out after 30s", and the `wiki.search` Gateway method hangs, when a large vault has source changes waiting to import and compile. The pages being searched for are already on disk.

## User Impact

Searches answer from the current wiki at once while the Gateway imports and compiles in the background. Content that changed in the sources since the last refresh shows up on the next search, not this one. That one-search delay is the only staleness: pages written with `wiki_apply` are read live, and a vault with no compiled snapshot yet still answers through the existing full scan.

Unchanged: `wiki_get`, `openclaw wiki search`, imports, compile, lint, apply and status still wait for the sync. `ingest.autoCompile: false` still never compiles. A caller with no running wiki service (one-shot hosts) still waits as before.

## Why This Change Was Made

When the wiki service is running, `wiki_search` and `wiki.search` run the query first and then start the service-owned source sync that the Overview and Import Insights dashboards already use (#132296). That helper moves from `gateway.ts` to `source-sync.ts` as `refreshMemoryWikiImportedSources`. It still single-flights equal requests, queues on the vault mutation lock, is cancelled by the service signal and is joined at shutdown. The refresh starts after the query because a cold read owner activates through the same vault queue, so a refresh started first would block the search.

The helper runs the sync with `runInDetachedAsyncContext`. Without it the built Gateway aborted every refresh after the `/tools/invoke` response with `Failed to open the plugin state database. | This operation was aborted`, so nothing was ever published. The dashboard path on main has the same defect and this fixes it too.

This takes over Baumus's PR. Thanks @Baumus for finding this, carrying the fix in your own deployment since 2026.10.10 and for the real-Gateway proof (#188256 (comment)), which also found the async-scope abort. Your commits stay in the branch. The commits on top replace the refresh coordinator (60 s freshness window, 5–60 s retry backoff, retry handles), the move to the plugin service scheduler, the query hook, the README section and the test-line allocation with the existing dashboard helper. No new freshness or retry policy is needed: the next search or dashboard poll is the retry, as for dashboards today.

## Evidence

The built Gateway (dist) runs in an isolated profile with a task-owned state, config and port. Requests go through `/tools/invoke` → `wiki_search` and through `openclaw gateway call wiki.search`. The importer and compiler are the real unsafe-local ones, with no mocks or delays. Fixture: a compiled vault with one `entities/cobalt.md`, then 6,000 new synthetic source files. Source `0` contains "Zirconium publication evidence." Harness and raw captures: #188256 (comment).

| Run | Base 6052fff | This PR |
| --- | --- | --- |
| `wiki_search cobalt`, run 1 | HTTP 500 at 30.5 s, `wiki_search timed out after 30s` | HTTP 200 at 4.9 s, `entities/cobalt.md`, 0 pages imported, no new publication |
| `wiki_search cobalt`, run 2 | HTTP 500 at 30.4 s, `wiki_search timed out after 30s` | HTTP 200 at 4.3 s, `entities/cobalt.md` |
| `wiki_search zirconium` after publication | n/a | HTTP 200 at 8.4 s, the newly imported source page |
| `wiki.search` RPC (`openclaw gateway call`), twice | no answer within 600 s; all 6,000 imported, still no publication | `entities/cobalt.md` in 8.8 s and 7.7 s; after publication `zirconium` returns the new page |

Controls on this PR:
- Cold vault with no compiled snapshot: answers `cobalt` in 4.3 s through the scan fallback.
- Two concurrent searches plus one `wiki.overview` poll: all answer, and exactly one compile is published.
- SIGTERM during the refresh: exit 0 in 2.2 s, no publication, journal unchanged after exit.
- `ingest.autoCompile: false`: the search answers, all 6,000 sources import, and nothing compiles.
- One-shot `openclaw wiki search zirconium`: still waits for import and compile (508 s on a loaded host) and returns the new page.
- Without `runInDetachedAsyncContext`, both runs logged `background source sync failed: Failed to open the plugin state database. | This operation was aborted` and never published.

Unit: `tool.deadline.test.ts` "answers from the current index while the service refreshes" fails on base with `wiki_search timed out after 30s` and passes here. Focused memory-wiki suites pass: 8 files, 95 tests. Local review on the head reports no findings.

## Merge Danger

Two-way door. No config, schema, protocol or stored-data change; a revert restores the awaited sync. Blast radius: memory-wiki search through the agent tool and the `wiki.search` Gateway method while the plugin service runs.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit f9f7bf7)
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
…#188256)

Root cause: `extensions/memory-wiki/src/tool.ts:174` awaits `syncMemoryWikiImportedSources` (import, then a full compile) inside the 30 s `wiki_search` deadline, and `extensions/memory-wiki/src/gateway.ts:277` awaits the same sync before `wiki.search` with no deadline, so a large pending import fails or stalls searches for pages that are already on disk.

Related: #187429, #132296, #166329

## What Problem This Solves

Fixes: `wiki_search` fails with "wiki_search timed out after 30s", and the `wiki.search` Gateway method hangs, when a large vault has source changes waiting to import and compile. The pages being searched for are already on disk.

## User Impact

Searches answer from the current wiki at once while the Gateway imports and compiles in the background. Content that changed in the sources since the last refresh shows up on the next search, not this one. That one-search delay is the only staleness: pages written with `wiki_apply` are read live, and a vault with no compiled snapshot yet still answers through the existing full scan.

Unchanged: `wiki_get`, `openclaw wiki search`, imports, compile, lint, apply and status still wait for the sync. `ingest.autoCompile: false` still never compiles. A caller with no running wiki service (one-shot hosts) still waits as before.

## Why This Change Was Made

When the wiki service is running, `wiki_search` and `wiki.search` run the query first and then start the service-owned source sync that the Overview and Import Insights dashboards already use (#132296). That helper moves from `gateway.ts` to `source-sync.ts` as `refreshMemoryWikiImportedSources`. It still single-flights equal requests, queues on the vault mutation lock, is cancelled by the service signal and is joined at shutdown. The refresh starts after the query because a cold read owner activates through the same vault queue, so a refresh started first would block the search.

The helper runs the sync with `runInDetachedAsyncContext`. Without it the built Gateway aborted every refresh after the `/tools/invoke` response with `Failed to open the plugin state database. | This operation was aborted`, so nothing was ever published. The dashboard path on main has the same defect and this fixes it too.

This takes over Baumus's PR. Thanks @Baumus for finding this, carrying the fix in your own deployment since 2026.10.10 and for the real-Gateway proof (#188256 (comment)), which also found the async-scope abort. Your commits stay in the branch. The commits on top replace the refresh coordinator (60 s freshness window, 5–60 s retry backoff, retry handles), the move to the plugin service scheduler, the query hook, the README section and the test-line allocation with the existing dashboard helper. No new freshness or retry policy is needed: the next search or dashboard poll is the retry, as for dashboards today.

## Evidence

The built Gateway (dist) runs in an isolated profile with a task-owned state, config and port. Requests go through `/tools/invoke` → `wiki_search` and through `openclaw gateway call wiki.search`. The importer and compiler are the real unsafe-local ones, with no mocks or delays. Fixture: a compiled vault with one `entities/cobalt.md`, then 6,000 new synthetic source files. Source `0` contains "Zirconium publication evidence." Harness and raw captures: #188256 (comment).

| Run | Base 6052fff | This PR |
| --- | --- | --- |
| `wiki_search cobalt`, run 1 | HTTP 500 at 30.5 s, `wiki_search timed out after 30s` | HTTP 200 at 4.9 s, `entities/cobalt.md`, 0 pages imported, no new publication |
| `wiki_search cobalt`, run 2 | HTTP 500 at 30.4 s, `wiki_search timed out after 30s` | HTTP 200 at 4.3 s, `entities/cobalt.md` |
| `wiki_search zirconium` after publication | n/a | HTTP 200 at 8.4 s, the newly imported source page |
| `wiki.search` RPC (`openclaw gateway call`), twice | no answer within 600 s; all 6,000 imported, still no publication | `entities/cobalt.md` in 8.8 s and 7.7 s; after publication `zirconium` returns the new page |

Controls on this PR:
- Cold vault with no compiled snapshot: answers `cobalt` in 4.3 s through the scan fallback.
- Two concurrent searches plus one `wiki.overview` poll: all answer, and exactly one compile is published.
- SIGTERM during the refresh: exit 0 in 2.2 s, no publication, journal unchanged after exit.
- `ingest.autoCompile: false`: the search answers, all 6,000 sources import, and nothing compiles.
- One-shot `openclaw wiki search zirconium`: still waits for import and compile (508 s on a loaded host) and returns the new page.
- Without `runInDetachedAsyncContext`, both runs logged `background source sync failed: Failed to open the plugin state database. | This operation was aborted` and never published.

Unit: `tool.deadline.test.ts` "answers from the current index while the service refreshes" fails on base with `wiki_search timed out after 30s` and passes here. Focused memory-wiki suites pass: 8 files, 95 tests. Local review on the head reports no findings.

## Merge Danger

Two-way door. No config, schema, protocol or stored-data change; a revert restores the awaited sync. Blast radius: memory-wiki search through the agent tool and the `wiki.search` Gateway method while the plugin service runs.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit f9f7bf7)
Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 28, 2026
…openclaw#188256)

Root cause: `extensions/memory-wiki/src/tool.ts:174` awaits `syncMemoryWikiImportedSources` (import, then a full compile) inside the 30 s `wiki_search` deadline, and `extensions/memory-wiki/src/gateway.ts:277` awaits the same sync before `wiki.search` with no deadline, so a large pending import fails or stalls searches for pages that are already on disk.

Related: openclaw#187429, openclaw#132296, openclaw#166329

## What Problem This Solves

Fixes: `wiki_search` fails with "wiki_search timed out after 30s", and the `wiki.search` Gateway method hangs, when a large vault has source changes waiting to import and compile. The pages being searched for are already on disk.

## User Impact

Searches answer from the current wiki at once while the Gateway imports and compiles in the background. Content that changed in the sources since the last refresh shows up on the next search, not this one. That one-search delay is the only staleness: pages written with `wiki_apply` are read live, and a vault with no compiled snapshot yet still answers through the existing full scan.

Unchanged: `wiki_get`, `openclaw wiki search`, imports, compile, lint, apply and status still wait for the sync. `ingest.autoCompile: false` still never compiles. A caller with no running wiki service (one-shot hosts) still waits as before.

## Why This Change Was Made

When the wiki service is running, `wiki_search` and `wiki.search` run the query first and then start the service-owned source sync that the Overview and Import Insights dashboards already use (openclaw#132296). That helper moves from `gateway.ts` to `source-sync.ts` as `refreshMemoryWikiImportedSources`. It still single-flights equal requests, queues on the vault mutation lock, is cancelled by the service signal and is joined at shutdown. The refresh starts after the query because a cold read owner activates through the same vault queue, so a refresh started first would block the search.

The helper runs the sync with `runInDetachedAsyncContext`. Without it the built Gateway aborted every refresh after the `/tools/invoke` response with `Failed to open the plugin state database. | This operation was aborted`, so nothing was ever published. The dashboard path on main has the same defect and this fixes it too.

This takes over Baumus's PR. Thanks @Baumus for finding this, carrying the fix in your own deployment since 2026.10.10 and for the real-Gateway proof (openclaw#188256 (comment)), which also found the async-scope abort. Your commits stay in the branch. The commits on top replace the refresh coordinator (60 s freshness window, 5–60 s retry backoff, retry handles), the move to the plugin service scheduler, the query hook, the README section and the test-line allocation with the existing dashboard helper. No new freshness or retry policy is needed: the next search or dashboard poll is the retry, as for dashboards today.

## Evidence

The built Gateway (dist) runs in an isolated profile with a task-owned state, config and port. Requests go through `/tools/invoke` → `wiki_search` and through `openclaw gateway call wiki.search`. The importer and compiler are the real unsafe-local ones, with no mocks or delays. Fixture: a compiled vault with one `entities/cobalt.md`, then 6,000 new synthetic source files. Source `0` contains "Zirconium publication evidence." Harness and raw captures: openclaw#188256 (comment).

| Run | Base fa7a528 | This PR |
| --- | --- | --- |
| `wiki_search cobalt`, run 1 | HTTP 500 at 30.5 s, `wiki_search timed out after 30s` | HTTP 200 at 4.9 s, `entities/cobalt.md`, 0 pages imported, no new publication |
| `wiki_search cobalt`, run 2 | HTTP 500 at 30.4 s, `wiki_search timed out after 30s` | HTTP 200 at 4.3 s, `entities/cobalt.md` |
| `wiki_search zirconium` after publication | n/a | HTTP 200 at 8.4 s, the newly imported source page |
| `wiki.search` RPC (`openclaw gateway call`), twice | no answer within 600 s; all 6,000 imported, still no publication | `entities/cobalt.md` in 8.8 s and 7.7 s; after publication `zirconium` returns the new page |

Controls on this PR:
- Cold vault with no compiled snapshot: answers `cobalt` in 4.3 s through the scan fallback.
- Two concurrent searches plus one `wiki.overview` poll: all answer, and exactly one compile is published.
- SIGTERM during the refresh: exit 0 in 2.2 s, no publication, journal unchanged after exit.
- `ingest.autoCompile: false`: the search answers, all 6,000 sources import, and nothing compiles.
- One-shot `openclaw wiki search zirconium`: still waits for import and compile (508 s on a loaded host) and returns the new page.
- Without `runInDetachedAsyncContext`, both runs logged `background source sync failed: Failed to open the plugin state database. | This operation was aborted` and never published.

Unit: `tool.deadline.test.ts` "answers from the current index while the service refreshes" fails on base with `wiki_search timed out after 30s` and passes here. Focused memory-wiki suites pass: 8 files, 95 tests. Local review on the head reports no findings.

## Merge Danger

Two-way door. No config, schema, protocol or stored-data change; a revert restores the awaited sync. Blast radius: memory-wiki search through the agent tool and the `wiki.search` Gateway method while the plugin service runs.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: memory-wiki P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants