Skip to main content

CSE 331: Persistent data

lecture

Course motto: Your job is to deliver code that you know works.

The book forgets

The guestbook we put JavaScript into keeps its messages in a Book. Let's start it in one terminal, in the directory that holds it:

$ javac Guestbook.java
$ java Guestbook
Serving at http://localhost:9331/

Then, from a second terminal, post a message with curl, as we did then:

$ curl -d 'name=ada&message=hello' http://localhost:9331/api/messages
["ada: hello"]

The server answered with the book, ada's message in it. Now stop the server, as you would to change its code: press Ctrl+C in its terminal. Then start it again. The server's terminal now reads:

$ java Guestbook
Serving at http://localhost:9331/
POST /api/messages
^C
$ java Guestbook
Serving at http://localhost:9331/

Back in the second terminal, ask for the messages:

$ curl http://localhost:9331/api/messages
[]

The book is empty. Ada's message is gone.

Is that a bug? Look at where the book lives. Book keeps the messages in a field, a list. That list is in the program's memory, the place a running program keeps its variables and objects. The operating system gives a program its memory when the program starts, and takes it back when the program stops. So every variable in the program, and every object, ends with the run. The next run starts with a new Book, and a new Book is empty.

Some data has to outlast the run. A real server stops all the time: to install a new version, when its machine restarts, and when it crashes. A guestbook that forgets everything at each of those is not much of a guestbook.

A file outlasts the run. The operating system keeps a file on the disk (a drive that keeps what is written on it with the power off) until some program deletes it. So the plan is to keep the book in a file, and to read it back when the server starts.

Definition: persistent

Data is persistent if it outlasts the run of the program that wrote it.

Persistence has a cost, and we have met smaller versions of it before. Ask how long a mistake in a program's state can last:

  • A batch program builds its state from one input, in one run. A bad state lasts at most until the program exits, and the next run starts clean.
  • An interactive program keeps its state across every input of a session. So a bad state can sit unnoticed for many inputs before it shows, and the program has to go on responding to the inputs after it. But quitting and starting again clears it.
  • Persistent data outlasts every run. A bad book written to the file is read back by every later run, and no restart clears it. Someone has to repair the file.

Each step stretches how long the program has to tolerate a mistake, or recover from one: from one run, to one session, to as long as the data is kept. With persistence, your bugs are forever. Exercise 1 shows one.

What "works" means now

Before we write any code, the motto asks what "works" means for a guestbook that keeps its book. Here is Book's specification so far:

/** The messages posted so far, oldest first. */

"So far" used to mean "so far in this run", since a run was all there was. Now we want it to reach across runs. What should a visitor be able to count on?

A visitor learns that a post worked from the server's response: the book, with the new message in it. So the promise is about posts that got a response:

When the server responds to a post request, that message will be saved forever.

"Forever" means through every stop of the server, whatever its reason. It covers the stops we choose. We stop the server ourselves to install a new version of it, or to upgrade the operating system it runs on, and the book has to be there after each of those normal shutdowns. The promise also takes something for granted: the book holds nothing but whole messages that were posted.

The motto asks for more than a promise, though. It asks us to know that the guestbook keeps it. When we studied testing, we named three ways to gain that knowledge: testing, tools, and reasoning. This lecture tries all three on the promise, and each turns out harder once data persists.

Saving the book

Here is the first try, inplace/Guestbook.java. Only Book changes from the JavaScript guestbook, and one line of main, which now makes the book from a file:

        book = new Book(Path.of("book.txt"));

The new Book is this:

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/** The messages posted so far, oldest first, kept in a file. */
class Book {
    private Path file;
    private List<String> messages = new ArrayList<String>();

    /**
     * @effects makes a book of the messages saved in file, one per
     *     line, or of no messages if there is no file
     */
    public Book(Path file) throws IOException {
        this.file = file;
        if (Files.exists(file)) {
            messages.addAll(Files.readAllLines(file, UTF_8));
        }
    }

    /**
     * @modifies this, file
     * @effects adds the message, signed with the name, after the
     *     messages already posted, and saves the book in file
     */
    public void add(String name, String message) throws IOException {
        messages.add(name + ": " + message);
        save();
    }

    /** @return the posted messages, oldest first, in a new list */
    public List<String> messages() {
        // A copy, so that a client cannot change the book through it.
        return new ArrayList<String>(messages);
    }

    /**
     * @modifies file
     * @effects writes the messages to file, one per line
     */
    private void save() throws IOException {
        try (FileOutputStream out = new FileOutputStream(file.toFile())) {
            out.write(text().getBytes(UTF_8));
        }
    }

    /** @return the messages, each followed by a line break */
    private String text() {
        String text = "";
        for (String m : messages) {
            text += m + "\n";
        }
        return text;
    }
}

The book is now in two places. The list is the copy the program reads, and the file is the copy that outlasts the run. The constructor fills the list from the file, a line per message (Files.readAllLines). Then add changes the list and calls save, which writes the whole list to the file again.

save is the new Java. Line 154 opens the file as a FileOutputStream, a stream of bytes into the file. Its specification says what opening does: "If the file exists, it is truncated, otherwise a new file is created." To truncate a file is to cut it short, here to no bytes at all. Line 155 writes the messages, a line for each, as bytes. The try closes the file when its block ends.

Does it work? Compile it and start it in the server's terminal, from the directory that holds it. Post ada's message from the second terminal, stop the server with Ctrl+C, start it again, and ask for the messages. The server's terminal:

$ javac Guestbook.java
$ java Guestbook
Serving at http://localhost:9331/
POST /api/messages
^C
$ java Guestbook
Serving at http://localhost:9331/
GET /api/messages

The second terminal:

$ curl -d 'name=ada&message=hello' http://localhost:9331/api/messages
["ada: hello"]
$ curl http://localhost:9331/api/messages
["ada: hello"]

Ada's message came back.

Testing a persistent program

That restart was a test, run by hand. Persistence changes what a test like it has to cover. The file is a new input: each run starts from whatever book.txt holds, so a test has to choose the file as well as the requests. No file, an empty one, a book, a book with a half-written line: each is a different input. The file is also a new output. A test has to check what a run leaves in book.txt, not only what it sends back, since the next run starts from it.

So the first tests are of the normal case, one for each direction:

  • Saving. After ada's post, book.txt should hold her message, alone on one line. It does:

    ada: hello
    
  • Loading. Stop the server, and write a book.txt of two lines by hand, with any editor:

    ada: hello
    bob: hi
    

    Start the server again, and ask for the messages. Both come back, oldest first:

    $ curl http://localhost:9331/api/messages
    ["ada: hello", "bob: hi"]
    

So the book outlasts a normal stop. Is it right? The promise says "forever", and a stop with Ctrl+C is only one kind of stop. "Forever" also covers the stops we do not choose, such as a crash: the program stops between two of its steps, without finishing the step it was on. A crash can come from a bug, from the operating system stopping the program, or from the machine losing power.

The promise covers only posts that got a response. A post that crashed before its response got none. So its visitor was never told the message was saved, and the promise allows the book to have it or not. What the promise does not allow is losing a message that a visitor was told was saved, or leaving half a message behind.

That tells the handler what to do: save the book first, and only then respond. Any other order can send a response for a message a crash then loses. The handler, which has not changed, does it in that order. It calls post, which adds the message, and only then calls send, which sends the response:

        } else if (path.equals("/api/messages")) {
            if (method.equals("POST")) {
                post(exchange);
            }
            send(exchange, 200, "application/json",
                json(book.messages()).getBytes(UTF_8));

So if add saves the book before it returns, every response goes out after its message is saved. Exercise 2 asks what goes wrong the other way around.

So try a crash.

A crash can land between any two steps of the program. To test one, we have to choose where. A crash does not wait for us, so the program has to crash itself, at a point the test names. Making a failure happen on purpose, so that a test can see what the program does after it, is fault injection. It is a new idea, and a case of designing a program to be tested, as we did when we studied coverage: we change the program so that a test can reach what it could not reach before. inplace-crash/Guestbook.java is the same program with one line added to save for testing, line 160, a crash point:

158
159
160
161
162
163
    private void save() throws IOException {
        try (FileOutputStream out = new FileOutputStream(file.toFile())) {
            Crash.at("opened");
            out.write(text().getBytes(UTF_8));
        }
    }

The class Crash, at the end of the file, is new too:

175
176
177
178
179
180
181
182
183
184
185
186
/** Crashes the program on purpose, at a point a test names. */
class Crash {
    /**
     * @effects halts the program at once, as a crash would, if the
     *     environment variable CRASH names this point
     */
    static void at(String point) {
        if (point.equals(System.getenv("CRASH"))) {
            Runtime.getRuntime().halt(1);
        }
    }
}

An environment variable is a named string the shell hands a program when it starts it. On a normal run there is no CRASH, and Crash.at does nothing. Started with CRASH set to opened, the program stops when it reaches line 160, just after the file is opened. Runtime.halt stops the program at once. It finishes nothing: no finally block runs, and no response goes out. That is as close as one line of Java can come to a crash.

So stop the server, and start the crash point's copy, with the book still holding ada's and bob's messages, as CRASH=opened java Guestbook. (In Windows PowerShell, run $env:CRASH="opened" first, then java Guestbook.) Cy posts, from the second terminal:

$ curl -d 'name=cy&message=hey' http://localhost:9331/api/messages
curl: (52) Empty reply from server

The server crashed, and cy got no response. So far that is allowed: the promise says nothing about cy's message. Now start the server again, without the crash. The server's terminal, from the crash on, reads:

$ CRASH=opened java Guestbook
Serving at http://localhost:9331/
POST /api/messages
$ java Guestbook
Serving at http://localhost:9331/

Cy's request arrived, and then the prompt came straight back, with no ^C: the program halted at line 160. Ask for the messages:

$ curl http://localhost:9331/api/messages
[]

Ada's and bob's messages are gone too, and both were in the book before cy posted. This run refutes the promise. book.txt is still there, but it holds no bytes at all. Line 159 truncated the file when it opened it, and the crash came before line 161 could write the new book. Writing a file over in place has a moment when the file holds neither the old book nor the new one.

Notice what it took to find this. Every ordinary run passes: post, restart, read back. The bug shows only on a run that crashes, at a point inside save, and only because we chose that point. A test of a crash tells us about the one point it crashes at. To test every point, we would need a crash point between every two steps, and a run for each. That is testing's limit again: a run refutes a claim, here the promise, but it cannot confirm one.

Old book or new book

The fix is to never write over the only copy. Here is save in Guestbook.java, the version the rest of these notes use:

154
155
156
157
158
159
160
161
162
163
164
165
166
167
    /**
     * @modifies file
     * @effects writes the messages to file, one per line
     */
    private void save() throws IOException {
        Path temp = Path.of(file + ".tmp");
        try (FileOutputStream out = new FileOutputStream(temp.toFile())) {
            Crash.at("opened");
            out.write(text().getBytes(UTF_8));
            out.getFD().sync();
        }
        Crash.at("written");
        Files.move(temp, file, ATOMIC_MOVE);
    }

It makes three changes, marked:

  1. Line 159 makes the path of a second file, book.txt.tmp. Lines 160 to 162 write the new book there, and leave book.txt as it was.
  2. Line 163 waits until the new file is on the disk. The section after this one says why.
  3. Line 166 moves book.txt.tmp to the name book.txt, in place of the old file.

Let's argue that the promise holds, instead of testing for it. The argument is about one claim, which we check at every point in save, as we did when we studied reasoning, with a claim between every two statements:

book.txt holds a whole book: the old one or the new one.

The old book is the messages before this post, and the new one is those messages and this post.

At each point:

  • Before line 166. Lines 159 to 165 write only book.txt.tmp. So book.txt holds the old book, whatever state book.txt.tmp is in. A crash here leaves the old book.
  • At line 166. The move is the one step that changes book.txt, and it has to replace the old file with the new one in a single step, with no moment in between. That is what ATOMIC_MOVE asks for.
  • After line 166. book.txt is the new file, whole, since line 162 wrote all of it before the move.

So the claim is true at every point, and a crash at any of them leaves a whole book in book.txt. The constructor reads only book.txt, so the next run starts from a whole book. A book.txt.tmp left behind by a crash is never read, and the next save truncates it on line 160.

The argument leans on the move. Here is what Files.move's specification says of ATOMIC_MOVE:

The move is performed as an atomic file system operation and all other options are ignored. If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException.

Atomic means the move happens all at once: anyone looking at the files sees them before the move or after it, never partway. But the specification leaves one thing open. If book.txt exists, the move may replace it, or it may throw. Throwing would not lose ada's message, but no second post would ever save. So our argument needs more than the specification promises. On macOS and Linux, the JDK's code does the move with the operating system's rename,1 and POSIX, the standard those systems follow, says rename replaces a file that is there, atomically. So the argument holds on those systems, because of a promise one layer down. On Windows, the JDK's code calls MoveFileEx and asks it to replace a file that is there.2 Microsoft's documentation of MoveFileEx says that it replaces the file, but it does not say that it does so atomically. So on Windows, our argument rests on behavior that no document we read promises. This is the cost of leaning on behavior a specification leaves open: the argument is only as good as what we read below it.

The crash points now agree with the argument. Start from the same book, ada's message alone, and crash bob's post at opened, then at written. Each time bob gets no response, and after the restart:

$ curl http://localhost:9331/api/messages
["ada: hello"]

After the crash at written, book.txt.tmp holds the new book, ada's message and bob's, and book.txt the old one. A post with no crash then saves both:

$ curl -d 'name=bob&message=hi' http://localhost:9331/api/messages
["ada: hello", "bob: hi"]

The server's terminal shows the crash at written and the run after it:

$ CRASH=written java Guestbook
Serving at http://localhost:9331/
POST /api/messages
$ java Guestbook
Serving at http://localhost:9331/
GET /api/messages
POST /api/messages

The tests pass at the two points they crash at. The argument covers every point, including the ones with no Crash.at.

A crash of the machine

Line 163 is the one change the argument above never used. Delete it, and rerun every run in these notes: they all come out the same. So why is it there?

Runtime.halt crashes the program, but not the machine. When line 162 writes, Java hands the bytes to the operating system, and the operating system writes them to the disk later, when it chooses. Until then they wait in the operating system's memory. If the program stops, the operating system is still running, and it still writes them. If the machine stops, from a power loss or a crash of the operating system, bytes that were still waiting are lost.3

That breaks the argument's last step. The move could reach the disk before the bytes do, and after a power loss, book.txt could name a file that is empty, or partly written. Line 163 closes that gap. getFD returns the stream's file descriptor, the operating system's handle for the open file, and sync "will not return until all in-memory modified copies of buffers associated with this FileDescriptor have been written to the physical medium." So by line 166, the new book is on the disk, before the move is.4

No test in these notes can show that. A test that halts the program cannot refute a claim about power loss, since the machine keeps running. So in these notes, reasoning from what sync promises is what puts line 163 in the code.

A test can simulate a power loss, though, with the right tool underneath. LazyFS5 is a file system built for this. It keeps the bytes a program writes in a separate cache, writes them to the disk only when the program syncs them, and on a test's command drops every byte not yet synced, as a power loss would. Run the guestbook on it, drop the cache right after the move, and check book.txt: that is a test of line 163, and of the claim about power loss that halting the program cannot reach.

The argument still has a gap, and it is the place to stop. The move changes the directory that holds book.txt, and after a power loss, even the move is safe only once the directory is on the disk too. (POSIX's promise that rename is atomic is about a running system. Whether a rename is still all or nothing after a power loss is up to the file system.6) The Linux man page for fsync, the operating system call that sync makes, says so:

Calling fsync() does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync() on a file descriptor for the directory is also needed.

The JDK's specification gives no way to do that. Further reading says where to learn more.

Three ways to know, with persistence

Each of the three ways told us something different about the promise, and persistence made each one harder:

  • Testing refuted the promise for the first save, with a run that crashed at a point we chose. Persistence makes testing harder in two ways. First, the file is a new input and a new output, so a test has to choose it and check it. Second, a crash can land between any two steps, so a test covers only the points it crashes at, and only the crashes it can cause: halting the program is not cutting the power, which takes a tool such as LazyFS.
  • Reasoning confirmed the promise for the second save, at every point, and it alone put line 163 in the code. It was harder in one way than when we first reasoned about statements. A claim then was about the variables, at one point in the code. This claim is about the files, and about every state a crash could leave them in: book.txt.tmp missing, partly written, or whole, beside the old book or the new one. The program's variables are gone after a crash. The files are all the next run has. And the argument leaned on the specifications of move and sync, and on the operating system below them.
  • Tools exist for this too. ALICE, a research tool,7 runs a program once, builds each state of its files that a crash at any point in that run could leave, and checks the program's recovery from each. It found missed fsyncs, of files and of directories, in widely used programs. Like the type checker, it checks one kind of claim, and checks it more thoroughly than a person can.

A database, the next section, is a tool in a different sense: another program, built and checked by others, that keeps the promise for us, instead of checking our code that keeps it.

Databases

Our save works, but it has costs. Every post writes the whole book again, every message ever posted, to add one line. With a few messages that is nothing. With a million, each post writes a million lines. The natural fix is to write only what changed: append the new message to the end of book.txt. But that changes the only copy again, in place. A crash partway through the append leaves half a message at the end of the file, which the next run reads as a whole one. The argument of "Old book or new book" no longer applies, since the move swaps a whole new file for the old one, and it cannot swap in one line. So keeping a large file both fast and safe needs more than the move.

Everything in this lecture, a database does for you, and more. A database is a program that keeps data in files and promises what our specification promised: a change it said it saved is still there after a crash. It also lets many programs read and change the data at once, and answers questions about it ("every message posted by ada"). And it changes only what changed, safely. SQLite, a widely used database, first copies the parts of its file a change will alter into a second file, a journal, so that after a crash it can put them back.8 Its authors argued for, and tested, the same kind of promise we did today, for far more than one file.

So a server with data to keep usually keeps it in a database. Ask of a database, or of any code that keeps your data, the two questions this lecture asked: what does it promise after a crash, and how does it know? CSE 344 covers databases.

Exercises

Each answer is folded under its question. Write yours first.

1. Start Guestbook.java with an empty book, and post a message whose text has a line break in it. curl can send one with --data-urlencode:

$ curl --data-urlencode 'name=eve' --data-urlencode $'message=hi\nthere' http://localhost:9331/api/messages
["eve: hi\nthere"]

(In JSON, \n in a string is a line break.) Restart the server and ask for the messages. What comes back, and what does it break in "What 'works' means now"? Which lines of Book are at fault, and what would you change?

Answer
  • What comes back. Two messages, where one was posted:

    ["eve: hi", "there"]
    

    (These notes' check script runs this exercise after the messages above, so its run has ada's and bob's messages first.)

  • What it breaks. What the promise takes for granted: the book holds nothing but whole messages that were posted. "there" was never posted, and eve's message came back cut in half.

  • The lines at fault. Line 173 writes each message followed by a line break, and line 134 reads the file back a line per message. The two agree only while no message holds a line break. So the file's form has a rule that the code never checks: no message contains a line break.

  • What to change. Either keep that rule, or write the messages in a form that can hold any text. To keep it, add could refuse a message with a line break, or replace it with a space, and say so in its specification. To lift it, text could write each message as a JSON string, as json already does for the response, with the constructor reading it back. Either way, the constructor and text have to agree, and only a test with a line break in it would have shown that they did not.

  • Why a restart does not help. Eve's message is now two lines in book.txt, so every later run reads two messages. Fixing the code does not fix the file: someone has to repair book.txt too.

2. Suppose handle sent the response first, and then called post. Which crash would break the promise? Describe the run.

Answer
  • The run. Ada posts. The server sends her the book with her message in it, then crashes before save writes the file, at opened or written. After the restart, her message is not in the book.

  • What it breaks. The promise itself. Ada's post got a response, so her message should be saved forever, and it was not.

  • The general point. A response is a promise to the visitor, so it may go out only after what it promises is true. Saving first means a crash can only cost a post that got no response, and the specification allows that.

3. A friend says: "Line 163 is pointless. I deleted it, and every test still passes." What do you say?

Answer
  • The tests are right, and so is line 163. Each test crashes the program with Runtime.halt, and the operating system keeps running and still writes the bytes to the disk. So no test of that kind can tell the two versions apart.

  • The case they cannot reach. A power loss after line 166 but before the operating system wrote the bytes. With line 163, the bytes are on the disk before the move. Without it, book.txt may name an empty or partly written file.

  • How we know. By reasoning from what sync promises. None of these runs lost power, so none of them can refute the claim. A test that can would run the guestbook on a tool such as LazyFS, which drops unsynced bytes as a power loss would.

Further reading


  1. OpenJDK's UnixFileSystem.move calls rename when asked for ATOMIC_MOVE, and rename0 calls the system's rename. The macOS file system class adds nothing to move. ↩

  2. OpenJDK's WindowsFileCopy.move calls MoveFileEx with MOVEFILE_REPLACE_EXISTING for ATOMIC_MOVE. Microsoft's page for MoveFileExW says of that flag that the function "replaces its contents with the contents of" the file moved, and nowhere uses the word atomic. ↩

  3. The Linux man page for write says a successful write "does not make any guarantee that data has been committed to disk." SQLite's documentation of PRAGMA synchronous draws the same line: data handed to the operating system is safe if the application crashes, but not if the operating system crashes or the machine loses power. ↩

  4. That is what sync promises. On macOS, the JDK's sync calls the operating system's fsync (FileDescriptor_md.c, with IO_Sync defined as fsync in io_util_md.h), and Apple's fsync manual page says that fsync moves the data to the drive, which may still hold it in the drive's cache. The JDK's FileChannel.force asks macOS for more, a full flush of the drive (FileDispatcherImpl.c). So on a Mac, sync promises more than it does. It is the same lesson as ATOMIC_MOVE: the argument is only as good as what we read below the specification. ↩

  5. Maria Ramos, João Azevedo, Kyle Kingsbury, José Pereira, Tânia Esteves, Ricardo Macedo, and João Paulo, When Amnesia Strikes: Understanding and Reproducing Data Loss Bugs with Fault Injection, VLDB 2024. LazyFS itself is at github.com/dsrhaslab/lazyfs. ↩

  6. Dan Luu, Files are hard (2015): "POSIX says that rename is atomic, but this only applies to normal operation, not to crashes." ↩

  7. Thanumalayan Sankaranarayana Pillai, Vijay Chidambaram, Ramnatthan Alagappan, Samer Al-Kiswany, Andrea C. Arpaci-Dusseau, and Remzi H. Arpaci-Dusseau, All File Systems Are Not Created Equal: On the Complexity of Crafting Crash-Consistent Applications, OSDI 2014. ↩

  8. SQLite, Atomic Commit In SQLite, section 3.5, "Creating A Rollback Journal File". ↩