Platform layer
nucleus-platform
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
The only way any nucleus code reaches files, time or randomness (PLAN.md principle 4).
3.1 Interface
Platform—fs(),clock(),rng(),parallelism()(the threads work can usefully run on: the CPUs on the real platform, asked of the OS once, when it is made; 1 in the simulation).FileSystem—open(path, OpenMode),remove_file,rename(atomic replace),create_dir_all,list_dir(sorted names),exists,sync_dir.File— positional only, no cursor, all&self(shareable between threads):read_at,write_at,read_exact_at,write_all_at,sync,sync_order(the writes so far ordered before any later one, whatever the sync policy — a barrier on macOS,syncelsewhere and by default: for a sync whose writes a later full sync makes durable anyway),size,set_len.OpenMode—ReadOnly,ReadWrite,Create,CreateNew; none truncates.Rng::fill_unpredictable(buf)— the operating system’s generator on the real platform (UUIDs, tokens); the simulation’s seed in a simulation.Kv::random_bytes(§6.1) andCallContext::randomreach it.Clock—now()monotonic since platform creation,wall(),sleep(d)(the simulated clock advances bydat once and waits at most 1 ms of real time, so threads backing off on the simulation still spread out).Rng—next_u64,below,chance_ppm,fill_bytes. Not cryptographic.SplitMix64is the implementation everywhere.
Durability rule (enforced by the simulation): a write is visible at once
but durable only after File::sync; a directory entry change (create,
remove, rename) is durable only after sync_dir of its parent. A failed
sync means the unsynced writes are lost, even if a later sync
succeeds — callers must treat it as fatal for that data.
3.2 Real platform (real::RealPlatform)
std, but for one call. sync follows the platform’s SyncPolicy
(PLAN.md D17; RealPlatform::with_sync, the KV’s Options::sync, the
server’s --sync): Full is File::sync_data, which std implements as
fdatasync on Linux/d-os (a length change made durable, the file’s
times not — PostgreSQL’s and SQLite’s choice there; PLAN.md §M14.28 L0),
fcntl(F_FULLFSYNC) on macOS (verified in std’s sys/fs/unix.rs) and
FlushFileBuffers on Windows; Ordered, the
default, is the same except on macOS, where it is
fcntl(F_BARRIERFSYNC) — the writes before it reach the drive before any
after it, without flushing the drive’s cache, so files are never left
inconsistent and a crash of the process or the OS loses nothing synced,
while a power loss may lose the last syncs (as PostgreSQL’s and SQLite’s
macOS defaults). A file system without barriers gets the full sync.
That fcntl and macOS’s sysctlbyname("hw.memsize") are the crate’s
only unsafe code (std has neither call; barrier_sync,
real::physical_memory — the memory the process may use: the machine’s,
or a container’s cgroup limit below it, read from /proc and
/sys/fs/cgroup on Linux; None elsewhere). The simulation’s sync is the full one: a power loss
under Ordered leaves the files as a crash before the last syncs would,
which the simulation tests. Positional I/O is
pread/pwrite, on Windows seek_read/seek_write (std maps
ERROR_HANDLE_EOF to Ok(0)). sync_dir opens and fsyncs the directory
on POSIX (the full fsync: what fdatasync makes of a directory is not
specified; on macOS by the policy) and only checks that it exists on
Windows (directories cannot be opened as files there; NTFS journals
metadata). FileSystem::writes_in_place is true but on Apple’s systems:
APFS writes a changed block elsewhere (copy-on-write), so a synced
overwrite costs it more than an append (measured: 16 KiB written a small
commit against 10–11); the simulation answers by its seed (or
SimFs::set_writes_in_place), so the seeded tests run both ways. The
RNG seed comes from getrandom.
3.3 Simulated platform (sim::SimPlatform)
In memory, deterministic from SimPlatform::new(seed) while one thread
drives it.
- Two images per file, current (reads) and durable (survives a crash);
syncapplies the queued operations to the durable one. The namespace has the same two layers;sync_dirmakes one directory’s entries durable. - Crashes:
sim_fs().crash()now, orcrash_after_ops(n)— the n-th operation from now crashes instead of running and fails withSimFault::Crash;crash()cancels a scheduled crash. After a crash every old handle fails withSimFault::StaleHandle; the file system itself carries on, as after a restart. An entry whose parent directory did not survive is gone too. CrashMode:DropUnsynced(default) loses everything unsynced.Tornkeeps a random subset: each unsynced write survives, is lost, or survives in some of its 512-byte sectors (SECTOR_SIZE), never part of one; each length and directory change survives or not.Faults: per-million probabilities of read, write and sync errors (SimFault::Injected). An injected write error changes nothing; an injected sync error forgets the pending writes (“fsyncgate”).sim_fault(&io::Error)tells simulated failures apart from real errors.- Paths are component lists (
/a/b=a/b);..is refused; directories cannot be renamed. sim_clock().advance(d)(andclock().sleep(d)) is the only thing that moves time. Wall time starts at 2026-01-01T00:00:00Z.
3.4 Harness (harness)
harness::run(name, default_cases, |seed| …) runs a case per seed. Seeds
are fixed per test name, so cargo test is reproducible. On failure it
prints the seed and the command to rerun it; NUCLEUS_SEED runs one seed,
NUCLEUS_SIM_CASES changes the count.
3.5 Tests
tests/conformance.rs— the same assertions against the real OS (temp dir), the simulation and the file system in memory: I/O semantics, open modes, rename, directories, clock, RNG. Runs on every CI target.tests/sim.rs— durability, directory sync, rename atomicity, fsyncgate, injected faults, scheduled crashes, determinism, torn sectors, and a proptest property: after a torn crash every byte is either its last-synced value or one a later write put there. Checked against mutations of the crash logic (keeping unsynced writes whole, or in part): each fails a test.
3.6 In memory (memory::MemoryPlatform)
A database in memory as a product (§M14.23: :memory: in the embedded
edition): MemoryFs keeps each file as one byte vector, shared by the
file’s open handles (a removed or renamed file stays readable through a
handle opened before, as on POSIX) — no durable second image and no
faults, as the simulation has, so a database in memory costs what its
files hold (MemoryFs::bytes). sync and sync_dir do nothing (the
files go with the process); locks are exclusive per path while held;
writes_in_place is true. Time and randomness come from another
platform — MemoryPlatform::new() the machine’s (RealPlatform),
MemoryPlatform::with(p) any. tests/conformance.rs runs its
assertions against it too.
3.7 A pool of slots (slots::SlotPlatform)
The browser edition’s files (§M14.23): a browser opens an OPFS file for
synchronous access only in a worker and only by an asynchronous call,
which the synchronous engine cannot wait for mid-statement — so the host
opens a pool of files ahead (the Slots trait: count, read, write,
size, truncate, flush, by slot number; slots may be added between
calls) and SlotFs keeps the database’s files in them, SQLite’s
opfs-sahpool idea. Each slot is one file: a 4 KiB header, then its
bytes. The header is two 2 KiB copies, each NCSLOT01, a generation,
the path’s length and bytes, and an FNV-1a checksum; a write goes to the
copy not holding the latest, with a generation above every other in the
pool, and is flushed at once. So a torn header write leaves the other
copy (the slot as it was), and a rename — the moved file’s header
rewritten with the new path, then the replaced file’s slot freed — that
a crash cuts between leaves two slots naming the path, of which the
newer wins when the pool is next read (the stale one freed). Opening,
creating, renaming and removing are header writes on handles already
open; directories are not stored (one exists where it was made in this
run or where a file lies under it); sync_dir does nothing (headers are
flushed as written). A removed or replaced file stays readable through
handles opened before: its slot is reused only when they are dropped.
With every slot taken a new file fails with StorageFull;
free_slots() tells the host when to add more (it keeps eight free,
adding sixteen). Locks are per path within the pool, which one page
holds at a time (OPFS’s handles are exclusive). MemorySlots is a pool
in memory for tests; tests/conformance.rs runs against a pool of
sixteen, and nucleus-kv’s contract test opens a database on one, then
again on the same slots.