Skip to content

feat(watch): add Rust-backed guarded filesystem observation - #690

Merged
steipete merged 5 commits into
mainfrom
codex/watch-rust-20260925
Sep 26, 2026
Merged

steipete merged 5 commits into
mainfrom
codex/watch-rust-20260925

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Supersedes #666. Preserve its guarded-scan model and smaller public API, while replacing the per-subscription Node Worker with a shared Rust hub. Native events are implemented on Linux, macOS, and Windows; Bun remains on explicit polling until TSFN lifetime is qualified.

Idle-hub follow-up: c66a694d6aa7fe19be06957096e5f3b5ddd9a109. The hub now blocks on kernel events or explicit commands, with no timer tick. Linux AWS measured 994 → 0 voluntary hub context switches over 10 seconds; post-change edit latency was 28.05 / 25.91 / 25.86 ms. All exact-head hosted checks are green (32 success, six intentional skips at verification); hosted proof is recorded below. Local macOS timing remains unqualified on this follow-up: the system FSEvents service stalled independently of the addon, including in the standalone C probe. No test threshold was relaxed and no shutdown wait was detached.

Design

Platform Transport Admission and retirement
Linux One shared inotify instance; nonrecursive watch per directory inode Shared guarded native open beneath Root, exact identities, verified procfs, register before child scan, close descriptors immediately. Last registration joins the hub.
macOS One FSEvents stream per subscription on one shared serial dispatch queue; FileEvents / NoDefer / WatchRoot, 30 ms latency Lexical canonical-Root prefix gate; outside names discarded. Dropped/wrapped streams and RootChanged trigger guarded reconciliation. Stop/Invalidate/Release synchronously on the queue, then drain callbacks before freeing context.
Windows Overlapped ReadDirectoryChangesW anchors on the shared IOCP hub, 64 KiB buffers Existing guarded handle-relative open, direct asynchronous NtCreateFile with READ/WRITE/DELETE sharing; recursive tree anchors deduplicate descendants. Re-arm before parsing. CancelIoEx, consume completion, then CloseHandle/free request storage. No detached waits.
Bun / unavailable addon / unsupported runtime Polling under auto Explicit events rejects helper-unavailable; existing native require policy remains enforced.

The shared hub sleeps on inotify plus eventfd (Linux), IOCP with a posted command sentinel (Windows), or the command channel (macOS). FSEvents callbacks enqueue bounded/coalesced drain notifications; JS consumption acknowledges queued batches so backpressure retries need no timer. Watch mutexes consistently recover poisoned guards.

Events remain advisory; guarded metadata scans through the admitted Root are authoritative. Literal entry/tree scopes, depth/budgets, no-follow symlink behavior, exact Root replacement refusal, private raw names, guarded detail admission, periodic reconciliation, immediate generation fencing, and joined close remain intact. Four reconciliation passes are internal. Initial admission and scope replacement publish one undetailed reconciliation.

Linux registers through /proc/self/fd/N/. because IN_DONT_FOLLOW plus IN_ONLYDIR rejects the bare procfs symlink. Inotify ENOSPC has the separate watch-limit failure code. Windows zero-byte and enumeration-loss completions overflow; immediate enumeration loss and expired anchors request guarded rebuilding instead of permanently disabling observation. macOS pathname hints may reflect activity after a swap; names never bypass guarded admission and the old Root is never replaced.

No new crates. The bounded, nonblocking Node-API callback wrapper owns rejected payloads explicitly, avoiding a leak in the locked napi-rs enqueue helper. Removed #666's Worker/eval/fs.watch transport, retained directory pins, unreachable JS recursion, persistent, configurable maxPasses, WatchFunction, public generations/scopes, extra health counters, and closing state.

Consumer migration

openclaw/openclaw#158182 must adopt onDirty → onInvalidate, WatchDirty → WatchInvalidation, update → setScopes, and required mode events/auto/poll instead of node. Read errors through health().failure.error and use directories for observed-directory pressure. Application settling/reload/indexing and async-work ownership remain in the consumer. Exports, declarations, API snapshot, docs/navigation, benchmarks, and CI are aligned; the changelog thanks @vincentkoc under the post-0.20.0 Unreleased section.

Idle-hub follow-up proof

  • Linux AWS lease cbx_8f956289a0c1, confirmed released: baseline, candidate. Same lease, one events subscription, no filesystem edits during the ten-second sample: 994 → 0 voluntary context switches, summed for the named hub thread under /proc/<pid>/task/*/status. Rust tests, clippy, 27 applicable focused tests, forced-no-openat2, real edits and three joined-exit cycles passed.
  • Local macOS top -l 2 -s 10 -stats pid,idlew,cpu -pid <pid> reported 0 → 0 IDLEW for before/after; that host-level counter did not expose the old timer wakes. The process CPU samples were 12.028 → 6.305 ms (approximately 11.4-second sampling commands), not a per-thread CPU measurement. Native build, clippy, five Rust watch tests, and the new full-callback-queue regression passed. Focused event timing failed; the full local pnpm check was stopped after event failures and a blocked FSEvents cleanup. A process sample showed the dispatch queue waiting in f2d_unregister_rpc, while the standalone C probe also received no events in normal OS temporary storage. The host's fseventsd was using 159–195% CPU. This does not change platform support or replace the required hosted proof.
  • Hosted macOS native job: mode events, six event cases, 49.16 ms suite latency, standalone edits 41.39 / 48.10 / 45.92 ms, three joined-exit cycles and zero hub threads after close. The ten-second top sample showed 1 IDLEW, 0.0% CPU.
  • Hosted Windows native job: events selected, all six event cases executed, 31.10 ms suite latency; standalone edits 28.76 / 27.32 / 27.74 ms. Three recursive-delete/cancel/join cycles and three joined-exit cycles passed, zero hub threads afterward. The newly created hub thread consumed 0 ms CPU over the ten-second idle window. A pre-change Windows CPU baseline was not collected; this is an after-change CPU observation, not a context-switch comparison.
  • Hosted Linux native job: six event cases, 32.35 ms suite latency; standalone edits 25.87 / 26.48 / 25.22 ms, 0 idle hub voluntary context switches, joined exit with zero hub threads. Linux musl also passed the required event suite.
  • Final fresh exact-head checks: 32 success, six intentional skips, no failures or pending checks. Linux coverage initially failed the existing specific-detail assertion at test/watch.test.ts:62; one unchanged-head rerun passed all 16,103 tests (648 platform/opt-in skips), with no code or threshold changes.
  • Independent Codex review of this follow-up: scoped-clean at P0–P2. No accepted/actionable findings.

Earlier feature proof (a690dc6)

  • macOS native binding built locally. FSEvents MustScanSubDirs/UserDropped/KernelDropped/wrap/unmount overflow, outside-path discard, guarded RootChanged replacement refusal, real Root rename, and joined cleanup are tested. Normal OS temporary storage is used. Isolated full watch selection: 57 applicable tests passed; standalone events samples: 41.34 / 254.83 / 467.94 ms, with zero hub threads after close. Earlier local cold-fixture/stress timing failures are retained in the report; the final full local gate and exact-head hosted gates passed. Latency measurements remain observations, not a hard real-time guarantee.
  • Linux AWS lease cbx_26d8fa6db974: run. Native build, clippy, Rust hub tests, required events suite, standalone edit and bounded process-exit proofs, forced no-openat2, real inotify ENOSPC with restored kernel limit, and full tests passed (16,092 tests passed, 647 platform/opt-in skips).
  • Windows Rust MSVC-target type-check passed on the earlier Linux lease with cross C tools; this is compilation evidence, not Windows execution. Hosted Windows MSVC proof passed: mode events, six event cases, 48.21 ms suite notification; standalone edits 36.58 / 30.82 / 44.71 ms; three recursive-delete/cancel/join cycles and three joined-exit cycles, zero hub threads afterward. The initial ReOpenFile directory failure was fixed with direct guarded asynchronous opens.
  • macOS native CI passed: mode events, six cases, 102.97 ms suite notification; standalone edits 54.38 / 57.78 / 109.92 ms, joined exit with zero hub threads. Linux native CI passed: 43.00 ms suite notification; standalone edits 35.06 / 26.80 / 28.48 ms. Linux musl also passed.
  • Native CI sets FS_SAFE_TEST_WATCH_EVENTS=1 unconditionally for linux/darwin/win32, fails missing backends or skipped event cases, asserts actual events mode, and runs a separate real-edit proof. Linux musl also requires events.
  • Independent Codex review: fixed immediate Windows ERROR_NOTIFY_ENUM_DIR recovery; subsequent feature review and direct-open follow-up review scoped-clean at P0–P2. All runtime gates passed independently. All task leases are expired/released and cleaned up.

Size and limits

Dedicated watch files #666 This head
TypeScript 999 763
Rust, including native unit tests 0 1363
Watch TypeScript tests 1241 471
Watch guide 246 145

Complete feature: 3085 additions / 10 removals, versus #666's 2899 additions / 26 removals. TypeScript meets the ~900-line goal. Rust is 1246 production lines plus 117 native test lines and exceeds its ~900-line aim: explicit callback ownership, wake/acknowledgement paths, and Windows cancellation/storage lifetime are retained rather than weakening those safety properties. Total cross-platform code now exceeds #666; the public TypeScript implementation and tests remain substantially smaller.

Polling can miss metadata-preserving content edits. Native streams remain lossy hints and make no transaction-log or hard real-time promise. Bun events remain unqualified. The local FSEvents-service stall remains explicitly unqualified; see the follow-up proof above.

@steipete
steipete requested a review from a team as a code owner September 26, 2026 03:33
@clawsweeper

clawsweeper Bot commented Sep 26, 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.

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 26, 2026, 11:59 AM ET / 15:59 UTC (Revision 10).

ClawSweeper review

What this changes

Adds a Root-bound filesystem watch API with a shared Rust event hub on Linux, macOS, and Windows, guarded scans, polling fallback, and supporting docs, tests, benchmarks, and CI checks.

Merge readiness

⛔ Blocked before merge - 5 items remain

Keep this PR open. Current main and v0.20.0 do not provide the watch API, and the related draft PR is unmerged. The callback contract for activity on a watched directory after it leaves the admitted Root still needs an owner decision and final-effect proof.

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

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Real cross-platform edit and shutdown evidence is useful, but the final callback authority boundary still limits merge confidence.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: Authority-chain proof required: linked hosted jobs on the earlier c66a694 head report real edits through the public watch API on Linux, macOS, and Windows and joined close. The supplied evidence does not compare an allowed edit with an outside-only moved-descendant edit at the final callback, including path reassignment before delivery. Add redacted terminal or log traces, update the PR body for automatic re-review, and ask a maintainer to comment @clawsweeper re-review if that does not occur. No stored-data contract changes.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Authority-chain proof required: linked hosted jobs on the earlier c66a694 head report real edits through the public watch API on Linux, macOS, and Windows and joined close. The supplied evidence does not compare an allowed edit with an outside-only moved-descendant edit at the final callback, including path reassignment before delivery. Add redacted terminal or log traces, update the PR body for automatic re-review, and ask a maintainer to comment @clawsweeper re-review if that does not occur. No stored-data contract changes.
Evidence reviewed 10 items Current-main boundary: Current main has no watch package subpath; the introduced diff adds one, so the central capability remains unimplemented on main.
Release boundary: The latest release, v0.20.0, also has no watch export.
Introduced public path: The pinned PR diff adds watch registration, guarded reconciliation, and the public invalidation callback.
Findings None None.
Security Needs attention Resolve moved-descendant callback authority: Linux can retain an inode watch after path movement, and the final callback can publish an undetailed invalidation from a pending hint. The allowed and outside-only final effects need an explicit contract and production-path proof.

How this fits together

Applications supply an admitted filesystem Root and literal paths to observe. Native events or polling trigger guarded scans, which send bounded invalidations and health information back to the application.

flowchart LR
A[Admitted Root and scopes] --> B[Watch subscription]
B --> C[Native events or polling]
C --> D[Guarded metadata scans]
D --> E{Root still valid?}
E -->|Yes| F[Invalidation callback]
E -->|No| G[Failure and joined close]
Loading

Decision needed

Question Recommendation
May outside-only activity on a watched descendant emit an undetailed onInvalidate callback after that descendant leaves the admitted Root, including when its path is reassigned before delivery? Require callback confinement: Suppress outside-only activity when guarded state is unchanged and demonstrate allowed and moved-out edits at the public callback.

Why: The public callback is an observable effect of persistent native observation, and the current contract and supplied proof do not establish which outcome the package owner intends.

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Authority-chain proof required: linked hosted jobs on the earlier c66a694 head report real edits through the public watch API on Linux, macOS, and Windows and joined close. The supplied evidence does not compare an allowed edit with an outside-only moved-descendant edit at the final callback, including path reassignment before delivery. Add redacted terminal or log traces, update the PR body for automatic re-review, and ask a maintainer to comment @clawsweeper re-review if that does not occur. No stored-data contract changes.
  • Resolve security concern: Resolve moved-descendant callback authority - Linux can retain an inode watch after path movement, and the final callback can publish an undetailed invalidation from a pending hint. The allowed and outside-only final effects need an explicit contract and production-path proof.
  • Resolve merge risk (P1) - A native registration can continue observing a descendant inode after that directory moves outside the admitted Root. The final callback outcome for an outside-only edit, including path reassignment before delivery, remains unproven and its permitted behavior has not been explicitly settled.
  • Complete next step (P2) - Settle whether outside-only moved-descendant activity may reach the public callback, then add redacted production-path proof for the chosen rule before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [medium] Resolve moved-descendant callback authority — src/watch.ts:265
Agent review details

Security

Needs attention: The persistent native registration and final callback leave the moved-descendant authority boundary unresolved.

Review metrics

Metric Value Why it matters
Dedicated watch implementation production +2,009 lines; tests +588 lines The PR explains that native callback ownership and joined shutdown account for much of the production growth.

Merge-risk options

Maintainer options:

  1. Constrain final callbacks (recommended)
    Settle the contract, then prove allowed and moved-out edits through the public watch callback before merge.
  2. Accept undetailed wakeups
    The package owner may accept this advisory behavior if it is documented and proof shows that outside names and data remain private.

Technical review

Best possible solution:

Keep native hints advisory while enforcing the chosen Root-membership rule at the final callback, with documented behavior and real move-and-reassignment regression proof.

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

Not applicable: this PR introduces a capability. Its real-edit checks cover allowed delivery, but no production-path trace shows the outside-only moved-descendant outcome.

Is this the best way to solve the issue?

Unclear: the shared hub and guarded scans fit the package's Root model, but the final callback rule for activity outside the Root needs an owner decision and proof.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against faa5f129ab5d.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a substantial new package capability with a bounded but unresolved callback boundary.
  • merge-risk: 🚨 security-boundary: Persistent native observation may carry outside-only filesystem activity to the public callback after a watched descendant moves.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Authority-chain proof required: linked hosted jobs on the earlier c66a694 head report real edits through the public watch API on Linux, macOS, and Windows and joined close. The supplied evidence does not compare an allowed edit with an outside-only moved-descendant edit at the final callback, including path reassignment before delivery. Add redacted terminal or log traces, update the PR body for automatic re-review, and ask a maintainer to comment @clawsweeper re-review if that does not occur. No stored-data contract changes.

Evidence

Security concerns:

  • [medium] Resolve moved-descendant callback authority — src/watch.ts:265
    Linux can retain an inode watch after path movement, and the final callback can publish an undetailed invalidation from a pending hint. The allowed and outside-only final effects need an explicit contract and production-path proof.
    Confidence: 0.79

What I checked:

  • Current-main boundary: Current main has no watch package subpath; the introduced diff adds one, so the central capability remains unimplemented on main. (package.json:98, faa5f129ab5d)
  • Release boundary: The latest release, v0.20.0, also has no watch export. (package.json:95, 86563e94c55b)
  • Introduced public path: The pinned PR diff adds watch registration, guarded reconciliation, and the public invalidation callback. (src/watch.ts:39, ef4e425e750d)
  • Persistent native observation: Linux registers the checked directory inode with inotify, then closes the admission descriptors; the native registration can outlive that directory's path membership. (native/src/watch_linux.rs:114, ef4e425e750d)
  • Final callback boundary: After guarded scans, a pending native hint can cause an undetailed callback even when the scan found no changed entry; current source does not settle the outside-only moved-descendant case. (src/watch.ts:265, ef4e425e750d)
  • Proof coverage: The production-path script observes real edits to an allowed file, reads it through the Root, and verifies joined close. It does not move a watched descendant outside the Root. (scripts/watch-events-proof.mjs:17, ef4e425e750d)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add final-effect proof for an allowed edit and the nearest outside-only moved-descendant edit, including reassignment before callback delivery.
  • Record the package owner's decision on whether outside-only activity may cause an undetailed callback.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • 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-review comments, 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-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-26T04:00:25.407Z sha e0318eb :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-26T04:16:30.892Z sha e0318eb :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-26T06:13:32.930Z sha ab27e92 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-26T06:21:14.764Z sha 1ec3642 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-26T06:38:31.711Z sha a690dc6 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-26T06:54:54.723Z sha a690dc6 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-26T07:06:56.453Z sha c66a694 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-26T07:25:23.807Z sha c66a694 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. label Sep 26, 2026
@steipete
steipete force-pushed the codex/watch-rust-20260925 branch from ab27e92 to 1ec3642 Compare September 26, 2026 06:15
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. label Sep 26, 2026
steipete and others added 5 commits September 26, 2026 08:54
Keep guarded Root scans authoritative, multiplex Linux advisory hints in one joined native hub, and select portable polling on unqualified platforms. Supersedes the design in #666 without changing its branch.

Co-authored-by: Vincent Koc <[email protected]>
Reject trailing-dot/space and reserved device components without changing POSIX literal names. Add portable Windows scope parser regressions for the hosted CI failure.

Co-authored-by: Vincent Koc <[email protected]>
Enable native events on macOS and Windows while preserving guarded scan authority and the existing public API. Keep request storage alive through cancellation completion, reconcile recoverable enumeration loss, and require real event and joined-exit proof in native CI.

Co-authored-by: Vincent Koc <[email protected]>
Open overlapped directory handles directly instead of using ReOpenFile. Preserve synchronous flags for every existing guarded caller and keep reparse/identity checks unchanged. Separate deterministic FSEvents decoding assertions from legitimate live overflow coalescing.

Co-authored-by: Vincent Koc <[email protected]>
Wake kernel waits for commands and acknowledge consumed callback batches so backpressure needs no timer. Recover poisoned watch locks and measure idle cost in native CI.

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

Labels

merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. P2 Normal priority bug or improvement with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant