This is the introductory reading for classes 24 & 25.
The deadline for this reading isSunday, December 6 at 9pm.
Recommended reading in Program Proofs: Chapter 17. Dynamic Heap Data Structures.
This reading does not include exercises because it falls due after the last assignment date.
In class 23 we were introduced to aggregate objects — objects implemented using other constituent objects — with the example (from Program Proofs chapter 16) of a CoffeeMaker that consists of a Grinder and a WaterTank. In normal object-oriented programming, we are used to nesting objects inside each other, but more care is needed to be completely formal about what makes that pattern work.
We learned about the idiom of dynamic frames, where each object includes a ghost field that tracks a set of objects that are contained within it (canonically including that object itself). Like many of our other conventions (such as representation invariants), dynamic frames are a pattern of effective Dafny use, not a single built-in feature. They turn out to work very well to combine the information hiding of data abstraction with the complexity of heap-allocated objects and their potential for confusing aliasing.
Example: dynamically allocated queue
In this reading we review and practice the simpler case of implementing an aggregate object using constituent pieces that are not themselves aggregate objects. Our example is a queue that stores its elements in an array.
clients can construct a new empty mutable Queue where the elements are of arbitrary type T,
Enqueue adds an element to the end of the queue,
Dequeue removes the element from the front of a nonempty queue.
This time we’ll use a ghost field Elements to represent the abstract state of the queue. Instead of writing a functionAF : R → A that interprets the rep as an abstract value (or writing a relation):
each operation (constructor, Enqueue, and Dequeue) will update Elements appropriately with ghost code,
and we will need somewhere to lock up the relationship between abstract Elements and the concrete rep (which we haven’t chosen yet).
We’ll make that relationship part of the predicate in Valid(), in a sense treating Elements as if it were just a regular field, and the relationship between nonexistent ghostElements and real existing rep fields as just another data structure invariant.
Test harness
It’s easy to miss necessary conditions on Repr and therefore quite valuable to write a test harness that exercises our specification.
For example, suppose we omit from Dequeue the freshness condition on new Repr objects…
import opened QueueSpecmethod QueueTestHarness() { var q := new Queue<int>(); q.Enqueue(2); q.Enqueue(4); q.Enqueue(6); assert q.Elements == [2, 4, 6]; var e: int; e := q.Dequeue(); assert e == 2 && q.Elements == [4, 6] by { assert [2, 4, 6][0] == 2 && [2, 4, 6][1..] == [4, 6]; } // q.Enqueue(8); // uncomment me! // e := q.Dequeue(); // or uncomment me}
It works? But try adding another call to Enqueue or Dequeue: that’s the point at which we can no longer prove the frame condition.
Even without formal verification, careful testing might also reveal bugs in expectations around nested objects and aliasing. However, to make testing do the job, we need to be sure to litter code with runtime assertions or other ways of detecting bad outcomes. If we are concerned about unexpected aliasing, then the usual outcome is just that the value of some object changes when we didn’t expect, and it is hard to anticipate that surprise and add assertions to catch it. If we did anticipate the issue, we would probably just notice and fix the bug in the first place! Dynamic frames, in connection to built-in Dafny features like frames of methods and loops, provide a principled way to enumerate the complete aliasing-relevant contract of a method and check that all code is consistent with it.
we’ll reallocate a larger buffer when we run out of space for elements,
and we’ll store the current elements in a contiguous section of the buffer, if we think of the buffer as cyclic so that after the last element we wrap around to the first. That is, the elements of the abstract queue might be the concatenation of a suffix of the buffer followed by a prefix.
Why bother with such a complex representation? As happens so often in programming, the motivation is performance. Both enqueue and dequeue run in constant time, meaning they don’t get slower as the data structure grows (with the caveat that this analysis must be amortized, a methodological decision orthogonal to the content of 6.S057). You may recall the purely functional two-stack queue we verified in an earlier class, which offered the same asymptotic performance, but its constant factors tend to be significantly worse in practice, as every now and then it does a lot of copying, even for a queue that stays within a fixed capacity bound indefinitely.
Dafny will prove that we have handled correctly a number of complexities of this new implementation: reallocation, updating indices, and wraparound.
Representation
dfy
ghost var Elements: seq<T>ghost var Repr: set<object>var arr: array<T>var start: natvar n: natghost predicate Valid() reads this, Repr{ && this in Repr && arr in Repr && |Elements| == n <= arr.Length && (arr.Length == 0 == start || start < arr.Length) && (start + n <= arr.Length ==> Elements == arr[start..start + n]) && (arr.Length < start + n ==> Elements == arr[start..] + arr[..start + n - arr.Length])}
The array arr stores the underlying data contents. The beginning of the specification-level Elements is position start within arr. The second logical element of the queue is at position start+1, and so on, wrapping around back to zero when going off the edge of arr. Field n tells us how many elements are represented logically, revealing that some contiguous range of array cells actually holds junk that we shouldn’t read from, unless it gets initialized later.
The Valid predicate indicates a tame case of dynamic frames, where only the current object and its arr are included. The other clauses just formalize the previous paragraph.
Operations
In the constructor, we allocate a 0-size array of T: we can do that regardless of the type T. We initialize Repr and the empty abstract Elements.
Here is the representation for an empty queue of integers:
dfy
constructor () ensures Valid() && fresh(Repr) ensures Elements == []{ arr := new T[0]; start, n := 0, 0; Repr := {this, arr}; Elements := [];}
1. First we check whether arr needs to be reallocated with a larger buffer because the entire array is full:
After enqueueing 2, if the initial growth increment was 4 instead of 128:
And then after enqueueing 4 and 6:
dfy
if n == arr.Length { var more := if arr.Length == 0 then 128 else arr.Length; var b := new T[arr.Length + more](_ => t); forall i | 0 <= i < arr.Length { b[if i < start then i else i + arr.Length] := arr[i]; } if arr.Length != 0 { start := start + more; } arr := b; Repr := Repr + {arr}; }
To allocate the new buffer, we need to fill it with some values of type T. We just use incoming element t.
Then we use a forall statement to assign “in parallel” all of the elements of the new buffer that need to be copied from the old one.
2. Now that we know there is sufficient space, we can store the new element t and update Elements to match:
dfy
var i := start + n; if arr.Length <= i { i := i - arr.Length; } arr[i] := t; n, Elements := n + 1, Elements + [t];
Dequeue is straightforward, if we don’t care to release the memory we have allocated to arr:
After dequeueing 2 and 4, leaving only 6 on the queue:
After then enqueueing 8 and 10, the queue elements wrap around:
Overall, we see only a moderate overhead in extra proof content, to establish that this somewhat convoluted data structure implements the familar abstraction of queues, expressed using just representation invariants and abstraction functions (here encoded with a field), plus the new specification patterns of dynamic frames.
Summary
One of the hardest parts of formally verifying an imperative data structure is staying true to the promise of data abstraction, where callers of the data structure don’t need to know its internal implementation details. As data structures often contain nested instances of other data structures, patterns of aliasing can be quite complex, and we don’t want to force authors of client code to understand them. If we are successful, then a totally new data structure could be substituted in, so long as it implements the same abstract interface. Dynamic frames are a key part of the Dafny toolbox for hiding details of memory references and ownership* of subobjects.
The goals of 6.S057
Since we’ve reached the end of the last class reading, let’s take a moment to reflect on our objectives and the goals we described in the first reading. If AI coding agents are increasingly being used to automate so much of software engineering, including writing formal proofs, what role is left for the human engineer? We argue the core skill is writing and understanding specifications, the mathematically precise descriptions of what a program or component thereof is supposed to do. If you learn to pin down informal requirements exactly in formal specifications, then it becomes safe to let inscrutable AI systems find proofs or even code implementations alongside them. AI mistakes should only lead to failures of verification, not creation of incorrect code. The full promise of this method does depend on writing specifications that are more complete than we cover in 6.S057, for instance constraining performance or cybersecurity, but ongoing research is demonstrating increasing capabilities in those dimensions, as well.
Even if coding agents are taking over the proof-writing business, we believe understanding specifications depends critically on experience with what can be proved and how – hence our design of this class to guide you through exercises where you spell out many proof steps yourself, still augmented with Dafny’s significant native automation capabilities. Even if you never engage with another formal specification again, you should be better-equipped to write less-formal specifications in English, whether they are used to communicate with AI agents or human coworkers.
Some informed commentators feel that specifications have become more central to software engineering than ever, with formal specification as the ultimate embodiment of the craft, and we hope you’ve enjoyed what may have been a tour of what’s coming soon to a large software project near you!