Repository navigation
perf(memory): move local file watching into a shared worker - #175157
Conversation
Keep readiness, health, dirty delivery and joined retirement with the existing MemoryFileWatcher owner. Reuse the Memory worker entry with a local transport while indexing remains host-owned. Native scale, warm non-regression and CI proof are pending.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs changes before merge. What this changesThis PR moves local Memory filesystem discovery, observation, and settling into one shared worker while keeping indexing on the Gateway. Example: Two agents watch the same memory directory containing 50,000 files.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 2 items remain Keep open: moving filesystem observation off-thread addresses a documented Gateway stall source, but failed-transport recovery and the shared manager test fixture need repair. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherMemory managers send workspace paths and watcher settings through a local message port; the existing MemoryFileWatcher observes files and returns facts that drive Gateway-owned indexing. flowchart LR
A[Memory managers] --> B[Local watcher proxies]
B --> C[Shared file worker]
C --> D[MemoryFileWatcher]
D --> E[Filesystem observation]
C --> F[Dirty and health facts]
F --> A
Technical reviewBest possible solution: Keep the shared-worker design, release exited transports for future watcher instances, and migrate the shared manager fixture to the new observation boundary. Do we have a high-confidence way to reproduce the issue? Current main constructs observation on the Gateway thread, and prior measured evidence establishes remaining initial-scan work; the failed-transport path is source-reproducible and existing manager failures appear in exact-head CI annotations. Is this the best way to solve the issue? Reusing the existing watcher inside a shared file worker is a focused solution that preserves root sharing and host-owned indexing, provided failure retirement and test fixtures complete the cutover. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 82d97d2fada9. Provenance checked
TestingProof path: none. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +435, Tests +753, Docs +7. Total +1195 across 15 files. Added test files: 3. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 17, 2026, 1:48 AM ET / 05:48 UTC. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 32018e5625
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| async remove(id: number, retired: Promise<void>): Promise<void> { | ||
| if (this.failure) { | ||
| this.subscriptions.delete(id); | ||
| return this.waitForExit(); |
There was a problem hiding this comment.
Clear the failed transport after its final subscriber exits
When the shared worker emits an error or exits unexpectedly, this early return deletes the subscription but never clears owner.transport. After the final watcher closes, every later LocalMemoryFileWatcher.start() reuses that failed singleton and add() immediately rethrows the old error, permanently disabling automatic local-memory observation for the rest of the Gateway process even though the worker has exited. Clear the owner after the failed worker is joined and the last subscription is removed so a later manager can start a replacement.
AGENTS.md reference: AGENTS.md:L7-L9
Useful? React with 👍 / 👎.
|
Follow-up from the P2 automatic review: allow a replacement local watcher transport after an unexpectedly failed worker has exited and its final subscription retires. Current failure handling marks observation unavailable and memory dirty, retains the failed join, and requires a Gateway restart to restore automatic observation. Normal retirement/reload recreates the worker and passed the live lifecycle tests. This remains a follow-up under the requested two-round review limit; no third review or additional recovery mechanism is added in this PR. |
…175353) The real Memory fixture imports its runtime directly into Vitest, while the Gateway test environment disables bundled discovery. After #175157 moved local file observation into the existing Memory worker, that worker could not resolve memory-core/worker-api.js and agent deletion failed. Prepare discovery at the shared fixture owner. Clear the disable override and select the same validated source public-artifact tree as its runtime import, so a prepared worker cannot borrow an unrelated older dist API. The existing Vitest environment cleanup restores both scoped overrides. Keep the real worker and every deletion, survivor-manager, custody and shutdown assertion. Production discovery and disable policy are unchanged. The unchanged current-main product proof reproduced the missing public surface: one case passed and one failed (211.32s wrapper). Final proof: all three shared-fixture consumer files pass 8/8 through the native Gateway configs with --maxWorkers=1 (401.68s wrapper, 387.56s Vitest; 52% transformation). The formerly failing external-state deletion takes 15.137s. Source artifact resolution is exercised with older built artifacts still present; no rebuild or deletion was used to make it pass. Gateway-server and Gateway-methods test types (10.4s/10.2s), lint, boundary lint, formatting, git diff --check, and P0-P2 autoreview pass. The mock-export guard passes without changing its baseline. No retries, skips, timeouts, production code, or CI dispatches/reruns were added.
Move local directory discovery, native observation, and settling into one shared dedicated Memory file worker. Preserve independent subscriptions, same-root sharing, readiness, health/capacity reporting, dirty notifications, and joined shutdown. Indexing retains its existing owner. Preserve the source-host ESM loader when compiled workers import source plugins. Keep controlled filesystem fixtures in-process and exercise native transport separately. Validation: native macOS and Linux Node worker integration, macOS Bun polling integration, watcher owner coverage, 22 reload cases, final CI types/lint/contracts/ratchets, and published-driver update. PostgreSQL passed all observed assertions before its 30-minute job deadline; accepted under the authorized deadline exception. Knip findings exactly match recent main. Owner SQL, requests, and T1 remain zero; this change targets main-thread filesystem work. Follow-up: an unexpected shared-worker failure remains sticky until Gateway restart; normal retirement/reload recreates the worker.
…penclaw#175353) The real Memory fixture imports its runtime directly into Vitest, while the Gateway test environment disables bundled discovery. After openclaw#175157 moved local file observation into the existing Memory worker, that worker could not resolve memory-core/worker-api.js and agent deletion failed. Prepare discovery at the shared fixture owner. Clear the disable override and select the same validated source public-artifact tree as its runtime import, so a prepared worker cannot borrow an unrelated older dist API. The existing Vitest environment cleanup restores both scoped overrides. Keep the real worker and every deletion, survivor-manager, custody and shutdown assertion. Production discovery and disable policy are unchanged. The unchanged current-main product proof reproduced the missing public surface: one case passed and one failed (211.32s wrapper). Final proof: all three shared-fixture consumer files pass 8/8 through the native Gateway configs with --maxWorkers=1 (401.68s wrapper, 387.56s Vitest; 52% transformation). The formerly failing external-state deletion takes 15.137s. Source artifact resolution is exercised with older built artifacts still present; no rebuild or deletion was used to make it pass. Gateway-server and Gateway-methods test types (10.4s/10.2s), lint, boundary lint, formatting, git diff --check, and P0-P2 autoreview pass. The mock-export guard passes without changing its baseline. No retries, skips, timeouts, production code, or CI dispatches/reruns were added.
What Problem This Solves
Initial Memory file-watcher setup traverses large workspaces synchronously on the Gateway main thread. Moving indexing work off-thread did not remove this separate source of event-loop stalls.
User Impact
Local Memory directory discovery, native observation, and change settling now run in one shared file worker. Agents keep independent subscriptions and share unchanged roots. Startup still waits for watcher readiness, health and capacity remain visible, and shutdown joins native cleanup and the final worker exit.
Why This Change Was Made
The existing Memory file worker entry and
MemoryFileWatcherremain the owners. Source hosts retain their configured ESM TypeScript loader when tests select a compiled worker that still imports source plugins. A local message-port transport replaces direct main-thread watcher construction; the remote stream protocol and the SQL/indexing pool are unchanged. The Gateway still owns indexing and consumes pushed dirty, settled, and health facts. No schema, public SDK, or configuration change is needed.Accepted scheduling edges: dirty notifications arrive on the earliest message delivery instead of the same JavaScript stack; the worker can settle newer filesystem events while host indexing is running. A newer dirty event clears pending settled readiness, so host indexing stays bounded without a callback-completion handshake. Shutdown errors stay visible; only after all native close attempts finish unsuccessfully does final retirement terminate and join the worker to release remaining handles.
Removed checks: none. The superseded direct local watcher construction path is removed; filesystem admission and existing watcher recovery remain with the same owner.
Evidence
Final test-only head:
32018e562524. Final Node tests, all ordinary static/security checks, and the macOS Bun polling integration passed. PostgreSQL conformance reached its configured 30-minute job deadline with no failed assertion; it is incomplete, not passing. Completed production and update evidence below usesc5c87c1ef894, with identical production code.Three alternating pairs used unchanged sqlharness-v3 on base
a2e6a6b0f9c437989aa8cdf80d495240381f7be8and candidate32018e5625241a1b65093694c6905cfc596e2519. The shared SQL harness used Node 24.22.0 / SQLite 3.54.0; exact build snapshots and runtime identities were checked for every arm. Each side has 30 warmed turns. All six arms completed without SQL errors, missing causal coverage, or remaining fixture processes. The request and statement ledgers reconcile to the recorded totals.Values below are median [min–max]: pooled individual turns for warmed values, three run totals per side for whole-workload and phase values. Causal values follow each turn across threads; raw values include background work overlapping its wall-clock window.
Watcher SQL / requests / T1: 0 / 0 / 0 → 0 / 0 / 0. Global T1: 182 → 182. This moves filesystem work off MAIN; it does not claim SQL savings.
Native watcher scale
All six scale probes used Node 26.12.0 on both sides, independently of the Node 24 shared SQL harness. The outer Node 24 hash receipt does not attest the child Node 26 libraries. Each probe completed all nine lifecycle phases with ready native observation, matching directory counts, root-replacement notifications, and zero owners after shutdown. The sizes below count ordinary files in the primary root; each setup also includes a secondary root with N/10 ordinary files. Both roots additionally include 24 deep files, three sparse files, and symlinks.
Candidate MAIN native watcher calls and SQL were zero throughout. Profiles used
--cpu-prof; the historical 113-second MAIN stall was not reproduced. Timing is descriptive on a busy host: this is evidence of filesystem work moving off MAIN, not faster readiness or reduced total filesystem work.Per-run, phase, shared-read-family, and lifecycle measurements
Background MAIN lease reads and memory corpus-inventory requests are recorded separately below. Lease reads can move between the first-turn and warmed windows without adding work. Corpus-inventory request counts distinguish transport calls from the number of calls that actually execute snapshot SELECTs.
Per-run warmed results
Shared read-family attribution
Counts identify executed SELECT/WITH statements by owner stack, including callbacks in pinned source ranges when deep stacks truncate the outer name. Requests count unique causal request IDs containing those reads; nested families may overlap. Zero means no executed read, not that the in-memory owner function was never called. All five families also have zero causal and raw warmed requests on both sides.
C2 executed two snapshot SELECTs in its existing shadow-rebuild corpus request (
66211:0:642); that request executed zero SQL in M1, C1, and M2. This is a cache miss/invalidity reload on an already-used worker, not a new transport request. The relevant cache/indexing source is identical. A sibling row-transcript write overlaps the earlier read, but retained ledgers do not record receipt values or completion ordering. The exact invalidating write and any indirect watcher-scheduling contribution cannot be established. The cold difference is disclosed rather than classified as generic noise.C3 likewise executes two snapshot SELECTs in the existing compaction shadow-rebuild request (
56562:0:636, worker 17), versus zero in M3. C3 also has one extra exact-entry SELECT in background request56562:0:132during the first-turn window (worker 16):session-transcript.worker.ts:345callsreadExactSessionEntriesWithLifecycle. Its retained origin stack contains queued worker-pool dispatch rather than the higher-level caller. The ordinary turn-scoped retained-facts read exists on both sides. These are cold differences with unresolved higher-level scheduling attribution; the measurements do not establish zero cold SQL cost or exclude an indirect watcher effect.Raw phase attribution
Warm windows are summed per run here. Compaction and settle are combined because memory first-use work can cross that boundary.
50k per-operation MAIN filesystem calls
Candidate MAIN native-watcher calls and SQL statements are zero in every scale phase. Remaining initial MAIN filesystem calls are two realpathSync calls and one or two writeSync calls. Worker diagnostics confirm native observation moved to the worker. CPU profiles were collected with --cpu-prof, summarized, and deleted with the synthetic fixtures.
These event-loop observations are descriptive on a busy host. No wall-time speedup or reduced total filesystem-work claim is made: source-launch readiness was slower with cold worker loading. The historical 113-second MAIN stall was not reproduced.
Focused proof covers client ordering, readiness, callback context, shared subscriptions, worker failure, joined cleanup, and native file edits. At
c5c87c1ef894, all 22 cases across the six changed test files passed in Linux CI, including the real Node Worker integration. That integration also passed on macOS Node 24. All 22 local reload tests passed: five live Memory reload cases and 17 service lifecycle cases. The existing 41-case watcher coverage also passed in CI, along with the remote worker and watcher configuration tests. Knip completed: all eight production and six full-tree findings match exact file/export tuples on recent mainbbb775bd(run 39006528379/job 117320109233), with identical source/config/lock/scanner inputs. The script scan has zero findings; no new unused export was introduced.The worker migration exposed a fixture boundary: the shared indexing fixture mocked filesystem observation only inside Vitest, while real Workers bypassed that mock. The fixture now retains in-process observation; separate integration tests exercise the real transport. All four failing indexing scenarios pass locally with unchanged assertions, including both captured-session vector variants. Bun integration explicitly selects supported polling; the installed filesystem dependency does not support Bun native event callbacks. Node retains required native-event coverage. The macOS Bun polling integration passed with the same shared-worker, edit-observation, and joined-exit assertions.
Both Codex autoreview rounds completed: round 1 scoped-clean through P2 and round 2 scoped-clean through P1. Follow-up changes repaired type/format/mock-export findings, preserved the configured source-host ESM loader in compiled workers importing source plugins, and corrected controlled test fixtures. No additional review rounds were run.
Final-head CI run 39010620192 passed all selected Node tests, type-aware lint, production/test types, source contracts, docs, Madge (zero cycles), T1 (182 → 182), compatibility inventory (10 → 10), every dialect class (0 → 0), and security checks. PostgreSQL conformance job 117332467074 passed its 49-file/296-case infrastructure group and preceding groups (70, 6, and 1 cases), then reached the configured 30-minute job deadline during Doctor command testing without a failing assertion. The four failures from the earlier candidate all passed on this run; the test-only change is not claimed to have fixed their root causes. Recent main job 117320108759 also reached that deadline. Landing uses the authorized relaxed-v4 deadline exception; PostgreSQL conformance and the aggregate gate remain incomplete/cancelled and failed respectively, not green.
The published-driver update cell passed against
c5c87c1ef894, whose production code is identical to the final head. Earlier unrelated remote-exec missing-worker failures also occurred on recent main and do not recur in final CI. The separate npm 12 package-acceptance job installed successfully but exceeded the existing file-count budget; main run 38874597379/job 116891947806 has the same failure class. This establishes inheritance of the failure, not an exact-base file-count delta.Current diff: production +473/−21 (net +452), tests +799/−0, docs +7/−0. The added code provides the shared local transport and its lifecycle; it does not duplicate filesystem observation or move watchers into the SQL task pool.
Follow-up from the automatic GitHub review (P2): after an unexpected shared-worker failure, the transport currently retains its failure for the Gateway process lifetime, even after the final subscriber closes. Managers mark observation unavailable and memory dirty; a Gateway restart restores automatic observation. Allowing a fresh transport after the failed worker is joined and every subscription retires is deferred under the requested two-round review limit. Normal retirement and reload recreate the worker and are covered above.