Repository navigation
feat(atomic): add retained-directory file staging - #151
Conversation
Add stageFileInDirectory under advanced with one owner for exclusive preparation, identity checks, publication, abort cleanup, and disposal. Retain the original parent descriptor so moving its pathname cannot strand an otherwise owned unpublished temporary file. Share the lifecycle with POSIX native streaming writes. Keep unpublished contents private until the published entry is identity-checked, preserve native error provenance, and distinguish committed or uncertain outcomes from failures that still permit abort cleanup. The new API requires native support on Linux/macOS. Existing Windows and JavaScript fallback contracts remain intact. Application authorization, cooperative locking, rollback, expected-inode publication, and crash recovery remain outside this lifecycle. Add real-filesystem regressions, fault/lifecycle coverage, public API documentation, and native CI coverage without changing dependencies or publishing a package.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs real behavior proof before merge. Reviewed August 28, 2026, 2:48 AM ET / 06:48 UTC. ClawSweeper reviewWhat this changesThe PR adds native Linux/macOS retained-directory file staging so aborted writes can remove an unpublished temporary file after its parent directory moves. Merge readiness⛔ Blocked until stronger real behavior proof is added - 5 items remain Keep open for maintainer review: the exact-head implementation appears correct, has real native regression evidence, and adds a deliberate new public advanced API that needs acceptance rather than cleanup closure. Priority: P2 Review scores
Verification
Live VerificationCommand: Result: FAIL (failed) — step 1 Assertions:
How this fits togetherThe atomic-write subsystem prepares private files beneath guarded directories, then publishes or removes them. This change retains the original directory descriptor through that lifecycle so cleanup can still address it after pathname drift. flowchart LR
A[Caller content and directory] --> B[Retained directory owner]
B --> C[Private staged file]
C --> D{Publish or abort}
D -->|Publish| E[Identity-checked final file]
D -->|Abort| F[Cleanup in original directory]
Decision needed
Why: The implementation is narrowly scoped and documented, but exporting a new filesystem-security lifecycle creates a long-lived package contract that cannot be decided from correctness evidence alone. Before merge
Agent review detailsSecurityNone. Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Adopt the lifecycle only as a clearly advanced API with its retained-directory, non-CAS, and caller-coordination limits preserved in documentation and native regression coverage. Do we have a high-confidence way to reproduce the issue? Yes: the focused native regression moves a parent after stream staging and verifies original-directory cleanup plus replacement-directory preservation; it is source-reproducible from the exact head. Is this the best way to solve the issue? Unclear: retained directory descriptors are a narrow technical solution, but maintaining the new exported lifecycle is a product-contract decision for maintainers. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 9603da1bbfce. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
Share native writer admission and exact Unix child cleanup, remove the synchronous lifecycle queue and forwarding factory, and use standard POSIX coordinator disposal while preserving public receipts and Windows close semantics. Reduce net production growth by 76 lines without counting moves or removing protected behavior.
Use distinct nonzero numeric inode fixtures instead of assuming another file always has a different Number identity, and verify the injected stat is consumed. Preserve real replacement tests and production identity policy.
Optional staging methods describe the matching Windows binary, not a supported independently upgraded native ABI. JavaScript and native code ship as one package; runtime behavior and packed bytes are unchanged.
Land-ready proof and review dispositionFinal head: A fresh, independently authored source-blind consumer run passed 59/59 live cases on Node 24.20.0, macOS arm64. This used the packed native package and real filesystem operations, not repository mocks. Observed results included:
The artifact SHA-256 is C6 is deliberately partial/blocked in this black-box lane for nine internal fault categories: independent preparation write/chmod/sync/close failures, post-commit validation/sync failures, indeterminate rename, retained-resource close failure, and deterministic recycling of hidden descriptors. Those are not inferred from successful calls. The separate real-native fault-injection suite covers the corresponding owner-boundary handling. No CAS, atomic conditional unlink, arbitrary-name recovery, crash cleanup, or macOS-to-Windows/Linux extrapolation is claimed. Latest ClawSweeper checklist and maintainer decisionThe latest review of this exact head, reviewed at 06:48 UTC, has cleared the earlier mixed-binary compatibility finding. Its four before-merge items and optional rank-up move are addressed as follows:
For the resolved earlier finding: the loader is byte-identical to shipped Final validationCI: all 15 jobs passed, including Linux/macOS/Windows native and package checks, musl, and the Node 22/24 fallback matrix. Coverage, including Windows and merged thresholds, benchmarks, and CodeQL passed. Fresh isolated Codex review of the full branch and the comment-only clarification reported no actionable P0 findings; this is not an all-priority audit. Fresh local build/package commands: pnpm buildpnpm native:buildpnpm package:smokegit diff --check origin/main...HEADThe PR body retains the full regression/local command ledger, earlier Windows fixture correction, and scoped Rustfmt limitation. Production growth remains +623 rather than +699. This landing does not publish a version, adopt the dependency in OpenClaw, or absorb the separate Root mode-000 repair. |
|
ClawSweeper status: review started. I am starting a fresh review of this pull request: feat(atomic): add retained-directory file staging This is item 1/1 in the current shard. Shard 0/1. This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking. Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted. |
What Problem This Solves
Consumers aborting a native write after the actual parent directory was moved could leave an unpublished temporary file in the moved original. Directory guards correctly rejected pathname drift, but cleanup still resolved the old pathname. A canonical pathname or an identity receipt alone cannot retain authority to that original directory.
Consumers performing application checks between preparation and publication also lacked an exported lifecycle that retained this cleanup authority.
Why This Change Was Made
Add
stageFileInDirectory()to the existing@openclaw/fs-safe/advancedsurface, with one owner for exclusive preparation, identity checks, publication, cleanup, and async disposal. Direct-child native creation hands off its descriptor before fallible post-open checks; exact descriptor/name checks andunlinkatkeep cleanup attached to the original directory. POSIX native streaming writes reuse this owner instead of keeping a second pathname-only cleanup path.Unpublished contents stay at
0600until the published entry passes its identity fence. Publication is recorded before permission finalization and post-checks; errors retain that recorded outcome, including after closure. Known namespace failures are not mislabeled as uncertain I/O; genuinely indeterminate rename outcomes remain explicit.Footprint cleanup
The follow-up cleanup reduces net production growth from +699 to +623 lines: 76 fewer lines (10.9%), discounting moves. Native writers now share root/parent admission, and staging and clone/copy share exact Unix child-removal mechanisms. The unnecessary promise queue, forwarding factory, exception-driven internal cleanup transport, duplicate open flags, and hand-written POSIX coordinator disposal plumbing are removed. Synchronous lifecycle methods remain await-free and preserve invocation order; one finalizer records cleanup and closes resources once.
POSIX coordinator double failures use standard
SuppressedError, retaining both the operation error and disposal error with their receipts. Public staged preparation/cleanup mappings and cached errors are unchanged. Existing Windows leaf behavior and close policy remain distinct. Directory durability was deliberately not folded into staging: pathname-current durability checks and retained-original-directory cleanup are different contracts, with different identity/platform requirements. Combining them would need a larger policy abstraction or weaken a guarantee.User Impact
The new API accepts buffered contents and an existing directory or directory receipt. Its staged object exposes
assertCurrent(), explicit replace/no-replacepublish(),cleanup(), and async disposal. It exposes no raw descriptors, writable-path callbacks, arbitrary child removal, or parent creation/permission changes. See the API and guarantee documentation.The lifecycle is native-required on Linux/macOS and rejects before file creation when support is off, absent, or unavailable. Windows is explicitly unsupported for this new API. Existing Windows native writes, JavaScript fallbacks, and
pinDirectory().assertCurrent()/.sync()retain their contracts. Published mode000is supported without reopening the staged inode.Directory-relative cleanup is not expected-inode/CAS replacement or atomic conditional unlink. The recorded temporary name must remain owned and removal must remain permitted; arbitrary leaf-renaming recovery, permission-revocation recovery, and crash cleanup are not promised. Namespace success is not a crash-durability guarantee. Application authorization, checks, locks, fingerprints, and rollback remain caller-owned.
No dependency, version, or configuration changes; no package publication or OpenClaw dependency adoption.
Evidence
Regression and local proof
The original real-native stream-abort regression failed before the feature because an extra
.native.tmpremained in the moved original. It passes with retained-directory ownership, while original destinations and replacement-parent sentinels preserve bytes, modes, and identities. Additional red-to-green cases protect private-until-publication permissions, ordinary publication errors, and closed-stage outcome receipts.The cleanup's frozen source passed the full local gate: 1,243 tests passed, 112 skipped, across 108 passing and four skipped files. Focused native/adjacent proof passed 316 tests, five platform skips; additional lock/fsync siblings passed 27 tests, six platform skips. 25 Rust tests, strict Clippy, owned Rust formatting, documentation examples/site, export/package checks, and bundled package smoke passed. The cleanup's local source/build/test gates passed without timeouts, and no test deadline or assertion was weakened. Earlier feature-development full runs hit host-load timeouts; the successful serial gate and hosted runs are retained as historical evidence, not substituted for this cleanup's fresh run.
Fresh isolated Codex autoreview reported no actionable P0 findings at its default threshold. This is not an all-priority audit.
Local runtime: Node 24.20.0 on macOS arm64, pnpm 10.34.5, Rust 1.98.0. The unreleased host-native tarball has SHA-256
aa794e50a9cfa7e555cd00bfd09d65ca19eac9e38e01f250f54e1e96aa7caa46. Package smoke covers native loading, native-absent auto fallback, and required-mode rejection. No real service or production state was used.Commands:
VITEST_MAX_WORKERS=1 FS_SAFE_PAX_REQUIRE_NATIVE=1 pnpm test test/native-staging-regression.test.ts test/staged-file.test.ts test/staged-file-failures.test.ts test/native-integration.test.ts test/native-write-containment.test.ts test/native-archive-equivalence.test.ts test/native-publish-equivalence.test.ts test/private-directory.test.ts test/directory-durability.test.ts test/publish-file-failure.test.ts test/archive-pax.test.ts test/archive-pax-security.test.ts test/archive-pax-compressed.test.tsVITEST_MAX_WORKERS=1 pnpm test test/sidecar-lock-acquire-failure.test.ts test/sidecar-lock-regression.test.ts test/sidecar-lock-windows-denial.test.ts test/pinned-write-fsync.test.tscargo test --workspace --lockedFull-workspace Rustfmt remains blocked by inherited formatting differences in unchanged main PAX files (
native/src/tar_meter.rs,native/src/tar_meter_tests.rs,native/src/tar_pax.rs). The cleanup-owned Rust files pass the scoped check; unrelated files were not reformatted.Consumer proof
The independently authored consumer harness was replayed against the smaller package, rather than rewriting assertions to fit the refactor. 63 unchanged cases passed, covering payloads, private/final modes, moved parents/ancestors, sentinel preservation, substitutions, real permission failures, concurrent ordering, closed outcomes, native-off/absent rejection, and existing fallback writes. Only candidate hash/source-identity metadata was refreshed.
The original 4 MiB preparation observer moved the directory after preparation had completed: cleanup succeeded, but that attempt correctly remained untriggered for the preparation-failure phase. A separate bounded 64 MiB payload, with the same observer and assertions and no timeout changes or implementation hooks, moved the parent immediately after creation. Preparation rejected with
path-mismatch, removed its temporary entry from the moved original, and preserved the original destination plus both replacement sentinels. This completes the 64-case observable coverage. Both attempts remain recorded; no target defect was observed, no warnings were suppressed, fixtures were removed, and the candidate hash/primary native package remained unchanged. This is a replay of previously independent probes, not a newly authored source-blind review.Four internal fault categories remain outside black-box coverage: preparation I/O/mode/sync/close faults independent of drift, post-commit faults, indeterminate rename results, and close failure/deterministic descriptor recycling. The implementation-aware fault suite exercises those through controlled injection around real native operations. Its added coordinator cases retain both errors and verify the surviving file's bytes/private mode; clone/copy cleanup also has sibling proof.
Fresh pre-land live proof
A new independent source-blind consumer passed 59/59 live cases against the freshly built native package on Node 24.20.0, macOS arm64. It verified original-directory cleanup and sentinel preservation, private/final modes including
000, substitutions, real permission errors, lifecycle ordering, stale receipts, native-off/absence rejection, and continued existing fallback writes. All three separate 64 MiB observers moved the parent immediately after creation; preparation rejected and removed the original temporary file. A diagnostic-only repeat with ordinary Node warnings enabled also passed 59/59, with no captured warnings and empty stderr. Original attempts were preserved; no target defect or assertion change was needed.The live lane explicitly leaves nine internal fault categories partial/blocked rather than claiming full C6 coverage; the existing owner-aware native tests cover corresponding error handling. Final source clarification only changes the Windows-capability comment and produces a byte-identical entire tarball (all 450 files, including 135 runtime/binary files). All owned runtime fixtures and the secondary package were removed. Fresh full-branch and comment-only autoreviews reported no actionable P0 findings.
Final live evidence and disposition of the latest review checklist record the accepted advanced/non-CAS contract, exact current-base CI, and why a separately upgraded old native binary is not a supported package state. The latest review has cleared that earlier compatibility finding; no runtime fallback was added.
Windows coverage follow-through
The first cleanup head passed all 15 CI jobs, benchmarks, and CodeQL, but Windows coverage failed an existing synthetic secret-file identity mismatch test. Its guard and test were unchanged across the branch, main, and actual merge checkout. The failed run used Node 22.23.2, pnpm 11.24.0, and Vitest 4.1.11; its original identity values and spy consumption were not logged, so no particular collision or zero-ID incident is claimed.
The fixture assumed another file's default numeric stat necessarily differed. Distinct 64-bit IDs can round to the same JavaScript number. Both synthetic secret/secure-file mismatch fixtures now preserve real Stats shape/mode/type, inject an explicitly distinct nonzero inode using the existing archive-test idiom, and assert that the injection was consumed. Unnecessary second-file setup was removed; real rename/replacement regressions and all production policy remain untouched. Each focused native-required and native-off run passed 40 tests with one platform skip. Fresh review of this test-only correction also reported no actionable P0 findings. The tarball and production source are unchanged from the cleanup proof above.
Exact-head hosted proof
Final head
80340e2is green:Final native CI's checkout log pins merge
f015221b01ca55ca44ddf32b8d990808c198b53a, whose parents are current main9603da1bbfce5dc6ae8239296f1111f2da34339band final head80340e2448488ede3b24d767b6e96e0c75821603.LOC and scope
Counts use the original PR base
f88c3d1, split Rust test blocks out, and count moves as zero savings. No existing protected behavior/tests or public receipt fields were removed. The remaining positive production delta supplies the new retained-directory lifecycle, exact identity/native mechanisms, and explicit publication/cleanup outcomes; those are the capability, not compatibility scaffolding. No generated output is committed.The separately reproduced existing
Root.writemode-000outer-verification failure remains outside this PR's scope.src/root-impl.tsand the existingrunPinnedWriteHelperinput/result contract are unchanged by this cleanup. A separate follow-up is also recorded to preserve exact 64-bit Windows identities across native/Node comparisons; the synthetic-fixture correction does not claim to repair that pre-existing runtime precision limitation.CHANGELOG.mdupdated when release-relevant