Skip to content

perf(watch): read directory names synchronously in bounded batches - #747

Merged
steipete merged 2 commits into
mainfrom
perf/watch-bounded-sync-names
Sep 28, 2026
Merged

steipete merged 2 commits into
mainfrom
perf/watch-bounded-sync-names

Conversation

@steipete

@steipete steipete commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Node watch scans spend about a second of a 50,000-file scan awaiting one-entry directory reads. Read those names synchronously with the existing one-entry buffer and yield every 32 reads. Keep every pre-read, post-read/pre-stat, and post-stat identity fence, exact identity handling, budget lookahead, and no-follow metadata observation. Bun and Deno retain asynchronous reads because bounded synchronous buffering is not established there.

Only openRootDirectoryListing({ exactIdentity: true }) selects this path. Its only production caller is src/watch-scan.ts; Root.list/walk, locks, JSON-store, and all other method benchmark rows cannot execute it. New regression tests cover runtime routing, budget lookahead, cancellation, and a directory swap between name read and leaf metadata. Native CI now runs all watch suites, and the stress workflow also runs 500 model seeds per mode and soak-short.

Accepted performance study

Dedicated AWS Crabbox cbx_dd3910954cd8 (released): c7a.8xlarge / AMD EPYC 9R14, Linux x64, Node v24.18.1, pnpm 12.4.2, Rust 1.98.1. Warm tmpfs fixture: 2,000 child directories × 25 files; the root adds one directory. This is metadata-cache performance, not cold-storage performance.

Frozen measured base: 25de32860e5f73dd2ba7aeeb9078197a22d5df96. This PR was applied to fresh main 85474b5e9cb57243e59f11fa614cc7971998b6c8; the watch scanner, listing helper, and directory guards are unchanged between those bases. The committed benchmark is byte-identical to the measured harness (SHA-256 d18eea480e79fd7d73153913de7915e7c37f0b2d8859af0fd98e2ec6155a112b). Both artifacts used native addon SHA-256 8e40530c1146079cd8285f64e9847f80b99eb6863df2a856086ded47b688843d.

Each transport uses one process, both distributions, and one unchanged fixture: public ready, then public reconcile(), with Root construction and close outside timing. One warmup per arm; five ABBA and five BAAB blocks, ten samples per arm per order (twenty pooled). The A/A control uses the identical baseline artifact. No samples discarded. The 95% intervals are paired-block bootstrap intervals (10,000 draws, fixed seed, stratified by order); control spread is the full range of paired-block percentage deltas.

Mode Timer Base median ms Candidate median ms Improvement 95% CI A/A spread, pp
poll ready 3067.02 2030.32 33.80% 33.59–33.96% 1.44
poll reconcile 3075.75 2047.62 33.43% 33.26–33.64% 1.72
events ready 3019.03 2198.87 27.17% 26.91–29.41% 2.20
events reconcile 2832.25 2018.55 28.73% 28.18–30.59% 2.09
Mode Timer ABBA improvement BAAB improvement
poll ready 33.71% 33.86%
poll reconcile 33.28% 33.66%
events ready 31.15% 27.19%
events reconcile 32.28% 28.75%

All targeted medians improve by more than 10% and twice the A/A spread, in both run orders.

strace -c -f includes startup, ready, one reconcile, and shutdown, with fixture construction outside tracing. Traced wall times are not acceptance timings. Expected readlink EINVAL probes come from realpath.

50k syscall Poll base → candidate Events base → candidate
statx 809,001 → 809,001 809,015 → 809,015
readlink 1,056,051 → 1,056,051 1,056,052 → 1,056,052
getdents64 8,006 → 8,006 8,006 → 8,006
futex 355,093 → 32,166 358,091 → 36,104
epoll_pwait 231,892 → 15,913 231,923 → 15,909

Full-method controls and scope

The unfiltered pnpm benchmark:methods suite ran before/after in both off and require modes, with 20 iterations, 10 samples, and one warmup: 994 measured off rows and 1,013 require rows. Harness SHA-256: 00a6edc40be6183253e778874fd517574ee264e0b3e59a99efd50beba404107c.

The broad sweeps flagged unrelated rows, but an identical-baseline rerun reproduced large drift: lock verification 562.28 → 983.52 µs (+74.92%); JSON-store read 445.82 → 666.04 µs (+49.40%). Those rows cannot reach the changed exactIdentity branch. The coordinator accepted this scope argument and environmental A/A evidence together with the reproducible targeted result and unchanged metadata syscall counts. These noisy rows are not claimed as measured improvements.

Reproduction

Build baseline and candidate separately, preserve each matching dist/native package layout, then run the same harness against both:

node scripts/watch-scan-benchmark.mjs setup /tmp/watch-perf-10k 400
node scripts/watch-scan-benchmark.mjs setup /tmp/watch-perf-50k 2000
node scripts/watch-scan-benchmark.mjs compare /tmp/watch-perf-50k 2000 /baseline/dist /candidate/dist
node scripts/watch-scan-benchmark.mjs compare /tmp/watch-perf-50k 2000 /baseline/dist /baseline/dist
strace -c -f -o counts.txt node scripts/watch-scan-benchmark.mjs once /tmp/watch-perf-50k 2000 /candidate/dist /candidate/dist poll
# Repeat traced once for events and both distributions, at both fixture sizes.
pnpm benchmark:methods --mode off --iterations 20 --samples 10 --warmup 1 --json methods-off.json
pnpm benchmark:methods --mode require --iterations 20 --samples 10 --warmup 1 --json methods-require.json

Validation

Fresh-head AWS proof used dedicated lease cbx_8215ceae7292 (released), run run_a253898cee60e802d83ce03a1d890ccb, at head cd485adc492f47bb8240342ce8ad5368eaecc7ad:

  • Watch suites: 193 passed, 23 expected skips.
  • Full pnpm check: 16,595 passed, 682 expected skips; file-size and filesystem-boundary lint, build, WASM allocator tests, docs, and installed-package checks passed.
  • Seeded model runner: 500 poll + 500 events seeds, 2,782 checkpoints, 5,541 invalidations, zero failures (58.405 seconds).
  • git diff --check passed. Scoped Codex autoreview was clean at P0–P2. The prior Bun eager-enumeration finding was fixed before this patch was accepted.
FS_SAFE_NATIVE_MODE=auto FS_SAFE_TEST_WATCH_EVENTS=1 pnpm test test/watch*.test.ts --maxWorkers=1 --testTimeout=30000
FS_SAFE_NATIVE_MODE=require node scripts/watch-stress/model-runner.mjs --seed 1 --seeds 500 --mode both --concurrency 4 --steps 32 --settle 40 --output model.json
env -u FS_SAFE_NATIVE_MODE -u OPENCLAW_FS_SAFE_NATIVE_MODE FS_SAFE_TEST_SERIAL=1 FS_SAFE_TEST_WATCH_EVENTS=1 pnpm check
git diff --check

Exact-head CI and watch stress both passed on attempt 1 at cd485adc492f47bb8240342ce8ad5368eaecc7ad. The stress artifacts verify churn, lifecycle, soak-short, 500 model seeds per mode, and every other dispatched scenario on Linux x64/arm64, macOS arm64/Intel, and Windows x64. The native CI watch suites also passed, including musl and Windows Server 2022. All PR checks are successful or intentionally skipped. No macOS or Windows speedup is claimed. Do not merge as part of this performance study.

@steipete
steipete requested a review from a team as a code owner September 28, 2026 05:10
@clawsweeper

clawsweeper Bot commented Sep 28, 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: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 28, 2026, 2:12 AM ET / 06:12 UTC (Revision 3).

ClawSweeper review

What this changes

The branch makes Node.js watch scans read directory names synchronously with periodic yields, and adds regression tests, a benchmark, documentation, and broader watch CI coverage.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open: this is a distinct, well-supported watch performance improvement absent from current main and the latest release. It merits maintainer review.

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

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong real-workload measurement and focused safety tests support a small patch, with the slow-storage latency tradeoff and release note still open.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The unchanged production listing helper at the proof and reviewed heads is exercised through public watch ready and reconcile on a real Linux Node.js 50,000-file fixture; the captured benchmark reports 27.17%–33.80% median improvements. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The unchanged production listing helper at the proof and reviewed heads is exercised through public watch ready and reconcile on a real Linux Node.js 50,000-file fixture; the captured benchmark reports 27.17%–33.80% median improvements. No stored-data contract changes.
Evidence reviewed 10 items Current main still reads names asynchronously: The current-main listing helper awaits Dir.read(), so the central optimization is not already implemented.
Latest release also lacks the change: The v0.21.1 listing helper awaits Dir.read(); the proposed synchronous path is neither released nor on current main.
Introduced Node watch path: The branch selects synchronous reads only for exact-identity listings on Node.js and yields between groups; the existing pre-read, post-read, and metadata fences remain in the listing loop.
Findings 1 actionable finding [P3] Add the measured watch improvement under Unreleased
Security None None.

How this fits together

The watch API takes an admitted filesystem Root and selected paths, then scans directory names and metadata behind identity checks to produce advisory invalidations. This change affects name reads during Node.js watch scans.

flowchart LR
  A[Admitted Root and scopes] --> B[Watch scan]
  B --> C[Guarded directory listing]
  C --> D{Runtime}
  D -->|Node.js| E[Bounded synchronous name reads]
  D -->|Bun or Deno| F[Asynchronous name reads]
  E --> G[Identity and budget checks]
  F --> G
  G --> H[Watch snapshot and invalidations]
Loading

Decision needed

Question Recommendation
Is synchronous name reading during Node.js watch scans acceptable on slow storage without measured event-loop delay? Measure slow-storage delay: Measure event-loop delay during a watch scan on slow storage and retain this path only if the observed stalls fit an accepted limit.

Why: The benchmark establishes a substantial warm-cache gain, but setting an acceptable stall limit for other application work requires watch-owner judgment.

Before merge

  • Add the measured watch improvement under Unreleased (P3) - The new watch documentation describes a measured public performance improvement, but CHANGELOG.md still has an empty Unreleased section. Repository policy requires a concise pending entry for measured performance gains.
  • Resolve merge risk (P1) - On slow or network filesystems, each new synchronous directory read can block Node.js; yielding after a bounded number of names does not cap wall-time event-loop delay, and the supplied warm-tmpfs study does not establish that delay.
  • Complete next step (P2) - Add an Unreleased performance entry, then provide slow-storage event-loop delay evidence or record explicit watch-owner acceptance before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P3] Add the measured watch improvement under Unreleased — docs/watch.md:169-172
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Implementation and validation lines production +7/−6; tests +92; benchmark +57 The production change is small relative to the focused regression and measurement support.
Measured watch improvement 4 warm-tmpfs timers improved 27.17%–33.80% The supplied public-API benchmark gives maintainers a concrete benefit to weigh against latency risk.

Merge-risk options

Maintainer options:

  1. Measure event-loop delay (recommended)
    Capture watch-scan event-loop delay on slow storage and use the result to set a defensible limit before merge.
  2. Accept synchronous stalls
    A watch owner may explicitly accept the slow-storage latency tradeoff and document its operator impact.

Technical review

Best possible solution:

Keep the watch-only Node.js optimization and its identity fences, record the measured gain for users, and establish an acceptable event-loop delay bound for slow storage.

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

Not applicable as a functional bug; the PR supplies a repeatable public watch benchmark and baseline-to-candidate timing results for the performance claim.

Is this the best way to solve the issue?

Yes for the measured Node.js hot path: the change is isolated to watch scans and retains the existing guards. Its slow-storage latency tradeoff still needs a bound or explicit acceptance.

Full review comments:

  • [P3] Add the measured watch improvement under Unreleased — docs/watch.md:169-172
    The new watch documentation describes a measured public performance improvement, but CHANGELOG.md still has an empty Unreleased section. Repository policy requires a concise pending entry for measured performance gains.
    Confidence: 0.97

Overall correctness: patch is correct
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a focused performance improvement to an existing watch workflow with a limited runtime scope.
  • merge-risk: 🚨 availability: Synchronous directory reads can delay unrelated Node.js work when filesystem reads are slow.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The unchanged production listing helper at the proof and reviewed heads is exercised through public watch ready and reconcile on a real Linux Node.js 50,000-file fixture; the captured benchmark reports 27.17%–33.80% median improvements. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The unchanged production listing helper at the proof and reviewed heads is exercised through public watch ready and reconcile on a real Linux Node.js 50,000-file fixture; the captured benchmark reports 27.17%–33.80% median improvements. No stored-data contract changes.

Evidence

What I checked:

  • Current main still reads names asynchronously: The current-main listing helper awaits Dir.read(), so the central optimization is not already implemented. (src/root-directory-list.ts:45, a3ccbc4cc2c6)
  • Latest release also lacks the change: The v0.21.1 listing helper awaits Dir.read(); the proposed synchronous path is neither released nor on current main. (src/root-directory-list.ts:45, 305ff575ce13)
  • Introduced Node watch path: The branch selects synchronous reads only for exact-identity listings on Node.js and yields between groups; the existing pre-read, post-read, and metadata fences remain in the listing loop. (src/root-directory-list.ts:476, 0a7e25bbb62f)
  • Production caller boundary: The watch scanner requests filesystem order and exact identities; public Root entries do not request that option. (src/watch-scan.ts:156, 0a7e25bbb62f)
  • Focused regression coverage: New tests cover runtime selection, budget lookahead, cancellation, and a directory-to-symlink swap before leaf metadata inspection. (test/watch-scan-scheduling.test.ts:13, 0a7e25bbb62f)
  • Real-workload proof: The captured PR body reports a dedicated Linux Node.js run through public watch ready and reconcile on an unchanged 50,000-file warm tmpfs tree, with four median improvements of 27.17%–33.80%, baseline controls, and 500 model seeds per mode. The committed benchmark hash matches the hash stated for the measured harness. (scripts/watch-scan-benchmark.mjs:1, 0a7e25bbb62f)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: 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 one concise Unreleased performance entry.
  • Measure slow-storage event-loop delay or record explicit watch-owner acceptance of that tradeoff.

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 (2 earlier review cycles)
  • reviewed 2026-09-28T05:13:39.378Z sha cd485ad :: blocked before merge. :: [P3] Add the measured watch improvement under Unreleased
  • reviewed 2026-09-28T05:45:59.477Z sha cd485ad :: blocked before merge. :: [P3] Add the measured watch improvement under Unreleased

@steipete
steipete merged commit 6776c6c into main Sep 28, 2026
44 checks passed
@steipete
steipete deleted the perf/watch-bounded-sync-names branch September 28, 2026 06:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant