[Bug]: memory-core native watcher pegs Gateway main thread (~1 core, 3.4 GB) on a large extraPaths tree (~100k .md / 7.8k dirs) on Linux
Summary
On Linux, a single memory.search.extraPaths root containing ~100k small .md files in ~7.8k directories keeps the Gateway main thread saturated: ~1 core continuously for 15+ hours since start, eventLoopUtilization ≈ 0.98–1.0 with active=0 waiting=0 queued=0, and 3.2–3.4 GB RSS. The watcher is in native mode (no CHOKIDAR_USEPOLLING, no "fallback polling" warning). A Gateway restart does not help: the load comes back right after startup.
This looks like the Linux/large-tree counterpart of #192629 (Windows, observation boundary, realpath-heavy). There, the cost comes from the boundary being too wide. Here, the boundary is correct but the tree itself is large and receives steady appends.
Environment
- OpenClaw 2026.11.3 (847611d), Node 24.22.3, Linux arm64 (Jetson-class box, 6 cores, 7.6 GB RAM)
agents.entries.main.memory.search.extraPaths = ["/home/<user>/Docs/.index"], globalmemory.search.extraPaths = []- Tree: 101,963
.mdfiles, 7,778 directories, ~565 MB. Layout is<folder>/<document>/page-NNN.md, one small file per page so that a chunk equals a page. - Another process appends ~5–15 files per minute (OCR pipeline). The tree grows steadily and is expected to reach several hundred thousand files.
- The Gateway holds 7,802 inotify watches (≈ one per directory).
- The log shows
Memory file watching is tracking 6726 observed directories…once per start.
Evidence
openclaw gateway call diagnostics.cpuProfile --params '{}', two captures of 5 s each (startBlockedMs ≈ 2.2 s in both):
| capture 1 | capture 2 | |
|---|---|---|
inclusive @openclaw/fs-safe (top frame) |
79.5% | 57.6% |
inclusive lstatSync (node:fs) |
23.7% | 22.2% |
inclusive file-watcher exclude |
8.1% | 5.4% |
self [native] |
62.6% | 61.2% |
Hot path: processImmediate / runNextTicks → @openclaw/fs-safe directory traversal (readdir, lstatSync, path.resolve/relative) → MemoryWatchPolicy.exclude / ignored in file-watcher-*.mjs (2026.11.3: exclude around line 127, watch(group.root, { scopes, mode, maxDirectories: 1e6, maxEntries: 1e6, maxPendingPaths: MEMORY_WATCH_MAX_PATHS, exclude, onInvalidate }) around line 320).
Process accounting: 915 min CPU in 935 min wall time. Over 95% of the CPU time is on the main thread. V8 workers are at ~12 min each.
Side effect: openclaw memory index from a cron job fails repeatedly with Cannot admit memory.cli for memory stores … This operation requires exclusive … (252 times/day).
Expected
Native watching of a large but correctly scoped tree costs work roughly proportional to the change events, not repeated synchronous traversal of the whole tree on the main thread. Alternatively, there could be a supported way to keep an extraPaths root indexed without watching it, for example indexed only by openclaw memory index. The docs currently say there is no supported memory.search.sync.watch and recommend removing or narrowing the roots. That does not work for a large document corpus that must remain searchable.
What I have not verified
- Whether the traversal happens with zero appends, i.e. truly idle. The appending process runs most of the day, and I did not stop it on the production box.
- Whether 2026.11.4 changes this. I found nothing obvious in the release notes, but I have not reproduced the problem on it.
Workaround on our side
We are moving the document index out of extraPaths into a separate process, so the Gateway no longer watches the tree.
Codex review: this still needs some work.
Summary Keep open: this issue provides concrete affected-release profiling, and current main’s worker isolation does not prove that sustained large-tree CPU and memory costs are resolved.
Reproducibility: The report supplies a concrete workload and affected-release profiles, but no reproduction was run during this read-only review; current-main source changes prevent treating the old main-thread mechanism as a proven current defect.
Next step Compare idle and append-driven workloads on the affected revision and current main, attribute full scans by trigger and thread, and establish a failing regression before choosing a focused repair.
Review details
Best possible solution:
Keep the corpus searchable while eliminating demonstrated scan amplification and preserving guarded observation, replacement detection, and bounded cleanup.
Do we have a high-confidence way to reproduce the issue?
The report supplies a concrete workload and affected-release profiles, but no reproduction was run during this read-only review; current-main source changes prevent treating the old main-thread mechanism as a proven current defect.
Is this the best way to solve the issue?
Measure idle and append-driven scan amplification before selecting a repair; worker isolation is relevant mitigation, while a new watch-disable setting would require a separate product decision.
AGENTS.md: found and applied where relevant.
Remaining risk / open question:
- Neither idle behavior nor the append-driven workload has been reproduced on current main.
- The event source, frequency of full guarded passes, and remaining total CPU and RSS costs are unestablished.
- The reported memory.cli admission failures have not been causally linked to watcher traversal.
Codex review notes: model internal, reasoning medium; reviewed against 9e66164c0ce4.
Label changes
Label changes:
No label changes.
Label justifications:
P1: The affected-release report describes sustained Gateway event-loop saturation and substantial memory consumption during an active memory workflow.impact:crash-loop: Reported event-loop utilization near 1.0 and blocked profiling requests indicate process-level responsiveness impairment, although no crash is established.
Evidence reviewed
Acceptance criteria:
- Establish an affected-revision/current-main idle-versus-append comparison through an isolated Gateway with per-thread profiles and guarded scan counts.
- Require a failing regression for the identified current defect before opening a repair PR.
- Run affected watcher lifecycle, filter, filesystem, and real-worker integration coverage after selecting the repair.
What I checked:
- Concrete affected-release report: The full issue identifies OpenClaw 2026.11.3 at 847611d on Linux arm64, 101,963 Markdown files, 7,778 directories, sustained CPU and RSS measurements, and two CPU-profile summaries; idle behavior and 2026.11.4 remain unverified.
- Reported revision constructs the watcher directly: Source at the reported commit constructs MemoryFileWatcher directly in ensureWatcher, whereas the review checkout constructs LocalMemoryFileWatcher. (
extensions/memory-core/src/memory/manager-watch-ops.ts:69, 847611dcaa3b) - Current local watcher isolation: The local transport starts a memory-files Worker and proxies readiness, health, dirty notifications, settled changes, and retirement. (
extensions/memory-core/src/memory/local-file-watcher.ts:52, 964ab5223098) - Merged mitigation has a narrower claim: Merged https://github.com/openclaw/openclaw/pull/175157 explicitly limits its performance claim to moving filesystem work off MAIN; its scale evidence does not claim reduced total filesystem work or establish this continuously appended 100k-file workload. (62ff6dabed53)
- Existing subscription and cadence mitigation: Current source shares subscriptions and passes a five-minute native reconciliation interval; merged https://github.com/openclaw/openclaw/pull/173468 explicitly leaves per-entry scan cost unresolved. (
extensions/memory-core/src/memory/file-watcher.ts:163, 964ab5223098) - Related reporter correction: In https://github.com/openclaw/openclaw/issues/192629, wangzh255 corrects the initial periodic-scan explanation to continuous hint-driven scanning and attributes plugin-build paths to plugin hashing rather than memory watching; the actual hint source remains unresolved.
How this review workflow works
- ClawSweeper keeps one durable marker-backed review comment per issue or PR.
- Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
- A fresh review can be triggered by eligible
@clawsweeper re-reviewcomments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch. - PR/issue authors and users with repository write access can comment
@clawsweeper re-reviewor@clawsweeper re-runon an open PR or issue to request a fresh review only. - Maintainers can also comment
@clawsweeper reviewto request a fresh review only. - Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge; those execution lanes are retired.
- Maintainers can comment
@clawsweeper explainto ask for more context, or@clawsweeper stopto stop active automation.
Reviewed November 16, 2026, 2:45 PM ET / 19:45 UTC.
Measured Gateway improvement proposed in PR #206339. On the same 101,963-file Linux fixture and indexed database, retaining only stale rows for final deletion lowered median whole-Gateway peak RSS from 2,200,084 to 2,045,792 KiB (−7.01%). Four of five matched pairs improved, and nearest-rank p95 fell from 2,328,164 to 2,271,336 KiB. Every run still observed 305,912 Markdown accesses. Median time from the first write to five successful search hits rose from 36.459 to 36.952 s, with p95 rising from 37.453 to 37.957 s. The median RPC itself took 0.935 s on both builds. All ten measured arms
Both builds also indexed and returned an equal-size edit under .venv with the original mtime restored. The exact-head CI run passed. The PR is awaiting a maintainer decision on the latency tradeoff. This issue remains open for full-tree read work and field behavior as the watched directory grows. Full-size sibling proof · CI
Gateway pilot with the upstream file-size hint. Two opposite-order pairs used the same OpenClaw head 074cfad1 and one 101,963-file checkpoint (288879c513601796304c3ca24e43ddfedfd30039279ae7b469615b21884c5a8f). Each pair compared shipped @openclaw/[email protected] with that package plus the upstream change that passes the opened file's known size to the bounded reader. Both smoke runs executed the same built Gateway caller, loaded the expected library bytes, and returned all five search hits. The upstream change has merged and is awaiting a package release. Upstream merge · Loaded-code checks · Shared checkpoint
| From first append, stock → size hint | Pair 1 (stock first) | Pair 2 (hint first) |
|---|---|---|
| Five files observed in the index (500 ms polling) | 36.517 → 34.513 s | 35.015 → 33.511 s |
| Five successful search hits | 37.442 → 35.432 s | 35.963 → 34.432 s |
| Gateway CPU through settling | 90.51 → 86.83 s | 88.91 → 83.47 s |
| Gateway peak RSS through settling | 1,965,440 → 1,913,704 KiB | 2,240,024 → 2,210,944 KiB |
Every arm returned the same five paths, observed 305,912 Markdown accesses across 101,968 distinct files, and recorded zero observer overflows. In the first 30.001 s, main-thread CPU rose from 7.790 to 8.470 s in pair 1 and from 9.110 to 9.240 s in pair 2. At search completion in pair 2, RSS rose by 28,660 KiB despite the lower peak over the full interval. The pilot measured variation in the dependency on fixed head 074cfad1. The separate five-pair 269fb089 to 074cfad1 comparison above remains the evidence for PR #206339's latency decision. All four Gateway arms
Follow-up on time to searchable results. Two instrumented pairs on the same 101,963-file checkpoint compared the proposed PR head 074cfad1 with a private variant (0d9ab304) that marks matched rows with one byte each. The second pair reversed the run order. In the scan that published the fifth file, total planning fell from 58.310 to 44.072 ms and from 56.388 to 46.789 ms. Both savings fell below the 20 ms per-scan target. Summed over both pre-publication scans in each arm, planning fell from 116.614 to 87.720 ms and from 118.823 to 91.700 ms. Discovery still took 7.13–7.65 s in the final scan. Phase timings and SQLite commits
Measured directly from first append to the live SQLite commit containing the last of the five paths, elapsed time went from 37.727 to 38.227 s and from 38.108 to 39.596 s. The database observer detected those commits 295–431 ms later. All four arms returned five search hits and recorded 305,912 Markdown accesses each. The flags variant was withdrawn after diagnosis. The five-pair RSS and latency results above apply to the original public head.
File inspection queue. A private in-process variant (3e7cc33d against 074cfad1) creates inspection callbacks as reads are admitted. On 101,963 paths with four reads paused, V8 counted 101,963 queued-or-active inspection closures on the public head and four on the variant. The drop in live heap attributable to admission was 9.333 and 9.334 MiB in two opposite run orders, including the variant's copy of the plugin path list. Both builds preserved duplicate order, null filtering and changes to the plugin callback. After an injected read error, both drained the four admitted reads and propagated the original error before a fifth read could start. Exact source diff · Paused heap and callback checks
A separate run timed the default resolver reading all 101,963 real Markdown files. Both builds returned identical ordered paths, mtimes, sizes and hashes. Stock to variant elapsed time was 5.799 to 5.818 s in the first pair and 5.842 to 5.810 s in the reversed pair. CPU time was 11.620 to 11.652 s and 11.697 to 11.631 s. These measurements cover file inspection. Whole-Gateway peak RSS and append-to-search latency for this variant remain unmeasured. Real-file comparison
Landed on main: large-directory file counts. With 160,000 eligible Markdown files in one configured root, openclaw memory status --agent main --json used to exit successfully with totalFiles: null and a stack error. It now reports 160,000 files and zero scan issues. Both passes returned every path in the independently expected order. The fix sorts the collected path strings and appends them individually. Merged PR #206011 · Squash commit · CLI and ordered-list proof
At 100,000 files both builds completed every listing with the same ordered digest. Across three interleaved process pairs, median peak RSS for the first file listing went from 274,044 to 265,784 KiB and for the repeat listing from 295,476 to 294,808 KiB. These measurements cover file discovery only. This issue remains open for the full-tree work and whole-Gateway CPU and RSS as the watched directory grows. Paired AWS measurements
The OpenClaw worker candidate is ruled out for this low-memory campaign. The field issue remains open. It moved file reads and hashes off the serving thread and preserved the five search results. It still read the entire corpus and raised peak RSS by 278,748 KiB (272 MiB). Paired AWS comparison · Experimental patch
Both arms ran on the same isolated Linux amd64 host from a byte-identical indexed database on 9ad935f281e018f9c6941dc1bf20fddc809d1a83. Both had 7,781 watch registrations and zero Markdown accesses in the settled warm-up. Each received five files at six-second intervals. All five were indexed before the next Gateway RPC. Each RPC returned the same five paths with the new marker. The passive observer covered 7,778 directories and reported zero overflows. The final measurement includes 20 seconds of quiet after retrieval.
| Five appends on 101,963 starting files | Stock main | Bounded reader |
|---|---|---|
| Successful five-result search after first append | 37.07 s | 38.59 s |
| Main-thread CPU through that search | 14.58 s | 3.57 s |
| Wall time through settlement | 71.09 s | 72.61 s |
| Main-thread CPU through settlement | 21.53 s | 5.37 s |
| Process CPU through settlement | 93.52 s | 98.03 s |
| Peak RSS through settlement | 2,125,864 KiB | 2,404,612 KiB |
| Distinct Markdown files read | 101,968 | 101,968 |
| Markdown access events through settlement | 305,912 | 305,912 |
A fixed-window comparison also found lower main-thread CPU through retrieval (9.34 to 3.57 s) and higher process CPU (56.72 to 69.13 s). One worker run read the full corpus during its idle window. The settled comparison above starts both arms from a measured quiet period and follows the background work after retrieval. Stock run · Worker run
The bounded reader passed 67 focused tests, the plugin package type check, and a real Gateway run pinned to two logical CPUs (one shared compute permit). It retrieved the new marker and the edited, unreported sibling. Focused tests and Gateway · Package boundary The patch SHA-256 is f8ca505180432f86512649a4988c73e5251c1806b784585e59f5cbd2a2e2674b. Scoped lint and format
Reproduce the five-append comparison on Linux (exact Gateway driver)
The script below generated the 101,963-page synthetic tree, ran the built CLI and Gateway, waited for all five new paths in SQLite, and checked each path in a real memory.search response. It used keyword-only search with provider: "none". RSS was sampled from the Gateway process. The corpus used short synthetic pages.
Save the Python block as settled-driver.py, including its final newline. Its SHA-256 is 89fc4509ec104495e72fe3b93dae4af165017a96f1d29d8e06af0774e3ee9b53. The measured worker used the eight-file patch with SHA-256 f8ca505180432f86512649a4988c73e5251c1806b784585e59f5cbd2a2e2674b on 9ad935f281e018f9c6941dc1bf20fddc809d1a83. The receipt contains the patch between BEGIN EXPERIMENTAL PATCH and END EXPERIMENTAL PATCH. Worker patch · Paired results
On an isolated Linux amd64 box, provide stock and patched pnpm build:runtime outputs in managed checkouts. Both should use Node 24.22.1. Set STOCK_CHECKOUT and WORKER_CHECKOUT to their absolute paths. The recipe below prepares one index and uses it for both timed runs, in the original worker-first order. It requires Python 3, ss, and a user inotify watch limit of at least 23,334.
set -euo pipefail
umask 077
: "${STOCK_CHECKOUT:?set the built stock checkout}" "${WORKER_CHECKOUT:?set the built patched checkout}"
driver=$(realpath settled-driver.py)
test "$(sha256sum "$driver" | cut -d' ' -f1)" = 89fc4509ec104495e72fe3b93dae4af165017a96f1d29d8e06af0774e3ee9b53
test "$(node --version)" = v24.22.1
fixture=$(mktemp -d /tmp/gateway-current-200227.XXXXXXXX)
mkdir -p "$fixture/home" "$fixture/node-v24.22.1-linux-x64/bin"
ln -s "$(command -v node)" "$fixture/node-v24.22.1-linux-x64/bin/node"
MEMORY_FIXTURE_INDEX_ONLY=1 python3 -u "$driver" "$fixture" "$STOCK_CHECKOUT" full
cp -a "$fixture/full" "$fixture/initial-state"
for arm in worker main; do
checkout=$WORKER_CHECKOUT
if [ "$arm" = main ]; then checkout=$STOCK_CHECKOUT; fi
mv "$fixture/full" "$fixture/before-$arm"
cp -a "$fixture/initial-state" "$fixture/full"
db=agents/main/agent/openclaw-agent.sqlite
cmp "$fixture/initial-state/$db" "$fixture/full/$db"
MEMORY_FIXTURE_LABEL="settled-$arm" python3 -u "$driver" "$fixture" "$checkout" full
done
import ctypes,json,os,re,shutil,secrets,select,signal,socket,sqlite3,struct,subprocess,sys,threading,time,urllib.error,urllib.request
from pathlib import Path
root=Path(sys.argv[1]).resolve();repo=Path(sys.argv[2]).resolve();kind=sys.argv[3]
assert kind in ('smoke','full','candidate')
assert root.name.startswith('gateway-current-200227.') and root.parent==Path('/tmp')
os.umask(0o077)
state=root/kind
state.mkdir(mode=0o700,exist_ok=True);state.chmod(0o700)
work=state/'workspace';work.mkdir(mode=0o700,exist_ok=True);work.chmod(0o700)
corpus=root/('corpus-small' if kind=='smoke' else 'corpus')
small=kind=='smoke';nfiles=3 if small else 101963; ndirs=1 if small else 7713
def filedir(i):
d=i%ndirs
return corpus/f'folder-{d%64:02d}'/f'doc-{d:05d}'
first=filedir(0); created=[first/'newly-created.md',*[first/f'appended-{i}.md' for i in range(1,5)]]
if not corpus.exists():
for n in range(ndirs):filedir(n).mkdir(parents=True)
for n in range(nfiles):
(filedir(n)/f'page-{n//ndirs:03d}.md').write_text('initial lindenharbor search marker\n' if n==0 else f'observation page {n}\n')
def out(phase,**kw):print(json.dumps(dict(phase=phase,version=os.environ.get('MEMORY_FIXTURE_LABEL',kind),**kw)),flush=True)
with socket.socket() as sk:
sk.bind(('127.0.0.1',0));port=sk.getsockname()[1]
token=secrets.token_hex(32)
config={'gateway':{'mode':'local','bind':'loopback','port':port,'auth':{'mode':'token'},'controlUi':{'enabled':False},'tailscale':{'mode':'off'}},'discovery':{'mdns':{'mode':'off'}},'cron':{'enabled':False},'browser':{'enabled':False},'update':{'checkOnStart':False},'agents':{'entries':{'main':{'workspace':str(work)}}},'memory':{'search':{'provider':'none','fallback':'none','sources':['memory'],'extraPaths':[str(corpus)],'store':{'vector':{'enabled':False}}}}}
cfg=state/'openclaw.json';cfg.write_text(json.dumps(config))
node=str(root/'node-v24.22.1-linux-x64/bin/node')
env={**os.environ,'CI':'1','HOME':str(root/'home'),'PATH':str(Path(node).parent)+':'+os.environ['PATH'],'OPENCLAW_STATE_DIR':str(state),'OPENCLAW_CONFIG_PATH':str(cfg),'OPENCLAW_GATEWAY_TOKEN':token,'OPENCLAW_GATEWAY_PORT':str(port),'OPENCLAW_DISABLE_BONJOUR':'1','NO_COLOR':'1'}
cli=[node,str(repo/'openclaw.mjs')]
def clean(value):return str(value).replace(token,'[fixture credential]')
def run(args,timeout):
r=subprocess.run(cli+args,env=env,cwd=repo,capture_output=True,text=True,timeout=timeout)
if r.returncode:raise RuntimeError(clean((r.stdout+' '+r.stderr)[-2200:]))
return r
dbfile=state/'agents/main/agent/openclaw-agent.sqlite'
def fetch(sql,params=()):
with sqlite3.connect('file:'+str(dbfile)+'?mode=ro',uri=True,timeout=1) as db:return db.execute(sql,params).fetchone()[0]
def rowcount():return fetch("select count(*) from memory_index_sources where source='memory'") if dbfile.exists() else 0
def added_count():
paths=[os.path.relpath(f,work) for f in created]
return fetch("select count(distinct path) from memory_index_chunks where source='memory' and path in (?,?,?,?,?) and text like ?",(*paths,'%foxglovepier%'))
def markindexed():return fetch("select exists(select 1 from memory_index_chunks where path=? and source='memory' and text like ?)",(os.path.relpath(created[0],work),'%foxglovepier%'))==1
assert not any(p.exists() for p in created),'stale additions in source corpus'
if rowcount()!=nfiles:
start=time.monotonic();r=run(['memory','index','--agent','main','--force'],3600)
assert rowcount()==nfiles,rowcount()
out('initial-index',sources=rowcount(),wallSec=round(time.monotonic()-start,2),stdout=clean(r.stdout.strip()[-180:]))
else:out('reuse-verified-index',sources=rowcount())
if os.environ.get('MEMORY_FIXTURE_INDEX_ONLY') == '1':sys.exit(0)
def search(m):
r=run(['gateway','call','memory.search','--params',json.dumps({'query':m,'agentId':'main','maxResults':8 if m=='foxglovepier' else 2,'minScore':0}),'--json','--timeout','600000'],640)
hits=[x.get('path') for x in json.loads(r.stdout).get('results',[]) if m in x.get('snippet','').lower()]
assert hits,'seed or appended search marker absent: '+m
return hits
def tool_search():
body={'tool':'memory_search','sessionKey':'agent:main:main','args':{'query':'lindenharbor','minScore':0,'maxResults':2}}
req=urllib.request.Request(f'http://127.0.0.1:{port}/tools/invoke',data=json.dumps(body).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/json'})
try:
with urllib.request.urlopen(req,timeout=600) as response:j=json.load(response)
except urllib.error.HTTPError as e:raise RuntimeError(clean(e.read().decode()[:600]))
result=json.dumps(j.get('result',{})).lower()
assert j.get('ok') and 'lindenharbor' in result and 'page-000.md' in result,'resident tool did not find seed page'
out('resident-search',hit='page-000.md')
def sample(pid):
p=Path('/proc')/str(pid)
def ticks(f):
t=f.read_text();a=t[t.rindex(')')+2:].split();return int(a[11])+int(a[12])
rss=int(next(x.split()[1] for x in (p/'status').read_text().splitlines() if x.startswith('VmRSS:')))
return time.monotonic(),ticks(p/'task'/str(pid)/'stat'),ticks(p/'stat'),rss
def metric(name,a,b,peak):
hz=os.sysconf('SC_CLK_TCK');out(name,wallSec=round(b[0]-a[0],2),mainCpuMs=round(1000*(b[1]-a[1])/hz),totalCpuMs=round(1000*(b[2]-a[2])/hz),rssKiB=b[3],peakRssKiB=peak)
def pause_until(t):
while time.monotonic()<t:time.sleep(min(.5,t-time.monotonic()) if t>time.monotonic()+.001 else .001)
def regcount(pid):
n=0
for f in (Path('/proc')/str(pid)/'fdinfo').iterdir():
try:n+=f.read_text().count('inotify wd:')
except OSError:pass
return n
def listener():
s=subprocess.run(['ss','-ltnpH','sport = :'+str(port)],capture_output=True,text=True,check=True).stdout
m=re.search(r'pid=(\d+)',s)
return int(m.group(1)) if m else None
stop=threading.Event();unique=set();accesses=overflow=0;record=False;guard=threading.Lock();observer_error=[];tool_error=[]
def observer():
global accesses,overflow
try:
lib=ctypes.CDLL(None,use_errno=True);fd=lib.inotify_init1(os.O_NONBLOCK);assert fd>=0
try:
dirs=[corpus]+[corpus/f'folder-{n:02d}' for n in range(min(64,ndirs))]+[filedir(n) for n in range(ndirs)]
assert int(Path('/proc/sys/fs/inotify/max_user_watches').read_text())>=len(dirs)*3
for d in dirs:assert lib.inotify_add_watch(fd,os.fsencode(d),0x01000000|1)>=0,ctypes.get_errno()
out('read-observer-ready',directories=len(dirs))
while not stop.is_set():
if not select.select([fd],[],[],.15)[0]:continue
buf=os.read(fd,1048576);p=0
with guard:
while p<len(buf):
wd,mask,_,sz=struct.unpack_from('iIII',buf,p);f=buf[p+16:p+16+sz].rstrip(b'\0');p+=16+sz
if not record:continue
if mask&16384:overflow+=1;continue
if mask&1 and not mask&0x40000000 and f.endswith(b'.md'):unique.add((wd,f));accesses+=1
finally:os.close(fd)
except Exception as e:observer_error.append(str(e))
if kind=='full' and not (root/'initial-state').exists():
shutil.copytree(state,root/'initial-state',symlinks=True)
out('fixture-checkpoint',sources=rowcount())
gwlog=state/'gateway.log'
p=None
try:
with gwlog.open('w') as log:
p=subprocess.Popen(cli+['gateway','run','--allow-unconfigured','--bind','loopback','--port',str(port)],cwd=repo,env=env,stdout=log,stderr=log,start_new_session=True)
ready=False; deadline=time.monotonic()+240
while time.monotonic()<deadline:
if p.poll() is not None:raise RuntimeError('Gateway exited '+str(p.returncode)+' before readiness')
try:
with urllib.request.urlopen(f'http://127.0.0.1:{port}/readyz',timeout=2) as r:
if r.status==200:ready=True;break
except (OSError,ValueError):pass
time.sleep(1)
assert ready,'Gateway readiness timeout'
pid=listener();assert pid
out('search-existing',hits=search('lindenharbor'),listeningPid=pid)
t=time.monotonic();obs=threading.Thread(target=observer,daemon=True);obs.start()
def warm():
try:
pause_until(t+(0 if small else 75));tool_search()
except Exception as e:tool_error.append(clean(e))
w=threading.Thread(target=warm,daemon=True);w.start()
w.join(640);assert not w.is_alive() and not tool_error,tool_error
with guard:record=True;unique.clear();accesses=overflow=0
def quiet(earliest,limit):
previous=sample(pid);stable=None;last=None;peak=previous[3];deadline=time.monotonic()+limit
while time.monotonic()<deadline:
time.sleep(.5);now=sample(pid);peak=max(peak,now[3])
with guard:seen=accesses
if last!=seen or now[0]<earliest or (now[2]-previous[2])/os.sysconf('SC_CLK_TCK')>.25*(now[0]-previous[0]):
stable=None
else:
if stable is None:stable=now[0]
if now[0]-stable>=20:return now,peak
last=seen;previous=now
raise RuntimeError('no 20-second quiet period within '+str(limit)+' s')
since=sample(pid);b,peak=quiet(t+120,300);metric('warmup-through-quiet',since,b,peak)
assert regcount(pid)>=7778
with guard:
out('settled-start',registrations=regcount(pid),distinctWarmMarkdownReads=len(unique),accessEvents=accesses,queueOverflows=overflow,observerError=observer_error)
assert overflow==0 and not observer_error
unique.clear();accesses=overflow=0
a=sample(pid);peak=a[3]
for i,f in enumerate(created):
f.write_text(f'new searchable foxglovepier page {i}\n')
end=time.monotonic()+6
while time.monotonic()<end:
peak=max(peak,sample(pid)[3]);time.sleep(.25)
b=sample(pid);peak=max(peak,b[3]);metric('five-new-pages',a,b,peak)
deadline=time.monotonic()+360
while added_count()!=len(created) and time.monotonic()<deadline:
peak=max(peak,sample(pid)[3]);time.sleep(.5)
assert added_count()==5,'not all five pages indexed before search'
b=sample(pid);peak=max(peak,b[3]);metric('five-pages-published',a,b,peak)
with guard:out('before-next-search',indexed=added_count(),distinctMarkdownRead=len(unique),accessEvents=accesses,queueOverflows=overflow)
hits=search('foxglovepier')
assert {Path(p).name for p in hits}=={f.name for f in created},hits
b=sample(pid);peak=max(peak,b[3]);metric('through-successful-search',a,b,peak)
out('search-new',hits=sorted(hits),secondsFromFirstCreation=round(b[0]-a[0],2))
b,tailpeak=quiet(time.monotonic(),300);peak=max(peak,tailpeak);metric('writes-through-settled-search',a,b,peak)
with guard:
out('settled-output',indexed=added_count(),distinctMarkdownRead=len(unique),accessEvents=accesses,queueOverflows=overflow,observerError=observer_error)
assert overflow==0 and not observer_error
except Exception as e:
out('failed',error=clean(e),gatewayLog=clean(gwlog.read_text(errors='replace')[-4900:]) if gwlog.exists() else '')
raise
finally:
stop.set()
if p is not None and p.poll() is None:
os.killpg(p.pid,signal.SIGTERM)
try:p.wait(timeout=30)
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
for f in created:f.unlink(missing_ok=True)
Released Gateway and pinned main
I also reproduced the reported Gateway main-thread saturation during appends on the published [email protected] package. On isolated Linux amd64, the fixture kept the reported file and directory counts and used shorter synthetic page bodies. The index contained 101,963 initial sources. The resident memory_search tool retrieved the seed page, and the Gateway had 7,789 inotify registrations.
| Gateway measurement | Wall time | Main-thread CPU | Process CPU | Peak RSS |
|---|---|---|---|---|
| Warm interval with no writer | 120.02 s | 20.12 s | 23.65 s | 1,587,032 KiB |
| Five new pages, one every six seconds | 30.0 s | 29.58 s | 33.14 s | 1,664,848 KiB |
All four unchanged probe pages were read twice during the append/retrieval interval. The first new page was in the database before the follow-up Gateway search. The search returned newly-created.md and appended-1.md with the new marker. This run measures a short append burst. The reporter's 15-hour duration and arm64 RSS remain separate observations. Gateway run
On pinned main the real CLI indexed 101,963 sources in 1,613.76 s. Gateway RPC and the resident memory_search tool both returned the seed. The 120.08 s warm idle window used 0.14 s of main-thread CPU and 1.58 s of process CPU with zero Markdown reads. Five appends took 30.02 s, used 8.36 s of main-thread CPU and 53.57 s of process CPU, and read 101,968 distinct Markdown files before the next search. Pinned-main Gateway
Guarded watching and index coverage
I reproduced a full-tree scan on Linux for each new Markdown file. The test used one native guarded watch on 101,963 Markdown files under 7,778 directories, the same five additions on each version, and the memory watcher’s five-minute verification interval. Every notification arrived, and the file contents matched. AWS run
| Published fs-safe | Entries examined per creation | Median elapsed | Median process CPU | Peak process RSS |
|---|---|---|---|---|
| 0.26.5 (OpenClaw 2026.11.3) | 109,741–109,745 | 6.05 s | 6.32 s | 375 MiB |
| 0.28.2 (current OpenClaw main) | 109,741–109,745 | 11.77 s | 13.65 s | 644 MiB |
The RSS and CPU above belong to the isolated dependency benchmark. The entry count is measured at the watch exclusion callback. Linux classifies a creation as structural, the adapter emits a rename, and the guarded watcher promotes it to a scope scan before notifying memory-core. A useful regression case is one regular-file creation on an already watched directory, with bounded entries examined and the correct settled notification. Overflow, directory replacement, and lost watches still need broad reconciliation. Linux event classification · Guarded watcher
On the pinned main revision I verified why reusing creation hints as the entire indexing plan would lose results. The native watcher named all five new pages. An already indexed Markdown file under the extra root's .venv directory also changed, with its original size and mtime preserved. There was no hint for that file. Stock memory-core included the edit in the index before the next search, and the real Gateway retrieved it. The indexer's file-discovery policy includes that page while the watch policy excludes its directory. Watcher filter · File discovery
An isolated additions-only prototype reduced the three-existing/five-new case from eight distinct Markdown reads to five and returned the new pages. It missed the edited sibling in the second case, and the real search failed. I ruled out that prototype for landing. Rejected prototype and failed retrieval
The outstanding OpenClaw requirement is fewer content inspections while retaining edits outside the notification set, including an equal-size, restored-mtime sibling. The native API currently exposes an exclusion callback and full guarded reconciliation. The shared OpenClaw filter reads live membership. A static-filter opt-in needs a runnable upstream revision and an OpenClaw subscription that refreshes its policy on membership changes before it can be tested on this corpus. Upstream watch options · Shared subscription
Memory-core already runs its filesystem watcher off the Gateway thread. The CLI startup registration optimization has a separate owner. Memory watcher change · CLI registration PR
Earlier collector experiment on pinned main (677fd700)
A second defect reproduces inside OpenClaw's memory file collector. With 160,000 eligible Markdown files in one configured extra root, openclaw memory status --agent main --json exits successfully but reports totalFiles: null and RangeError: Maximum call stack size exceeded. The collector supplies every path as an argument to a single push. A collector-only patch keeps the eligible path strings, sorts each root in place and appends each path individually. The same CLI then reports 160,000 eligible, zero issues. Path resolution, watcher exclusions and dirty-signal handling use the stock code. Pinned source · CLI and comparison receipts
| Matched input and metric | Stock | Collector only |
|---|---|---|
| 101,963-file inventory, cold median process peak RSS | 272,448 KiB | 260,152 KiB |
| Same process after its second pass, median high-water RSS | 301,328 KiB | 284,068 KiB |
| Cold inventory, median wall / CPU | 1,323 / 2,977 ms | 1,306 / 2,815 ms |
| Second inventory, median wall / CPU | 1,270 / 2,903 ms | 1,248 / 2,808 ms |
| Gateway, median time from first write to five successful search hits | 36.04 s | 35.53 s |
| Gateway, median main / total CPU through settled search | 20.68 / 90.56 s | 19.99 / 88.18 s |
| Gateway, median sampled peak RSS through settled search | 2,196,588 KiB | 2,259,164 KiB |
| Gateway, Markdown access events through settled search, every run | 305,912 | 305,912 |
The inventory medians use five interleaved pairs on the same 101,963 files and 7,778 directories. Every pass returned the identical ordered path digest. For the Gateway figures, five stock runs and three collector runs began with the same indexed database. All eight runs published all five new pages before the next RPC and returned all five matches. Whole-Gateway peak RSS ranges overlapped (stock 2,076,020–2,344,496 KiB, collector 2,175,388–2,264,772 KiB). Its median rose 2.85%. The equal-size, restored-mtime edit under .venv was indexed before the next search and returned by that search. All 65 focused tests passed on the final patch. Stock Gateway · Gateway results, sibling check and exact diffs · Focused tests
Two other experiments bounded pending canonical path lookups. Ordered streaming lowered standalone inventory RSS but increased settled Gateway total CPU from 88.25 to 92.07 seconds across its three paired runs. Fixed windows of eight increased median warm inventory time from 1,259 to 1,330 ms. Both experiments retained the full content-read workload. The field report remains open. The remaining gate is fewer full-tree content inspections on real Gateway writes, with correct sibling search results and a demonstrated whole-process memory benefit. The collector patch below reproduces the narrower stack-limit fix. Ordered comparison · Fixed windows
Collector-only reproduction patch against 677fd700 (SHA-256 2bea7f6001f25e7f9ae28f6d5204185bde04e65adf1e1bb75b46765550fc7fd7)
diff --git a/config/knip.config.ts b/config/knip.config.ts
index a692cc3f08d..49278aa3987 100644
--- a/config/knip.config.ts
+++ b/config/knip.config.ts
@@ -299,6 +299,7 @@ const repositoryScriptEntries = [
"scripts/bench-inbound-metadata-stream.mts!",
// Maintained guides and source headers invoke these focused workloads by exact path.
"scripts/bench-memory-publication.mjs!",
+ "scripts/perf/memory-file-inventory.mjs!",
// Merged benchmark PRs and source headers invoke these retained workloads by exact path.
// The transcript broadcast benchmark loads the stall recorder through --gateway-preload.
"scripts/bench-filesystem-preconditions.mts!",
diff --git a/packages/memory-host-sdk/src/host/internal.ts b/packages/memory-host-sdk/src/host/internal.ts
index 5bb3d7ee2f3..df0be340a6e 100644
--- a/packages/memory-host-sdk/src/host/internal.ts
+++ b/packages/memory-host-sdk/src/host/internal.ts
@@ -250,6 +250,7 @@ async function collectMemoryFilesFromDir(
shouldSkipPath?: (absPath: string) => boolean,
extraPathEntries?: NormalizedExtraMemoryPath[],
): Promise<void> {
+ const paths: string[] = [];
const scan = await scanMemorySource(dir, () =>
walkDirectory(dir, {
symlinks: "skip",
@@ -261,21 +262,31 @@ async function collectMemoryFilesFromDir(
extraPathEntries.some((extraPathEntry) =>
matchesExtraMemoryPathEntry(extraPathEntry, entry.path, { directory: true }),
)),
- include: (entry) =>
- !shouldSkipPath?.(entry.path) &&
- entry.kind === "file" &&
- isAllowedMemoryFilePath(entry.path, multimodal) &&
- (!extraPathEntries ||
- extraPathEntries.some((extraPathEntry) =>
- matchesExtraMemoryPathEntry(extraPathEntry, entry.path),
- )),
+ include: (entry) => {
+ if (
+ !shouldSkipPath?.(entry.path) &&
+ entry.kind === "file" &&
+ isAllowedMemoryFilePath(entry.path, multimodal) &&
+ (!extraPathEntries ||
+ extraPathEntries.some((extraPathEntry) =>
+ matchesExtraMemoryPathEntry(extraPathEntry, entry.path),
+ ))
+ ) {
+ paths.push(entry.path);
+ }
+ // Descent is independent of inclusion. Keep paths without retaining the walker's Dirent records.
+ return false;
+ },
}),
);
const operationalFailure = scan.failedDirs.find((failure) => !isFileMissingError(failure.error));
if (operationalFailure) {
throw new MemorySourceScanError(operationalFailure.path, operationalFailure.error);
}
- files.push(...scan.entries.map((entry) => entry.path).toSorted());
+ // A large root can exceed the maximum number of arguments in a single push call.
+ for (const file of paths.sort()) {
+ files.push(file);
+ }
}
export async function listMemoryFiles(
diff --git a/scripts/perf/memory-file-inventory.mjs b/scripts/perf/memory-file-inventory.mjs
new file mode 100644
index 00000000000..303506f549c
--- /dev/null
+++ b/scripts/perf/memory-file-inventory.mjs
@@ -0,0 +1,54 @@
+// After pnpm build:runtime, run both builds on the same unchanged Markdown tree:
+// node --expose-gc scripts/perf/memory-file-inventory.mjs <extra-root> <expected-files> [built-storage-module]
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { performance } from "node:perf_hooks";
+import { pathToFileURL } from "node:url";
+
+const [rootArg, countArg, moduleArg] = process.argv.slice(2);
+const count = Number(countArg);
+if (!rootArg || !Number.isSafeInteger(count) || count < 1) {
+ throw new Error(
+ "Usage: node scripts/perf/memory-file-inventory.mjs <extra-root> <expected-files> [built-storage-module]",
+ );
+}
+
+const root = path.resolve(rootArg);
+const storage = moduleArg
+ ? pathToFileURL(path.resolve(moduleArg))
+ : new URL("../../dist/plugin-sdk/memory-core-host-engine-storage.js", import.meta.url);
+const { listMemoryFiles } = await import(storage.href);
+const workspace = await mkdtemp(path.join(os.tmpdir(), "memory-file-inventory-"));
+try {
+ for (const pass of ["cold", "warm"]) {
+ globalThis.gc?.();
+ const cpu = process.cpuUsage();
+ const start = performance.now();
+ const files = await listMemoryFiles(workspace, [root]);
+ const wallMs = Math.round(performance.now() - start);
+ const used = process.cpuUsage(cpu);
+ assert.equal(files.length, count);
+ const digest = createHash("sha256");
+ let previous = "";
+ for (const file of files) {
+ assert.ok(previous < file);
+ digest.update(path.relative(root, file) + "\n");
+ previous = file;
+ }
+ console.log(
+ JSON.stringify({
+ pass,
+ files: files.length,
+ sha256: digest.digest("hex"),
+ wallMs,
+ cpuMs: Math.round((used.user + used.system) / 1000),
+ processMaxRssKiB: process.resourceUsage().maxRSS,
+ }),
+ );
+ }
+} finally {
+ await rm(workspace, { recursive: true, force: true });
+}