Netflix's Chaos Monkey shuts down machines at random in the production fleet. While I like the idea of finding out how a service copes with losing a machine when someone is around to watch, I can't quite bring myself to unplug a satellite running SpaceOS to see what its software does next :-) So, I'd like to know what happens when the radio link drops halfway through a transfer, or the power goes out just after my software says it has saved a file. My tests usually run on a laptop, where I can save the file a thousand times and never exercise the recovery code. I could write a test for each place I think a write might fail, but then I'd have to do it all again for the next application, with much the same disk underneath.
One answer is Antithesis, which gets control of the disk, the network and the clock by running the whole operating system in a deterministic hypervisor. It can run unmodified software that way and replay the sequence of events that broke it. In MirageOS, though, I'm already writing operating-system code in user space, with OCaml libraries for storage and networking. So the natural next step is to turn the chaos into a library too, and run these experiments from an ordinary unit test. eio-chaos, eio-fs and eio-net now do something close for an Eio application, for everything it reaches through Eio:
$ opam install eio-chaos eio-fs eio-net hermetic
let () =
Eio_chaos.run [ Eio_fs_chaos.disk (); Eio_net_chaos.network () ]
@@ fun env -> My_app.main env
There is no test script here telling a particular write to fail.
Instead, My_app.main runs several times with a different history each time.
In one run the disk might lose power, in another the client might lose
a TCP handshake. The test then restarts the application on what survived.
If that goes badly, the report ends with a line of OCaml to paste
into the test to run that one case again.
Capabilities
The reason this fits in a unit test is the env argument that
My_app.main takes anyway. Nowadays, most of my applications use
Eio,
which gives them a filesystem, a network and clocks as ordinary OCaml
values.
In Eio's terminology, a
capability
is a value that grants access to a resource. If a function saves a config
file, it can be given just the directory where the file belongs. It can
open a file there and pass the open file to another function that knows
how to write the config. That second function doesn't need access to the
directory at all.
Usually that directory is on the host's disk. In the test above, env
holds a directory on a simulated disk instead, and the function saves
its config in exactly the same way. So what happens when the disk loses
power is written once, and reused in every application that takes its
directory as an argument.
Nothing stops the application from calling open_in and reading a
file on the host by mistake. That's an ambient capability. open_in
takes just a filename, so even when the test passes a simulated
directory, the read goes straight to the host filesystem. To catch those
calls, I wrote and released
hermetic. With
open! Hermetic at the top of a file, calls such as open_in and
Unix.gettimeofday raise a compile-time alert that points to the
corresponding Eio capability. Yoann Padioleau's
caps, presented at this year's
OCaml Workshop, takes the
opposite approach: it keeps those calls, but makes each one ask for a
capability token.
The chaos itself comes from three new libraries. eio-chaos chooses the faults and runs the application on a scheduler and virtual clock adapted from Eio_mock. eio-fs and eio-net supply the devices. A scripted mock has to be told what each operation returns. Here, instead, the simulated disk keeps track of writes, renames and syncs, so it knows what would survive a power cut.
A rename is not durable until its directory is synced
Suppose an application keeps its settings in a file called config,
which holds the string "old", and wants to replace it with "new".
The classic way is to write "new" to a temporary file, sync that file
and rename it over config. As the rename is atomic, readers opening
config see one complete version or the other. But the rename changes
an entry in the parent directory, so syncing the file alone does not
make it durable. On Linux, the application therefore also has to sync
the directory before it tells the user the new config is safe on disk.
To check that, the sync_dir flag below runs the save both ways. The
setup first writes a durable copy of "old". The test then saves
"new" and calls ack to record what config must hold after a
restart.
let save ~sync_dir dir v =
let tmp = Eio.Path.(dir / "config.tmp") in
let create = `Or_truncate 0o644 in
Eio.Path.with_open_out ~create tmp (fun f ->
Eio.Flow.copy_string v f;
Eio.File.sync f);
Eio.Path.rename tmp Eio.Path.(dir / "config");
if sync_dir then Eio.Path.sync_dir dir
let test ~sync_dir () =
Eio_fs_chaos.run
~setup:(fun env -> save ~sync_dir:true env#fs "old")
(fun env ->
save ~sync_dir env#fs "new";
Eio_fs_chaos.ack env Eio.Path.(env#fs / "config"))
With the directory sync, the test passes. Without it, the recording
shows a power cut just after the acknowledgement. The temporary file's
contents had reached the disk, but neither its directory entry nor the
rename survived. When the application restarted, config held "old"
again.
To find that cut, Eio_fs_chaos.run first records a run without faults. At each
operation in that run it tries the individual faults the model allows,
then uses a fixed seed to try pairs of faults. It checks for hangs,
unexpected exceptions and failed restarts. After a restart it also
checks the contents of each acknowledged file.
Like LazyFS, which does it with
FUSE, the simulated disk drops the writes that were not synced. The
restart check is the one
ALICE
runs on applications and
CrashMonkey
on filesystems. The disk model is a port of
Ferrite's model of ext4, with its
tests: ext4 mounted with data=writeback, which may lose more than the
default data=ordered. The macOS model keeps those rules and changes
only what each kind of sync makes durable on APFS. Under both models,
unsynced writes can survive out of order, and in the ext4 model even
individual 512-byte sectors of a page can survive while others still
hold the old data.
And as a failed check raises Failure with the report, the test runs
directly in Alcotest, which
points each failure at its test.
Alcotest.test_case "power cut" `Quick (test ~sync_dir:true)
Failed syncs and silent peers
There's a wrinkle in the config example on macOS. Even with both
syncs, fsync can return while the data is still in the drive's cache.
Flushing that cache as well takes F_FULLFSYNC (the reason SQLite has a
fullfsync pragma).
This has always been convoluted to test, but with eio-fs it is just
Eio_fs_chaos.run ~os:`Macos. Eio_fs_unix.sync_file and
Eio_fs_unix.sync_dir issue the stronger barrier when the program runs
on macOS.
Another example of a contrived failure mode is a failed sync on Linux.
The kernel may already have dropped the pages it couldn't write, so a
retried sync succeeds because there's nothing left to flush. The PostgreSQL developers ran into this in 2018
(fsyncgate).
It's one of the cases Eio_fs_chaos.run tries, and a good example of
why returning an error from a mock isn't quite enough. What the next
call sees depends on what the disk did during the failed one.
On the network, news of a failure can take a long time to arrive. When a satellite goes out of range at the end of a pass, the radio link can disappear without the peer sending a FIN or a RST. A client waiting for a reply can sit there until its timeout expires. The eio-net README has a test for just such a client. With a virtual clock, the test lets the timeout expire without waiting that long.
Does the simulated device behave like the real one?
All of this assumes the simulated devices are right. If the disk quietly makes every rename durable, for example, a save without the directory sync passes every time. The code on the other side of the capability needs testing too.
Even without a power cut, filesystems disagree about fairly ordinary
things. On macOS's default volume, a file written as a opens as A.
On a typical Linux filesystem the lookup fails.
Earlier work such as SibylFS checked real filesystems against
a specification. eio-fs goes the other way, as the systems it imitates
are at hand. Short sequences of operations run on each OS, the
recordings keep what Eio sees, and the in-memory implementation is
checked against them on every commit.
The test takes a function that builds the filesystem to check. Here
the in-memory filesystem stays in its default Linux mode, and
conformance compares it with the macOS recordings. The first three
differences all come from what happens to a name after a change of
case.
let () =
Eio_fs_chaos.conformance ~os:`Macos (fun ~sw:_ _env -> Eio_fs_mem.v ())
Eio_fs_chaos.conformance: 42 of 101 scenarios differ from macOS
scenario operations expected got
------------------------------------------------------------------------------
case lookup write a x; stat A file 1 ENOENT
case exclusive create write a x; open A x EEXIST ok
case non-ascii write é x; stat É file 1 ENOENT
...
59 passed, 42 differed, 14 left out: 11 that need ~user, 3 that need a native
path
The first row is the lookup above. macOS found a one-byte file, but
the in-memory filesystem returned ENOENT. With Eio_fs_mem.v ~os:`Macos ()
instead, the check passes. Eio_net_chaos.conformance does the same for network
devices, with scenarios drawn in part from
gVisor's socket tests.
These checks also run on a device that depends on another device.
For example, the eio-fs tests include a remote filesystem.
Passing ~under:[ Eio_net_chaos.network () ] lets the test interrupt
its network. A filesystem operation may then return a disk error, but
it still has to finish.
One option that turned out surprisingly effective is ~os:`Windows. For
historical reasons, a good development setup is
harder to get on Windows
than on Linux or macOS, so code rarely gets tested there. With this
option, a chaos test on a Mac answers as Windows does: if the code
renames a file it still holds open, the test catches it before Windows
does. The Windows answers were recorded through Eio's backend on
GitHub's Windows runners. Each time a recording differed from the model,
there was a short sequence of operations to look at, and several times
the bug was not in the model.
I opened issues for Eio's Windows backend
(eio#986,
eio#987,
eio#988,
eio#989,
eio#990,
eio#991,
eio#992,
eio#993 and
eio#994) and for
OCaml's Unix library
(ocaml#15335 and
ocaml#15336).
Since then, Anil Madhavapeddy has moved Eio's
Windows backend to IO completion ports in
eio#996, which fixes
most of the Eio ones.
The model still has gaps. In particular, Eio's Windows backend doesn't sync directories, and there are no recordings of what survives a power cut on NTFS, so the Windows model uses the Linux crash behaviour.
Using the devices on their own
For tests that just need a disposable directory, eio-fs.mem works
without the fault injector. It started as Patrick Ferris's
eio_mem, and Eio_fs.Path adapts
eio_mem's POSIX-only version of
Daniel Bünzli's
fpath.
Likewise, eio-net.mem runs a client and a server in the same test
without picking a free port on the host.
If a test needs a whole tree of fixtures, eio-fs-crunch can embed the
tree in the executable. A Dune rule regenerates the OCaml module when
the files change, and Eio_fs_mem.Crunch.load turns it back into a
filesystem the test can read through Eio.Path. Much the same trick
gives a unikernel somewhere to keep its static files when it has no
disk, as ocaml-crunch does in
MirageOS.
As the config example shows, the file synchronisation dance is hard to
get right, and Eio could not even sync a directory before
Eio.Path.sync_dir
arrived in Eio 1.7. Eio_fs.Sync does the whole dance, with the barrier
you give it (Eio_fs_unix.barrier on macOS), and its tests run it
through power cuts and I/O errors. eio-fs.unix also has bindings for
file locks and the full sync calls above.
I'd be happy to contribute those upstream if others need them.
On the network side, the frame channels in eio-net read one protocol
message at a time, however many reads it takes, over datagram sockets
and byte streams, with a length-prefix codec in Eio_net.Framing. Their
tests found that eio_linux refused to send a datagram to a Unix-domain
address (eio#963).
Eio_net.Accept bounds the connections a server's accept loop serves
and, when the loop is full or out of file descriptors, drops the
connection whose request has made the least progress. Its tests found
that a second listener whose bind failed on a Unix socket path already
in use could delete the first listener's socket file
(eio#970). Both are
fixed in Eio 1.7, whose release in turn crashed eio-net's tests on
Alpine, where the GC freeing a locked mutex corrupts musl's memory
(ocaml#15392).
Trying it out
If you try this on an Eio application, I'd like to hear what breaks. I'm especially interested in failures you can replay in the simulator but can't explain on a real machine. I may have got the model wrong. You can report those on the trackers for eio-chaos, eio-fs, eio-net and hermetic. I'd also like to hear whether upstreaming hermetic's alerts to the OCaml standard library would even be a good idea :-)
