Skip to content

perf: make metadata observations synchronous inside async hot paths - #238

Merged
steipete merged 2 commits into
mainfrom
perf/sync-metadata-hops
Sep 7, 2026
Merged

steipete merged 2 commits into
mainfrom
perf/sync-metadata-hops

Conversation

@steipete

@steipete steipete commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Async filesystem hot paths spent 50–70% of profiled wall time waiting for libuv metadata round-trips. On the profiling machine, lstat cost about 14 µs asynchronously versus 1.4 µs synchronously. This change performs metadata observations synchronously inside async operations, while open, data reads/writes, fsync, rename, directory creation, unlink, and close remain asynchronous.

Every existing containment, identity, symlink, hardlink, mode, retry, and publication check stays in its original order. Awaited production test hooks stay in place. The path resolution result does not carry a final stat, so the independent pre-open observation remains. Existing-ancestor resolution retains its lstat-based missing/error behavior rather than adopting the sync API's existsSync semantics.

Changes by file

  • root-path.ts, root-path-existing.ts, root-path-symlink.ts, symlink-parents.ts: synchronous lexical traversal and symlink/ancestor observations, with existing async signatures and error mapping.
  • root-context.ts, path-policy.ts, root-paths.ts, absolute-path.ts: synchronous root, canonical alias, and directory observations.
  • root-impl.ts, root-write-mode.ts, root-write-verification.ts: synchronous pre-open/path/canonical observations and fstat via retained descriptors, including mode inheritance and post-publication checks.
  • opened-realpath.ts, strict-file-identity.ts: synchronous observers in the existing async-shaped identity retry and descriptor/path resolution flows; parent enumeration remains async.
  • directory-guard.ts, guarded-mkdir.ts, directory-durability.ts: synchronous guard and directory receipt observations, used by the existing guarded mutation helpers; mkdir/open/fsync/close remain async.
  • pinned-write.ts, native-pinned-write.ts, replace-file-descriptor.ts, replace-file-temp-owner.ts, secret-file.ts: synchronous staging, parent admission, retained-fd, temp/path, and published-file observations.
  • regular-file.ts, file-store.ts, file-store-boundary.ts, file-store-prune.ts: synchronous read/exists and related store observations; JSON readers inherit the change through the guarded regular-file reader.
  • bounded-read.ts: read min(maxBytes, observed regular-file size) + 1 bytes in one initial async call. A short read is accepted only after a fresh same-fd size observation confirms that the bytes consumed cover the current file size; otherwise reading continues through the existing bounded streaming loop. This refines the proposed short-read shortcut because short regular-file reads are not necessarily EOF. Read-only adapters and non-regular/unknown-size inputs retain streaming behavior.
  • test/fs-call-budget.test.ts: separate async-hop budgets, updated total-call budgets, and counting of FileHandle.close own properties as well as prototype methods.
  • test/bounded-read.test.ts: one-read coverage for empty, small and multi-chunk-sized files, growth below/above the cap, partial reads before EOF, and custom/unknown-size adapters.
  • docs/reading.md, CHANGELOG.md: document brief synchronous metadata observations and asynchronous data I/O.

The explicit compatibility exception is custom replaceFileAtomic filesystem adapters: their public interface exposes only async metadata functions and FileHandles, so those observations remain async. The default Node backend uses synchronous observations. No mutation-metadata call was converted.

Async-hop and total-call budgets

Measured on macOS with native mode off, including FileHandle.close. Async counts include only fs/promises functions and FileHandle methods; synchronous observations are excluded. Total-call limits retain two calls of platform headroom; async limits are measured + 1.

Operation Async before Async after Async limit Total before/after Total limit
root.readBytes 13 3 4 13 / 14 16
readRegularFile 7 3 4 7 / 7 9
tryReadJson 8 3 4 8 / 8 10
replaceFileAtomic 17 8 9 18 / 18 20
writeJson durable:false 17 8 9 18 / 18 20
root.write 56 11 12 58 / 58 60
root.exists 5 0 1 5 / 5 7

Remaining read hops are open/read/close. Atomic replacement retains mkdir, two opens, two closes, writeFile, chmod, and rename. Root.write retains three opens/closes, writeFile, chmod, rename, and two durability syncs.

Interleaved A/B

Baseline: origin/main at 9ad2d5c, separately compiled with the same dependencies and prepared WASM artifact. Node 24.20.0 on macOS. The supplied harness alternates baseline/PR for five rounds and reports the best ms/op; 150 iterations per small case and 20 per 1 MiB case. The repository benchmark script is unchanged.

Native auto

mode=auto  (best of 5 rounds, ms/op)
root.write                 base   11.298  pr   11.320     -0% faster
root.write 1MiB            base   12.362  pr   12.288      1% faster
root.readBytes             base    0.232  pr    0.121     48% faster
root.readBytes 1MiB        base    0.757  pr    0.247     67% faster
replaceFileAtomic          base    0.647  pr    0.560     13% faster
writeJson durable:false    base    0.605  pr    0.511     16% faster
writeJson                  base   10.114  pr   10.454     -3% faster
tryReadJson                base    0.132  pr    0.076     42% faster
readRegularFile            base    0.102  pr    0.070     32% faster

Native off

mode=off  (best of 5 rounds, ms/op)
root.write                 base   13.936  pr   12.424     11% faster
root.write 1MiB            base   13.865  pr   13.851      0% faster
root.readBytes             base    0.236  pr    0.123     48% faster
root.readBytes 1MiB        base    0.726  pr    0.325     55% faster
replaceFileAtomic          base    0.604  pr    0.517     14% faster
writeJson durable:false    base    0.601  pr    0.533     11% faster
writeJson                  base   12.164  pr   12.995     -7% faster
tryReadJson                base    0.147  pr    0.090     39% faster
readRegularFile            base    0.121  pr    0.088     27% faster

The 40% readBytes target is met in both modes. tryReadJson reaches 42% in auto and 39% in off, just below the 40% off-mode target. replaceFileAtomic improves 13–14%, below the 30% target; its eight remaining async calls are listed above. Durability costs remain unchanged. The tables report the fixed five-round run after the earlier full-suite run finished.

Validation

  • pnpm exec tsc --pretty false: passed.
  • pnpm lint:file-size, pnpm lint:fs-boundary, pnpm docs:check, node scripts/check-pack.mjs, git diff --check: passed.
  • pnpm test:security: 226 passed, 5 files.
  • Final pnpm test --maxWorkers=4: 7,809 passed, 80 skipped, 2 known local failures; 231 files passed, 2 skipped, 1 failed. Both failures are in consumer-pnpm-lifecycle.test.ts, where this local launcher does not expose the expected pnpm lifecycle JavaScript CLI.
  • The local Node 24 stdin fixture needed explicit CommonJS mode to avoid a hang during the unrelated ClawSweeper dispatch test. A temporary PATH wrapper adds --input-type=commonjs only to no-argument Node invocations; file-based scripts and the library tests use the same Node runtime unchanged. The dispatch fixture then passed, including in the final full run.
  • The archive suite passed with --maxWorkers=1 and in the final full run. An earlier store-overlap run reported the existing fail-closed path-mismatch during concurrent replacement; isolated reruns and the final full run passed without changing that test or relaxing identity checks.
  • pnpm check reached the known local WASM build failure (missing wasm32-unknown-unknown Rust target). The prepared WASM artifact was restored; TypeScript and all remaining component checks were run explicitly as requested.
  • Independent Codex autoreview: scoped-clean through P2. The short-read finding was addressed with the fresh descriptor-size check and focused partial-read/overflow regressions.

Re-pointed race/fault tests

The following test files and shared fixture were updated to intercept the new synchronous observation. All scenarios and parameterized cases remain. Synthetic filesystem swaps inside synchronous spies now use synchronous fixture mutations. Async owner-release scenarios retain their barriers at the existing pre-resolution hook or async resolver wrapper; directory-preparation authority expiration is injected before the synchronous observation returns.

  • test/absolute-directory.test.ts
  • test/archive.test.ts
  • test/deepsec-regression.test.ts
  • test/deny-mutations.test.ts
  • test/directory-guard-exact-identity.test.ts
  • test/helpers/read-admission-identity.ts
  • test/json-durable-queue-batch-durability.test.ts
  • test/json.test.ts
  • test/move-path-authority.test.ts
  • test/native-write-mode-ownership.test.ts
  • test/new-primitives.test.ts
  • test/opened-realpath-observation.test.ts
  • test/opened-realpath.test.ts
  • test/regular-file-failure.test.ts
  • test/root-copy-read-identity.test.ts
  • test/root-directory-errors.test.ts
  • test/root-error-coverage.test.ts
  • test/root-path-store-coverage.test.ts
  • test/root-read-identity.test.ts
  • test/root-write-exact-identity.test.ts
  • test/root-write-inheritance.test.ts
  • test/root-write-lifetime.test.ts
  • test/root-write-reopen.test.ts
  • test/root-write-verification.test.ts
  • test/secret-directory-receipt.test.ts
  • test/secret-write-publication.test.ts
  • test/sibling-temp-directory-mode.test.ts
  • test/sidecar-lock-root-ancestry.test.ts
  • test/sidecar-lock-root-create-denial.test.ts
  • test/sidecar-lock-root-preopen-boundary.test.ts
  • test/sidecar-lock-root-resolver.test.ts
  • test/sidecar-lock-root-unlink.test.ts

@steipete
steipete requested a review from a team as a code owner September 7, 2026 01:23
@clawsweeper

clawsweeper Bot commented Sep 7, 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 6, 2026, 9:59 PM ET / September 7, 2026, 01:59 UTC.

ClawSweeper review

What this changes

The PR makes metadata checks synchronous within asynchronous filesystem operations, adds a size-based read optimization, and updates race tests, performance budgets, and documentation.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 4 items remain

This remains useful, distinct performance work, but the previously reported allocation defect is unchanged at the reviewed head.

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

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful performance work has convincing real-run evidence, but the persistent allocation defect limits patch readiness.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The supplied macOS Node 24 interleaved benchmark output exercises real Root, regular-file, JSON, and atomic-write entrypoints through the changed metadata and read owners, showing improved read latency in native auto and off modes; slow-mount responsiveness remains a separate merge-risk decision.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied macOS Node 24 interleaved benchmark output exercises real Root, regular-file, JSON, and atomic-write entrypoints through the changed metadata and read owners, showing improved read latency in native auto and off modes; slow-mount responsiveness remains a separate merge-risk decision.
Evidence reviewed 8 items Applicable repository policy: Read the complete root AGENTS.md and contribution/security guides. The policy treats filesystem boundaries and exported behavior as compatibility contracts. No nested AGENTS.md or maintainer-notes directory was found. Builds, tests, and target-bundled autoreview were not executed under the read-only review contract.
Persistent allocation defect: The first buffer is allocated from the entire observed file size, while the public helper reads from the handle's current offset. The EOF return retains that buffer through a subarray. Large files already at EOF therefore allocate and retain memory unrelated to the remaining content.
Re-review continuity: The comparison against the previous reviewed head returned no changes to either the bounded reader or its tests. The earlier allocation finding remains applicable; this is not a newly discovered finding.
Findings 1 actionable finding [P2] [P2] Cap the size-based initial read allocation
Security None None.

How this fits together

fs-safe checks untrusted paths and filesystem identities before applications read or modify files. These shared checks feed root-scoped operations, atomic writes, secret files, and file stores.

flowchart TD
  A[Application paths and file handles] --> B[Root and path checks]
  B --> C[Synchronous metadata observations]
  C --> D{Identity and containment valid?}
  D -->|No| E[Reject operation]
  D -->|Yes| F[Asynchronous data reads or writes]
  F --> G[Bounded results and publication checks]
Loading

Decision needed

Question Recommendation
Should synchronous metadata become the default for existing async APIs used on documented rclone FUSE mounts? Preserve async scheduling for now: Retain asynchronous metadata in existing APIs until a compatible performance approach or acceptable slow-mount responsiveness is established.

Why: Local throughput gains cannot determine the acceptable event-loop blocking tradeoff for existing consumers.

Before merge

  • [P2] Cap the size-based initial read allocation (P2) - The previously reported defect remains unchanged. These public helpers read from the descriptor's current offset, but stat.size is the entire file length. An already-consumed 1 GiB file with maxBytes: Infinity therefore allocates roughly 1 GiB before discovering EOF, and the returned empty subarray retains that backing buffer; the previous implementation needed only a 64 KiB scratch buffer. Cap the shortcut independently of file size, stream above that cap, and avoid retaining oversized buffers after EOF or truncation.
  • Resolve merge risk (P1) - Existing applications using rclone FUSE or other slow mounts can have their entire JavaScript event loop blocked by newly synchronous metadata calls; representative responsiveness evidence and acceptance of that scheduling change remain unresolved.
  • Complete next step (P2) - Repair the initial allocation and obtain a maintainer decision on synchronous metadata for existing slow-mount consumers, supported by representative responsiveness evidence or preserved async scheduling.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P2] [P2] Cap the size-based initial read allocation — src/bounded-read.ts:51-57
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test LOC production +41 net (+189/-148), tests +135 net (+470/-335) Production growth has a stated performance justification, with tests adapting fault injection and covering the read shortcut.

Merge-risk options

Maintainer options:

  1. Retain responsive metadata scheduling (recommended)
    Preserve asynchronous metadata behavior while landing only independently safe, bounded read improvements.
  2. Approve measured blocking costs
    Accept synchronous metadata only after reviewing slow-mount event-loop latency and documenting the operational tradeoff.

Technical review

Best possible solution:

Keep read allocations independently bounded and preserve responsive slow-mount operation unless maintainers explicitly accept the scheduling change with representative latency evidence.

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

Yes, from source for the PR defect: read an already-consumed large file with maxBytes set to Infinity; the shortcut allocates the full file size before discovering EOF. This was not executed, and current main uses the bounded streaming implementation.

Is this the best way to solve the issue?

No, not as submitted: the read shortcut needs an independent allocation cap, and default synchronous metadata needs an explicit slow-mount scheduling decision.

Full review comments:

  • [P2] [P2] Cap the size-based initial read allocation — src/bounded-read.ts:51-57
    The previously reported defect remains unchanged. These public helpers read from the descriptor's current offset, but stat.size is the entire file length. An already-consumed 1 GiB file with maxBytes: Infinity therefore allocates roughly 1 GiB before discovering EOF, and the returned empty subarray retains that backing buffer; the previous implementation needed only a 64 KiB scratch buffer. Cap the shortcut independently of file size, stream above that cap, and avoid retaining oversized buffers after EOF or truncation.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded performance improvement with a concrete allocation defect, without evidence of an urgent shipped regression.
  • merge-risk: 🚨 availability: Synchronous metadata moves potentially slow mount operations onto the JavaScript event loop for existing async callers.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The supplied macOS Node 24 interleaved benchmark output exercises real Root, regular-file, JSON, and atomic-write entrypoints through the changed metadata and read owners, showing improved read latency in native auto and off modes; slow-mount responsiveness remains a separate merge-risk decision.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied macOS Node 24 interleaved benchmark output exercises real Root, regular-file, JSON, and atomic-write entrypoints through the changed metadata and read owners, showing improved read latency in native auto and off modes; slow-mount responsiveness remains a separate merge-risk decision.

Evidence

What I checked:

  • Applicable repository policy: Read the complete root AGENTS.md and contribution/security guides. The policy treats filesystem boundaries and exported behavior as compatibility contracts. No nested AGENTS.md or maintainer-notes directory was found. Builds, tests, and target-bundled autoreview were not executed under the read-only review contract. (AGENTS.md:29, 5aaa0489f15d)
  • Persistent allocation defect: The first buffer is allocated from the entire observed file size, while the public helper reads from the handle's current offset. The EOF return retains that buffer through a subarray. Large files already at EOF therefore allocate and retain memory unrelated to the remaining content. (src/bounded-read.ts:51, 5aaa0489f15d)
  • Re-review continuity: The comparison against the previous reviewed head returned no changes to either the bounded reader or its tests. The earlier allocation finding remains applicable; this is not a newly discovered finding. (src/bounded-read.ts:51, 5aaa0489f15d)
  • Main and release behavior: Inspected the bounded reader at fetched main and v0.8.3: both use a scratch buffer capped at 64 KiB and lack the proposed initial size-based allocation. The introduced diff also confirms main still uses asynchronous metadata observations. No merged replacement is established by the supplied context; the supplementary GitHub search could not connect. (src/bounded-read.ts:6, 274292202089)
  • Real performance evidence: The complete supplied PR body, captured under sourceRevision 86bb0ccbe5c793c016b753086796b09a6108cba21061374bddd9fa975e75053b, reports interleaved real filesystem runs on macOS with Node 24.20.0 against baseline 9ad2d5c. Public Root, regular-file, JSON, and atomic-write entrypoints exercise the changed owners; small Root reads improve from 0.232 to 0.121 ms in native auto and 0.236 to 0.123 ms with native off. These results support the optimization but do not measure responsiveness on slow mounts.
  • Documented slow-mount use case: The writing guide explicitly supports rclone FUSE through the renameIdentity compatibility policy. The introduced synchronous metadata calls also run on that path; local operation-latency benchmarks do not establish how long unrelated timers and requests can be blocked by mount metadata latency. (docs/writing.md:322, 5aaa0489f15d)

Likely related people:

  • Peter Steinberger: 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.

  • Bound the initial allocation and cover large files at EOF, nonzero offsets, and truncation without retaining oversized backing buffers.
  • Resolve the default scheduling tradeoff for documented FUSE workloads through maintainer approval and representative responsiveness evidence.

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-07T01:26:20.047Z sha e25437b :: blocked before merge. :: [P2] Cap the size-based initial read allocation
  • reviewed 2026-09-07T01:47:33.623Z sha 32754e7 :: blocked before merge. :: [P2] [P2] Cap the size-based initial read allocation

@steipete
steipete force-pushed the perf/sync-metadata-hops branch from e25437b to 8b7a99a Compare September 7, 2026 01:40
@steipete
steipete force-pushed the perf/sync-metadata-hops branch from 8b7a99a to 32754e7 Compare September 7, 2026 01:43
Use realpathSync.native for observations converted from fs.promises.realpath so Windows short paths retain their expanded canonical spelling. Keep identity and durability checks unchanged, repoint fault injection and separate-process secret probes, and count both native and legacy realpath observations.

Validation: TypeScript, file-size and filesystem-boundary lint, docs, package checks, 226 security tests, 245 focused tests, and independent P2 review passed. Full single-worker suite: 7,984 passed and 81 skipped, with two launcher-specific failures subsequently passing with the exact pnpm 11.25.0 JavaScript CLI. Root-only npm and pnpm package smoke passed.
@steipete
steipete merged commit c516611 into main Sep 7, 2026
25 checks passed
@steipete
steipete deleted the perf/sync-metadata-hops branch September 7, 2026 02:08
steipete added a commit that referenced this pull request Sep 9, 2026
…ove paths (#248)

Complete the synchronous-observation rule from #238 across archive extraction, copy and publication, move, sibling staging, secure and secret reads, hashing, locks, queues, and directory-mode paths: lstat, stat, realpath (native semantics) and fstat via retained descriptors run synchronously; open, read, write, fsync, rename, mkdir, unlink and close stay asynchronous. Injected custom filesystem adapters keep their async metadata contract. Every containment, identity, hardlink, symlink, permission, ownership, deadline and publication check keeps its order; error codes are unchanged. Race and fault tests are re-pointed at the synchronous observation, including one mechanism spy in the security suite whose assertions are unchanged; the Windows hash-identity proof observes the synchronous checks. Async metadata calls in a 500-file extraction drop to zero (total async calls down 48-62 percent) and extraction wall time improves 24-43 percent in paired runs.
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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant