Definition
A state transition guard is a true-or-false condition that must hold for a state machine §8.33 to make a particular transition. The guard reads the current state and the request, as in “replace the active version only if the active version is still 7”. A well-formed request whose guard is false is refused. The guard protects only if it is still true when the transition takes effect, so the test and the state change must be one indivisible step with respect to every other operation that can change that state.
The idea
Two update requests reach a device over two connections at almost the same time. Both were prepared against the active configuration, version 7, and both say “replace version 7”. Request A would install version 8, request B version 9. One handler, a piece of code that processes a request, runs for each. Handler A reads the active version, sees 7, and decides it may proceed. Before A writes anything, handler B reads, also sees 7, and also decides it may proceed. A installs 8. Then B installs 9. B’s premise, “the active version is 7”, was true when B tested it and false when B acted, and A’s change is lost without any error. This is a race condition §9.2 of the check-then-act kind, called time-of-check to time-of-use §9.26 (TOCTOU).
Guards matter most when a request only makes sense relative to what is already installed. A full update carries the complete new image, the whole program or configuration, so its result does not depend on what was there before. A partial update, also called a delta update, carries only the differences between one particular old image, its base, and the new image; the device rebuilds the new image from the base and the differences. A delta is often much smaller than the full image, which matters over a slow radio link. But a delta applied to any image other than its base produces bytes that nobody built or tested. So a delta must name its exact base, and the device must guard the rebuild: proceed only if the installed image is that base.
Two bank clerks paying from one account are a fair picture. If the second clerk can pay between the first clerk’s balance check and payment, both pay against the same balance. The fix is for each clerk to hold the account book from the check until the payment is written in it. The picture stops at one point: on a device, a reset can also fall between check and payment, and no grip on the book survives a reset.
How it works
A guarded transition takes four design decisions.
Write the guard as a test on named data, for example: the active version equals the base version named in the request, and the request passed its authenticity checks.
List every operation that can change the data the guard reads: other threads (independent sequences of instructions in the same program), interrupt service routines §6.12 (code the processor runs when hardware signals an event), a second connection, a timer, and the recovery code that runs after a reset.
Make the test and the change one indivisible step. Common mechanisms:
A lock, such as a mutex §9.5 (a lock that one thread at a time can hold). Every operation that changes the guarded data takes the same lock, tests the guard, makes the change and releases the lock, so this critical section §9.4, the code between taking and releasing the lock, never runs in two operations at once.
Compare-and-swap §9.9 (CAS), an atomic operation §9.8, one that no other code can observe half done, that replaces a value in memory only if it still equals an expected value and reports whether it did. It suits a guard that reads one machine word and a change that writes the same word.
A single owner: one worker thread performs every transition, taking requests from a queue one at a time, so no two transitions overlap.
Disabling interrupts §6.11 briefly on a processor with one core, which stops all other code for the few instructions of the test and the change.
Every writer must use the chosen mechanism; one writer that bypasses the lock breaks the guarantee for all. When the change alters two or more fields, readers of those fields need protection too, or a reader can see the change half made; the Coherent snapshot §9.23 entry describes the methods.
Decide what a failed guard does: refuse with a reason, or read the state again and decide again. A retry starts from the new state. B, finding 8 where it expected 7, must not install 9 anyway; it reports that its base is out of date, and its sender prepares a new request against 8.
Two further points belong to the same design. First, the guard must test the same bytes that the transition uses: copy the request once into memory that no other code can change, check that copy, and use that copy. Second, a lock or a CAS coordinates only code that is running. If the transition writes to persistent storage, a reset can stop it between two writes, and no lock survives the reset. The write ordering §8.20, the order in which writes reach storage, together with one final write that makes the change take effect, decides what recovery finds. Recovery then evaluates the guard again from the stored facts.
Worked example
Let the active version be stored in one word , with . Handler A runs : the word holds 7, which equals the expected 7, so the word becomes 8 and the call reports success. Handler B then runs : the word holds 8, not the expected 7, so the word stays 8 and the call reports failure together with the value 8 it found. B refuses its request with the reason “base 7 is no longer active; version 8 is”. Exactly one request took effect, and the sender of the other knows that it did not.
A partial update shows why the base must be named. Write each image as a string of bytes, shown here as letters. The base, version 7, is the 6 bytes A B C D E F. The new version 8 is the 7 bytes A B X C D E F. The delta from 7 to 8 says: copy 2 bytes from position 0 of the base; insert X; copy 4 bytes from position 2 of the base, counting positions from 0.
On a device that holds version 7:
A B, thenX, thenC D E F, givingA B X C D E F, the intended 7 bytes.On a device that holds version 6, the bytes
A C D E F G:A C, thenX, thenD E F G, givingA C X D E F G, 7 bytes that match no released version.
The guard “installed version = 7” refuses the delta on the second device. A second guard after the rebuild, “the hash of the result equals the hash of version 8 that the delta names”, where a hash is a short fingerprint computed from the bytes, catches a base whose version number is right but whose bytes differ.
Stated precisely
Let be the current state, the request and the guard. A guarded transition from to is atomic with respect to competing operations, the other operations that can run at the same time, when the test and the whole change appear to each of them to happen at one instant: they share one linearization point §8.6, the instant at which an operation can be treated as taking effect. It is enough that, in every execution, from the transition’s first read, normally the evaluation of , until the state becomes , no competing operation writes data that the transition reads or writes, which includes the data that reads, and none reads data that the transition writes. Excluding only the writes to the data that reads keeps the guard true until the change begins, but it is not enough when the change alters two fields one after the other: a reader that reads both between those two writes sees a state that is neither nor .
Compare-and-swap gives this for one word. does the following as one atomic operation: if the word holds the expected value , it writes the new value and reports success; otherwise it leaves unchanged and reports failure together with the value it found. With and : if , then becomes 9; if , then stays 8 and the caller learns that it held 8.
The contract rests on three assumptions.
One discipline for all writers: every write to is atomic and goes through the same mechanism; one plain write elsewhere can slip between another operation’s read and its CAS. In C and C++, every read of that can run at the same time as such a write must be atomic as well: a plain read there is a data race §9.3, which these languages leave undefined.
A one-word guard: the guard depends on alone. A guard over two or more values needs a lock or a transaction §8.7.
Equal values mean an unchanged state: if can go from 7 to 8 and back to 7, a CAS that expects 7 succeeds although the state changed in between. This is the ABA problem §9.25, named for the value sequence A, B, A. A version number that only ever increases avoids it.
Limits and common mistakes
A guard tested in one function and acted on in another, with the lock released in between, is stale and has exactly the race of the first example. An atomic final write does not repair this: the write cannot be half done, but the test it relies on may already be false.
A CAS covers one word. A transition that changes a version number and a pointer to an image together must take a lock, or place both values in one record and publish a pointer to that record with one CAS.
Side effects made before the final step are not undone when the guard fails. If B erased flash memory §6.6 or sent a message before its CAS failed, the failure does not reverse that. Prepare in a private place, such as a separate storage area, and make the guarded step the only one that other code can see.
An interrupt service routine must not wait for a mutex: it must run to completion, and the thread that holds the lock cannot run until the routine returns. State shared with an interrupt handler needs brief disabling of interrupts, an atomic operation, or a hand-off to a thread.
A delta’s version guard assumes that equal version numbers mean equal bytes. Checking the hash of the base, or of the rebuilt result, removes that assumption.
Questions answered
Are the guard and state change atomic with respect to competing operations?
They are atomic only if a specific mechanism makes them so, and the question is answered by finding that mechanism, not by reading the guard. First list every operation that can change the data the guard reads: other threads, interrupt service routines, other connections, timers and recovery code. Then check that every one of them is excluded between the test and the change, for example because all of them take the same mutex, because the guard and the change are one compare-and-swap on a single word, or because one worker thread performs every transition. If any of them can run between the test and the change, the guard can become false after it was tested, and the transition goes ahead on a stale premise. To be sure that the whole transition is atomic, also exclude operations that write any other data the transition reads or writes and, when the change alters two or more fields, operations that read those fields; a reader that is not excluded can see the change half made. Atomicity §8.3 with respect to running code says nothing about resets: whether a reset can leave the change half made is a separate question about the order of writes to persistent storage.
Related entries: Compare-and-swap (§9.9), Time-of-check to time-of-use (TOCTOU) (§9.26), Linearization point (§8.6), Write ordering (§8.20), ABA problem (§9.25), Mutex (§9.5).