Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,19 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo clippy --workspace --all-targets --release -- -D warnings
- run: cargo test --release --workspace --no-fail-fast

windows:
runs-on: windows-latest
timeout-minutes: 90
env:
RUST_BACKTRACE: 1
steps:
- run: git config --global core.autocrlf false
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.92.0
components: clippy
- uses: Swatinem/rust-cache@v2
- run: cargo clippy --workspace --all-targets --release -- -D warnings
- run: cargo test --release -p ferro --no-fail-fast
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

146 changes: 136 additions & 10 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ of `T`, and all earlier versions stay readable.
and `history_of_range`.
- `watch.rs`: `Watcher<T>`, `Closer<T>` and the per-branch feed behind them.
- `reclaim.rs`: the copy into a new generation, which `Db::compact` and `admin::compact` share.
- `platform.rs`: the file calls that differ between Unix and Windows, described under Windows.
- `sync.rs`: `Have`, `Bundle`, and `Db::pull`, `push` and `receive`, which copy a branch between files.

## Objects and links
Expand Down Expand Up @@ -642,7 +643,8 @@ itself that it reached the disk whole. A commit does this:

In `Durability::Fsync` the superblock is written only after its frame is durable, so it anchors
itself and never names anything a crash can lose, and the next fdatasync carries it to disk. A crash
leaves it at most one sync behind.
leaves it at most one sync behind. On Windows every fdatasync here is a `FlushFileBuffers`, as
described under Windows.

Open picks the valid slot with the highest sequence and scans forward from its anchor. A frame
counts only if its magic, sequence (the previous one plus 1), end offset and check are all right,
Expand Down Expand Up @@ -857,9 +859,9 @@ voluntary switch with no watchers and one with 8 or 32.
A `Snapshot<T>` keeps its version readable for as long as it is held, even past pruning, and so
does any `Map` or `Table` cloned from it, and a `Log` or `History` handle. All of them hold the
`Store`, and so the open file, but not the writer lock. The lock is a `flock` on the writer's file
descriptor, and closing a writer's store, when the last `Db` handle drops or a cycle retires a
generation, truncates the reservation and then unlocks, in that order, so a new writer can open while
they live. They read what they read before. The new writer's open truncates only past the last
descriptor, or on Windows a one-byte `LockFileEx` range on its handle, and closing a writer's
store, when the last `Db` handle drops or a cycle retires a generation, truncates the reservation
and then unlocks, in that order, so a new writer can open while they live. They read what they read before. The new writer's open truncates only past the last
valid frame, and every published object lies before it. It appends after that, and a cycle writes a
new file and renames it over the path, so the old inode stays whole for whoever holds it. A closed
store writes nothing more, and a second close does nothing, so it never truncates under the new
Expand Down Expand Up @@ -2166,8 +2168,8 @@ is larger, so the copying stays proportional to what was written.
3. Sync, with no lock, so the pause does not pay for it.
4. Swap, under the `tip` mutex. This is the only pause. Wait for queued commits, copy what is left,
write both superblock slots and sync. Open the new file, which takes its writer lock, and read
every branch's tip and root from it. Rename it over the old one, sync the directory, and rebind
every branch.
every branch's tip and root from it. Rename it over the old one, sync the directory (on Windows,
flush the renamed file), and rebind every branch.
5. Retire, with no lock. Clear the old generation's cache. Its file goes when the last handle does.

The new file continues the frame sequence, so group commit tickets stay in order. It has no frames
Expand Down Expand Up @@ -2211,8 +2213,8 @@ with `Error::StalePointer` if it is not there. A pointer read back from the curr
fine, because the copy rewrote it. One held in memory across a cycle is refused.

A read-only handle keeps its view, in the old file if need be, and `refresh` notices that the path
names a new inode, opens it, and rebinds. Its watchers fire only if the version moved. A process that
never refreshes never fails, and holds the old file open instead.
names a new inode, or a new file index on Windows, opens it, and rebinds. Its watchers fire only if
the version moved. A process that never refreshes never fails, and holds the old file open instead.

### Crashes

Expand All @@ -2227,8 +2229,9 @@ commits yet.

A failed copy, a full disk or a failed rename removes the temp file and reports the error from
`Db::compact` or in `Space::last_error`, and commits never notice. A store poisoned while a cycle
copied stays poisoned, because the swap checks first. The new file takes the old one's mode and owner,
and a path through a symlink stays a symlink.
copied stays poisoned, because the swap checks first. On Unix the new file takes the old one's mode
and owner, and a path through a symlink stays a symlink. Windows changes how the rename and its sync
work, but not this order, as described under Windows.

### Measurements

Expand Down Expand Up @@ -2312,6 +2315,129 @@ in a private copy of the refs and needs no user types. The copy is iterative, be
deep as the number of commits. A read-only handle follows it on `refresh` the same way it follows a
cycle.

## Windows

`platform.rs` holds everything the store asks of the OS that differs between Unix and Windows:
positioned reads and writes, the writer lock, the identity of a file, a reader's sync, the directory
sync and the owner of a new generation. The rest of the store is shared.

### Reads, writes and the lock

Positioned I/O loops over `seek_read` and `seek_write`, which can return short counts as `pread`
and `pwrite` can. They also move the handle's file pointer, which nothing reads. Windows serialises
requests on a handle opened without `FILE_FLAG_OVERLAPPED`, which `std` never sets, so readers in one
process queue behind each other and behind frame writes, where `pread` lets them run side by side.
That costs throughput, not correctness.

`File::lock` would shut readers out. On Windows it is `LockFileEx` over the whole file, and Windows
byte-range locks are mandatory: any other handle, in this process or another, fails to read a locked
range with `ERROR_LOCK_VIOLATION`, so no read-only open could read beside a writer. The writer lock is
`LockFileEx` on the single byte at offset 2^62 instead, past the end of any real file, exclusive for
a writer and shared for a reader's scan, and always with `LOCKFILE_FAIL_IMMEDIATELY`, so it behaves
as `try_lock` does. A lock belongs to its handle, so a second writer in the same process conflicts,
as with `flock`, and closing the handle releases it. `Store::close` unlocks explicitly, because
Windows documents that it releases the locks of a process that dies after a delay that "depends upon
available system resources", so a writer that opens right after another was killed can get
`Error::Locked`.

The identity that `open_locked` checks after locking, and that `refresh` compares to notice a cycle,
is the 64-bit file index from `GetFileInformationByHandle`, read through a handle opened with no
access rights, as `std::fs::metadata` does. `std` keeps the index behind the unstable
`windows_by_handle` feature. On NTFS it is unique on the volume and survives a rename, which is all
both checks need. ReFS ids are 128 bits, and this 64-bit index is not guaranteed to tell two files
apart there.

### Durability

`sync_data` and `sync_all` both call `FlushFileBuffers`, which writes the file's cached data and
metadata and then flushes the device's write cache. Every commit therefore pays for an fsync, not an
fdatasync, and the durability point does not move: once the flush returns, the frame survives a
power cut, unless the disk ignores flushes or Windows was told not to send them ("Turn off Windows
write-cache buffer flushing on the device"), the same caveat as a Linux disk mounted without
barriers.

The flush needs a handle with write access. A read-only open that has to sync the frames a dead
writer left, as described under File format and durability, first checks that the path still names
its file. If it does, the reader opens the path for writing and flushes that. A process that may not
write the file gets `PermissionDenied` there, rather than reading frames that a power cut could
still take back, and opens normally once a writer has recovered the file. If the path names another
file, a cycle replaced this one and there is nothing to sync. A writer lets go of a generation only
after the rename that replaced it is durable, so no crash names it again, unless the writer died or
poisoned between the rename and its flush. Even then, `Durability::Fsync` synced every frame before
the swap, and `Buffered` may lose commits by contract. The reader keeps the old view, and its next
`refresh` moves to the new file.

The reader used to reopen its own file with `ReOpenFile` instead. That failed with access denied
whenever it had opened the path just before a swap and taken the lock just after the writer retired
the old file, because Windows refuses every new handle to a file that has lost its name. Checking
the path also means the reader never needs write access to a file that is not the database any more.

Windows has no directory sync. A directory opens only with `FILE_FLAG_BACKUP_SEMANTICS`, and nothing
documents what `FlushFileBuffers` does to one. Where Unix syncs the parent directory, after creating
a file and after a cycle's rename, Windows opens the path for writing and flushes the file it names.
NTFS logs a create or a rename as one transaction in its metadata journal, so after a crash the name
points at the old file or the new one, never at neither. The rename also changed the renamed file's
own record, and ferro relies on a flush of that file committing the journal through the rename.
PostgreSQL's `durable_rename` relies on the same thing, since it too skips the directory on Windows
and flushes the file under its new name, but no Win32 document promises it. With the directory sync
read as this flush, the argument under Reclamation holds unchanged: writers stay paused until it
returns, and a failed flush poisons the store. FAT32 and exFAT keep no journal and are not
supported.

### Renaming over an open file

A cycle renames a new file over one that is still open, since the old generation stays open for
every snapshot, `Log` and follower that holds it, and Windows normally refuses that. It works when
two things hold. Every handle on the file must share delete: `std` opens files with
`FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE` unless told otherwise, and ferro never
tells it otherwise. And the rename must use POSIX semantics. `platform::rename` opens the new file
with `DELETE` access and calls `SetFileInformationByHandle(FileRenameInfoEx)` with
`FILE_RENAME_FLAG_REPLACE_IF_EXISTS | FILE_RENAME_FLAG_POSIX_SEMANTICS`, which Windows 10 1607 and
later accept where the file system supports it, as NTFS does. Only when that call is refused as
unsupported does it fall back to `std::fs::rename`. That tries `MoveFileExW` first, which an open
target refuses, and today retries with the same POSIX rename, but `std` documents that its choice of
calls may change, so ferro makes the call itself. The name then moves to the new file at once, and
the old file loses its name but stays whole for every handle until the last one closes, as an
unlinked inode does on Unix. Snapshots keep reading the old generation, its space comes back when
the last of them drops, and `refresh` finds a new file index at the path. `admin::compact` renames
the same way.

An open of the path that races the rename can still fail, which on Unix it cannot. If the lookup
found the old file just as it lost its name, Windows refuses the open with access denied, because
that file is now waiting to be deleted. `canonicalize` opens the path and then asks the handle for
its name, so if the handle reached the old file it fails with not found. Both last only for the
instant of a swap, after which the path names the new file. So on Windows every open of the path,
and the `canonicalize` in `Db::open`, retries those two errors up to 20 times a millisecond apart,
and a real permission error is reported about 20 ms late. CI found this: a reader opening in a loop
beside 60 cycles failed in about one run in two, and a probe saw about one `canonicalize` in 80
fail and one read-only open in 150.

If either does not hold, because another program holds the file open without `FILE_SHARE_DELETE` or
the file system has no POSIX rename, the rename fails before anything has changed. The cycle then
fails like any failed rename: the temp file goes, the error lands in `Db::compact` or
`Space::last_error`, commits carry on in the old file, and the next trigger tries again. Nothing is
lost, but the file does not shrink. The cycle is the retry, so the rename does not loop on its own,
which would hold the `tip` mutex and stall commits.

Two other designs were weighed. Generation-numbered files, with a small file naming the current
one, never rename over an open file and work on any file system, but the path would stop being the
database, so copying or backing up one file would no longer work, and the small file needs its own
atomic, durable update, which is a rename again. Deleting the old file and then renaming the new one
into place needs no POSIX semantics, but a crash between the two leaves no database at the path.

A new generation keeps the old file's read-only attribute, which is all `set_permissions` carries on
Windows, and takes its ACL from the directory rather than from the old file. The owner is not
copied.

### Tests

CI runs the library's tests on `windows-latest`. Tests that interpose libc symbols through `dlsym`
(`fdatasync`, `fsync`, `pread64`, `pwrite64`, `rename`, `clock_gettime`), run a child under `sh`
with `ulimit -f`, kill or abort a child process, or make symlinks or check mode bits are
`#[cfg(unix)]`. The traced crash simulations replay ferro's own writes and run on both. So on Windows
failed syncs, failed renames and process death go unexercised, and as on Unix, power loss was never
tested on hardware.

## Schema evolution

The derive macro writes structs as `(tag, length, payload)` fields, where the tag is a 16-bit
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,13 @@ including caveats about sled, are in `benchmarks/compare/RESULTS.md`.
This is an experiment, not a production database.

- The file format is not stable and may change without migration.
- It runs on Unix only.
- It runs on Unix and Windows. On Windows the file must be on NTFS: a reclamation cycle renames the
new file over one that snapshots still hold open, which needs POSIX rename semantics, and Windows
cannot sync a directory, so the rename is made durable by flushing the renamed file, which relies
on the NTFS journal. Every sync is a `FlushFileBuffers`, which flushes metadata too, like fsync
rather than fdatasync. Performance on Windows was never measured, and CI skips the tests that
intercept libc calls or kill processes there, so failed syncs and process death are tested on Unix
only.
- A single-key commit writes about 3.5 KB at this size, so batch related changes into one commit.
Secondary indexes add to that. Without retention the file only grows.
- A reclamation cycle copies everything retained, so it needs that much free disk, and reads that
Expand Down
29 changes: 26 additions & 3 deletions ferro-bench/src/bin/delta.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashMap;
use std::fs::File;
use std::os::unix::fs::FileExt;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
Expand All @@ -14,8 +14,24 @@ use ferro::{Db, Durability, Map, Options, Ptr, hash_of};

const FRAME_BYTES: usize = 68;

#[cfg(target_os = "linux")]
struct Counter(Option<i32>);

#[cfg(not(target_os = "linux"))]
struct Counter;

#[cfg(not(target_os = "linux"))]
impl Counter {
fn instructions() -> Counter {
Counter
}

fn read(&self) -> u64 {
0
}
}

#[cfg(target_os = "linux")]
impl Counter {
fn instructions() -> Counter {
let mut attr = [0u64; 16];
Expand All @@ -40,6 +56,12 @@ impl Counter {
}
}

#[cfg(not(unix))]
fn cpu_ns() -> u64 {
0
}

#[cfg(unix)]
fn cpu_ns() -> u64 {
let mut now = libc::timespec {
tv_sec: 0,
Expand Down Expand Up @@ -231,9 +253,10 @@ struct Framed {
parts: Parts,
}

fn frame_of(file: &File, start: u64, end: u64) -> Framed {
fn frame_of(mut file: &File, start: u64, end: u64) -> Framed {
let mut frame = vec![0u8; (end - start) as usize];
file.read_exact_at(&mut frame, start).unwrap();
file.seek(SeekFrom::Start(start)).unwrap();
file.read_exact(&mut frame).unwrap();
let recs = records(&frame, start);
let n = recs.len();
assert!(n >= 4, "a commit frame holds at least four records");
Expand Down
22 changes: 22 additions & 0 deletions ferro-bench/src/bin/tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,24 @@ use booking::seed::{Plan, seed};
use booking::{BookingError, Hotels, HoldRequest, Reservations, Why};
use ferro::{Db, Durability, Options};

#[cfg(target_os = "linux")]
struct Counter(Option<i32>);

#[cfg(not(target_os = "linux"))]
struct Counter;

#[cfg(not(target_os = "linux"))]
impl Counter {
fn instructions() -> Counter {
Counter
}

fn read(&self) -> u64 {
0
}
}

#[cfg(target_os = "linux")]
impl Counter {
fn instructions() -> Counter {
let mut attr = [0u64; 16];
Expand All @@ -33,6 +49,12 @@ impl Counter {
}
}

#[cfg(not(unix))]
fn cpu_ns() -> u64 {
0
}

#[cfg(unix)]
fn cpu_ns() -> u64 {
let mut now = libc::timespec {
tv_sec: 0,
Expand Down
3 changes: 3 additions & 0 deletions ferro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ quick_cache = "0.6"
thiserror = "2"
xxhash-rust = { version = "0.8", features = ["xxh3"] }

[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_WindowsProgramming"] }

[dev-dependencies]
parking_lot = "0.12"
proptest = "1"
Expand Down
4 changes: 2 additions & 2 deletions ferro/src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::db::{Commit, Refs};
use crate::error::{Error, Result};
use crate::log::Closures;
use crate::map::Map;
use crate::reclaim::{Copier, Roots, sibling, sync_parent};
use crate::reclaim::{Copier, Roots, rename, sibling, sync_parent};
pub use crate::reclaim::{Compacted, Reclaim, Space};
use crate::store::{Store, StoreOptions};

Expand Down Expand Up @@ -258,7 +258,7 @@ pub fn compact(path: impl AsRef<Path>, keep: Keep) -> Result<Compacted> {
let refs = load_refs(&store, Some(head))?;
let temp = sibling(path);
let result = write_copy(&store, &refs, keep, &temp, before_bytes).and_then(|mut report| {
fs::rename(&temp, path)?;
rename(&temp, path)?;
sync_parent(path)?;
report.before_bytes = before_bytes;
Ok(report)
Expand Down
Loading