Skip to content

fix(native): offload staged file creation and publication - #1052

Merged
roboclaw-bot merged 2 commits into
mainfrom
roboclaw/fix-staged-file-async
Oct 31, 2026
Merged

roboclaw-bot merged 2 commits into
mainfrom
roboclaw/fix-staged-file-async

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

POSIX Root.write/Root.create returned promises while their staged-file open and publication still ran synchronously on the JavaScript thread. On shared storage under I/O contention, these calls stalled the Team Gateway main thread for 5–13 seconds, delaying liveness heartbeats and causing agent.wait timeouts.

Production evidence after the R9b symbol attribution deployment (2026-10-31):

  • 08:56:31Z: 13,006 ms stall, write@@openclaw/fs-safe:133 → publish@:340 → [native]; the native self sample carried 12,994.5 ms.
  • 08:56:40Z: 8,349 ms stall, runPinnedWriteNative@:76 → write@:133 → create@:116 → #prepare@:259 → [native] at staged creation.
  • Earlier 5–10 second profiles carried the same offsets. These identify the native staging/publication boundary; they are not per-syscall duration traces.

The owner calls are src/native-staged-file.ts:277 (createStagedFile) and :342/:344 (replace/no-replace rename) on v0.27.0. Creation uses openat(O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC, 0600); publication uses the existing retained-parent rename primitives. File and directory fsync already use asynchronous Node APIs. A separate small-buffer fast path used writeSync.

Dispatch staged creation and publication through the existing N-API AsyncTask/NativeTask pattern and use asynchronous writes for small buffers. Retain descriptors through rename settlement and all durability/verification fences so concurrent cleanup cannot close or recycle a worker's descriptors. Reuse the existing native primitives and JS-thread error conversion, preserving flags, atomicity, no-replace fallback provenance, permission checks and durability ordering. Public promise APIs are unchanged. Synchronous admission, metadata/permission checks, cleanup, and generic synchronous rename owners retain their existing contracts; this does not claim every filesystem operation is nonblocking.

Validation:

  • Real-binding regression: all three native dispatch cases fail with the v0.27.0 binding and pass with the rebuilt binding. With UV_THREADPOOL_SIZE=1, a real FIFO open holds the pool until a JS timer releases it; staged create/replace/no-replace must queue without blocking that timer. Two updated small-buffer cases also fail on base source and pass after the fix.
  • Extended the existing publish/cleanup concurrency proof across a delayed rename using the real binding; consolidated the former small-buffer cases. Net test growth is 44 lines, needed for the isolated real-binding FIFO fixture and lifetime proof.
  • Focused native/staged-write group: 356 passed, 3 skipped. Additional relevant consumer/security groups: 120 passed, 13 skipped. Both Rust staged-file tests passed; native-library clippy with warnings denied, TypeScript compilation, file-size/boundary lint and git diff --check passed.
  • An existing pinned-mutation link-count expectation fails on this host with both unchanged base source and the fix; recorded separately. Full local suites/build-all were prohibited by the host rules; exact-head CI supplies broad platform validation.
  • The initial CI native budget gate exposed its old synchronous resource expectation. Updated create/write to pin exactly two native tasks and one asynchronous write request, and warmed the default pool before measurement. Optimized-binding create/write budgets pass with every filesystem syscall count unchanged, including the no-openat2 mode.
  • Fresh committed-branch autoreview: Codex GPT-6.1 Sol, P0–P2, scoped-clean.

A changelog entry is included because CONTRIBUTING.md and docs/contributing.md require one for user-visible operational fixes. No version bump, tag, npm publication, or OpenClaw dependency bump is included. Maintainers must publish the next fs-safe patch through the documented protected-tag release flow before OpenClaw can consume this fix.

Requested by @steipete

Work sessions

Discussion, implementation and verification

Dispatch POSIX staged opens and atomic renames through native libuv tasks,
retain descriptor ownership through publication settlement, and keep small
buffer writes asynchronous under storage contention.

Co-authored-by: steipete <[email protected]>
@roboclaw-bot
roboclaw-bot requested a review from a team as a code owner October 31, 2026 09:12
@clawsweeper

clawsweeper Bot commented Oct 31, 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.

Pin the two native tasks and asynchronous content write in create/write
resource budgets. Warm the default libuv pool before syscall counting so
allocator CPU probes are excluded with the existing startup work. Preserve
all filesystem syscall counts exactly.

Co-authored-by: steipete <[email protected]>
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 Urgent regression or broken agent/channel workflow affecting real users now. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 31, 2026
@clawsweeper

clawsweeper Bot commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR moves POSIX staged creation and publication onto native workers and removes synchronous small-buffer writes.

Example: Root.create('config.json', '{}') runs on slow shared storage.

  • Before: Native staging and publication can block JavaScript timers.
  • After: Creation and publication queue on libuv workers while JavaScript timers can run.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful root-cause repair with meaningful native regression coverage, but two source-verifiable public lifecycle defects block merge.
Proof confidence 🦐 gold shrimp (3/6) The supplied maintainer-authored designation exempts ordinary live-proof gating; the body reports real-binding FIFO and lifecycle regressions, while its production profiles describe the pre-fix behavior.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Awaited filesystem writes stall the application's JavaScript thread under storage contention, delaying heartbeats and agent responses.
Reason: The reported released behavior and source establish a concrete operational problem, and the supplied maintainer direction authorizes this focused scheduling repair.

Merge readiness

⛔ Needs changes before merge - 3 items remain

Keep open: main still performs synchronous native staging I/O, and this useful fix introduces two publication-lifecycle regressions that need repair.

Priority: P1
Reviewed head: aae9366e11c707d65e8d88c08cafa1a86ae55161

Before merge

  • [P2] Snapshot overwrite policy before deferring publication (P2) - The new microtask passes the caller's original options object into #publish, which reads overwrite only later. With an existing final file, const options = { overwrite: false }; const pending = staged.publish('final', options); options.overwrite = true; now selects replacement rename and destroys the existing file; the base captured false synchronously and refused replacement. Capture the boolean during publish invocation and pass that captured value into the deferred operation.
  • [P2] Serialize assertCurrent behind pending publication (P2) - Calling const pending = staged.publish('final', { overwrite: false }); await staged.assertCurrent(); now resolves the assertion before the deferred publication starts, or while its rename is pending, because assertCurrent only checks the still-open stage. The documented lifecycle serializes calls in invocation order, and the base rejected this assertion after publication had consumed the stage. Join the pending publication before checking current state, and extend the delayed-rename test to assert this result instead of checking only cleanup settlement.
  • Explain or restore the original intent of Public lifecycle invocation ordering - d733275: feat(atomic): add retained-directory file staging #151 deliberately preserved invocation order; the new publication deferral leaves assertCurrent outside that ordering without explaining a contract change.

Findings

  • [P2] [P2] Snapshot overwrite policy before deferring publication — src/native-staged-file.ts:319-320
  • [P2] [P2] Serialize assertCurrent behind pending publication — src/native-staged-file.ts:315-320

Provenance

  • Public lifecycle invocation ordering changes intended behavior without addressing why it exists (d733275: feat(atomic): add retained-directory file staging #151 deliberately preserved invocation order; the new publication deferral leaves assertCurrent outside that ordering without explaining a contract change.)

Tests

  • Missing end-to-end proof: No after-fix shipped-package Root.write or Root.create run under storage contention is supplied; the reported real-binding regressions exercise primitive dispatch.
Agent review details

How this fits together

Root writes and advanced staged-file APIs pass content into a retained-directory owner, which creates a private file, writes and synchronizes it, atomically publishes it, and returns verified receipts.

flowchart TD
  A[Root or advanced API] --> B[Retained staging owner]
  B --> C[Native worker queue]
  C --> D[Descriptor relative filesystem operations]
  D --> E[Identity permissions and durability checks]
  E --> F[Publication receipt]
  B --> G[Cleanup after settlement]
Loading

Technical review

Best possible solution:

Keep worker dispatch in the existing staging owner while snapshotting publication policy at invocation and serializing assertCurrent with pending publication.

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

Current main directly executes native creation, rename, and small-buffer writes synchronously; the report supplies attributed production stalls and describes real-binding before/after regressions, but no target code was run during this review.

Is this the best way to solve the issue?

Offloading these operations through existing NativeTask and shared write owners addresses the remaining blocking calls, provided publication ordering and input capture retain their existing semantics.

Full review comments:

  • [P2] [P2] Snapshot overwrite policy before deferring publication — src/native-staged-file.ts:319-320
    The new microtask passes the caller's original options object into #publish, which reads overwrite only later. With an existing final file, const options = { overwrite: false }; const pending = staged.publish('final', options); options.overwrite = true; now selects replacement rename and destroys the existing file; the base captured false synchronously and refused replacement. Capture the boolean during publish invocation and pass that captured value into the deferred operation.
    Confidence: 0.99
  • [P2] [P2] Serialize assertCurrent behind pending publication — src/native-staged-file.ts:315-320
    Calling const pending = staged.publish('final', { overwrite: false }); await staged.assertCurrent(); now resolves the assertion before the deferred publication starts, or while its rename is pending, because assertCurrent only checks the still-open stage. The documented lifecycle serializes calls in invocation order, and the base rejected this assertion after publication had consumed the stage. Join the pending publication before checking current state, and extend the delayed-rename test to assert this result instead of checking only cleanup settlement.
    Confidence: 0.98

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 67dee5ef4c03.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test test/staged-file.test.ts test/staged-file-failures.test.ts test/staged-file-error-settlement.test.ts test/native-staged-file-responsive.test.ts
  • pnpm check
  • git diff --check

What I checked:

  • Current main retains blocking operations: The released base invokes staged creation and rename synchronously; its callback-free buffer path also selects synchronous writes up to 64 KiB. (src/native-staged-file.ts:277, 67dee5ef4c03)
  • Publication inputs are read after yielding: publish schedules #publish in a microtask, passes the original mutable options object, and leaves public assertCurrent independent of the pending publication task. (src/native-staged-file.ts:319, aae9366e11c7)
  • Documented lifecycle ordering: The public contract says concurrent calls serialize in invocation order and checks after successful publication reject. (docs/staged-file.md:106, aae9366e11c7)
  • Relevant native regression coverage: The FIFO fixture exercises real native dispatch with an occupied worker pool; the extended lifecycle test delays rename and checks cleanup settlement, but does not assert the intervening assertCurrent result. (test/staged-file.test.ts:267, aae9366e11c7)
  • Dispatch authority contract: Authority checks fence dispatch; already-dispatched I/O is explicitly non-revocable, while cleanup, permissions, and durability remain owned by the operation. (docs/root.md:174, aae9366e11c7)
  • Earlier performance tradeoff: perf(native): streamline retained staged publication #948 deliberately introduced the bounded synchronous buffer path to reduce overhead; this PR explains reversing that scheduling choice with production stall profiles. (src/pinned-write-input.ts:46, 70aa9f5b8d65)

Likely related people:

  • Peter Steinberger: Raw commit c0aa03b adds src/native-staged-file.ts:394 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c0aa03b408d2; files: src/native-staged-file.ts)

Review metrics

Metric Value Why it matters
Production and regression footprint Production +57/-40; tests and fixtures +151/-107 The modest production growth reuses existing native operations; most test churn adapts asynchronous bindings, with focused additions for worker dispatch and descriptor lifetime.

Labels

Label changes:

  • add P1: The report ties current released synchronous filesystem calls to multi-second event-loop stalls that disrupt gateway heartbeats and agent waits.
  • add merge-risk: 🚨 compatibility: Deferred publication changes public lifecycle ordering and can replace an existing destination after an invocation originally requested no replacement.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: The report ties current released synchronous filesystem calls to multi-second event-loop stalls that disrupt gateway heartbeats and agent waits.
  • merge-risk: 🚨 compatibility: Deferred publication changes public lifecycle ordering and can replace an existing destination after an invocation originally requested no replacement.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 31, 2026, 5:32 AM ET / 09:32 UTC.

@roboclaw-bot
roboclaw-bot merged commit b7dc2a9 into main Oct 31, 2026
63 of 64 checks passed
@roboclaw-bot
roboclaw-bot deleted the roboclaw/fix-staged-file-async branch October 31, 2026 09:42
@steipete

Copy link
Copy Markdown
Contributor

Independent verification of the merged repair at b7dc2a9763be7bfaafe9d67413a076f8aef73288 (same tree as reviewed head aae9366e11c707d65e8d88c08cafa1a86ae55161): exact-head CI 41188193244 succeeded, and a separate Codex review found no actionable P0–P2 issues.

Rebuilt base 67dee5ef and candidate native addons. The real-binding FIFO scheduling regression fails for create/replace/no-replace on base and passes all three on candidate. The four focused staging/input/durability suites pass 59/59 tests. Across all 20 candidate benchmark batches, synchronous content writes, fsyncs and native renames are zero; both asynchronous durability flushes remain. Each small baseline publication has one synchronous content write, native create and native rename. Metadata/permission/cleanup operations remain outside this change.

The committed measurement driver now accepts separate source-built package/native artifacts. The synthetic fixture has 62,000 files / 1,116,000,000 logical bytes on APFS. No real user data or database fixture was used; these file owners do not access databases. This is owner-level evidence, not a whole-Gateway or btrfs reproduction.

For 1 KiB Root.write with 100 ms injected IO delay (five single-write samples), timer responsiveness improves while the owner still waits for IO and durability:

Seam Base timer median ms Candidate timer median ms Base/candidate owner median ms
Content write 110.517 1.523 150.809 / 132.968
Native create 111.771 1.496 136.471 / 129.660
Native publication 114.710 1.351 123.519 / 129.419

Five interleaved A1/B/A2 timing passes, 50 warm-ups and 100 operations per batch; separate five A/B allocation passes. Medians below are batch means. The shared host was heavily loaded (peak 1-minute load 84), so these are not isolated throughput measurements:

1 KiB operation Main CPU µs A1 / A2 / B Total CPU µs A1 / A2 / B Elapsed ms A1 / A2 / B Allocation bytes A / B
Root.write 3,965 / 3,897 / 1,834 4,432 / 4,448 / 4,245 29.052 / 33.727 / 36.268 113,696 / 116,858
Root.create 3,277 / 3,204 / 1,885 3,585 / 3,544 / 5,060 26.467 / 29.434 / 40.300 101,195 / 101,352
fileStore.write 3,499 / 3,857 / 2,116 4,106 / 4,649 / 4,491 27.715 / 32.486 / 46.966 119,120 / 121,424

The blocking/count improvement is clear, but the Root.create total-CPU increase (+41–43%) and elapsed increases are real measured tradeoffs, not a claim of universal throughput improvement. This verification completed after the source merge; explicit acceptance or a quieter Linux comparison belongs in the release/dependency-uptake decision. No npm release or dependency bump was performed.

Runtime delta is net +17 LOC: existing native-task dispatch entry points and binding types, offset by deletion of the synchronous buffer shortcut/options. No cache, new manager, configuration, or schema.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P1 Urgent regression or broken agent/channel workflow affecting real users now. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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.

2 participants