Act VI · One Machine, Many Programs
Part 35 of 61Databases
How can a program say what data it wants and leave the database to work out how to find it?
The Job is written twice: as Part 17's program, every step chosen by hand, and as one line of SQL over the thirty novels loaded as 4,609,954 rows, with the same twenty words as the answer. Codd's 1970 idea, against the pointer-chasing programs of IMS and CODASYL, is that a query states its result. The part builds what that needs: relational algebra, functional dependencies and normal forms, Volcano iterators, four join algorithms costed in pages, and Selinger's dynamic program over join orders: the 120 orders of a five-table chain differ by a factor of 10,532. Its weak point is guessing sizes: under independence a city and its own country are estimated at 25 rows where 492 match. The part then turns from one query to many users: schedules, the precedence graph and conflict serializability, two-phase locking and its proof, snapshots and the write skew of two doctors on call, and six isolation levels against five anomalies. ARIES recovers a crashed log by analysis, redo and undo, column stores speed up analytics, and the part ends with our own database planning the Job as a hash aggregate, checked against sqlite3: ledger row 13.
What you need. Sets and relations; reading a little SQL helps. The hash tables and B-trees of Part 17 and the journal of Part 34 are assumed.
- Mathematics, ideas and history
- the relational model, algebra and SQL, joins, Selinger's optimizer, B+ trees, serializability, 2PL, MVCC and snapshot isolation, ARIES, column stores
- What we build or compute
- a relational database; the Job as SQL
What you will be able to do
Degree
- Write a query in relational algebra and in SQL, and evaluate it by hand on small tables.
- Compute an attribute closure, find a key, and decompose a table into BCNF without losing rows.
- Draw a schedule's precedence graph, decide whether it is conflict-serializable, and show that two-phase locking prevents a lost update.
Graduate
- Derive the page I/O of block nested loops, sort-merge and Grace hash joins, and choose among them for a given amount of memory.
- Run Selinger's dynamic program on a small join graph, and explain how independence assumptions make its size estimates fail.
- Recover a crashed log by ARIES's analysis, redo and undo passes, and explain why redo repeats history.
Research
- State the AGM bound for the triangle query and explain why a generic join meets it where every plan of binary joins does not.
- State what is open in learned cardinality estimation and in checking isolation from black-box histories, where serializability is NP-complete to test.
Industry
- Read a query plan from EXPLAIN, and decide whether an index, a covering index or fresh statistics will change it.
- Pick an isolation level knowing which anomalies it admits, and recognise write skew under snapshot isolation.
- Choose a row store or a column store for a workload from what each scan reads.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 25 min · Graduate 47 min · Research 51 min · Industry 30 min.
- 0One line of SQLDegree2 min
- 1Ask for what, not howDegree2 min
- 2Relational algebraDegree2 min
- 3Dependencies and normal formsDegree2 min
- 4How a query runsDegree2 min
- 5Joins, page by pageGraduate3 min
- 6The optimizerGraduate3 min
- 7Guessing sizesGraduate3 min
- 8IndexesDegree4 min
- 9TransactionsDegree3 min
- 10Two-phase lockingDegree3 min
- 11Optimism and snapshotsGraduate4 min
- 12Isolation levelsIndustry2 min
- 13Recovery: ARIESGraduate4 min
- 14Column storesIndustry3 min
- 15Our database runs the JobDegree2 min
- 16Frontier: joins, guesses, guaranteesResearch4 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
One line of SQLDegree2 min
For thirty parts the Job has been a program: tokenize the novels, count the words in a hash table, sort, print the top twenty. Every step of it chosen by hand, with the data structure, the hashing and the sort each a part of this course. Here is the same job as one line of SQL. It says what we want: for each word, how many times it occurs, the twenty most common. It says nothing about how. Loaded into a database as four point six million rows, one per word, it gives exactly the same twenty answers, and sqlite, on this machine, answers in about two seconds, with no instructions at all about hash tables or sorts.
So who decides how? A database turns the query into a plan in stages. The parser reads the SQL; the optimizer considers many plans that would all give the right answer, and estimates what each would cost; the executor runs the cheapest. Here is the plan our own database, built for this part, chose for the Job: scan the words, aggregate them in a hash table, and keep the top twenty in a heap. It found Part 17's program by itself. And underneath is a second machine, the transaction manager, which lets thousands of users read and write at once, each as if alone, even through crashes.
1Ask for what, not howDegree2 min
The first databases were structures you walked. IBM's IMS, built in the 1960s for the parts lists of the Apollo programme, stored records in a hierarchy: a library holds books, a book holds chapters. The CODASYL standard of 1969 joined records with pointers into a network. A program navigated: get this book; get the next chapter within it; and again, until the status code said there were no more. Every new question was a new program, written by someone who knew the pointers. And if the data was reorganised on disk, for speed, the old programs broke.
In 1970 Edgar Codd, a mathematician at IBM, proposed something else. Users of large shared databases, he wrote, must be protected from having to know how the data is organised in the machine. Data should be relations: sets of tuples, tables, with no pointers and no order. Tables connect through values: a key that identifies a book appears in the rows that refer to it. A query states what the result is, in logic, and the system works out how to compute it. And so the physical design, indexes, layout, the order of rows, can change without changing a single query. Many at IBM doubted it could be made fast. System R and Berkeley's Ingres proved it could, and System R's query language, SEQUEL, became SQL.
We can watch data independence at work in our own database. Here is a question about the novels: which books use the word whale most? Without an index on the word column, the database must read every page of the words table: twelve hundred pages, on a sample of the corpus. Add a B-plus tree on that column, and the same query, unchanged, reads 85 pages, because the optimizer now finds the whale rows through the index. Moby Dick, of course. The query never mentioned the index. That is Codd's point.
2Relational algebraDegree2 min
Codd gave his model an algebra: operators that each take tables and return a table, so they can be combined freely. Here are two small tables, books and authors. Selection keeps the rows that satisfy a condition: the books published before 1900. Projection keeps some columns, and drops the duplicate rows that may result: the authors. Join pairs every book with every author it agrees with on the shared column: now each book carries its author's year of birth. And the set operations, union and difference, work on tables of the same shape, here the books not in a second list, with renaming to make shapes match. That is all. Every question of the kind SQL asks is a composition of these.
Combining operators gives a tree. Which books did their authors publish before the age of forty-five? Join books to authors, select the rows where the year minus the birth year is under forty-five, and project the titles. In SQL it reads almost like English, and the database translates it back into a tree like this one. Emma, Persuasion and Ulysses qualify; Dracula does not: Stoker was fifty. Codd also showed that the algebra is exactly as expressive as a logic of tuples, the relational calculus, which is closer to how SQL states things. And because operators obey laws, the tree can be rewritten, selections pushed down, joins reordered, without changing the answer. Choosing among those rewritings is the optimizer's job.
3Dependencies and normal formsDegree2 min
Tables can be designed badly. Here is one that records students, their courses, each course's instructor, and the instructor's office. If Codd moves office, three rows must change, and an update that misses one leaves him with two offices. A course that has no students yet cannot be recorded at all, because every row needs a student. And when the last student drops the operating systems course, the fact that Ritchie sits in room w3 disappears with her. These are update, insertion and deletion anomalies, and they all have one cause: the table records several independent facts, and repeats each of them.
The theory that names the problem is functional dependency. A course determines its instructor, and an instructor determines an office: wherever two rows agree on the left side, they agree on the right. Armstrong's three axioms derive every dependency that follows from these, and no others. The closure of course is course, instructor and office. A key is a set whose closure is every attribute: here, the student and the course together. Boyce-Codd normal form asks that the left side of every dependency be a key. Course determines instructor and office, but course is not a key, so the table is not in normal form, and that is exactly where the repetition comes from.
The cure is to decompose. Split the table along the offending dependency, and repeat until every piece is in normal form: instructors and offices; courses and instructors; students and courses. Each fact is now stored once. The split must be lossless: joining the pieces must give back exactly the original rows, and the chase, a mechanical test, confirms it. A careless split, students and courses in one table, students, instructors and offices in another, fails the test: joining them invents rows that were never there. There is a price. Sometimes no Boyce-Codd decomposition keeps every dependency checkable inside one table. The third normal form, built by Bernstein's synthesis, always keeps them, at the cost of a little redundancy, and that is the compromise most designs make.
4How a query runsDegree2 min
A plan is a tree of operators, and almost every database runs it the same way. Each operator is an iterator, with three calls: open, next, close. Next returns one tuple, or says there are no more. The root asks its child for the next tuple, which asks its child, down to the scan, which reads a row from a page and passes it up. Tuples flow up one at a time, so the scan never stores the table. Some operators must see all their input before producing anything: a sort, a hash join building its table, an aggregate. Goetz Graefe's Volcano made this the standard model, because any operator can sit under any other.
Here is the Job's plan from our database, with what happened when it ran. The scan produced four point six million tuples. The hash aggregate folded them into fifty-eight thousand groups, one per distinct word. And the top-twenty operator kept a heap of twenty. The table was read once, forty-six thousand pages; the other plan, sorting the words to group them, was estimated at five times as many page reads, and rejected. Our engine, in Python, took seven seconds; sqlite, in C, two. The answers agree to the last count.
The first choice is how to reach each table: read it all, or use an index. Here is the whale query on a sample of the corpus, three ways. Scan the words and join with nested loops. Scan and hash join: the same pages, a cheaper join. Or, as the optimizer chose, look up whale in an index, fetch only those rows, and join the books to them: eighty-five pages instead of twelve hundred. Its guess was off, ten whale rows where there are eighty-one, but the choice was still right. Chapter 7 shows what happens when a guess is far worse.
5Joins, page by pageGraduate3 min
To compare join algorithms, count what is expensive. A disk moves whole pages, and in Part 34 a random page cost milliseconds while the processor's work on it cost microseconds. So the cost of a join is the number of pages read and written, given the size of each table in pages, M and N, and the number of pages of memory, B. Here R has four hundred pages and S two hundred. The simplest join fills memory with a block of R, keeping two pages for input and output, and reads all of S to find the matches, then the next block, and again. With five pages of memory, that is a hundred and thirty-four blocks, each reading all of S: twenty-seven thousand page reads, to join tables that hold only six hundred.
There are four classic ways to join. Block nested loops, which needs nothing: no index, no order. Index nested loops: for each row of R, look its key up in an index on S. Each lookup costs a page or two, so it wins when R is small. Sort-merge: sort both tables on the join key, with Part 16's external merge sort, then walk them together once. Its cost is the sorting passes, and its output comes out in order, which a later operator may want. And the hash join, in the form first built for the Grace database machine in Tokyo: hash both tables into buckets on disk, so that matching rows land in matching buckets, then join each pair of buckets in memory. Every page is read, written and read again: three times M plus N, as long as each bucket fits in memory.
Formulas like these fill database textbooks. Our joins count every page they touch, so we can check them, for five sizes of memory. Block nested loops and sort-merge match their formulas exactly, page for page. Index nested loops reads less than its formula, because the formula assumes every probe finds a match, and thirteen percent of R's keys have none. The hash join pays a little for buckets whose last page is half full, and with under forty pages of memory a bucket no longer fits, so a real system would partition it again. Most important, the winner changes. With eighty pages of memory the simplest join is the cheapest; with five, hashing is fifteen times cheaper. The right algorithm depends on the sizes, and only the database knows the sizes. That is why it, and not the programmer, should choose.
6The optimizerGraduate3 min
Here is a query that joins five tables in a chain, a to b to c to d to e, with sizes from fifty rows to thirty thousand, asking for the rows of a with small ids. Joins can be done in any order. Joining one table at a time, five tables can be ordered a hundred and twenty ways; allowing joins of joins, sixteen hundred and eighty. With twelve tables, which real queries reach, there are half a billion orders, and twenty-eight trillion trees. And each join has four algorithms, and each table may have indexes. Nobody can try them all. But look at the last column: the number of subsets of the tables grows far more slowly. That is the key to the solution.
Does the order matter? We can cost all hundred and twenty left-deep orders of our five tables, using hash joins throughout. They all compute the same count. The best starts with the ten rows of a that pass the filter, and grows along the chain, keeping intermediate results small: twenty-three hundred pages. The median order costs twenty times as much. The worst starts with b and d, which no condition connects, so the first join is a cross product, six hundred million pairs. Between the best and the worst is a factor of ten thousand. Choosing the order is the optimizer's most important decision.
Patricia Selinger's team at IBM found the method in 1979, for System R, and nearly every optimizer since descends from it. Work up from small sets of tables to large. For each set, keep only the cheapest plan that joins exactly those tables. To plan a set of tables, take away one table, look up the best plan for the rest, which is already known, and join the table back on, with every algorithm; keep the best result. This is dynamic programming, from Part 19, and it works because the best plan for a set is built from the best plans for its parts. One refinement: a more expensive sub-plan may be worth keeping if its output is sorted, because a later merge join or ORDER BY gets the order for free. Selinger called these interesting orders. Our database's optimizer does this. It costed 395 plans, where trying every order and algorithm costs twelve hundred, and found the same plan: start with a's ten rows, join along the chain. With more tables the gap becomes astronomical.
7Guessing sizesGraduate3 min
The optimizer's costs depend on how many rows each step produces, and it cannot know that without running the query. It guesses, from statistics. Our database keeps, for each table, the number of rows, and for each column the number of distinct values and the smallest and largest. An equality condition is guessed to keep one row in the number of distinct values; a range, the fraction of the span it covers. And two conditions together are assumed independent, so their fractions multiply. Here are a hundred thousand people. One city: the guess is five hundred, the truth 492. An age range: almost exact. A city and an age, which really are independent: right again. But a city and its own country: the guess is twenty-five, the truth 492. The country adds nothing once the city is known, and the independence assumption cannot see that.
Distinct counts assume every value is equally common, and real data is rarely like that. In a sample of the novels, a hundred and twenty thousand words with twelve thousand distinct, the guess for any single word is ten rows. Whale, eighty-one. Ship, twenty-six. Zeal, none at all. And the: six thousand, seven hundred and seventy-six. Word frequencies follow Zipf's law, which we met in Part 17, and the guess is wrong by a factor of almost seven hundred. A plan chosen for ten rows, a nested loop with an index probe per row, is a disaster for seven thousand. So real systems keep histograms, and a list of each column's most common values with their counts.
In a query with several joins, the errors compound. Each join's output is estimated from the estimates of its inputs, times a guessed fraction, so the errors multiply. Our chain query's guesses drift: four hundred rows guessed where 376 came, then 343, and by the end, thirty-nine thousand guessed for twenty thousand. Ioannidis and Christodoulakis proved in 1991 that such errors can grow exponentially with the number of joins. And when Viktor Leis and colleagues tested real optimizers on real data in 2015, they found estimates wrong by factors of ten thousand and more in every system. What saves us is that a plan only has to be good, not perfect, and a factor of two rarely changes the choice. When it does, systems now re-optimize in the middle of a query, or sample the data, or learn the estimates from experience, which is where the frontier is.
8IndexesDegree4 min
The index nearly every database uses is the B-tree of Rudolf Bayer and Edward McCreight, from 1972, in the variant called the B-plus tree. Here we insert twelve words from Moby Dick into a tiny one, where each node holds at most three keys. The first three go into one leaf, in order. The fourth overflows it. The leaf splits into two, and a copy of the first key of the right half goes up into a new root, as a separator: smaller keys to the left, others to the right. More inserts, more leaf splits, and each split adds a separator to the root. When the root itself is full, it splits, and a new root appears above it. That is the only way the tree grows taller, so every leaf is always at the same depth, and the tree is always balanced. To search, start at the root and follow the separators down, one node per level. And all the keys are in the leaves, linked in order, so a range is a search for its first key followed by a walk along the leaves.
In a real database each node is a page of the disk. A four-kilobyte page holds about four hundred keys and pointers, so each level multiplies the number of keys reachable by four hundred. A thousand keys need two levels, a million three, a billion four, a trillion five. The top levels are small enough to stay in memory, so finding any key costs about one read from the disk. Our database's index on the Job's word column covers four point six million rows and fifty-eight thousand distinct words in a tree two levels high. A binary search tree, from Part 17, would be at least sixteen levels deep, and on a disk each level is a seek. The price is paid on writes: each insert may split nodes, and a table with five indexes does six writes for every new row.
Finding keys in the index is only half of the work: the rows themselves must be fetched. Take the range from whale to whales: seventeen hundred rows of the Job's four point six million. The words table is stored in the order of the books, so those rows are scattered, and fetching them touches 966 different pages, more than one for every two rows. If the table were stored sorted by word, clustered on that key, the same rows would sit together on eighteen pages, fifty times fewer. A table can be in only one order, so it can be clustered on only one key, and the optimizer accounts for this when it estimates the cost of using an index. There are other kinds of index for other jobs: hash indexes for pure equality, bitmaps for analytics, the LSM trees of Part 34 for heavy writing, and inverted indexes for text. And an index that contains every column a query needs answers it without reading the table at all.
9TransactionsDegree3 min
Now the second machine inside a database. Move a hundred from Ana's account to Ben's: two updates, wrapped in a transaction. It must be atomic: if the machine crashes between the updates, the money must not vanish from one account without arriving in the other. Each transaction, run alone, keeps the data consistent: here, the total stays the same. It must be isolated: while thousands of transactions run at once, each must behave as if it ran by itself. And it must be durable: once the commit returns, the transfer survives any crash. Jim Gray set out these ideas; Härder and Reuter gave them their initials, ACID. Atomicity and durability come in chapter thirteen. Isolation takes the next four.
What does it mean for interleaved transactions to be correct? A schedule is the order in which their steps happen. Here two transactions each read x and write it back, plus something: two deposits. Both read the old balance; both write; the second write overwrites the first, and one deposit is lost. Two steps conflict if they come from different transactions, touch the same item, and at least one writes; then their order matters. Draw an arrow from the transaction that went first to the one that went second. Here T1 read x before T2 wrote it, and T2 read x before T1 wrote it: arrows both ways, a cycle. No serial order is equivalent. Here is another interleaving, of two transactions touching x and y. Every conflict has T1 first, so the graph is one arrow, and the schedule is equivalent to running T1, then T2. That is the theorem of Eswaran, Gray, Lorie and Traiger, from 1976: a schedule is conflict-serializable exactly when its graph has no cycle.
There is a wider definition. In this schedule, T2 and T3 write x without reading it, blind writes, and the conflict graph has a cycle. Yet T1 reads the value it would read if the three ran in order, and the last write is T3's, as in that order. The schedule is view serializable: no one could tell the difference. But testing view serializability is NP-complete, as Christos Papadimitriou showed in 1979, while a cycle check takes linear time. Our checker enumerates all ninety interleavings of three small transactions. Ten are conflict-serializable, and here no others are view-serializable either. So databases aim for conflict serializability, and they must achieve it on the fly, deciding each step as it arrives, without knowing what comes next.
10Two-phase lockingDegree3 min
The classic answer is locking. Before reading an item, a transaction takes a shared lock on it; before writing, an exclusive lock. Many readers can share, but a writer excludes everyone, and a request that conflicts must wait. Locks alone are not enough. The rule that makes them work is two-phase locking: a transaction may acquire locks, then release them, but never acquire another after its first release. Its locks grow, peak, and shrink. Here is why this suffices. If T i comes before T j in the conflict graph, then T j obtained a lock that T i had released, so T i passed its peak, its lock point, first. A cycle in the graph would put some lock point before itself, which is impossible. So every schedule two-phase locking allows is serializable, equivalent to running the transactions in the order of their lock points. In practice the locks are held until commit, strict two-phase locking, so that nobody reads a value that might still be rolled back. And there are choices about what to lock, rows or pages or whole tables, and how to lock ranges, so that a new row cannot appear in the middle of someone's query.
Locking has a price. T1 reads A and will write B; T2 reads B and will write A. Run them interleaved. Each takes its shared lock. Then T1 asks for B, which T2 holds, and waits; T2 asks for A, which T1 holds, and waits. Each waits for the other, and will wait forever: a deadlock, the cycle in the waits-for graph that Part 33 met in the dining philosophers. A database does not prevent it by careful lock order, because transactions are written by users. It finds the cycle and aborts one transaction, which releases its locks. Our scheduler aborted T2, and T1 finished. T2 can simply be run again.
There are two families of remedy. Detection lets transactions wait, and looks for cycles. Prevention uses age. In wait-die, an older transaction may wait for a younger one, but a younger one that asks for an older one's lock is aborted on the spot. In wound-wait, it is the other way round: an older transaction aborts the younger holder, and a younger one waits. Either way, waiting only goes in one direction of age, so no cycle can form, and a restarted transaction keeps its original age, so it eventually becomes the oldest and wins. We ran four hundred random mixes of four transactions under each policy. Every resulting schedule passed the serializability check. Detection found 342 deadlocks and aborted only those; the prevention schemes never deadlocked, but aborted more than twice as many transactions, many of which would never have deadlocked. That is why most systems detect.
11Optimism and snapshotsGraduate4 min
Locking is pessimistic: it assumes conflict and makes transactions wait. H. T. Kung and John Robinson proposed the opposite in 1981. Let each transaction run freely on private copies, and check only at the end: did any transaction that committed in the meantime write something I read? If not, install my writes; if so, start again. Nobody waits and nothing deadlocks. When conflicts are rare this is fast; when they are common, work is thrown away again and again. A third method gives each transaction a timestamp when it starts, and rejects any read or write that arrives too late to fit that order. All three produce serializable schedules. They differ in who waits, and who starts over.
What most databases actually do today is keep the old versions. Each write creates a new version of the item, stamped with the time its transaction committed, and the old ones remain. A transaction that started at time nine reads the newest version committed before nine, here twenty-five, however many writes have come since. It sees a consistent snapshot of the whole database as of its start. This is multiversion concurrency control, from David Reed's thesis of 1978. Readers never wait for writers, and writers never wait for readers. Only two writers of the same item collide, and the first to commit wins. This is snapshot isolation. It is what Oracle gives when you ask for serializable, and what PostgreSQL gives at repeatable read. It feels serializable. It is not.
Here is the classic counterexample. A hospital requires at least one doctor on call. Alice and Bob are both on call, and both feel ill. Each runs the same transaction: count the doctors on call, and if there are two, take myself off. Under snapshot isolation, both start from the same snapshot, both count two, and Alice takes herself off while Bob takes himself off. Our database, run at each isolation level, shows the result. At read committed and at snapshot isolation, both commit, and nobody is on call. The two transactions wrote different rows, so the first-committer rule never fired. Yet in any serial order the second would have counted one and stayed. This anomaly is write skew. At the serializable level, with two-phase locking, one of them is aborted and the rule holds.
Can snapshots be made serializable without giving up their speed? Look at what happened. T1 read Bob's row, which T2 then overwrote: an arrow from T1 to T2, called a read-write antidependency. And T2 read Alice's row, which T1 overwrote: an arrow back. A cycle. Alan Fekete and colleagues proved in 2005 that every anomaly of snapshot isolation contains a transaction with such an arrow coming in and another going out. In 2008 Michael Cahill turned this into an algorithm: track the read-write arrows as transactions run, and abort any transaction that becomes such a pivot. Our database implements it. T1 is aborted, Alice stays on call, and readers still never wait. PostgreSQL has used this method for its serializable level since 2011. Its cost is an occasional abort that was not strictly necessary.
12Isolation levelsIndustry2 min
SQL lets each transaction choose how much isolation it gets. Our database implements six levels, and we ran each of five classic anomalies against each, as a little program and an interleaving, and recorded whether the anomaly happened. A dirty read sees a write that is later rolled back. A non-repeatable read reads the same item twice and gets two values. A lost update we have seen. A phantom is a row that appears between two counts. Write skew is the doctors. Read uncommitted permits everything. Read committed, the default in PostgreSQL, Oracle and SQL Server, stops only dirty reads. Repeatable read, with locks on what was read, stops all but phantoms. Snapshot isolation stops phantoms but not write skew: the two weaker-than-serializable levels fail in different places, so neither is stronger than the other. And only the serializable levels, by locking or by SSI, stop all five.
The standard's definitions turned out to be a problem. SQL-92 defined each level by the phenomena it forbids, described in English. In 1995 Hal Berenson, Phil Bernstein, Jim Gray and colleagues showed that the wording was ambiguous, that it missed anomalies such as lost updates and write skew, and that snapshot isolation, already shipping, fitted none of the levels. Atul Adya's thesis of 1999 put it right. Draw a graph whose nodes are committed transactions and whose edges are the dependencies between them: who read whose write, who overwrote whose, who overwrote what someone else had read. Each level forbids a kind of cycle. Serializable forbids them all; snapshot isolation allows a cycle with two consecutive anti-dependencies, which is write skew. These definitions do not mention locks or versions, so they apply to any implementation, and can be checked after the fact on what actually happened. That is exactly what the tool Elle does, and testing real databases with it has found many that do not deliver the level they promise.
13Recovery: ARIESGraduate4 min
Part 34 made a file system survive crashes with a journal. A database faces the same problem with stricter demands, and the standard answer is ARIES, by C. Mohan and colleagues at IBM, from 1992. Pages are changed in a buffer in memory, and the buffer writes them back when it likes. ARIES allows it to steal: to write a page that an uncommitted transaction has changed. So after a crash, the disk may hold changes that must be undone. And it allows no-force: a commit does not wait for the data pages to be written. So the disk may lack committed changes, which must be redone. Both are safe because of one rule, write-ahead logging: every change is first described in an append-only log, and a page may go to disk only after its log records have. A transaction has committed when its commit record is on disk. Each log record holds its sequence number, its transaction, the page, the values before and after, and a pointer to the transaction's previous record. And each page records the sequence number of the last change applied to it.
Here is a crash, from our implementation. Three transactions updated four pages. The log that reached the disk has twelve records: T3 made three updates to page 0, committed, and ended; T2 updated page 1 three times and committed; T1 updated pages 3 and 2 and 3 again, and had not committed. Then the power failed. The buffer pool is gone; the disk has whatever pages happened to be written. Page 0 has the value 72, from T3's first update: its last two updates never reached the disk, though T3 committed. And page 3 holds T1's first change, though T1 never committed. The right state is on the right: every committed change, and none of T1's.
Recovery runs in three passes. Analysis reads the log forward and rebuilds what memory held: which transactions were active, here only T1, the loser, and which pages may have been dirty, which tells redo where to start. Redo reads forward again and repeats history: it reapplies every logged update, including the loser's, except where the page's own sequence number shows the change already reached the disk. Four updates are redone and five skipped. Now the pages are exactly as they were at the instant of the crash. Undo then walks the loser's records backward through their pointers, 11, then 5, then 1, restoring the before values. Each undo is itself logged, as a compensation record, which says where undoing should resume. If the machine crashes during recovery, the next recovery redoes these records and never undoes the same change twice. The result is exactly the committed state.
One example proves little, so we crash it on purpose. Five hundred random workloads, each cut off by a crash at a random moment, then recovered: every one ends in exactly the committed state. Then the same five hundred, crashed again partway through undo, and recovered a second time: all five hundred correct. In real systems, checkpoints bound the work: from time to time the tables that analysis rebuilds are written to the log, and analysis begins there instead of at the start of time. ARIES's ideas, write-ahead logging, repeating history, logged undo, are in DB2 and SQL Server and many others. PostgreSQL gets by with redo alone, because its old row versions stay in the table, and a version written by a transaction that never committed is simply invisible.
14Column storesIndustry3 min
Everything so far has stored a table row by row, every attribute of a row together on a page. That suits transactions, which fetch or change a whole row: one order, one account. But turn the table sideways and store each column on its own pages. An analytic query, adding up one column over the rows that pass a test on another, touches two attributes of millions of rows. A row store must carry all sixteen columns through the memory hierarchy to get at two. A column store reads only those two, each a contiguous array: an eighth of the bytes.
We measured this, on a million rows of sixteen columns: add one column where another is under a hundred. Processing one tuple at a time, as an interpreter running the iterator model does, takes seventy-four milliseconds. Processing whole arrays of values per operation, which is called vectorized execution, on the row layout: fourteen milliseconds, because the loops are tight and the per-call overhead is paid once per thousand values, not once per row. And vectorized on the column layout: four milliseconds, because it moves sixteen megabytes instead of a hundred and twenty-eight. The other modern answer is to compile each query into machine code, as HyPer does: the compiler of Part 13, invoked for every query.
Storing columns apart has a second payoff. The Job's words table records, for each word, which book it came from, and the rows are in book order, so that column is thirty long runs. Stored run by run, four point six million values, thirty-seven megabytes, become four hundred and eighty bytes. The word column has fifty-eight thousand distinct values, so each can be replaced by a sixteen-bit code into a dictionary, and twenty-four megabytes become under ten. A column holds values of one type, often sorted, often repeated, and so it has far less entropy than a row of mixed fields. Better still, operators can work on the compressed form directly: the sum of a run is its value times its length. Michael Stonebraker's C-Store showed all of this in 2005. Today almost every analytic system stores columns: Parquet files, BigQuery, Snowflake, ClickHouse, and DuckDB, which runs inside a program the way sqlite does.
15Our database runs the JobDegree2 min
Back to the Job. Our database considered two ways to group the words. Hash aggregation: keep a hash table of counts, one entry per distinct word. Fifty-eight thousand entries fit in memory, so it reads the table once: forty-six thousand pages. Sort aggregation: sort all four point six million rows by word, so equal words are adjacent, and count the runs. The rows do not fit in memory, so the sort writes runs to disk and merges them: five times the page traffic. So it chose hashing. Part 16 sorted the words and Part 17 replaced the sort with a hash table and was six times faster. The optimizer made the same decision from its cost model, without being told.
We check our database against sqlite, the most widely deployed database in the world, which ships inside every phone and every browser. Its plan: scan the words, and group them in a temporary B-tree, a sort by another name. Our engine, written in Python, takes seven seconds. Sqlite, in C, takes two and a quarter. Give sqlite an index on the word column and it changes plan by itself: the index holds the words already in order, so it reads the index alone, counting runs, in a quarter of a second. The query did not change. Every one of these gives the same twenty words with the same counts as Part 17's hand-written program.
The ledger gets row thirteen. One line of SQL, answered by sqlite on this machine in two and a quarter seconds, and we never said how. That is slower than Part 24's engineered C, by about thirty times, and that program took a whole part to write. With an index it is a quarter of a second. And the same database answers the whale question, or any other, with one more line and no new program. That trade, some speed for never having to say how, is Codd's bargain, and the world took it.
16Frontier: joins, guesses, guaranteesResearch4 min
Everything in this part's optimizer joins two tables at a time. Here is a query where that is provably the wrong idea. Join an edge table to itself three times to find triangles in a graph: a and b connected, b and c, and c back to a. Any plan made of two-way joins must first join two of the three, which produces every path of two edges. In a graph with a few hubs, a node with d edges makes about d squared over two such paths, and almost none of them close a triangle. On our graphs, four and a half thousand edges give over a million paths, to find four hundred and thirty-two triangles. A different kind of join binds one variable at a time: for each edge, intersect the neighbour lists of its two ends. Ten thousand steps instead of a million.
How large can the answer to a join be? In 2008 Albert Atserias, Martin Grohe and Dániel Marx gave an exact answer for any join query: the product of the table sizes, each raised to a weight from a small linear program, the fractional edge cover. For triangles, each table gets weight one half, and the bound is N to the three halves: with forty-five hundred edges, at most three hundred thousand triangles could exist. But a plan of binary joins can take time proportional to N squared on such inputs, more than the largest possible answer. In 2012 Hung Ngo and colleagues found join algorithms whose running time never exceeds the bound, and Todd Veldhuizen's leapfrog triejoin is a practical one. They are called worst-case optimal. They now appear in commercial and research systems, and the open questions are when to use them instead of ordinary joins, and how to estimate their cost.
The second frontier is estimation. We saw how badly independence assumptions fail. One line of research trains models, on the data itself or on the queries already run, to predict the sizes of results, capturing correlations that histograms miss. Another learns the plans directly. Neo, in 2019, replaced the optimizer with a neural network trained on experience. Bao, two years later, was more modest: it keeps the classical optimizer and learns only which hints to give it, query by query. The difficulty is trust. A model can be wrong in ways no one predicted, and a query that suddenly takes an hour instead of a second is worse for its users than one that was always a little slow. The goal is learning with guarantees: never much worse than the classical method, often much better.
The third frontier is checking. How do we know a database delivers the isolation it promises? Run many transactions against it at once, record what each read and wrote, and check the history. In general this is hard: deciding whether a history is serializable is NP-complete, and so, it was shown in 2019, is deciding snapshot isolation, although read committed is easy. The way out is to design the test so that every read reveals which write it saw, for example by appending to lists and reading whole lists. Then the dependency graph of chapter twelve can be built directly and searched for cycles. Elle does exactly this, and Cobra uses a constraint solver; between them they check millions of operations, and they have found real anomalies in many shipped databases. Further out are proofs: verified semantics for SQL and verified rewrites, though in general deciding whether two SQL queries are equivalent is undecidable, a cousin of Part 25's halting problem.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. A relational database: Codd's algebra over tables, the theory of good design, a SQL parser, iterators, four join algorithms whose page counts match their formulas, and Selinger's optimizer, searching subsets instead of orders, with the statistics it relies on and the ways they fail. B-plus trees. Then transactions: serializability and its graph, two-phase locking and deadlock, snapshots and write skew, the isolation levels, and ARIES recovering from five hundred crashes. Column stores, and the Job as one line of SQL.
Where this comes back. Part 39 stretches transactions across machines, with two-phase commit and Spanner's clocks. Part 43 builds services on top of a database, with idempotent requests and sagas in place of distributed transactions. Part 46 turns the write-ahead log into a stream that other systems follow, and builds warehouses on column stores. Part 47 scales the inverted index to the web. And Part 48 puts shards, replicas and caches in front of a database.
In practice. Start with PostgreSQL; use SQLite inside a program and DuckDB for analysis on one machine. When a query is slow, run EXPLAIN ANALYZE and compare the estimated rows with the actual rows: a large gap means the statistics are stale or the columns are correlated. Index the columns your queries filter, join and sort on, and remember that every index slows every write. Know your isolation level, which is usually read committed, and when an invariant spans several rows, like the doctors on call, use serializable and retry on aborts. And normalize first; denormalize only when you have measured why.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give our database histograms, and watch the estimate for the most common word come right. The last, marked with a star, is a research problem: how many of serializable snapshot isolation's aborts were really necessary, and how few can any scheduler that sees only read-write conflicts make?
Next time, Part 36: Networks, moving bits. The telephone network reserved a wire for every call; Paul Baran and Donald Davies proposed cutting messages into packets that find their own way. We derive what limits each layer of the Internet, from Shannon's capacity to ALOHA's one over two e, and route packets across a network of our own. Part 36, Networks.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 39 stretches transactions across machines with two-phase commit and Spanner's clocks. Part 43 builds services on a database, with idempotent requests and sagas; Part 46 turns the write-ahead log into a stream and builds warehouses on column stores; Part 47 scales the inverted index to the web; Part 48 puts shards, replicas and caches in front of a database.
Key results
The part's results in one place, for revision.
Try it
Lab 35 · Joins by the page, and which interleavings are safe
Join a 400-page table with a 200-page table by block nested loops, sort-merge and Grace hash with 5 to 80 pages of memory, and compare every measured page count with its formula. Then test interleaved transactions with the precedence graph, against a brute-force search over serial orders, with and without two-phase locking.
python -m videos.cs.labs 35
needs numpy, scipy, matplotlib · download lab35.py ·
source on GitHubB = 5: block nested loops measured 27,200 formula 27,200
B = 5: sort-merge measured 6,200 formula 6,200
B = 80: block nested loops measured 1,600 formula 1,600
B = 80: sort-merge measured 3,000 formula 3,000
Grace hash, formula 3(M + N) 1,800 (measured within 12% at every B; buckets fit in memory from B = 40)
interleavings of three transactions 90, conflict-serializable: 10 (the film: 90 and 10)
random interleavings serializable, 2 / 3 / 4 transactions 66% 36% 16% with strict 2PL: 100% 100% 100%
The cheapest join depends on the memory: block nested loops with 80 buffer pages, hashing with 5. Most interleavings are not serializable, and the precedence graph finds exactly the ones that are; two-phase locking admits only those.
The code (114 lines; it asserts its own result)
"""Lab 35: count the page I/Os of four join algorithms, then test schedules for serializability."""
from videos.coursekit import labs # noqa: I001 (first, so the library imports without manim)
import itertools
import numpy as np
from explainer.cs.db import joins
from explainer.cs.db import txn
TITLE = "Joins by the page, and which interleavings are safe"
GOAL = ("Join a 400-page table with a 200-page table by block nested loops, sort-merge and Grace hash with 5 to 80 "
"pages of memory, and compare every measured page count with its formula. Then test interleaved "
"transactions with the precedence graph, against a brute-force search over serial orders, with and "
"without two-phase locking.")
TASKS = [
"Make the outer table 10 times larger (n_r=200_000) at B = 80. Which join wins now, and what does the formula say?",
"Run txn.run_2pl with policy='wait-die' and 'wound-wait' and count r['aborted']. Which aborts more, and why?",
"Count how many of the 90 interleavings are view-serializable (txn.view_serializable). Which ones are new?",
]
BUFFERS = (5, 10, 20, 40, 80)
THREE = {1: [("r", "x"), ("w", "y")], 2: [("r", "y"), ("w", "x")], 3: [("w", "x"), ("w", "y")]} # Chapter 9's three
def schedule(programs, order):
"""Interleave the programs in this order of turns, with no locks, and commit them all."""
at = dict.fromkeys(programs, 0)
s = []
for t in order:
if at[t] < len(programs[t]):
s.append((t, *programs[t][at[t]]))
at[t] += 1
return s + [(t, "c", None) for t in programs]
def serial_order_exists(s):
"""Brute force: is there an order of the transactions that every conflicting pair of steps respects?"""
ops = [st for st in s if st[1] in "rw"]
pairs = {(a[0], b[0]) for i, a in enumerate(ops) for b in ops[i + 1:]
if a[0] != b[0] and a[2] == b[2] and "w" in (a[1], b[1])}
names = sorted({st[0] for st in s})
return any(all(p.index(a) < p.index(b) for a, b in pairs) for p in itertools.permutations(names))
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. joins, page by page (Chapter 5): M = 400 and N = 200 pages of 50 rows
rows = {B: joins.compare(B=B, seed=seed) for B in BUFFERS}
for B in (5, 80):
m, f = rows[B]["measured"], rows[B]["formula"]
lab.row(f"B = {B}: block nested loops", f"measured {m['block nested loops']:,} formula {f['block nested loops']:,}")
lab.row(f"B = {B}: sort-merge", f"measured {m['sort-merge']:,} formula {f['sort-merge']:,}")
for B in BUFFERS:
m, f = rows[B]["measured"], rows[B]["formula"]
assert m["block nested loops"] == f["block nested loops"] and m["sort-merge"] == f["sort-merge"], B
assert abs(m["grace hash"] / f["grace hash"] - 1) < 0.12, "partial pages cost Grace hash a few percent"
assert m["index nested loops"] <= f["index nested loops"], "keys without a match read no data page"
small, large = rows[5]["measured"], rows[80]["measured"]
lab.row("Grace hash, formula 3(M + N)", f"{rows[5]['formula']['grace hash']:,} (measured within 12% at every B;"
f" buckets fit in memory from B = {min(B for B in BUFFERS if rows[B]['buckets_fit'])})")
assert min(large, key=large.get) == "block nested loops", "with 80 pages of memory the simplest join wins"
assert min(small, key=small.get) == "grace hash" and small["block nested loops"] > 10 * small["grace hash"]
# 2. conflict serializability (Chapter 9): the 90 interleavings of three two-step transactions
orders = sorted(set(itertools.permutations([1, 1, 2, 2, 3, 3])))
good = sum(txn.conflict_serializable(schedule(THREE, o))[0] for o in orders)
lab.row("interleavings of three transactions", f"{len(orders)}, conflict-serializable: {good} (the film: 90 and 10)")
assert (len(orders), good) == (90, 10)
# 3. the precedence graph against brute force, and what two-phase locking guarantees (Chapter 10)
free, locked = {}, {}
for n in (2, 3, 4):
ok_free = ok_2pl = 0
for _ in range(300):
progs = {t: [(str(rng.choice(["r", "w"])), str(rng.choice(list("ABC")))) for _ in range(3)]
for t in range(1, n + 1)}
order = [int(t) for t in rng.integers(1, n + 1, 12 * n)]
s = schedule(progs, order + list(progs) * 3)
verdict = txn.conflict_serializable(s)[0]
assert verdict == serial_order_exists(s), "no cycle exactly when a serial order exists"
assert not verdict or txn.view_serializable(s)[0], "conflict-serializable implies view-serializable"
ok_free += verdict
ok_2pl += txn.conflict_serializable(txn.run_2pl(progs, order)["schedule"])[0]
free[n], locked[n] = ok_free / 300, ok_2pl / 300
lab.row("random interleavings serializable, 2 / 3 / 4 transactions",
" ".join(f"{free[n]:.0%}" for n in (2, 3, 4)) + " with strict 2PL: "
+ " ".join(f"{locked[n]:.0%}" for n in (2, 3, 4)))
assert all(v == 1.0 for v in locked.values()), "every 2PL schedule is conflict-serializable"
assert free[4] < free[2] < 0.9
lab.note = ("The cheapest join depends on the memory: block nested loops with 80 buffer pages, hashing with 5. "
"Most interleavings are not serializable, and the precedence graph finds exactly the ones that "
"are; two-phase locking admits only those.")
fig, ax = labs.figure(2, size=(11, 4.2))
for name, c in (("block nested loops", labs.RED), ("sort-merge", labs.BLUE), ("grace hash", labs.GREEN)):
ax[0].plot(BUFFERS, [rows[B]["formula"][name] for B in BUFFERS], color=c, label=f"{name}, formula")
ax[0].plot(BUFFERS, [rows[B]["measured"][name] for B in BUFFERS], "o", color=c)
ax[0].plot([], [], "o", color=labs.GREY, label="measured page I/Os")
ax[0].set(title="Joining 400 pages with 200", xlabel="buffer pages B", ylabel="page I/Os", xscale="log",
yscale="log", xticks=BUFFERS, xticklabels=[str(b) for b in BUFFERS])
ax[0].minorticks_off()
ax[0].set_yticks([2000, 5000, 10000, 20000], ["2,000", "5,000", "10,000", "20,000"])
ax[0].legend()
x = np.arange(3)
ax[1].bar(x - 0.2, [free[n] for n in (2, 3, 4)], width=0.4, color=labs.RED, label="no locks")
ax[1].bar(x + 0.2, [locked[n] for n in (2, 3, 4)], width=0.4, color=labs.GREEN, label="strict two-phase locking")
ax[1].set_xticks(x, ["2 transactions", "3", "4"])
ax[1].set(title="Random interleavings that are conflict-serializable", ylabel="fraction of 300", ylim=(0, 1.3))
ax[1].legend(loc="upper right", ncols=2)
lab.fig = fig
return lab
Now change it
- Make the outer table 10 times larger (n_r=200_000) at B = 80. Which join wins now, and what does the formula say?
- Run txn.run_2pl with policy='wait-die' and 'wound-wait' and count r['aborted']. Which aborts more, and why?
- Count how many of the 90 interleavings are view-serializable (txn.view_serializable). Which ones are new?
Problems, with solutions
Try each problem before opening its solution.
-
Conflict serializability. Prove that a schedule is conflict-serializable if and only if its precedence graph is acyclic.
Solution
(⇒) Suppose the schedule is conflict-equivalent to the serial order T_{π1}, …, T_{πn}. Equivalence preserves the order of every pair of conflicting operations, and in the serial schedule every operation of an earlier transaction precedes every operation of a later one. So each edge Ti → Tj (some operation of Ti precedes a conflicting one of Tj) points forward in π, and a graph whose edges all point forward in a linear order has no cycle. (⇐) If the graph is acyclic, take a topological order π. Repeatedly swap adjacent operations of different transactions that are out of π's order. Such a pair cannot conflict (a conflict would be an edge pointing backward in π), and swapping non-conflicting adjacent operations preserves equivalence. Each swap removes one inversion, so the process ends in the serial schedule for π.
-
Two-phase locking. Prove that every schedule produced by two-phase locking is conflict-serializable, and give a serializable schedule that 2PL cannot produce.
Solution
Let ℓ(T) be T's lock point, the moment it holds its last new lock. If Ti → Tj, some operation of Tj conflicts with an earlier one of Ti on an item x; Tj could lock x only after Ti released it, and Ti released nothing before ℓ(Ti), so ℓ(Ti) < (Ti's release of x) < (Tj's lock of x) ≤ ℓ(Tj). A cycle would give ℓ(T) < ℓ(T). So the graph is acyclic and, by problem 1, the schedule is serializable, in lock-point order. The schedule w1(x) r2(x) w1(y) is serializable (T1 then T2, the only conflict being on x), but under 2PL T1 must release x before T2 reads it, and then cannot lock y. 2PL's schedules are a strict subset of the conflict-serializable ones.
-
Sort and hash costs. Derive the I/O cost of external merge sort with B buffers, and the memory Grace hash join needs for one partitioning pass.
Solution
Pass 0 reads M pages B at a time and writes ⌈M/B⌉ sorted runs; each later pass merges B − 1 runs into one (one input buffer per run, one output buffer), so ⌈log_{B−1}⌈M/B⌉⌉ merge passes follow. Every pass reads and writes every page: 2M(1 + ⌈log_{B−1}⌈M/B⌉⌉) I/Os, which is the formula our counts matched exactly (for M = 400, B = 5: 5 passes, 4,000 I/Os). Grace hash splits R into B − 1 buckets of about M/(B − 1) pages; the build phase holds one bucket in B − 2 pages, so it needs M/(B − 1) ≤ B − 2, about B ≥ √M. For M = 400 that is B ≥ 21; with uneven buckets our measurement needed B = 40, which is why the formula 3(M + N) is printed in red below that.
-
Plan space. Count the bushy join trees over n tables, and the work of Selinger's dynamic program on chain, star and clique queries.
Solution
A join tree is a full binary tree with n labelled leaves. There are C_{n−1} = (2n − 2)!/(n!(n − 1)!) shapes (Catalan) and n! ways to place the tables, so n!·C_{n−1} = (2n − 2)!/(n − 1)! trees: 1,680 for n = 5, 28,158,588,057,600 for n = 12. The dynamic program does work proportional to the number of (connected subset, way to split it) pairs. A chain has n(n + 1)/2 connected subsets (intervals), and an interval of k tables has k − 1 splits into two intervals: Θ(n³) bushy, Θ(n²) left-deep. A star (one hub, n − 1 leaves) has 2^{n−1} connected subsets containing the hub, each with up to n − 1 ways to remove a leaf: Θ(n·2^n) left-deep. A clique has 2^n − 1 subsets, all connected, and splitting every subset into two non-empty parts gives (3^n − 2^{n+1} + 1)/2 pairs: Θ(3^n) bushy, Θ(n·2^n) left-deep. This is why systems fall back to greedy or genetic search beyond a dozen or so tables (PostgreSQL's
geqo_thresholdis 12). -
Build: histograms. Add a histogram per column to our database's statistics, and measure the
word = 'the'estimate before and after.Solution
The simplest effective form is PostgreSQL's: a list of the k most common values with their exact counts, plus an equi-depth histogram (or, for equality, a uniform guess) for the rest. In
Database.analyze, keepCounter(col).most_common(k); in the selectivity estimate forcol = v, return the stored count if v is in the list, else (rows − Σ listed counts)/(distinct − k). On the 120,000-word sample with k = 100: the top 100 words hold 63,367 occurrences, so the is estimated exactly, 6,776 (it was 9.9). Every other word is now estimated at (120,000 − 63,367)/12,066 ≈ 4.7: ship, 26, is now off by 5.5× instead of 2.6×, and whale, 81, by 17× instead of 8×. The list fixes the frequent values, which matter most for plan choice, and slightly worsens the rest. For ranges, an equi-depth histogram with b buckets bounds the error of any range estimate by about 2/b of the rows. -
★ Research. False aborts. On random workloads, how many of SSI's aborts were unnecessary? Find the fewest aborts any online scheduler that sees only rw-edges can make, and a rule that achieves it.
What is known, and a way in. An abort is necessary only if committing the transaction would make the history non-serializable; SSI aborts whenever a pivot (an rw-edge in and an rw-edge out) appears, but a pivot is dangerous only if the two edges close a cycle. Measure first: run
txn.run_level("snapshot + SSI", …)on random programs; for each abort, re-run the schedule with that transaction allowed to commit and test the committed history withtxn.conflict_serializable(with the rw-, wr- and ww-dependencies of Adya's graph). Cahill's original rule aborted on any pivot; PostgreSQL's implementation (Ports and Grittner 2012) aborts only if the outgoing transaction commits first and ignores safe read-only transactions, and reports far fewer false aborts. A lower bound needs an indistinguishability argument: two histories identical in their rw-edges up to the moment of decision, one of which closes a cycle later through a wr-edge the scheduler cannot yet see. Any online scheduler that must decide at commit time must abort both or risk the bad one, so some false aborts are forced; the open question is the optimal competitive ratio against an offline scheduler that knows the whole history, and a practical rule that attains it.
Notes and sources
Glossary
- relation: a set of tuples over named attributes; a table with no row order and no duplicates.
- key: a minimal set of attributes whose values identify a tuple; foreign key: a key of another table, stored to refer to its row.
- relational algebra: selection σ, projection π, join ⋈, union ∪, difference −, renaming ρ.
- functional dependency X → Y: rows that agree on X agree on Y; closure X⁺: everything X determines.
- BCNF: every non-trivial dependency's left side is a key; 3NF: or its right side is part of a key.
- lossless decomposition: one whose pieces join back to exactly the original.
- iterator (Volcano) model: operators with open, next and close, pulling tuples from their children.
- selectivity, cardinality: the fraction of rows a condition keeps; the number of rows an operator produces.
- left-deep plan: a join tree whose right child is always a base table; bushy: any shape.
- interesting order: a sort order of an intermediate result that a later operator can use.
- B+ tree: a balanced search tree of page-sized nodes with all keys in linked leaves.
- clustered index: one whose order is the table's storage order.
- transaction, ACID: atomic, consistent, isolated, durable.
- schedule: an interleaving of transactions' operations; conflict: two operations of different transactions on the same item, one a write.
- conflict-serializable: equivalent, by swapping non-conflicting operations, to a serial schedule.
- two-phase locking (2PL): no lock acquired after one is released; strict 2PL: write locks held to commit.
- deadlock: a cycle of transactions each waiting for another; wait-die, wound-wait: prevention by age.
- MVCC: keeping old versions so readers see a snapshot; snapshot isolation: reads from the snapshot at start, first committer wins.
- write skew: two transactions read overlapping data and write disjoint data, breaking an invariant.
- SSI: serializable snapshot isolation, aborting pivots of rw-antidependencies.
- isolation level: the anomalies a database promises to prevent.
- WAL (write-ahead log); LSN (log sequence number); steal, no-force; CLR (compensation log record).
- ARIES: recovery by analysis, redo (repeating history) and undo, with CLRs.
- column store: a table stored column by column; vectorized execution: operators over arrays of values.
- worst-case optimal join: a join whose time is bounded by the AGM bound on its largest possible output.
Sources
- A. Silberschatz, H. F. Korth and S. Sudarshan, Database System Concepts.
- R. Ramakrishnan and J. Gehrke, Database Management Systems.
- H. Garcia-Molina, J. D. Ullman and J. Widom, Database Systems: The Complete Book.
- J. M. Hellerstein and M. Stonebraker (eds.), Readings in Database Systems (the Red Book).
- J. Gray and A. Reuter, Transaction Processing: Concepts and Techniques.
- P. A. Bernstein, V. Hadzilacos and N. Goodman, Concurrency Control and Recovery in Database Systems.
- G. Weikum and G. Vossen, Transactional Information Systems.
- S. Abiteboul, R. Hull and V. Vianu, Foundations of Databases.
- E. F. Codd, "A Relational Model of Data for Large Shared Data Banks", CACM (1970); "Relational Completeness of Data Base Sublanguages" (1972).
- D. D. Chamberlin and R. F. Boyce, "SEQUEL: A Structured English Query Language" (1974).
- W. W. Armstrong, "Dependency Structures of Data Base Relationships" (1974); P. A. Bernstein, "Synthesizing Third Normal Form Relations from Functional Dependencies", ACM TODS (1976).
- R. Bayer and E. McCreight, "Organization and Maintenance of Large Ordered Indexes", Acta Informatica (1972); D. Comer, "The Ubiquitous B-Tree", ACM Computing Surveys (1979).
- P. G. Selinger et al., "Access Path Selection in a Relational Database Management System", SIGMOD (1979).
- G. Graefe, "Volcano — An Extensible and Parallel Query Evaluation System", IEEE TKDE (1994).
- M. Kitsuregawa, H. Tanaka and T. Moto-oka, "Application of Hash to Data Base Machine and Its Architecture", New Generation Computing (1983).
- Y. E. Ioannidis and S. Christodoulakis, "On the Propagation of Errors in the Size of Join Results", SIGMOD (1991).
- V. Leis et al., "How Good Are Query Optimizers, Really?", PVLDB (2015).
- K. P. Eswaran, J. N. Gray, R. A. Lorie and I. L. Traiger, "The Notions of Consistency and Predicate Locks in a Database System", CACM (1976).
- C. H. Papadimitriou, "The Serializability of Concurrent Database Updates", JACM (1979).
- J. Gray, "The Transaction Concept: Virtues and Limitations", VLDB (1981); T. Härder and A. Reuter, "Principles of Transaction-Oriented Database Recovery", ACM Computing Surveys (1983).
- D. J. Rosenkrantz, R. E. Stearns and P. M. Lewis, "System Level Concurrency Control for Distributed Database Systems", ACM TODS (1978).
- H. T. Kung and J. T. Robinson, "On Optimistic Methods for Concurrency Control", ACM TODS (1981).
- D. P. Reed, "Naming and Synchronization in a Decentralized Computer System", MIT thesis (1978).
- H. Berenson et al., "A Critique of ANSI SQL Isolation Levels", SIGMOD (1995).
- A. Adya, "Weak Consistency: A Generalized Theory and Optimistic Implementations for Distributed Transactions", MIT thesis (1999).
- A. Fekete et al., "Making Snapshot Isolation Serializable", ACM TODS (2005); M. J. Cahill, U. Röhm and A. Fekete, "Serializable Isolation for Snapshot Databases", SIGMOD (2008); D. R. K. Ports and K. Grittner, "Serializable Snapshot Isolation in PostgreSQL", PVLDB (2012).
- C. Mohan et al., "ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging", ACM TODS (1992).
- M. Stonebraker et al., "C-Store: A Column-oriented DBMS", VLDB (2005); P. Boncz, M. Zukowski and N. Nes, "MonetDB/X100: Hyper-Pipelining Query Execution", CIDR (2005); T. Neumann, "Efficiently Compiling Efficient Query Plans for Modern Hardware", PVLDB (2011).
- J. M. Hellerstein, M. Stonebraker and J. Hamilton, "Architecture of a Database System" (2007).
- M. Stonebraker and A. Pavlo, "What Goes Around Comes Around… And Around…", SIGMOD Record (2024).
- A. Atserias, M. Grohe and D. Marx, "Size Bounds and Query Plans for Relational Joins", FOCS (2008); H. Q. Ngo, E. Porat, C. Ré and A. Rudra, "Worst-case Optimal Join Algorithms", PODS (2012); T. Veldhuizen, "Leapfrog Triejoin" (2014).
- R. Marcus et al., "Neo: A Learned Query Optimizer", PVLDB (2019); "Bao: Making Learned Query Optimization Practical", SIGMOD (2021); A. Kipf et al., "Learned Cardinalities" (2019).
- R. Biswas and C. Enea, "On the Complexity of Checking Transactional Consistency", OOPSLA (2019); K. Kingsbury and P. Alvaro, "Elle: Inferring Isolation Anomalies from Experimental Observations", PVLDB (2020); C. Tan et al., "Cobra: Making Transactional Key-Value Stores Verifiably Serializable", OSDI (2020).
- S. Chu et al., "Cosette: An Automated Prover for SQL", CIDR (2017).
About this partfrom its README
Part 35 of a sixty-one-part course in computer science (see the series plan and the syllabus), and the start of the data half of the course. In 1970 Codd said programs should ask for what data they want and never how to find it. That one idea created a mathematics (relational algebra and dependency theory), an optimizer that searches for the cheapest of many correct plans, and the theory of transactions, which lets thousands of users act as if each were alone, even through crashes. The Job becomes one line of SQL, and our own database finds Part 17's hash table by itself.
The instruments are in explainer/cs/db/ (tested in tests/test_cs35_db.py, and cross-checked against sqlite3):
rel.py: relations as sets of tuples; selection, projection, renaming, product, natural join, union, difference and grouping; functional dependencies, attribute closure, keys, projected dependencies, BCNF test and decomposition, minimal cover, Bernstein's 3NF synthesis, and the chase test for lossless joins.engine.py: our database. A SQL subset (SELECT, FROM with JOIN … ON, WHERE with AND, GROUP BY, ORDER BY, LIMIT, COUNT and SUM) parsed into a tree; tables on 100-row pages;ANALYZE-style statistics (rows, distinct values, min and max per column) and selectivity estimates under the independence assumption; B+ tree indexes; Volcano iterators (scan, index scan, filter, four join methods, hash and sort aggregation, a top-k heap, sort, project) that count the pages they read; a cost model in page I/Os; Selinger's dynamic program over connected subsets (left-deep, with every join method and access path), or an exhaustive search for comparison;EXPLAIN.joins.py: block nested loops, index nested loops, sort-merge with external merge sort and Grace hash, over explicit pages with every read and write counted, beside the textbook formulas.bptree.py: a B+ tree (leaf splits copy a key up, interior splits move one up, linked leaves, range scans, an invariant checker).txn.py: schedules; the precedence graph and the conflict-serializability test; view serializability by search; strict two-phase locking with deadlock detection, wait-die or wound-wait; six isolation levels (read uncommitted, read committed, repeatable read, snapshot, snapshot with Cahill's SSI, and serializable by 2PL) running small programs step by step; the five classic anomalies as programs and interleavings.aries.py: a page store with a buffer pool under steal and no-force, a write-ahead log with prevLSNs, page LSNs, CLRs and checkpoints; workloads of transactions under strict 2PL on pages; crashes at any record; recovery by analysis, redo (repeating history) and undo; crashes during undo; the committed state for checking.
Chapter notes
- Hook. The Job twice: Part 17's program, every step chosen by hand, and one line of SQL. Over the thirty novels, loaded as 4,609,954 rows, both give the same twenty words; sqlite3 answers in 2.25 s. Our database's plan: scan, hash aggregate, top-20 heap.
- 1. Ask for what, not how. IMS (1968) and CODASYL (1969): programs that navigate pointers. Codd (1970): relations, keys, a query that states its result, and data independence. System R and Ingres; SEQUEL became SQL. The whale query on a sample: 1,201 pages without an index, 85 with one, the query unchanged.
- 2. Relational algebra. σ, π, ⋈, ∪, −, ρ on books and authors; a query as a tree; the books their authors published before 45 (Emma, Persuasion, Ulysses); Codd's theorem; rewriting trees.
- 3. Dependencies and normal forms. Update, insertion and deletion anomalies; functional dependencies, Armstrong's axioms, closure, keys; BCNF and a lossless decomposition (the chase); a careless split that invents rows; BCNF can lose a dependency, Bernstein's 3NF keeps them.
- 4. How a query runs. Volcano iterators: open, next, close; pipelines and blocking operators. The Job's plan run: 4,609,954 tuples scanned, 57,895 groups, a heap of 20; 46,100 pages against 230,500 estimated for sorting; our engine 7.4 s, sqlite3 2.25 s. Access paths for the whale query: 1,201 pages by scan, 85 by index.
- 5. Joins, page by page. The cost unit is the page. Block nested loops, index nested loops, sort-merge, Grace hash, with formulas; measured on M = 400, N = 200 pages for B = 5 … 80: BNLJ and sort-merge equal their formulas exactly, INL reads less (13% of keys have no match), Grace hash pays 1–9% for partial pages and stops fitting below B = 40. With B = 80 BNLJ wins; with B = 5 hashing wins by 15×.
- 6. The optimizer. Plan space: n! left-deep orders, n!·C(n−1) bushy trees (28 trillion for 12 tables) against 2^n subsets. The 120 orders of a five-table chain with hash joins: best 2,302 pages, median 43,448, worst 24,243,824 (a cross product first), a factor of 10,532. Selinger's dynamic program, the principle of optimality, interesting orders; 395 plans costed against 1,200 for exhaustive search, both finding cost 550.
- 7. Guessing sizes. Statistics and selectivity; a city and its own country: estimate 25, actual 492; a city and an age: 250 against 256. Skew: one guess, 9.9 rows, for every word; the has 6,776. Histograms and most-common values. Errors multiply through joins (Ioannidis and Christodoulakis 1991; Leis et al. 2015).
- 8. Indexes. A B+ tree grown key by key, splitting and rising; search and range scans. Fanout 400: a thousand keys in two levels, a trillion in five; our index on the Job's 57,895 words is two levels high. Unclustered against clustered: the 1,704 rows from whale to whales lie on 966 pages, or 18. Hash, bitmap, LSM, inverted and covering indexes.
- 9. Transactions. ACID on a bank transfer (Gray 1981; Härder and Reuter 1983). Schedules, conflicts and the precedence graph; the lost update's cycle; Eswaran et al.'s theorem. View serializability and blind writes; NP-complete to test (Papadimitriou 1979). Of 90 interleavings of three small transactions, 10 are serializable.
- 10. Two-phase locking. Shared and exclusive locks; the growing and shrinking phases and the lock-point proof; strict 2PL; granularity, intention locks and phantoms. Deadlock and the waits-for graph. 400 random runs per policy, every schedule serializable: detection 342 aborts, wait-die 734, wound-wait 723, prevention never deadlocking.
- 11. Optimism and snapshots. Kung and Robinson's optimistic control; timestamp ordering. MVCC (Reed 1978): version chains and snapshots; first committer wins. Write skew with two doctors on call: under read committed and snapshot isolation both commit and nobody is on call; SSI aborts T1; 2PL aborts T2. Fekete's dangerous structures and Cahill's SSI, PostgreSQL's SERIALIZABLE since 2011.
- 12. Isolation levels. Six levels against five anomalies, each run: read uncommitted allows all, read committed stops only dirty reads, repeatable read all but phantoms, snapshot all but write skew, the serializable levels all. ANSI SQL-92's wording, Berenson et al.'s critique (1995), Adya's graph definitions (1999), Elle (2020).
- 13. Recovery: ARIES. Steal, no-force and write-ahead logging; LSNs and page LSNs. A crashed log of twelve records: T3 and T2 committed, T1 the loser; page 0 missing committed changes, page 3 holding an uncommitted one. Analysis, redo from LSN 1 (4 redone, 5 skipped), undo of 11, 5 and 1 with three CLRs: exactly the committed state. 500 random crashes recovered, and 500 crashed again during undo: all correct.
- 14. Column stores. Rows against columns; SUM over 1,000,000 rows of 16 columns: tuple at a time 74 ms, vectorized row store 13.9 ms, vectorized column store 4.1 ms (16 MB read instead of 128 MB). Run-length coding of the Job's book column: 4.6 million values in 30 runs, 37 MB to 480 bytes; a 16-bit dictionary for the words, 24.0 MB to 9.7 MB. C-Store, MonetDB/X100, HyPer; Parquet to DuckDB.
- 15. Our database runs the Job. Hash aggregate (46,100 page I/Os) against sort aggregate (230,500): Parts 16 and 17 in one decision. sqlite3's plan (a temporary B-tree), 2.25 s; with an index, a covering index scan, 0.25 s; ours 7.4 s; all three equal to Part 17's answer. Ledger row 13: one line of SQL, 2.25 s natively. Key-value, document, graph and distributed SQL stores.
- 16. Frontier: joins, guesses, guarantees. The triangle query: binary joins build 1,132,558 two-paths for 4,500 edges where a generic join does 10,228 steps; the AGM bound N^{3/2} and worst-case optimal joins (Ngo et al. 2012, leapfrog triejoin). Learned cardinalities and optimizers (Neo, Bao). Checking isolation in black-box histories (NP-complete for serializability and SI; Elle, Cobra). Six open problems.
- Outro. Recap, payoffs, practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Before Codd: IMS and CODASYL. Codd 1970 and data independence.
- Relations, keys, relational algebra (σ π ⋈ ∪ − ρ) acting on tables; relational calculus and Codd's theorem; SEQUEL and System R (1974).
- Functional dependencies, Armstrong's axioms, BCNF and 3NF; update anomalies.
- The Job as SQL, and the question of how a database answers it.
- Query processing: iterators (Volcano, Graefe); scans; index selection.
- Joins: nested loops, block, index, sort–merge, Grace hash. I/O costs derived (callback to Part 9's external memory).
- Selinger's optimizer (1979): dynamic programming over join orders with interesting orders; the size of plan space (Catalan × n!); cardinality estimation and how independence assumptions fail.
- Indexes: B+ trees (three levels index a billion rows); clustered against unclustered; hash and bitmap indexes; LSM (Part 34).
- Transactions: ACID; schedules; conflict serializability by precedence graphs (a cycle means not serializable, proved); view serializability is NP-complete.
- 2PL ⇒ serializable (proved); strict 2PL; deadlock handling (wait-die, wound-wait); intention locks.
- Optimistic concurrency and timestamps; MVCC; snapshot isolation and write skew (two doctors on call); serializable SI (Cahill 2008).
- Isolation levels and their anomalies (Berenson et al. 1995; Adya 1999).
- Recovery: WAL, steal/no-force; ARIES (Mohan 1992) with its analysis, redo and undo passes over LSNs; checkpoints.
- Analytics: column stores (C-Store, MonetDB/X100, DuckDB); compression (callback to Part 21); vectorized against compiled execution.
- Our database runs the Job's SQL on the novels and shows the plan it chose against the alternatives, with
costs, cross-checked against
sqlite3. Ledger row 13. - Beyond relational: key-value, document and graph stores; distributed transactions (Part 39). Outro.
Computed: join I/O against formulas; Selinger DP against exhaustive search; estimation errors under correlation; a
serializability checker; 2PL; write skew; ARIES on crashed logs; row against column scans; our database.
Visuals: tables transformed by algebra operators; join trees with costs; a precedence-graph cycle lighting up;
ARIES' three sweeps over the log; row against column layouts.
In practice: PostgreSQL and MySQL internals, reading query plans (EXPLAIN), index design, isolation-level bugs, SQLite everywhere, DuckDB for analytics.
Reading: Silberschatz, Korth & Sudarshan, Database System Concepts; Ramakrishnan & Gehrke; Garcia-Molina, Ullman &
Widom, Database Systems: The Complete Book; Hellerstein & Stonebraker, Readings in Database Systems (the Red
Book); Gray & Reuter, Transaction Processing; Weikum & Vossen; Bernstein, Hadzilacos & Goodman; Abiteboul, Hull &
Vianu, Foundations of Databases; Codd 1970; Selinger et al. 1979; Mohan et al. 1992; Berenson et al. 1995; Adya
1999; Hellerstein, Stonebraker & Hamilton 2007.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
冲突可串行化。 证明:一个调度是冲突可串行化的,当且仅当其优先图无环。
解答
(⇒)设调度与串行顺序 T_{π1}, …, T_{πn} 冲突等价。等价保持每一对冲突操作的先后,而在串行调度中,较早事务的 每个操作都在较晚事务的每个操作之前。所以每条边 Ti → Tj(Ti 的某操作先于 Tj 的一个与之冲突的操作)在 π 中都指向前方; 边全都沿一个线性序向前的图没有环。(⇐)若图无环,取一个拓扑序 π。反复交换相邻的、属于不同事务且与 π 的顺序相反的两个 操作。这样的一对不可能冲突(否则就是一条在 π 中向后的边),而交换相邻的非冲突操作保持等价。每次交换消除一个逆序,最终得到 π 对应的串行调度。
-
两阶段锁。 证明两阶段锁产生的每个调度都是冲突可串行化的,并给出一个 2PL 无法产生的可串行化调度。
解答
记 ℓ(T) 为 T 的锁点,即它获得最后一把新锁的时刻。若 Ti → Tj,则 Tj 的某操作与 Ti 较早的一个操作在某项 x 上 冲突;Tj 只能在 Ti 释放 x 之后才锁住 x,而 Ti 在 ℓ(Ti) 之前不释放任何锁,所以 ℓ(Ti) < (Ti 释放 x)< (Tj 锁住 x) ≤ ℓ(Tj)。若有环,就会得到 ℓ(T) < ℓ(T)。所以图无环,由第 1 题,调度可串行化,等价于按锁点排序的串行顺序。调度 w1(x) r2(x) w1(y) 是可串行化的(先 T1 后 T2,唯一的冲突在 x 上),但在 2PL 下 T1 必须在 T2 读 x 之前释放 x,之后就不能 再锁 y。2PL 能产生的调度是冲突可串行化调度的真子集。
-
排序与哈希的代价。 推导 B 个缓冲页下外部归并排序的 I/O 代价,以及 Grace 哈希连接一趟分区所需的内存。
解答
第 0 趟每次读入 B 页,写出 ⌈M/B⌉ 个有序段;之后每趟把 B − 1 个段归并成一个(每段一个输入缓冲,一个输出缓冲), 共需 ⌈log_{B−1}⌈M/B⌉⌉ 趟归并。每趟读写每一页一次:总计 2M(1 + ⌈log_{B−1}⌈M/B⌉⌉) 次 I/O,正是我们的计数逐页吻合的公式 (M = 400、B = 5 时为 5 趟,4,000 次 I/O)。Grace 哈希把 R 分成 B − 1 个桶,每桶约 M/(B − 1) 页;构建阶段要把一个桶放进 B − 2 页,所以需要 M/(B − 1) ≤ B − 2,约为 B ≥ √M。M = 400 时是 B ≥ 21;由于桶大小不均,我们的测量需要 B = 40,所以在此 之下公式 3(M + N) 用红色标出。
-
计划空间。 计算 n 张表上浓密连接树的数目,以及 Selinger 动态规划在链形、星形和完全图查询上的工作量。
解答
连接树是有 n 个带标号叶子的满二叉树:形状有 C_{n−1} = (2n − 2)!/(n!(n − 1)!) 种(卡塔兰数),放置表的方式有 n! 种,共 n!·C_{n−1} = (2n − 2)!/(n − 1)! 棵:n = 5 时 1,680 棵,n = 12 时 28,158,588,057,600 棵。动态规划的工作量正比于 (连通子集,拆分方式)对的个数。链有 n(n + 1)/2 个连通子集(区间),k 张表的区间有 k − 1 种拆成两个区间的方式:浓密树 Θ(n³),左深树 Θ(n²)。星形(一个中心、n − 1 个叶子)有 2^{n−1} 个含中心的连通子集,每个至多有 n − 1 种去掉一个叶子的方式: 左深 Θ(n·2^n)。完全图有 2^n − 1 个子集,全部连通,把每个子集拆成两个非空部分共有 (3^n − 2^{n+1} + 1)/2 对:浓密 Θ(3^n), 左深 Θ(n·2^n)。所以系统在十几张表以上改用贪心或遗传搜索(PostgreSQL 的
geqo_threshold为 12)。 -
动手:直方图。 为我们数据库的统计信息加上每列的直方图,比较
word = 'the'的估计在前后的变化。解答
最简单有效的形式是 PostgreSQL 的:k 个最常见值及其确切计数,其余部分用等深直方图(等值查询则用均匀猜测)。在
Database.analyze中保存Counter(col).most_common(k);估计col = v的选择率时,若 v 在列表中就返回保存的计数,否则 返回 (行数 − 列表计数之和)/(不同值数 − k)。在 120,000 词的样本上取 k = 100:前 100 个词共出现 63,367 次,于是 the 被 精确估计为 6,776(原来是 9.9)。其余每个词现在估计为 (120,000 − 63,367)/12,066 ≈ 4.7:ship(26)的误差从 2.6 倍变为 5.5 倍,whale(81)从 8 倍变为 17 倍。这个列表修正了对计划选择最要紧的高频值,而略微恶化了其余的值。对范围查询,b 个桶 的等深直方图把任何范围估计的误差限制在约 2/b 的行数之内。 -
★ 研究:多余的中止。 在随机工作负载上,SSI 的中止有多少是不必要的?找出只看得见读写反依赖边的在线调度器至少要中止 多少次,以及达到这一下界的规则。
已知的情况与入手的方法。 只有当提交某事务会使历史不可串行化时,中止才是必要的;SSI 只要出现枢纽(一条读写边进、一条 读写边出)就中止,而枢纽只有在两条边闭合成环时才危险。先测量:在随机程序上运行
txn.run_level("snapshot + SSI", …); 对每次中止,让该事务提交并重放调度,再用txn.conflict_serializable检验已提交的历史(使用 Adya 图中的 rw、wr、ww 依赖)。 Cahill 最初的规则在任何枢纽上都中止;PostgreSQL 的实现(Ports 与 Grittner,2012)只在出边一端的事务先提交时才中止,并忽略 安全的只读事务,报告的多余中止少得多。下界需要一个不可区分性论证:两个历史在决策时刻之前的读写边完全相同,其中一个之后经由 一条调度器尚看不见的 wr 边闭合成环。任何必须在提交时作出决定的在线调度器,要么两个都中止,要么冒险放过坏的那个,所以某些 多余中止是不可避免的;开放的问题是相对于知道整个历史的离线调度器的最优竞争比,以及达到它的实用规则。
Build the film
python -m videos.cs.cs35.compute # the part's numbers, into .cache/cs35
python tools/build.py cs35 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs35 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs35. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs35.compute # every item (job loads 4.6 million rows into sqlite3: about a minute)
python -m unittest tests.test_cs35_db
python tools/build.py cs35