Repository navigation
fix(tool): create files on volumes without no-replace renames, such as exFAT - #730
Merged
Merged
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
hakula139
force-pushed
the
fix/exclusive-create
branch
2 times, most recently
from
October 28, 2026 15:37
0d7209b to
d00f1c4
Compare
Creating a file staged a temporary copy and published it with tempfile's persist_noclobber, which renames with RENAME_EXCL (renameatx_np on macOS, renameat2 on Linux) and falls back to a hard link only on ENOSYS or EINVAL. A volume that supports neither, such as exFAT on macOS, returns ENOTSUP, so every write that created a file there failed with "Operation not supported". Open the new path with create_new instead. O_EXCL (CREATE_NEW on Windows, where std adds FILE_FLAG_OPEN_REPARSE_POINT) never replaces an existing entry, including a dangling symlink, and the kernel applies the umask and any default ACL, so the staged copy, the 0666 mode probe, and the stage checks for creation go away. The staging helpers stay for the Linux atomic replacement only. A failed write can now leave a partial new file, while no earlier content exists to lose. A write or sync error says a partial file remains and asks the model to read it before writing again, and the design pages record the tradeoff.
hakula139
force-pushed
the
fix/exclusive-create
branch
from
October 28, 2026 15:54
d00f1c4 to
9cc93b4
Compare
13 tasks done
hakula139
added a commit
that referenced
this pull request
Oct 28, 2026
## Summary Sessions lived in one JSON lines file per session, which the loader replayed and repaired on every resume, and two `ox` processes on one session interleaved their entries in the same file. Sessions now live in one SQLite database, `$XDG_DATA_HOME/ox/sessions.db`, and JSON lines remain only as the interchange form that `ox export` writes and `ox -r <file>` imports. This is PR 4 of the session storage redesign, following #714 and #719. - **Store:** rusqlite with bundled SQLite, so every platform gets the fix for the WAL-reset corruption bug that concurrent writers in separate processes can hit ([3.51.3](https://www.sqlite.org/releaselog/3_51_3.html)). WAL mode, `synchronous = NORMAL` with `checkpoint_fullfsync = ON`, a 5 s busy timeout, foreign keys, and `STRICT` tables. `NORMAL` survives a process crash, and power loss may roll back the last commits but leaves the file intact as long as each checkpoint reaches the disk in order, which macOS guarantees only under `F_FULLFSYNC`. The schema has three tables: `sessions`, with the head pointer and metadata; `messages`, immutable rows keyed by `(session_id, id)` whose composite foreign key makes "parents first, one session" a database invariant; and `usage`, one row per billed request. `PRAGMA user_version` versions the schema, and a per-session `format` column versions message content, so listings hide a session a newer build wrote. Each process opens the store once and hands it to the picker, `ox --list`, and `ox export`. Switching a fresh file to WAL upgrades a read lock to a write lock, which SQLite fails at once without calling the busy handler, so `open` holds an exclusive lock on `locks/sessions.db.lock` while it sets the file up. A store already at this revision opens without taking the write lock. A file whose header or schema SQLite cannot read fails with the recovery steps in order: quit every `ox`, run `sqlite3 .recover` while the WAL still sits beside the database, then move the database aside with its `-wal` and `-shm` files. The path in the steps is quoted. - **Writes:** the actor commits each batch in one `BEGIN IMMEDIATE` transaction on a blocking task. A fresh session gets its row with its first message. A failed commit rolls back and stops persistence for the rest of the process's session, with no retry, and later batches fail with `session persistence stopped after an earlier write failed`. Each ack carries a `WriteReport { failure, fork }`, which reports a failure once per session, except to archive, which reports every failure. - **Lazy fork:** a commit that moves the head compares the stored head with the one this process last committed or loaded. A different head means another process wrote since, so the commit inserts a fork with `forked_from`, the title, and the manual flag copied, copies the base chain since the last compaction with its message IDs unchanged, and writes the batch there. Usage stays in the source. The handle's live session ID and artifact directory follow the fork, so the next request's `x-claude-code-session-id` and the next tool call use it. The engine emits `Event::SessionForked`, which the TUI notes in chat while moving its status bar to the fork, the stdio drivers print to stderr, and the headless result reports as `session_id`. Listings label a fork `(fork of {id8})`. - **Liveness locks:** an open session holds a shared lock on `locks/{id}.lock`, and delete takes a non-blocking exclusive lock, refusing a session another process has open. `FileLock` gains `shared` and `try_exclusive`. - **Resume:** the loader walks the chain from the head with a recursive CTE to the nearest root, the session start or the last compaction, so compaction, rewind, and refused-turn rollback are head moves with no loader rules. The first-prompt title latch derives from the chain and a stored `title_manual` flag. - **Listing:** keyset-paged queries ordered by last activity, so the picker's pages never overlap. Prefix lookups use the primary key and match nothing for a GLOB metacharacter. The `--list` and picker message column shows `0` for a session without messages, the delete modal always shows the project, and truncation shortens the title before a fork label. - **Export and import:** `ox export <id-prefix>` writes the session record, then every message in commit order, then every usage record. `ox -r <file>` validates the session ID, the `forked_from` source ID, and the format on line 1 and parent order, names the failing line, and lands by which messages each side holds: it fast-forwards when the local head is among the exported messages, keeps the local copy when that holds the exported head, extends an existing fork that relates the same way, and otherwise creates a fork. Membership holds across compaction and rewind, where an ancestry walk stops at the compaction root. A session the import creates is filed under the importing host's project and working directory. An import that moves the head of a session another process has open makes that process fork at its next write. - **Removed:** the JSONL entry types, chain builder, and path layout, with their prerelease shims. The store starts empty and does not read the old `sessions/` tree, which the guide tells users they can delete. - **Tooling:** `scripts/check-leaks.sh` searches a `sqlite3 .dump` of the store, since a byte scan of the database can miss a value split across pages, and the dev shell adds `sqlite3`. The live harness reads sessions through `ox export`. - **Docs:** the persistence design is rewritten, and the sessions and headless guides, README, SECURITY, RELEASING (the stability surface and the two release fixtures, `.sql` and `.jsonl`), the testing conventions, and the design docs that referenced session files are updated. ### Measurements - `libsqlite3-sys` build on an M-series MacBook: dev 8.4 s with 241 MB peak RSS, release 25.6 s with 511 MB peak RSS. - Release binary on `aarch64-apple-darwin`: 13,547,952 bytes on main, 15,491,280 bytes on this branch, +1,943,328 bytes (+14.3%), with the JSONL code removed. ### Design notes - `find_head` returns `Option<Option<Uuid>>` (a missing session differs from one whose branch is empty) and carries `#[expect(clippy::option_option)]`, and `SessionState` carries `#[expect(clippy::struct_excessive_bools)]` for its independent lifecycle flags. - Fault injection uses triggers that raise `disk full`, which exercise the real rollback path. - The `/resume` picker's page worker has no cancel flag, since each page is one query, and a stale view's page is discarded when it arrives. - The session-format snapshot and round-trip tests live in `session::handle` `session_format`, next to the resume tests they share fixtures with. - First-run setup serializes on a lock file instead of building the store in a temp file and publishing it with `persist_noclobber`. tempfile publishes with a no-replace rename and falls back to a hard link only on `ENOSYS` or `EINVAL`, so on macOS exFAT, where the rename returns `ENOTSUP` (#730), the first run would fail. The liveness locks already need file locks in `locks/`, so the setup lock adds no filesystem requirement, and its name holds a dot, which no session ID can, so it cannot collide with a liveness lock. ## Test plan - [x] `store::schema` and `store::open_in`: two first runs racing through `SessionStore::open` create one schema, a set-up store opens while another connection holds a write, the first-run race repeated over 100 fresh directories (it fails within the first few races when the setup lock is released before `schema::open`), a store a newer build migrated opens untouched, per-connection pragmas including `checkpoint_fullfsync`, a damaged file's error naming the recovery steps, a table of SQLite codes that only `NOTADB` and `CORRUPT` count as damage, and on Unix `sessions.db`, `-wal`, and `-shm` are `0600` - [x] `store::load`, `store::listing`, `store::export`: chain and state reads, the first-prompt title latch table, usage across compactions, newer-format refusal, keyset pages without gaps, scope and archive filters, prefix lookups, an import table over new, behind, empty local branch, ahead, diverged, compacted on either side, and rewound exports, one fork extended across repeated diverged imports, a second fork for an export no existing fork relates to, imported sessions filed under this project, line-named import errors including a `forked_from` that is no session ID, and an import forking an open handle - [x] `session::state` `lazy_fork`: the six-scenario table from the design, the copied chain since the last compaction with IDs, title, and manual flag kept, usage left in the source, both locks, a fork from an empty branch, and a stale finish leaving the source's snapshots alone - [x] `session::actor`: a failed commit surfaces once except to archive, the fork rides on the first head-moving ack, and commands queued behind the first commit in order - [x] `session::handle` `session_format`: snapshots of the SQL dump and the export of a session holding every row kind, an import of that export reproducing the same rows, and a resume of the dump this build writes - [x] Engine: two engines on one store, where another engine's prompt makes the stale one fork when it records its next prompt, emits `SessionForked` once, and writes later records to the fork, whose ID both of that turn's requests and its tool call carry. A second test moves the head from a second handle during a tool call, so the round's commit forks mid-turn: the forked round's request carries the source ID, while the next round in the same turn, or the auto-compaction summary and the rounds after it, carry the fork's ID, and the next tool call sees the fork's ID and artifact directory - [x] Frontends: the TUI fork notice snapshot with the status bar's new ID, the picker's fork label, the stdio fork notice ordering, the headless result's `session_id`, and `crates/ox/tests/cli.rs` running `ox export` into a file, then `ox -r <file>` headless in a fresh data dir, plus an archived import unarchiving with a note and a non-export file failing by name - [x] Live tests through an Anthropic-compatible gateway (`OX_LIVE=1 cargo live`): 5 passed, including `--resume` and auto-compaction read back through `ox export` - [x] `cargo mutants` over `session::store` before the review fixes (145 mutants): 73 caught, 27 timed out, 40 unviable, and 5 missed. New tests now fail on the `now_millis` and fork `created_at` mutants, and the lock-file `NotFound` check moved into an `ignore_missing` helper with its own test. The timeouts are engine `run` tests whose `next_matching` waits for an event a broken store never sends, so they hang until the timeout instead of failing - [x] `cargo fmt --check`, `cargo build`, `cargo clippy --all-targets`, `cargo clippy`, and `cargo doc --no-deps`: pass - [x] `cargo llvm-cov`: 3453 tests pass with 99.19% line coverage - [x] `cargo deny check`: pass, with no new duplicate crates - [x] `pnpm format`, `pnpm lint`, and `pnpm spellcheck`: pass Uncovered changed lines are `?` propagation of SQLite and I/O errors, `unreachable!` arms, the fixture loop that has no fixtures until `v0.1.0`, the TUI startup wiring, and the migration's revision recheck under `BEGIN IMMEDIATE`, which finds the schema already created only when a writer outside the setup lock, such as another SQLite client, set it up first. The TUI fork notice and picker were checked through snapshots, not in a live terminal.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
On a volume that supports neither a no-replace rename nor hard links, such as an exFAT drive on macOS, every
writethat created a file failed with "Operation not supported", while edits of existing files worked. Creation staged a temporary copy and published it with tempfile'spersist_noclobber, which renames withRENAME_EXCL(renameatx_npon macOS,renameat2on Linux) and falls back to a hard link only onENOSYSorEINVAL, so theENOTSUPsuch a volume returns ended the call. New files are now created with an exclusive open, sowritecreates files on those volumes too.createopens the path withOpenOptions::new().write(true).create_new(true), then writes and syncs it.O_EXCL(CREATE_NEWon Windows) never replaces an existing entry, including a dangling symlink, which the existingcreate_new_refuses_existing_entries_and_dangling_linkstest pins on every platform. std already addsFILE_FLAG_OPEN_REPARSE_POINTto acreate_newopen on Windows, so the open skipsopen_no_follow, whose Windows reopen would fail withAlreadyExistsafter the first open had created the file. The kernel applies the umask and any default ACL itself, so the.ox-mode.probe that computed the creation mode is gone, along with the staged copy, its byte recheck, and its name check for new files.... A partial file remains. Read it before writing again., so the model knows why a retriedwriteasks it to read the file first. Removing the file instead would need an identity check followed by an unlink, which leaves a window where a file another process put at the name gets deleted. Staging bought atomic publication of a file nobody had yet, which did not justify a code path that fails outright on common removable media.file-mutation.mdrecords this as the design decision New files trade crash atomicity for portability.staged_fileandverify_name, now compiled on Linux only, and its stage tests keep their existing-file cases.concurrent_create_is_never_replacedis deleted, since the race it injected between staging and publication now falls inside the one exclusive open, whichcreate_new_refuses_existing_entries_and_dangling_linkscovers.refuses_directory_suffixed_new_paths_before_preparationmoved frommod write_withintomod writeasrefuses_directory_suffixed_new_paths, sincecreateno longer takes checkpoints.left_partial_filegets a test of its message and error kind.docs/design/file-mutation.mddescribes the exclusive open, and its design decisions now separate new files from the Linux atomic path and record that creation, like an in-place write, can leave partial content.Rebased onto #720, which moved the stage checks into
seal, now compiled on Linux only with the rest of the staging. Part of the tool design review. Replacing existing files in place on every platform follows in a separate PR.Test plan
cargo fmt --check: pass.cargo build: pass.cargo clippy --all-targets: pass.cargo clippy: pass.cargo doc --no-deps: pass.cargo llvm-cov: pass, 150,386 lines at 98.85%. The 29 changed coverable lines are all covered, by the lcov estimate.cargo deny check: skipped, since no dependency changed.pnpm format,pnpm lint,pnpm spellcheck: pass.commit::write(path, b"hello", None)on the mounted volume failed onmainwithOs { code: 45, message: "Operation not supported" }and passed on this branch, where a follow-up edit of the same file also succeeded. The scratch test is not committed, since a disk image cannot be built inside the hermetic test suite.Limits: this host ran the macOS paths only. The Linux-gated stage tests and the Windows
CREATE_NEWpath run in CI. No hermetic test fails a write after the open, soleft_partial_fileis tested directly and its call site runs only on the success path.