Version Control, Builds and Dependencies
What happens to a change between the keyboard and production, and why can each step be trusted?
The part opens in April 2005, when BitKeeper's licence was withdrawn and Torvalds wrote git within days, and with the series' own object store giving three files, their tree and their commit the same names as git 2.43. Names are hashes of content, so history is a Merkle graph: editing one file renames only the objects on its path, and a flipped bit is caught by rehashing. Merge bases, three-way merge over Myers' diff, rebase and bisection follow, then deltas that store forty versions of the syllabus in 154 KB instead of 4.2 MB. The second machine is the build system: make trusts clocks and rebuilds all 202 targets after a fresh checkout, a build that hashes its inputs rebuilds none and stops early after a comment edit, and a clean build has work 235 s and span 34 s. The third is the package manager, and here the part turns: choosing versions is NP-complete, by a reduction from 3-SAT shown as packages, so resolvers are SAT solvers. Above the three, a merge queue tests batches and bisects failures, and a canary needs 100,000 requests to catch a doubled 0.1% error rate reliably. It ends at the frontier of structured merge, build correctness and authors that are programs.
What you need. Everyday use of a version-control system and a compiler; graphs and binary search.
- Mathematics, ideas and history
- git as a Merkle DAG, merge bases and three-way merge, bisect, build systems à la carte, hermetic builds, version resolution is NP-complete, merge queues, canaries and rollouts
- What we build or compute
- a git-compatible object store; a build engine; a version solver
What you will be able to do
Degree
- Compute a git object id by hand from its header and content, and say which objects one edit renames.
- Find the merge base of two commits, perform a three-way merge, and bisect a history.
- Explain why a build driven by timestamps rebuilds too much or too little, and what early cutoff saves.
Graduate
- Classify a build system by its scheduler and its rebuilder, and bound a parallel build by its work and span.
- Reduce 3-SAT to package installability, and encode a dependency diamond as clauses.
- Compute the test runs a merge queue needs per change and the power of a canary test.
Research
- State what structured merge, build minimality and complete version solving each leave unsolved.
- Design a merge-queue policy for changes with individual failure probabilities and argue for its batch sizes and bisection order.
Industry
- Make a build hermetic and cached, commit lockfiles, and verify what a dependency update brings in.
- Deliver through a merge queue, a canary, feature flags and expand-contract migrations, and choose between rolling back and rolling forward.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 21 min · Graduate 42 min · Research 45 min · Industry 31 min.
- 0Ten days in 2005, and our own gitDegree1 min
- 1Git's objectsDegree4 min
- 2Merging and bisectingDegree6 min
- 3Storing historyGraduate4 min
- 4Build systemsDegree7 min
- 5DependenciesGraduate6 min
- 6Continuous integrationIndustry4 min
- 7Continuous deliveryIndustry6 min
- 8Frontier: merging and building, correctlyResearch3 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.
Ten days in 2005, and our own gitDegree1 min
Version control is older than most of computing's habits. In the seventies and eighties, SCCS and RCS tracked one file at a time, and you locked a file to change it. CVS, in 1990, tracked whole projects on a central server; Subversion, in 2000, made commits atomic. From 2002 the Linux kernel used BitKeeper, a proprietary distributed system, under a free licence. In April 2005 that licence was withdrawn. Linus Torvalds started writing a replacement. Within days it could manage its own source code, and within a few weeks the kernel's. He called it git.
Git is simpler inside than its commands suggest, simple enough to rebuild. We wrote a small object store, a few dozen lines, and asked it and the real git to record the same three files with the same author and time. Every name is identical: the three files, the directory tree, and the commit. Each object's name is the hash of its contents, Part 29's SHA-1, so any copy of git anywhere computes the same names for the same history. This part opens up the three machines every change passes through: version control, the build, and the package manager.
1Git's objectsDegree4 min
Git stores four kinds of object, each named by the hash of its contents. A blob is a file's bytes and nothing else, not even its name. A tree is a directory: for each entry, its mode, its name and the name of the object it points to. A commit names one tree, the snapshot of the whole project, plus its parent commits, its author and a message. And a tag names a commit, usually with a signature. Nothing is ever overwritten. A new version of a file is a new blob with a new name; the old one stays. The hash was SHA-1, and since researchers produced a practical SHA-1 collision in 2017, git has been moving to SHA-256.
Because every name is a hash of contents that include other names, the objects form a Merkle graph, Ralph Merkle's tree of hashes from Part 39's anti-entropy. Here is our small project: a commit, its tree, and below it the files and subdirectories. Change one line of one file. Its blob gets a new name; so does the tree that lists it, and the tree above that, and the root, and the commit. Everything else keeps its name and is shared between the two snapshots, not copied. Two consequences. A commit's name vouches for every byte of the project and its whole history: change anything and the name changes. And comparing two snapshots is fast: equal names mean equal subtrees, so git skips them without looking inside.
Content addressing gives integrity checking for free. We stored a file, then flipped a single bit of it, as a failing disk might: novels became novdls. Asked for the object, our store rehashes what it read, gets a completely different name, and refuses. No disk, network or malicious server can hand you different content under the same name, and git fsck checks every object this way. It also makes signatures cheap: signing one commit's hash vouches for the whole history beneath it. That depends on the hash. In 2017 researchers published two different PDF files with the same SHA-1, after about two to the sixty-three computations. Git now detects that attack's fingerprint, and supports repositories hashed with SHA-256.
Hashes are not names people can use, so git adds a thin layer of mutable pointers. A branch is a small file containing one commit's name. Committing writes a new commit whose parent is the old one, and moves the branch to it. HEAD records which branch you are on. The index is the tree of the next commit, being assembled: adding a file writes its blob and records it there. Checking out another commit rewrites the working files to match its tree, touching only paths whose names differ. And the reflog records every position each branch has had, so a commit you think you lost is still there, by name, until garbage collection removes objects that nothing points to.
Most of git's confusing commands become simple once you see the three trees it keeps. HEAD is the tree of the last commit. The index is the next commit, being assembled. The working tree is the files you actually edit. Adding copies a file from the working tree into the index; committing turns the index into a new commit and moves HEAD. Status compares them pairwise: what is staged, and what is changed but not yet staged; files whose hashes agree are skipped without being read. And reset, the command people fear most, moves HEAD and then overwrites none, one or both of the other two trees, depending on whether it is soft, mixed or hard.
2Merging and bisectingDegree6 min
History is a directed acyclic graph: every commit points to its parents. To merge two branches, git first finds where they diverged. A merge base is a best common ancestor: a commit that both branches contain and that is not an ancestor of another such commit, the lowest common ancestor of Part 18 generalized to graphs. Usually there is one. But in this history each branch merged the other, a criss-cross, and commits five and six have two merge bases, one and two, neither better than the other. Git's recursive strategy merges the two bases first into a virtual ancestor, and merges against that. Its replacement since 2021, called ort, does the same, many times faster.
How does git find merge bases quickly in a history of millions of commits? It walks backwards from both commits at once, newest first, painting each commit it reaches with the side or sides that reached it. A commit painted by both sides is a common ancestor. Its own ancestors are painted stale, so they will not be reported as well, and the walk stops when only stale commits are left. The cost depends on how far the branches have drifted, not on the length of history, and since 2018 a commit-graph file storing generation numbers lets git stop earlier still. The same walk answers which commits one branch has that another lacks, and whether a push only moves a branch forward.
Every merge rests on a diff, and Part 21 showed what a diff is: a shortest path. Lay the old text along the top and the new down the side. Moving right deletes a letter of the old; moving down inserts a letter of the new; and where the letters match, a diagonal keeps it, for free. The shortest edit script is the path with fewest horizontal and vertical steps. For Eugene Myers' own example it needs five edits and keeps four letters. His algorithm of 1986 explores paths in order of how many edits they use, keeping only the furthest point each can reach, so its time grows with the size of the difference rather than the size of the files. Since versions of a file usually differ a little, that is exactly the case that matters.
With a merge base in hand, the merge itself compares three versions. Here a base, and two branches: ours lower-cased the words; theirs changed twenty to ten. Diff the base against each side, with Myers' algorithm from Part 21. A region changed on only one side takes that side's version; a region changed identically on both takes it once. Our merge keeps both changes, and no person is needed. But if theirs had also rewritten line two, differently, no rule can choose, and git writes both versions between conflict markers for a person to resolve. Without the base, a two-way comparison could not tell which side changed anything at all.
When a merge does conflict, someone has to decide. A conflict is a question only a person, or a test, can answer: which combination of two intentions is correct? Git can at least avoid asking twice. Its rerere feature, reuse recorded resolution, remembers how you resolved a conflict, keyed by a hash of its two sides, and replays the answer when the same conflict comes back, as it does when a branch is rebased repeatedly. After resolving, build and test the result: a merge with no textual conflict can still be wrong, as the frontier chapter will show. And the cheapest conflict is the one that never happens, because changes were small and merged often.
There are two ways to bring a branch up to date. A merge commit has two parents and records history as it happened, branches and all. A rebase instead replays each of the branch's diffs on top of the new main line, making new commits with new names, and gives a straight history. Cherry-pick applies a single commit's diff elsewhere. Because rewriting changes names, the one rule is never to rebase commits that other people already have: their copies of history would refer to commits that, in yours, no longer exist.
History also answers the question every developer eventually asks: when did this break? Mark one old commit good and the current one bad. Git checks out the commit halfway between; you test it and say good or bad; the range halves. In a thousand commits, the one that introduced the bug is found in ten tests. It is Part 16's binary search: a million commits need twenty. Given a script that decides good or bad, git bisect runs the whole search by itself. With merges, history is a graph rather than a line, and git picks the commit that splits the remaining candidates most evenly.
3Storing historyGraduate4 min
If every version of every file is a whole object, history should be enormous. This repository's syllabus has been committed forty times, growing to three hundred kilobytes. Stored whole, even compressed, the forty versions take four megabytes. Stored as the difference from the version before, a hundred and fifty kilobytes: nearly thirty times less. Git does this when it packs objects: it finds similar objects, often versions of the same path, and stores all but one as deltas, copy instructions and new bytes, the same idea as Part 21's diff, in chains of bounded depth so that reading any version stays fast. The object names do not change when objects are packed: content addressing describes what an object is, and packing is only a decision about how to store it, made again whenever git finds a better one.
How much does history cost in practice? We asked this repository. A hundred and sixty commits, seventeen thousand objects. The current commit's files take about nine hundred megabytes. Every object ever stored, uncompressed, is only a little more, and packed on disk it is less than the snapshot alone. Most files here were written once and rarely changed, and the few that change constantly, like the syllabus and the translation tables, pack into deltas. For repositories whose history is far larger than any snapshot, a shallow clone fetches only the latest commit, and a partial clone defers each file's contents until something actually reads it.
Which object should each delta be taken against? Any object could serve as the base for any other, so the best packing is a search problem, and git uses a heuristic. It sorts objects by type, by a hash of the end of their path, so that versions of the same file sit together, and by size, largest first; then tries each object against the ten before it, its window, and keeps the smallest delta. Chains have a bounded depth, fifty by default, so that reading any object applies at most fifty deltas: deeper chains are smaller on disk and slower to read. The same packs travel over the network. A fetch sends only the objects the other side lacks, found by the walk of the merging chapter.
How much code can one history hold? In 2016 Rachel Potvin and Josh Levenberg described Google's monorepo: most of the company's code in a single repository, about two billion lines and eighty-six terabytes, changed by some twenty-five thousand engineers, on a custom system called Piper. One repository means one version of everything and atomic changes across projects; it requires tooling that git alone does not provide, and builds that only redo what changed. The alternative, many repositories, gives each project its own history and releases, at the price of the version management of this part's dependency chapter. Git itself has grown tools for size: shallow clones fetch recent history only, partial clones fetch file contents on demand, sparse checkouts materialize only some directories.
Git's model is not the only possible one. Git stores snapshots and computes differences when you ask for them. Patch-based systems, Darcs from 2003 and now Pijul, store the changes themselves, and reason about when two patches commute, meaning they can be applied in either order with the same result. Then cherry-picking is exact, and the result of a merge never depends on the order in which branches were combined. Pijul represents a file as a graph of lines in which a conflict is a perfectly valid state, recorded and resolved later by another patch. And for data whose merges can be made conflict-free, Part 39's CRDTs offer version control in which merging never needs a person at all.
4Build systemsDegree7 min
Stuart Feldman wrote Make at Bell Labs in 1976, the story goes, after a colleague lost a morning debugging a program that had simply not been recompiled. A makefile lists targets, the files each one needs, and the command that makes it. Together they form a directed acyclic graph. Make walks it in topological order, Part 18's algorithm, so that every target is built after what it needs, and rebuilds a target only when one of its prerequisites is newer than it.
Modification times are a guess about content, and the guess is often wrong. We built both kinds of build system, on a project of two hundred source files and twenty headers. Change a comment in one source file. Make recompiles it, then relinks the library and reruns the tests, although the compiled object is byte for byte the same. A build that remembers the hash of every input, and stops when a rebuilt output is unchanged, recompiles one file and stops. A real change in a header used by thirty-nine files rebuilds the same forty-one targets in both. But check out the project afresh, which gives every file a new time and the same content: Make rebuilds all two hundred and two targets, and the hashing build rebuilds none.
One famous mistake shows what a build needs. Large projects used to run a separate Make in each directory, each one seeing only its own part of the dependency graph. In 1997 Peter Miller explained why this fails: a dependency that crosses directories is invisible, so the build is either wrong, leaving something stale, or slow, rebuilding everything just to be safe. The cure is to give one tool the whole graph: a build can only be as correct as the dependencies it can see. Modern build files, Bazel's among them, declare small targets in every directory, but a single tool loads all of them into one graph before doing anything.
Here is the idea of a minimal rebuild on a project small enough to draw: twelve sources, four headers, twelve objects, a library and a test report. Change one header. The targets that must be rebuilt are exactly those reachable from it along the graph's edges: the six objects whose sources include it, then the library and the tests. Every other target's recorded inputs still match, so it is skipped without being looked at again. That reachable set is the least work any correct build system can do, and it is the same set that test selection computed over imports: one idea, used twice.
In 2018 Andrey Mokhov, Neil Mitchell and Simon Peyton Jones showed that the whole zoo of build systems comes from two independent choices. A scheduler decides the order in which tasks are visited: in topological order, or by starting a task and restarting or suspending it when it discovers a dependency it did not declare. A rebuilder decides whether a task must run again: a dirty bit, verifying traces like ours, or constructive traces. Constructive traces store the outputs too, keyed by the hash of the inputs, which turns the build into a shared cache: a file compiled on one machine is downloaded by everyone else. And Excel is a build system: cells are targets and formulas are rules, with dependencies that are only discovered while computing.
We added constructive traces to our build engine: a cache shared between machines, holding every output under the hash of the task and all of its inputs. Machine A builds the project from scratch: two hundred and two tasks. Machine B checks out the same commit: it runs nothing and downloads all two hundred and two outputs. A changes a header and rebuilds the forty-one affected targets; B pulls the change and downloads those forty-one. A team builds each distinct thing once, and every other engineer and every CI machine starts where the first left off. The price is discipline: a task that reads an input it did not declare can put a wrong output in the cache, and then everyone's build is wrong.
Independent tasks can be built at the same time. A clean build of our project has two hundred compiles of about a second each, then an eight-second link and twenty seconds of tests: two hundred and thirty-five seconds of work in total, and a longest chain, the span, of thirty-four. Part 10's bound says the time on P workers lies between the larger of work over P and the span, and their sum. One worker takes the full two hundred and thirty-five seconds; eight take fifty-four; beyond thirty-two, nothing improves, because the link and the tests cannot be split. Speeding up builds past that point means making the critical path itself shorter.
Hash-based building only works if the hashes are honest. A hermetic build runs each task in a sandbox that sees only its declared inputs, so that the hash of those inputs really names everything the result depends on. A reproducible build produces bit-identical outputs from the same inputs, which means banishing timestamps, absolute paths and random orders from the files it writes. Eelco Dolstra's Nix stores every package under the hash of all its inputs; Google's Bazel distributes execution and caching across machines. The payoff goes beyond speed: if builds are reproducible, anyone can rebuild a released program and check that it matches, which defends against a build machine that has been compromised.
Nix takes content addressing all the way. A package is described by every input that goes into building it: its source, the exact compiler, the exact libraries, the flags. It is installed under a directory named by the hash of all of them. Change one flag and you get a different name, a different package, installed side by side with the first. Two builds with the same name are the same build, two versions of anything can coexist, so the diamond disappears here too, and upgrading means installing new paths and switching one pointer, which is also how you roll back: switch it again.
5DependenciesGraduate6 min
Programs depend on packages, and packages on other packages, each published in many versions. Semantic versioning numbers releases major, minor, patch, and constraints say which releases a package expects to work with. Here an application needs A and B. A needs C version two or later; B version one point zero needs C before two. No single C satisfies both, and only one version of each package can be installed: the diamond. A resolver backtracks: B one point one allows C two, and everything fits. A lockfile records the answer, so every machine and every build installs exactly the same versions until someone asks to update.
Semantic versioning is a promise, and promises can be checked. The promise is that upgrading within a major version never breaks you. When Steven Raemaekers and colleagues compared successive releases in Java's Maven repository, about a third of releases contained at least one breaking change, minor and patch releases included. And Hyrum's law from Part 40 means that even a genuine bug fix breaks someone who relied on the bug. So lockfiles pin exact versions, upgrades are tested, and some ecosystems check the promise mechanically: Elm refuses to publish a release whose version number understates its API changes, and Rust has tools that do the same comparison.
How hard is this in general? As hard as anything in Part 26. Take any formula in three-variable clauses. For each variable, publish a package with two versions, zero and one. For each clause, publish a package with one version per literal, and let version k require the variable package at whichever value makes literal k true. Finally let the root require every clause package, in any version. A consistent installation chooses, in every clause, a literal that its variable choices make true: it is a satisfying assignment, and every satisfying assignment gives one. So deciding whether a set of packages can be installed is NP-complete, as Roberto Di Cosmo and colleagues showed in 2006. Our resolver, given the packages for this formula, returns an assignment that satisfies it.
Drawn out, the reduction looks like any package graph. At the top, the root requires every clause package. Each clause package offers one version per literal, and each of those versions requires one version of one variable package. A resolver's answer picks one version of every package, here in green. Following the chosen arrows down, every variable gets exactly one value, and every clause has a literal that value makes true. Installing these packages and satisfying the formula are the same problem, written in two notations.
Here is what a simple resolver does on the diamond, step by step. It takes the requirements in order and tries the newest allowed version of each: the application, A version one, B version one point one, and then C version three, the newest. But B one point one allows C only up to two: a conflict. The resolver undoes its choice of C and tries the next version, two, which satisfies everyone. This depth-first search, newest first, is exponential in the worst case, as the reduction promises, and quick when constraints are loose. CDCL and PubGrub add learning: once a combination has failed, it is never tried again.
NP-completeness is about the worst case. Write random hard formulas as packages, at Part 26's threshold of four point two six clauses per variable, and our CDCL solver's work climbs steeply: six conflicts at twenty variables, over four hundred at eighty. Real package universes are far kinder: most constraints are loose, the newest version usually works, and conflicts are rare. Natalie Weizenbaum's PubGrub, written for Dart and now also used by Python's uv, learns from each conflict as CDCL does, and can explain in plain words why no solution exists. Go chose to remove the problem instead. Its minimal version selection allows only lower bounds, and takes the oldest version that satisfies all of them, which is computable in polynomial time.
Ecosystems answer the diamond differently. JavaScript's npm lets several versions of the same package coexist, each nested under the packages that need it. The diamond disappears, and an ordinary application installs thousands of packages. Python's pip and most operating-system package managers allow one version of each package, which keeps installs small and brings back the resolution problem we just saw. Small packages make long chains. In March 2016 an eleven-line npm package called left-pad was withdrawn by its author, and builds across the industry that depended on it, often without knowing, failed within hours. Today lockfiles record a hash of every package's contents, Chapter 1's idea again, so that a name and version can never silently become different code.
Every dependency is code written by strangers that runs with your program's privileges. In 2018 a new maintainer of the popular event-stream package added code that tried to steal cryptocurrency wallets. In 2020 attackers who had compromised SolarWinds' build system shipped a backdoor inside a signed update. In 2024 came xz. The defences are signatures on releases and commits, software bills of materials that list everything inside a build, and the SLSA levels, which grade how trustworthy the process that produced a build was. Reproducible builds let independent parties check a binary against its source, and Part 61 returns to the deeper question of trusting software at all. Vendoring, copying dependencies into your own repository, trades easy updates for control.
6Continuous integrationIndustry4 min
Merge queues serve a way of working. In trunk-based development everyone commits to one main line, in small changes, at least daily, and branches live for hours rather than weeks. Part 40's simulation showed why: conflicts per week of work grow with a branch's lifetime. Fast tests run before a change lands. Slower and broader ones run after, on the merged result, and when they fail, the failure is bisected to the change that caused it. Flaky tests threaten all of it. A suite of a thousand tests, each flaky one percent of the time independently, fails somewhere on almost every run, and people learn to ignore red. They must be quarantined and fixed, never allowed to block. And unfinished features ship switched off, behind flags, instead of living on long branches.
Continuous integration means merging into the main line at least daily, with every change tested. With hundreds of engineers, testing each change alone is too slow, and testing them separately lets two changes that each pass break main together. A merge queue tests changes in order, on top of everything ahead of them, in batches. If a batch passes, all of it lands. If not, the queue bisects the batch to find the bad changes and lands the rest. A batch of b changes is green with probability one minus p to the b. We simulated twenty thousand changes. When one change in a hundred is bad, batches of sixty-four need an eighth of a test run per change. When one in ten is bad, big batches nearly always fail, and the best batch is about four. Either way, only tested combinations ever land, so main stays green, which is how Uber's SubmitQueue and the merge queues of GitHub and GitLab let thousands of changes a day through. Uber's system goes further and predicts, from a change's history, how likely it is to fail, so that risky changes are tested alone and safe ones in large groups: the research problem at the end of this part.
The other way to make testing affordable is to run only the tests a change could affect. Walk the import graph of this repository, the one we measured in Part 40, backwards from the changed module: everything that imports it, directly or indirectly, could behave differently, and nothing else can. Change the module behind our KWIC experiment, and one test file must run. Change Pebble's assembler, and twenty-two test modules out of two hundred. Change the narration engine, caught in Part 40's cycle with the library's root, and the change reaches nearly two thousand modules and seventy-one test files. Google's test platform and Bazel do this at enormous scale. A precise dependency graph, and an architecture without needless cycles, is what makes testing every change affordable.
How much does selection save in this repository? We changed each of the library's modules in turn, in imagination, and counted the test modules that could be affected. For the median module, one percent of the tests. On average, under five percent, and for nearly three quarters of the modules less than that. A full run is needed only for the few modules at the root of everything. The saving rests on the graph being right: a dependency the graph does not see, a file read at run time or an import computed from a string, is a test that should have run and did not.
7Continuous deliveryIndustry6 min
A merged change is not yet running for anyone. Delivering it safely means never betting everything on one moment. Blue-green deployment runs the new version beside the old and switches traffic at once, keeping the old one ready to switch back. A canary, named for the birds miners carried to detect gas, sends a small share of traffic to the new version and compares it with the old. Progressive rollout widens the share in stages, one percent, five, twenty-five, all, rolling back automatically at any stage. And feature flags ship new code switched off, to be turned on for some users later, so that deploying code and releasing a feature become separate decisions.
How big must a canary be? It is a question of statistics. Suppose the old version fails one request in a thousand, and a bad new version fails two in a thousand: twice as often, and still rare. Compare the two with a standard test of proportions, allowing one false alarm in a hundred. With a thousand requests to each, the bad release is almost never caught: one or two failures cannot be told from noise. With three thousand, seven percent of the time; with thirty thousand, eighty. Rare failures need a lot of traffic to see, which is why canaries run for hours, and why Part 44 treats these comparisons as experiments with power calculations.
Some failures appear only under real traffic, so large services test there, carefully. Shadow traffic copies real requests to the new version and compares its answers with the old version's, while users only ever see the old ones. A dark launch runs a new feature's work for real users with the results hidden, to measure its cost before anyone depends on it. And a kill switch is a flag that turns a feature off in seconds without a deploy, which must itself be tested, since it is used only on the worst day. Each of these turns a release from one irreversible moment into a series of measured, reversible steps.
The hardest changes to deliver are changes to stored data, because during a rollout the old and new versions of the code run side by side against the same database. So schema changes go in expand and contract steps. Add the new column. Make the code write both old and new. Copy the old rows across. Switch reads to the new column. And only then, when nothing reads the old column, drop it. Each step is deployed and verified on its own and can be undone; only the last destroys anything, and it runs when nobody needs what it destroys.
Delivery failures can be very expensive. On the first of August 2012, Knight Capital deployed new trading code that reused an old feature flag. One of its eight servers had not received the new code, so on that server the flag switched on a function that had been dead for nine years. In forty-five minutes it sent millions of unintended orders and lost about four hundred and forty million dollars; the firm needed rescuing within days. The lessons are this part's: deploy one artifact everywhere and verify that it arrived, delete dead code and retired flags, roll out gradually, and keep an automatic way to stop. Flags are a form of debt: each one doubles the states the code can be in, so they must be tracked and removed when their rollout is over.
When a release goes wrong, there are two ways out. Rolling back returns to the last good version. It is fast and safe, provided the release changed nothing that cannot be undone. Rolling forward means fixing the problem and shipping again, and it is the only option once data or clients have moved on: a schema already contracted, files already written in a new format. Small, frequent releases make both easy, because a change of ten lines is quick to revert, to review and to bisect, which is the mechanism behind Part 40's DORA finding. The rule that follows is the expand-and-contract rule again: keep every release revertible until its last irreversible step, and make that step come last.
Follow one change through all of it: a single line in the Job's word counter. It becomes a commit, a new node in the Merkle graph whose name vouches for the whole history. People review it. The merge queue tests it on top of everything ahead of it. The build recompiles only what its hash touches and fetches the rest from the cache. A canary compares it against the old version on real traffic, and the rollout widens step by step. At every stage the question is the one the build system asked: what is the least we must redo, and how do we know we can stop?
8Frontier: merging and building, correctlyResearch3 min
Merging by lines is the frontier's first target. Two branches each add an import, one in the middle of the list and one at the end. A line-based merge may report a conflict, although the meaning is simply a set of imports. Worse, it silently accepts edits that clash in meaning: one branch renames a function, another adds a call to its old name, and the merged program no longer runs. Structured merge parses each version and merges syntax trees, as Sven Apel and colleagues proposed in 2011 and newer tools such as Spork and Mergiraf do. The open problem is the deeper one: a merge that is semantically safe, whose result does what both changes intended, checked by tests, types or proofs.
Build systems have their own correctness questions. An incremental build is correct if its outputs equal those of a clean build, and minimal if nothing ran that did not need to. Both fail when the declared dependencies are wrong, so newer tools, such as Neil Mitchell's Rattle, trace every file a task actually reads instead of trusting what it declared. Version solving wants resolvers that are complete, finding a solution whenever one exists and proving and explaining it when none does, while staying as fast as a greedy guess on real universes. And reproducibility at scale is close: Debian and NixOS rebuild most of their packages bit for bit, and the last few percent are a long tail of compilers, archive formats and clocks.
One more frontier is arriving quickly: authors that are programs. Automated systems already made most of the changes to Google's repository in 2016, dependency updates, large refactorings and generated code, about twenty-four thousand of forty thousand changes a day. AI coding agents add authors that can write many plausible patches very quickly. The merge queue, the tests and the canary then become the judge of every one, and Part 40 showed how much a test suite can miss. Provenance matters more than ever: who or what wrote a change, from which inputs, and who reviewed it, recorded in signed commits and attestations. The open question is how to review and test changes at a rate that grows with the number of authors rather than the number of reviewers.
Open problems. Semantic merge: detecting, before merging, that two changes which merge cleanly will break each other. Dependency evolution: predicting which upgrade will break a program, and repairing it automatically. Test selection with guarantees, choosing the fewest tests that still catch a change's bugs, even when dependencies are discovered at run time. And safe rollout: the fastest schedule that bounds the expected harm a bad release can do. This part's research problem asks for the best merge-queue policy, its batch sizes and the order of its bisection, when each change has its own learned probability of failing.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. A git object store whose names match the real git, and the Merkle graph those names form. Merge bases, three-way merges and their conflicts, rebasing, and bisection in logarithmic time. Deltas that store forty versions of a file in a thirtieth of the space. A build system that trusts hashes rather than clocks and stops early, and the work and span of building in parallel. Package versions as satisfiability, NP-complete by a reduction you can read. And merge queues, test selection, canaries and migrations that deliver a change a little at a time. Three machines, one idea: name things by what they contain, and redo only what a change can reach.
Where this comes back. Part 42's browser caches assets by content hash. Part 43 versions the interfaces between services and rolls them out compatibly. Part 44 turns canaries into experiments with proper statistics. Part 50 releases and rolls back under the pressure of an incident. And Parts 55 and 61 return to the supply chain, and to whether a compiler can be trusted at all.
In practice. Make small commits whose messages say why, rebase work that is only yours and merge work that is shared. Let git bisect run your test script when something breaks, and check the reflog before you panic. Declare every input your build uses, and make it hermetic and cached. Commit lockfiles, update dependencies on purpose, and prefer fewer, better-kept ones. And deliver through a merge queue, a canary, feature flags and expand-and-contract migrations.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give our build engine a shared cache of outputs, keyed by the hash of their inputs, and measure how little a second machine must do. The last, marked with a star, is a research problem: the best merge-queue policy when every change carries its own learned chance of failing.
Next time, Part 42: the browser and the web. How a URL becomes pixels, through parsing, the document tree, layout and painting; JavaScript's event loop and the budget of a single frame; the same-origin policy and the attacks it stops; and caches and service workers that keep a web app working offline.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 42's browser caches assets by content hash, Part 43 versions the interfaces between services, and Part 44 turns canaries into experiments with proper statistics. Part 50 releases and rolls back during incidents, and Parts 55 and 61 return to the supply chain and to whether a compiler can be trusted.
Key results
The part's results in one place, for revision.
Try it
Lab 41 · Three machines, one idea: hashes, rebuilds and version solving
Check the series' object store against two ids every git installation produces, and count the objects one edit renames in a random tree. Rebuild a 202-target project after six kinds of edit with make's timestamps and with hashes and early cutoff. Then turn random 3-SAT formulas into package universes and check that the solver installs them exactly when brute force finds a satisfying assignment.
python -m videos.cs.labs 41
needs numpy, scipy, matplotlib · download lab41.py ·
source on GitHubblob ids of '' and 'hello world' e69de29b..., 3b18e512... identical to git's
edit d0/e0/f0.txt in a tree of 40 objects 4 objects renamed (the blob and 3 trees above it), 36 shared
rebuild after: a comment in one source make 3 hashes 1 of 202 targets
rebuild after: a real change in one header make 41 hashes 41 of 202 targets
rebuild after: every file touched make 202 hashes 0 of 202 targets
128 random 3-SAT formulas as packages solver and brute force agree on 128 bisecting 1,000,000 commits: 20 tests
installable share at clause ratios 1, 2, 3, 4, 5, 6, 8, 10 100% 100% 100% 94% 25% 19% 6% 0%
Names that are hashes of content make an edit rename only its path to the root, let a build skip everything whose inputs hash the same, and leave version choice as the one hard problem: it is 3-SAT in disguise.
The code (104 lines; it asserts its own result)
"""Lab 41: name objects as git does, rebuild by hashes instead of clocks, and install packages iff a formula is satisfiable."""
from videos.coursekit import labs
import itertools
import math
import numpy as np
from explainer.cs.vcs import build
from explainer.cs.vcs import deps
from explainer.cs.vcs import git
TITLE = "Three machines, one idea: hashes, rebuilds and version solving"
GOAL = ("Check the series' object store against two ids every git installation produces, and count the objects one "
"edit renames in a random tree. Rebuild a 202-target project after six kinds of edit with make's timestamps "
"and with hashes and early cutoff. Then turn random 3-SAT formulas into package universes and check that "
"the solver installs them exactly when brute force finds a satisfying assignment.")
TASKS = [
"Edit a file one directory deeper (add a level to the path). How many objects get new names, and how many are shared?",
"Call build.build_traces(p, built, cutoff=False) for the comment edits. Which rebuild counts change, and why?",
"Raise the number of variables from 10 to 14 and watch where the installable share crosses one half. Does it move towards 4.26?",
]
RATIOS = (1, 2, 3, 4, 5, 6, 8, 10)
N_VARS, TRIALS = 10, 16
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. content addresses: the two ids below are what `git hash-object` prints for an empty file and "hello world"
assert git.obj_id("blob", b"") == "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
assert git.obj_id("blob", b"hello world\n") == "3b18e512dba79e4c8300dd08aeb37f8e728b8dad"
files = {f"d{i}/e{j}/f{k}.txt": f"file {i}{j}{k} {rng.integers(1 << 30)}\n".encode()
for i in range(3) for j in range(3) for k in range(3)}
victim = sorted(files)[int(rng.integers(len(files)))]
edited = dict(files, **{victim: files[victim] + b"one more line\n"})
c = git.changed_ids(files, edited)
renamed = c["objects_b"] - c["shared"]
depth = victim.count("/")
lab.row("blob ids of '' and 'hello world'", "e69de29b..., 3b18e512... identical to git's")
lab.row(f"edit {victim} in a tree of {c['objects_a']} objects", f"{renamed} objects renamed (the blob and {depth + 1} trees above it), {c['shared']} shared")
assert renamed == depth + 2 and c["root_a"] != c["root_b"], "an edit renames exactly the objects on its path to the root"
# 2. builds: make's clocks against hashes with early cutoff
s = build.scenarios(seed=seed)
rows = {r["edit"].split(" \\")[0]: r for r in s["rows"]}
for name in ("a comment in one source", "a real change in one header", "every file touched"):
lab.row(f"rebuild after: {name}", f"make {rows[name]['make']} hashes {rows[name]['traces']} of {s['targets']} targets")
assert all(r["traces"] <= r["make"] for r in s["rows"]), "hashes never rebuild more than timestamps"
assert rows["a comment in one source"]["make"] == 3 and rows["a comment in one source"]["traces"] == 1, "early cutoff"
assert rows["every file touched"]["make"] == s["targets"] and rows["every file touched"]["traces"] == 0
assert rows["a real change in one header"]["traces"] == s["h3_users"] + 2, "a real change reaches its users, the library and the tests"
b = git.bisect(1_000_000, int(rng.integers(1, 1_000_000)))
assert b["steps"] <= math.ceil(math.log2(1_000_000)), "bisection is binary search"
# 3. version solving is satisfiability: installable iff satisfiable, formula by formula
share, agree, total = [], 0, 0
assignments = np.array(list(itertools.product((False, True), repeat=N_VARS)))
for ratio in RATIOS:
ok = 0
for _ in range(TRIALS):
clauses = [[int(v) * int(rng.choice((-1, 1))) for v in rng.choice(np.arange(1, N_VARS + 1), 3, replace=False)]
for _ in range(ratio * N_VARS)]
sat = np.ones(len(assignments), bool)
for cl in clauses:
sat &= np.any([assignments[:, abs(l) - 1] == (l > 0) for l in cl], axis=0)
universe, root = deps.from_3sat(N_VARS, clauses)
chosen, _, _ = universe.solve(root, seed=seed)
installable = chosen is not None
assert installable == bool(sat.any()), "the packages install exactly when the formula is satisfiable"
assert not installable or deps.check_assignment(clauses, chosen), "and the chosen versions satisfy it"
agree, total, ok = agree + 1, total + 1, ok + installable
share.append(ok / TRIALS)
lab.row(f"{total} random 3-SAT formulas as packages", f"solver and brute force agree on {agree} bisecting 1,000,000 commits: {b['steps']} tests")
lab.row("installable share at clause ratios " + ", ".join(map(str, RATIOS)), " ".join(f"{x:.0%}" for x in share))
assert share[0] > 0.9 and share[-1] <= 0.2, "few constraints: always installable; many: never"
lab.note = ("Names that are hashes of content make an edit rename only its path to the root, let a build skip "
"everything whose inputs hash the same, and leave version choice as the one hard problem: it is "
"3-SAT in disguise.")
fig, ax = labs.figure(2, size=(11, 4.4))
order = ["a comment in one source", "a real change in one source", "a comment in one header",
"a real change in one header", "every file touched"]
y = np.arange(len(order))
ax[0].set_axisbelow(True)
ax[0].barh(y - 0.2, [rows[k]["make"] for k in order], 0.4, color=labs.RED, label="make: timestamps")
ax[0].barh(y + 0.2, [rows[k]["traces"] for k in order], 0.4, color=labs.GREEN, label="hashes, with early cutoff")
for k, name in enumerate(order):
ax[0].text(rows[name]["make"] + 3, k - 0.2, str(rows[name]["make"]), va="center", color=labs.INK, fontsize=9)
ax[0].text(rows[name]["traces"] + 3, k + 0.2, str(rows[name]["traces"]), va="center", color=labs.INK, fontsize=9)
labels = ["comment in\na source", "real change\nin a source", "comment in\na header", "real change\nin a header", "fresh checkout\n(all touched)"]
ax[0].set(title=f"Targets rebuilt, of {s['targets']}", xlabel="targets rebuilt", yticks=y, yticklabels=labels, xlim=(0, s["targets"] * 1.15))
ax[0].invert_yaxis()
ax[0].legend(loc="center right")
ax[1].plot(RATIOS, share, color=labs.GOLD, marker="o", label="installable (solver) = satisfiable (brute force)")
ax[1].axvline(4.26, color=labs.MUTED, ls="--", lw=1)
ax[1].text(4.36, 0.93, "4.26: the threshold\nfor large formulas", color=labs.MUTED, fontsize=9, va="top")
ax[1].set(title=f"Random 3-SAT with {N_VARS} variables, as packages", xlabel="constraints per variable (clauses / variables)",
ylabel="share that can be installed", ylim=(-0.05, 1.12))
ax[1].legend(loc="center right")
lab.fig = fig
return lab
Now change it
- Edit a file one directory deeper (add a level to the path). How many objects get new names, and how many are shared?
- Call build.build_traces(p, built, cutoff=False) for the comment edits. Which rebuild counts change, and why?
- Raise the number of variables from 10 to 14 and watch where the installable share crosses one half. Does it move towards 4.26?
Problems, with solutions
Try each problem before opening its solution.
-
Merkle ripples. Show that changing one file changes exactly the ids of the trees on its path and the commit, and that two snapshots share every other object.
Solution
A blob's id is the hash of its content, so the edited file's blob changes and no other blob does. A tree's id is the hash of its entries (mode, name, child id); the tree containing the file has one entry with a new child id, so its own id changes (with overwhelming probability, by collision resistance); inductively every ancestor tree up to the root changes. A tree not on the path has entries whose child ids are all unchanged, so its content and id are unchanged; the same holds for every blob off the path. The commit names the root tree, so it changes. In our example: 4 objects changed (a blob, two trees, the root), 2 shared.
-
Two merge bases. Give a history with two merge bases, and show that merging against either one alone can give a different result.
Solution
The criss-cross: 0 → 1 and 0 → 2; 3 merges 1 and 2; 4 merges 2 and 1; 5 extends 3, 6 extends 4. The common ancestors of 5 and 6 are {0, 1, 2}; 0 is an ancestor of 1, so the best are 1 and 2. Let line L be "x" in 0, "y" in 1 and unchanged in 2, and let the merge at 3 keep "y" while the merge at 4 resolved the same conflict as "z". Merging 5 and 6 with base 1 sees L unchanged on side 5 ("y") and changed on side 6 ("z"), and takes "z" silently; with base 2 (where L is "x") both sides changed it differently: a conflict. Git's recursive strategy first merges 1 and 2 into a virtual base, so that the answer does not depend on an arbitrary choice.
-
Bisection. Prove that ⌈log₂ n⌉ tests suffice on a linear history and that none fewer suffice in the worst case.
Solution
With a known good and a known bad commit, n candidates remain for the first bad one. Testing the middle one leaves at most ⌈n/2⌉, so ⌈log₂ n⌉ tests reduce the candidates to one. Conversely each test has two outcomes, so k tests distinguish at most 2ᵏ cases; to identify one of n candidates requires 2ᵏ ≥ n.
-
Build correctness. Show that verifying traces are correct when every task is deterministic and declares all its inputs, and give a timestamp scenario that makes Make incorrect.
Solution
By induction in topological order. A task that is skipped has the same input hashes as when it was last run; if every input it reads is declared and it is deterministic, rerunning it would produce the same output, so the stored output equals what a clean build would produce. A task that runs produces the clean-build output by determinism, given that its inputs are by induction the clean-build values. For Make: restore an older version of a source file from a backup, keeping its old modification time, which is older than the object built from the newer version; Make sees the object as newer than its source and does not rebuild it, so the build output corresponds to a source that no longer exists.
-
Build. Add constructive traces to our build engine and measure a second machine's build.
Solution
Solution sketch. Key every output by (target, hashes of its inputs) in a cache shared between engines; before running a task, look its key up and download on a hit. Our implementation (
build_cached): machine A's clean build runs 202 tasks; machine B, at the same commit, runs 0 and downloads 202; after a header change A runs 41 and B downloads those 41. -
★ Research. Find the merge-queue policy that maximizes throughput when each change has its own learned failure probability.
Discussion. Open. With equal probabilities p, the expected test runs per change for a batch of b with binary-splitting is minimized near b ≈ 1/√p for small p (our table: 64 at 1%, 4 at 10%). With heterogeneous, predicted pᵢ, natural policies batch low-risk changes together and test high-risk ones alone, and order bisection by risk; the problem becomes adaptive group testing with priors, latency constraints and prediction error. A good answer would give a policy, bounds against the optimum, and an evaluation on real CI logs.
Notes and sources
Glossary
- content addressing, object id — naming data by the hash of its content.
- blob, tree, commit, tag — git's four object kinds: bytes, a directory, a snapshot with parents, a named commit.
- Merkle graph (DAG) — a graph whose node names are hashes covering their children.
- ref, branch, HEAD, index, reflog — mutable names; the current branch; the staged next tree; ref history.
- merge base, criss-cross merge — a best common ancestor; a history with more than one.
- three-way merge, conflict, rerere — merging two sides against a base; a region both changed differently; replaying a recorded resolution.
- rebase, cherry-pick, bisect — replaying commits on a new base; applying one commit's diff; binary search for a bad commit.
- packfile, delta, window, depth — compressed storage of objects as differences; search width; chain length.
- shallow, partial, sparse clone — less history; contents on demand; some directories.
- build target, rule, topological order — a file to make, how to make it, an order respecting dependencies.
- dirty bit, verifying traces, constructive traces, early cutoff — rebuild markers; recorded input hashes; cached outputs; stopping when an output is unchanged.
- hermetic, reproducible build — sees only declared inputs; bit-identical outputs.
- semantic versioning, lockfile, vendoring — MAJOR.MINOR.PATCH; pinned versions and hashes; copied dependencies.
- diamond dependency, version resolution — two paths requiring incompatible versions; choosing compatible versions (NP-complete).
- SBOM, SLSA — a list of a build's components; levels of build provenance.
- trunk-based development, pre-/post-submit, merge queue — short-lived branches on one main line; tests before and after landing; batched, ordered testing before merging.
- test selection — running only the tests a change can affect.
- blue/green, canary, progressive rollout, feature flag, kill switch — release strategies.
- shadow traffic, dark launch — testing with real requests without exposing results.
- expand–contract migration — changing a schema in reversible steps.
Sources
- S. Chacon and B. Straub, Pro Git (2nd ed., 2014); git documentation (
gitformat-pack,git-merge-base). - R. Merkle, "A digital signature based on a conventional encryption function", CRYPTO 1987; M. Stevens et al., "The first collision for full SHA-1", CRYPTO 2017.
- E. Myers, "An O(ND) difference algorithm and its variations", Algorithmica 1986.
- R. Potvin and J. Levenberg, "Why Google stores billions of lines of code in a single repository", CACM 2016.
- D. Roundy, Darcs (2003); Pijul; M. Kleppmann et al., "Local-first software", 2019.
- S. Feldman, "Make — a program for maintaining computer programs", 1979; P. Miller, "Recursive make considered harmful", 1997.
- A. Mokhov, N. Mitchell and S. Peyton Jones, "Build systems à la carte", ICFP 2018 (and JFP 2020); S. Spall, N. Mitchell and S. Tobin-Hochstadt, "Build scripts with perfect dependencies", OOPSLA 2020.
- E. Dolstra, The Purely Functional Software Deployment Model (thesis, 2006).
- R. Di Cosmo et al., "Managing the complexity of large free and open source package-based software distributions", ASE 2006; N. Weizenbaum, "PubGrub: next-generation version solving", 2018; R. Cox, "Minimal version selection", 2018.
- S. Raemaekers, A. van Deursen and J. Visser, "Semantic versioning versus breaking changes: a study of the Maven repository", SCAM 2014.
- S. Ananthanarayanan et al., "Keeping master green at scale", EuroSys 2019 (SubmitQueue).
- J. Humble and D. Farley, Continuous Delivery (2010); B. Beyer et al., Site Reliability Engineering (2016); T. Winters, T. Manshreck and H. Wright, Software Engineering at Google (2020), chs. 16–24.
- SEC, In the Matter of Knight Capital Americas LLC, 2013.
- S. Apel et al., "Semistructured merge: rethinking merge in revision control systems", ESEC/FSE 2011; S. Larsén et al., "Spork: structured merge for Java with formatting preservation", TSE 2022.
About this partfrom its README
Part 41 of a sixty-one-part course in computer science (see the series plan and the syllabus), the second part of Act VIII, Building Software. Every change to modern software passes through three machines. The version-control system is secretly a content-addressed Merkle graph; the build system is an incremental computation over a dependency graph; the package manager is a satisfiability solver, because choosing versions is NP-complete. Above them, continuous integration and delivery turn a change into running software a little at a time. Where we can, we measure this repository itself.
The instruments are in explainer/cs/vcs/ (tested in tests/test_cs41_vcs.py):
git.py: an object store in git's own formats (blob, tree and commit ids checked against git 2.43); Merkle ripples and corruption detection; random histories, merge bases with criss-cross cases, bisection; three-way merge over Myers' diff (Part 21); Myers' edit graph; deltas over every committed version of a file in this repository; the size of this repository's history.build.py: a synthetic C-like project (sources, headers, objects, a library, a test report) built by make's timestamps, by verifying traces with early cutoff and by constructive traces with a shared cache; a drawable twelve-file project; work, span and greedy scheduling of a clean build.deps.py: package universes encoded as SAT and solved with Part 26's CDCL; the diamond; the 3-SAT reduction (Di Cosmo et al. 2006); a backtracking resolver's trace; solver work at the satisfiability threshold.ci.py: a merge queue that tests batches and bisects failures; canary analysis by a two-proportion test.
Chapter notes
- Hook. SCCS to Subversion; BitKeeper and April 2005. Our object store and git 2.43 give identical names to the same three files, their tree and their commit.
- 1. Git's objects. Blobs, trees, commits, tags; nothing overwritten; SHA-1 to SHA-256. The Merkle graph: editing
one file renames 4 of 6 objects, every one on its path; 2 are shared. One flipped bit ("novdls") is caught by
rehashing; SHAttered. Branches, HEAD, the index, checkout, the reflog; the three trees and
reset. - 2. Merging and bisecting. Merge bases as best common ancestors; a criss-cross with two (1 and 2); recursive and ort; how git paints the graph to find them. Myers' edit graph for ABCABBA → CBABAC (D = 5, four letters kept). A three-way merge that keeps both sides' changes, and one that conflicts; rerere. Merge against rebase, cherry-pick. Bisect: commit 637 of 1,000 in 10 tests; a million commits in 20.
- 3. Storing history. Forty versions of this series' syllabus: 4.2 MB stored whole, 154 KB as deltas. This repository: 159 commits, 17,440 objects, 861 MB of current files, 888 MB of objects ever, 695 MB packed. The delta window and depth. Google's monorepo; shallow, partial and sparse clones. Patch theory (Darcs, Pijul); CRDTs.
- 4. Build systems. Make (1976) and topological order. On 202 targets: a comment edit costs make 3 rebuilds and a hashing build 1; a fresh checkout costs make 202 and the hashing build 0. Recursive make considered harmful. A twelve-file project lit up: one header change rebuilds 8 targets. Build systems à la carte. A shared cache: a second machine runs 0 of 202 tasks. Work 235 s, span 34 s: one worker 235 s, eight 54 s, beyond 32 no faster. Hermetic and reproducible builds; Nix store paths.
- 5. Dependencies. Semantic versioning, and how often it is kept (a third of Maven releases break something). The diamond: app, A, B 1.0/1.1, C 1–3; resolved to B 1.1 and C 2; a resolver's seven steps. The 3-SAT reduction on screen and drawn as packages; installable iff satisfiable. Solver conflicts at the threshold: 6, 43, 183, 416 for 20–80 variables. PubGrub; Go's minimal version selection. npm against pip; left-pad; lockfile hashes. The supply chain: event-stream, SolarWinds, xz; signatures, SBOMs, SLSA; vendoring.
- 6. Continuous integration. Trunk-based development, pre- and post-submit tests, flaky tests. A merge queue on 20,000 changes: with 1% bad changes, batches of 64 need 0.125 test runs per change; with 10% bad, batches of 4 are best (0.61). Test selection over this repository's import graph: the KWIC module reaches 1 test module, the assembler 22, the narration engine 71 of 200; the median library module 1%.
- 7. Continuous delivery. Blue/green, canaries, progressive rollout, feature flags; shadow traffic, dark launches and kill switches. A canary that must detect a doubled 0.1% error rate: caught 1%, 7%, 32%, 80% and 100% of the time at 1,000 to 100,000 requests (α = 0.01). Expand–contract migrations. Knight Capital (2012). Roll back or roll forward. The Job's change, end to end.
- 8. Frontier: merging and building, correctly. Structured merge (semistructured merge, Spork, Mergiraf); build correctness and minimality; complete version solving; reproducibility at scale; authors that are programs. Four open problems, and the ★ research problem.
- 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
- Hook: the 2005 BitKeeper split and git's first ten days; from RCS, CVS and SVN to distributed version control.
- Git's object model: blobs, trees, commits, tags, all content-addressed (callback to Part 29's hashes); history as a Merkle DAG, with integrity for free. We build a small object store and check its hashes against real git's.
- Refs, branches, the index and the reflog; what checkout actually does.
- Merging:
- merge bases as lowest common ancestors in the DAG (several of them, and git's recursive strategy);
- three-way merge over Myers' diff (callback to Part 21);
- conflicts; ort.
- Rebase against merge; cherry-pick as applying a diff; bisect as binary search over history.
- Storage: packfiles and delta compression (callback to Part 21); shallow and partial clones; monorepos at scale (Google, cited) against polyrepos.
- Other models: patch theory (Darcs, Pijul) and commuting patches; CRDT-based version control (callback to Part 39).
- Build systems:
- Make (Feldman 1979): the dependency DAG, timestamps and how they lie;
- topological order (callback to Part 18);
- parallel builds as a work–span problem (callback to Part 10).
- Build systems à la carte (Mokhov, Mitchell & Peyton Jones 2018):
- schedulers × rebuilders;
- static and dynamic dependencies; minimality and correctness;
- early cutoff;
- the spreadsheet as a build system.
- Hermetic, reproducible, remote-cached builds (Bazel, Nix): content hashes as cache keys.
- Dependencies:
- semantic versioning;
- version resolution is NP-complete (reduction from 3-SAT, on screen; Di Cosmo et al. 2006);
- CDCL and PubGrub solvers in practice (callback to Part 26);
- lockfiles, diamond dependencies, vendoring.
- Supply-chain hygiene: signatures, SBOMs, SLSA (Part 55 returns to it).
- Continuous integration: trunk-based development; merge queues (the probability that a batch is green, and bisection on failure, computed); test selection by dependency graph.
- Continuous delivery:
- blue/green and canary deploys, with statistical detection of a bad canary (callback to Part 44);
- progressive rollout, feature flags, rollback;
- expand–contract schema migrations.
- The Job's own pipeline end to end: commit, CI, build cache, canary, rollout. Outro.
Computed: our object store against git's hashes; LCAs on synthetic DAGs; bisect step counts; a make-like engine with early cutoff on a synthetic project (rebuild counts); a version solver on a reduced 3-SAT instance; merge-queue throughput against batch size and failure rate; canary detection power. Visuals: hashes changing all the way up the DAG when one blob changes; three columns converging in a three-way merge; the build DAG lighting the minimal rebuild set; the 3-SAT gadget written as package versions. In practice: git workflows, Bazel/Buck/Nix, npm/pip/cargo resolvers, CI/CD pipelines, monorepo tooling, release engineering. Reading: Chacon & Straub, Pro Git; Mokhov, Mitchell & Peyton Jones 2018; Feldman 1979; Dolstra 2006 (the Nix thesis); Di Cosmo et al. 2006; Humble & Farley, Continuous Delivery; Winters, Manshreck & Wright ch. 16–24; Potvin & Levenberg 2016; Beyer et al., Site Reliability Engineering (release engineering).
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
Merkle 涟漪。 证明修改一个文件恰好改变其路径上各个树对象和提交的标识,而两个快照共享其余全部对象。
解答
blob 的标识是其内容的哈希,所以被编辑文件的 blob 改变,其他 blob 不变。树的标识是其条目(模式、名字、子对象标识) 的哈希;包含该文件的树有一个条目的子标识变了,所以它自己的标识也变(由抗碰撞性,以压倒性概率);归纳地,直到根的每个祖先 树都变。不在路径上的树,其条目的子标识都没变,所以内容和标识不变;路径外的每个 blob 也一样。提交指向根树,所以提交也变。 在我们的例子里:改变了 4 个对象(一个 blob、两个树、根),共享 2 个。
-
两个合并基。 给出一个有两个合并基的历史,并说明只用其中任一个合并,结果可能不同。
解答
交叉合并:0 → 1、0 → 2;3 合并 1 和 2;4 合并 2 和 1;5 接在 3 后,6 接在 4 后。5 和 6 的公共祖先是 {0, 1, 2}; 0 是 1 的祖先,所以最佳的是 1 和 2。设第 L 行在 0 中是 "x",在 1 中是 "y",在 2 中未变;3 处的合并保留 "y",而 4 处的合并把 同一冲突解决成 "z"。以 1 为基合并 5 和 6:5 一侧 L 未变("y"),6 一侧变成 "z",于是悄悄取 "z";以 2 为基(L 为 "x"),两侧都 以不同方式改了它:冲突。git 的递归策略先把 1 和 2 合并成一个虚拟基,答案就不依赖于一个任意的选择。
-
二分。 证明在线性历史上 ⌈log₂ n⌉ 次测试足够,且最坏情况下不能更少。
解答
已知一个好的和一个坏的提交时,第一个坏提交有 n 个候选。测试中间那个,最多剩 ⌈n/2⌉ 个,所以 ⌈log₂ n⌉ 次测试把候选 减到一个。反过来,每次测试只有两种结果,k 次测试最多区分 2ᵏ 种情况;要从 n 个候选中确定一个,必须 2ᵏ ≥ n。
-
构建的正确性。 证明当每个任务都是确定性的且声明了全部输入时,验证型追踪是正确的;并给出一个让 Make 出错的时间戳场景。
解答
按拓扑序归纳。被跳过的任务,其输入哈希与上次运行时相同;若它读的每个输入都已声明且它是确定性的,重跑会得到同样的 输出,所以存下的输出等于干净构建的输出。被运行的任务,由确定性和(归纳得到的)输入都是干净构建的值,产出干净构建的输出。对 Make:从备份恢复某源文件的旧版本并保留其旧修改时间,它早于由新版本编译出的目标文件;Make 认为目标比源新而不重建,于是构建产物 对应的是一个已不存在的源文件。
-
动手。 给我们的构建引擎加上构造型追踪,并测量第二台机器的构建。
解答
解答要点。 把每个输出按(目标,其输入的哈希)存入一个在多个引擎间共享的缓存;运行任务前先查键,命中就下载。我们的实现 (
build_cached):机器 A 干净构建运行 202 个任务;机器 B 在同一提交上运行 0 个、下载 202 个;改了一个头文件后,A 运行 41 个, B 下载这 41 个。 -
★ 研究。 当每个变更都有自己学习得到的失败概率时,求使吞吐量最大的合并队列策略。
讨论。 尚未解决。失败概率都等于 p 时,用二分拆分的大小为 b 的批次,每个变更的期望测试次数在 p 较小时于 b ≈ 1/√p 附近最小 (我们的表:1% 时为 64,10% 时为 4)。若概率各异且为预测值 pᵢ,自然的策略是把低风险变更一起批量测试、高风险的单独测试,并按 风险安排二分顺序;问题变成带先验、延迟约束和预测误差的自适应组测试。好的答案应给出策略、与最优解的差距界,以及在真实 CI 日志 上的评估。
Build the film
python -m videos.cs.cs41.compute # the part's numbers, into .cache/cs41
python tools/build.py cs41 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs41 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs41. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs41.compute
python -m unittest tests.test_cs41_vcs
python tools/build.py cs41