<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://fzakaria.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://fzakaria.com/" rel="alternate" type="text/html" /><updated>2026-11-17T11:16:49-08:00</updated><id>https://fzakaria.com/feed.xml</id><title type="html">Farid Zakaria’s Blog</title><subtitle>I&apos;m a software engineer, father and wishful amateur surfer. If you&apos;ve come seeking my political views, you&apos;ve found the wrong &lt;a href=&quot;https://fareedzakaria.com/&quot;&gt;Fareed&lt;/a&gt;.</subtitle><author><name>Farid Zakaria</name></author><entry><title type="html">beer.drv.drv.drv</title><link href="https://fzakaria.com/2026/11/14/beer-drv-drv-drv" rel="alternate" type="text/html" title="beer.drv.drv.drv" /><published>2026-11-14T12:00:00-08:00</published><updated>2026-11-14T12:00:00-08:00</updated><id>https://fzakaria.com/2026/11/14/beer-drv-drv-drv</id><content type="html" xml:base="https://fzakaria.com/2026/11/14/beer-drv-drv-drv"><![CDATA[<p>Have you heard about <a href="/2025/03/11/nix-dynamic-derivations-a-practical-application">dynamic derivations</a>?</p>

<p>They are an experimental-feature in Nix that lets a derivation produce other derivations as its output. Why ? This lets you dynamically create your build graph, instead of having to know it all at evaluation time. It’s Nix’s answer to try and match the build speed of other build systems like <a href="https://bazel.build/">Bazel</a> or <a href="https://buck2.build/">buck2</a>.</p>

<p style="--image-width: 20rem"><a href="/assets/images/dyn_drv_so_hot_meme.png"><img src="/assets/images/dyn_drv_so_hot_meme.png" alt="So hot right now meme: Mugatu from Zoolander under the caption &quot;Dynamic derivations&quot;, above &quot;So hot right now&quot;" /></a></p>

<p>There is not much written about dynamic derivations, and the documentation is sparse. I have <a href="/2025/03/10/an-early-look-at-nix-dynamic-derivations">written</a> <a href="/2025/03/11/nix-dynamic-derivations-a-practical-application">a</a> <a href="/2025/03/12/nix-dynamic-derivations-a-lang2nix-practicum">few</a> <a href="/2026/09/20/a-build-graph-that-rolls-dice">posts</a> about them, so I sometimes get questions about them.</p>

<p>Recently, I got a DM from <a href="https://www.linkedin.com/in/evanwp/">Evan Porter</a> over <a href="https://www.linkedin.com/">LinkedIn</a>, the ultimate bug triaging network, about whether it is possible to query the deriver of a dynamic derivation to get the initial derivation.</p>

<blockquote>
  <p>For dynamic derivations let’s say I have a .drv.drv file. This file outputs a derivation.
Is it usually possible to query deriver the output derivation to obtain the initial derivation?</p>
</blockquote>

<p>They had tried it and got this:</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-store <span class="nt">--query</span> <span class="nt">--deriver</span> <span class="se">\</span>
<span class="gp">    $</span><span class="o">(</span>nix-store <span class="nt">--query</span> <span class="nt">--deriver</span> ./result<span class="o">)</span>
<span class="go">unknown-deriver
</span></code></pre></div></div>

<p>That should work. 🤨 Every path a build registers carries a <code class="language-plaintext highlighter-rouge">deriver</code>, the <code class="language-plaintext highlighter-rouge">.drv</code> that produced it, and a <code class="language-plaintext highlighter-rouge">.drv</code> that came out of a build is still a path a build registered.</p>

<p>When I tried it, it worked. 🤷</p>

<p class="aside">You will need <code class="language-plaintext highlighter-rouge">extra-experimental-features = dynamic-derivations ca-derivations recursive-nix</code> in your <code class="language-plaintext highlighter-rouge">nix.conf</code> to drive the samples in this post.</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix build <span class="nt">-f</span> default.nix <span class="se">\</span>
<span class="go">    --print-out-paths
/nix/store/v4hkwn8y4m083gsap6523c0m5r985ygr-result

</span><span class="gp">$</span><span class="w"> </span>nix-store <span class="nt">--query</span> <span class="nt">--deriver</span> <span class="se">\</span>
<span class="go">    /nix/store/v4hkwn8y4m083gsap6523c0m5r985ygr-result
/nix/store/6pniymfhwcyrmkns0np7ap1argjziqq2-result.drv

</span><span class="gp">$</span><span class="w"> </span>nix-store <span class="nt">--query</span> <span class="nt">--deriver</span> <span class="se">\</span>
<span class="go">    /nix/store/6pniymfhwcyrmkns0np7ap1argjziqq2-result.drv
/nix/store/m5x261fv29jkn0rvznqj2fzkaql01xiy-result.drv.drv
</span></code></pre></div></div>

<p>Turns out, there is a case where you do get <code class="language-plaintext highlighter-rouge">unknown-deriver</code> if you set <code class="language-plaintext highlighter-rouge">__contentAddressed = true</code> on the producer. If the producer is content-addressed, its output path is not known until after the build, and Nix does not fill in the <code class="language-plaintext highlighter-rouge">deriver</code> of a path that already exists.
I filed <a href="https://github.com/NixOS/nix/issues/16823">NixOS/nix#16823</a>.</p>

<p>The question though made me wonder how far back you can walk the chain of dynamic derivations. I had to try it. 😈</p>

<p>Let’s pick a fun example to see how far we can go. Here is a derivation that imitates the classic song <em>99 bottles of beer</em> by producing a chain of derivations, each one outputting the next verse.<sup id="fnref:recursive-nix"><a href="#fn:recursive-nix" class="footnote" rel="footnote" role="doc-noteref">1</a></sup></p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">export </span><span class="nv">PATH</span><span class="o">=</span><span class="nv">$busybox</span>/bin

<span class="c"># A content-addressed derivation does not know its output path, so its</span>
<span class="c"># "out" variable holds this placeholder and Nix swaps in the real path at</span>
<span class="c"># build time. It is "/" + nix32(sha256("nix-output:out")), the same for</span>
<span class="c"># every derivation with an output named "out".</span>
<span class="nv">OUT_PLACEHOLDER</span><span class="o">=</span>/1rz4g4znpzjwh1xymhjpm42vipw92pr73vdgl6xs1hycac8kf2n9

bottles<span class="o">()</span> <span class="o">{</span>
  <span class="k">case</span> <span class="nv">$1</span> <span class="k">in
    </span>0<span class="p">)</span> <span class="nb">echo</span> <span class="s2">"no more bottles"</span> <span class="p">;;</span>
    1<span class="p">)</span> <span class="nb">echo</span> <span class="s2">"1 bottle"</span> <span class="p">;;</span>
    <span class="k">*</span><span class="p">)</span> <span class="nb">echo</span> <span class="s2">"</span><span class="nv">$1</span><span class="s2"> bottles"</span> <span class="p">;;</span>
  <span class="k">esac</span>
<span class="o">}</span>

<span class="c"># The last derivation in the chain writes the punchline instead of a .drv.</span>
<span class="k">if</span> <span class="o">[</span> <span class="s2">"</span><span class="nv">$n</span><span class="s2">"</span> <span class="nt">-eq</span> 0 <span class="o">]</span><span class="p">;</span> <span class="k">then
  </span><span class="nb">echo</span> <span class="s2">"No more bottles of beer on the wall, no more bottles of beer."</span> <span class="o">&gt;</span>&amp;2
  <span class="nb">echo</span> <span class="s2">"Go to the store and buy some more."</span> <span class="o">&gt;</span> <span class="nv">$out</span>
  <span class="nb">exit </span>0
<span class="k">fi

</span><span class="nv">next</span><span class="o">=</span><span class="k">$((</span>n <span class="o">-</span> <span class="m">1</span><span class="k">))</span>
<span class="nb">echo</span> <span class="s2">"</span><span class="si">$(</span>bottles <span class="nv">$n</span><span class="si">)</span><span class="s2"> of beer on the wall, </span><span class="si">$(</span>bottles <span class="nv">$n</span><span class="si">)</span><span class="s2"> of beer."</span> <span class="o">&gt;</span>&amp;2
<span class="nb">echo</span> <span class="s2">"Take one down, pass it around, </span><span class="si">$(</span>bottles <span class="nv">$next</span><span class="si">)</span><span class="s2"> of beer on the wall."</span> <span class="o">&gt;</span>&amp;2

<span class="c"># Input sources must be sorted.</span>
<span class="nv">srcs</span><span class="o">=</span><span class="si">$(</span><span class="nb">printf</span> <span class="s1">'"%s"\n'</span> <span class="s2">"</span><span class="nv">$busybox</span><span class="s2">"</span> <span class="s2">"</span><span class="nv">$script</span><span class="s2">"</span> | <span class="nb">sort</span> | <span class="nb">paste</span> <span class="nt">-sd</span>, -<span class="si">)</span>

<span class="c"># Write the derivation for the next verse. A .drv is a single line of</span>
<span class="c"># ATerm, so strip the spaces and newlines that are only here for reading.</span>
<span class="c"># Nix takes a derivation's name from its store path, so the next name is</span>
<span class="c"># ours minus one ".drv".</span>
<span class="nb">tr</span> <span class="nt">-d</span> <span class="s1">' \n'</span> <span class="o">&gt;</span> <span class="nv">$out</span> <span class="o">&lt;&lt;</span><span class="no">EOF</span><span class="sh">
Derive(
  [("out", "", "text:sha256", "")],
  [],
  [</span><span class="nv">$srcs</span><span class="sh">],
  "</span><span class="nv">$system</span><span class="sh">",
  "</span><span class="nv">$busybox</span><span class="sh">/bin/sh",
  ["</span><span class="nv">$script</span><span class="sh">"],
  [
    ("builder", "</span><span class="nv">$busybox</span><span class="sh">/bin/sh"),
    ("busybox", "</span><span class="nv">$busybox</span><span class="sh">"),
    ("n", "</span><span class="nv">$next</span><span class="sh">"),
    ("name", "</span><span class="k">${</span><span class="nv">name</span><span class="p">%.drv</span><span class="k">}</span><span class="sh">"),
    ("out", "</span><span class="nv">$OUT_PLACEHOLDER</span><span class="sh">"),
    ("outputHashAlgo", "sha256"),
    ("outputHashMode", "text"),
    ("script", "</span><span class="nv">$script</span><span class="sh">"),
    ("system", "</span><span class="nv">$system</span><span class="sh">")
  ]
)
</span><span class="no">EOF
</span></code></pre></div></div>

<blockquote class="alert alert-tip">
  <p><strong>Tip</strong>
A derivation whose output is a <code class="language-plaintext highlighter-rouge">.drv</code> must set <code class="language-plaintext highlighter-rouge">outputHashMode = "text"</code>.</p>
</blockquote>

<p>In our example we are using a content-addressed derivation, but the same idea works with an input-addressed one, but it’s more work to compute the output path in the shell, unless you are using <code class="language-plaintext highlighter-rouge">nix-instantiate</code> to do it for you with recursive Nix.</p>

<p>The Nix side builds the first derivation and then follows <code class="language-plaintext highlighter-rouge">builtins.outputOf</code> once per bottle.</p>

<div class="language-nix highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span>
  <span class="nv">pkgs</span> <span class="o">=</span> <span class="kr">import</span> <span class="p">(</span><span class="kr">fetchTarball</span> <span class="p">{</span>
    <span class="nv">url</span> <span class="o">=</span> <span class="s2">"https://github.com/NixOS/nixpkgs/archive/6dadaf4375be35033e1c84395adbd53ff5fded96.tar.gz"</span><span class="p">;</span>
  <span class="p">})</span> <span class="p">{</span> <span class="p">};</span>
  <span class="kn">inherit</span> <span class="p">(</span><span class="nv">pkgs</span><span class="p">)</span> <span class="nv">lib</span><span class="p">;</span>

  <span class="c"># maximum bottles of beer on the wall,</span>
  <span class="c"># 50 is the most that fits in a store path!?</span>
  <span class="nv">bottles</span> <span class="o">=</span> <span class="mi">50</span><span class="p">;</span>

  <span class="nv">top</span> <span class="o">=</span> <span class="kr">derivation</span> <span class="p">{</span>
    <span class="nv">name</span> <span class="o">=</span> <span class="s2">"beer"</span> <span class="o">+</span> <span class="nv">lib</span><span class="o">.</span><span class="nv">concatStrings</span> <span class="p">(</span><span class="nv">lib</span><span class="o">.</span><span class="nv">replicate</span> <span class="nv">bottles</span> <span class="s2">".drv"</span><span class="p">);</span>
    <span class="nv">system</span> <span class="o">=</span> <span class="kr">builtins</span><span class="o">.</span><span class="nv">currentSystem</span><span class="p">;</span>
    <span class="nv">builder</span> <span class="o">=</span> <span class="s2">"</span><span class="si">${</span><span class="nv">pkgs</span><span class="o">.</span><span class="nv">busybox</span><span class="si">}</span><span class="s2">/bin/sh"</span><span class="p">;</span>
    <span class="nv">args</span> <span class="o">=</span> <span class="p">[</span> <span class="sx">./bottles.sh</span> <span class="p">];</span>
    <span class="nv">script</span> <span class="o">=</span> <span class="sx">./bottles.sh</span><span class="p">;</span>
    <span class="nv">busybox</span> <span class="o">=</span> <span class="nv">pkgs</span><span class="o">.</span><span class="nv">busybox</span><span class="p">;</span>
    <span class="nv">n</span> <span class="o">=</span> <span class="nv">bottles</span><span class="p">;</span>
    <span class="nv">__contentAddressed</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
    <span class="nv">outputHashMode</span> <span class="o">=</span> <span class="s2">"text"</span><span class="p">;</span>
    <span class="nv">outputHashAlgo</span> <span class="o">=</span> <span class="s2">"sha256"</span><span class="p">;</span>
  <span class="p">};</span>
<span class="kn">in</span>
<span class="c"># Follow the chain of outputs down to the last derivation.</span>
<span class="nv">lib</span><span class="o">.</span><span class="nv">foldl</span><span class="err">'</span> <span class="p">(</span><span class="nv">drv</span><span class="p">:</span> <span class="nv">_</span><span class="p">:</span> <span class="kr">builtins</span><span class="o">.</span><span class="nv">outputOf</span> <span class="nv">drv</span> <span class="s2">"out"</span><span class="p">)</span> <span class="nv">top</span><span class="o">.</span><span class="nv">outPath</span> <span class="p">(</span><span class="nv">lib</span><span class="o">.</span><span class="nv">range</span> <span class="mi">1</span> <span class="nv">bottles</span><span class="p">)</span>
</code></pre></div></div>

<p class="aside">While working through this example, I hit a bug in Nix that made me set <code class="language-plaintext highlighter-rouge">__contentAddressed = true</code> on the top derivation. That is not necessary for a derivation that outputs a <code class="language-plaintext highlighter-rouge">.drv</code>, but it works around the bug. I filed <a href="https://github.com/NixOS/nix/issues/16830">NixOS/nix#16830</a>.</p>

<p>You might notice that we limit the number of beers to 50. Why 50 and not 99?</p>

<p>Well, 50 is the most that fits in a store path.</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="go">error: path '…-beer.drv.drv.drv…' is not a valid store path:
  name 'beer.drv.drv.drv…' must be no longer than 211 characters
</span></code></pre></div></div>

<p>The maximum length of a store path is <a href="https://github.com/NixOS/nix/blob/7f1ff3fec92f9d60327e4ca9e51acd565a91cc6c/src/libstore/include/nix/store/path.hh#L48">211 characters</a>. A derivation’s store path must include the <code class="language-plaintext highlighter-rouge">.drv</code> suffix, and every <code class="language-plaintext highlighter-rouge">.drv</code> in a chain adds four characters. The top derivation is named <code class="language-plaintext highlighter-rouge">beer</code> and if you add 51 <code class="language-plaintext highlighter-rouge">.drv</code>s we get 208 characters. No room for any more beer. 🍻</p>

<blockquote class="alert alert-note">
  <p><strong>Aside</strong>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mrow><mi>b</mi><mo>&#x0002B;</mo><mn>4</mn><mi>n</mi><mo>&#x02264;</mo><mn>211</mn><mspace width="1em" /><mo>&#x021D2;</mo><mspace width="1em" /><mi>n</mi><mo>&#x0003D;</mo><mrow><mo stretchy="true" fence="true" form="prefix">&#x0230A;</mo><mfrac><mrow><mn>211</mn><mo>&#x02212;</mo><mi>b</mi></mrow><mrow><mn>4</mn></mrow></mfrac><mo stretchy="true" fence="true" form="postfix">&#x0230B;</mo></mrow></mrow></math></p>

  <p>Even with a name of length 1, <math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mrow><mi>b</mi><mo>&#x0003D;</mo><mn>1</mn></mrow></math>, we get a theoretical limit of <math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mrow><mi>n</mi><mo>&#x0003D;</mo><mn>52</mn></mrow></math>.</p>
</blockquote>

<figure class="plotnine"><img src="https://fzakaria.com/assets/figures/1e222aa44c5c1fa1.svg" alt="Figure" width="446" height="248">
</figure>

<p>Let’s <del>build</del> sing it.</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix build <span class="nt">-f</span> beer.nix <span class="se">\</span>
<span class="go">    --print-out-paths \
    --print-build-logs
building '/nix/store/di5x9yrhh6pfn214c41bnpxh1avya51c-beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv'...
</span><span class="gp">beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv&gt;</span><span class="w"> </span>50 bottles of beer on the wall, 50 bottles of beer.
<span class="gp">beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv&gt;</span><span class="w"> </span>Take one down, pass it around, 49 bottles of beer on the wall.
<span class="go">building '/nix/store/zg35ykl6qvh6gasy6q4pc6d4kyqcq0sd-beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv'...
</span><span class="gp">beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv&gt;</span><span class="w"> </span>49 bottles of beer on the wall, 49 bottles of beer.
<span class="gp">beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv&gt;</span><span class="w"> </span>Take one down, pass it around, 48 bottles of beer on the wall.
<span class="go">building '/nix/store/g07drgnkmwkbyccwk8vzzibbfdznpqjd-beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv'...
</span><span class="gp">beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv&gt;</span><span class="w"> </span>48 bottles of beer on the wall, 48 bottles of beer.
<span class="gp">beer.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv.drv&gt;</span><span class="w"> </span>Take one down, pass it around, 47 bottles of beer on the wall.
<span class="c">...
</span><span class="go">building '/nix/store/0vr55qvmaswc2vkjvy4i2blcgc6phv85-beer.drv.drv'...
</span><span class="gp">beer.drv&gt;</span><span class="w"> </span>1 bottle of beer on the wall, 1 bottle of beer.
<span class="gp">beer.drv&gt;</span><span class="w"> </span>Take one down, pass it around, no more bottles of beer on the wall.
<span class="go">building '/nix/store/kb16larpavss7y26ivyib5mgc23gicn6-beer.drv'...
</span><span class="gp">beer&gt;</span><span class="w"> </span>No more bottles of beer on the wall, no more bottles of beer.
<span class="go">/nix/store/kp2aln1pr2cy4gn9qs8vzkq850blj60i-beer

</span><span class="gp">$</span><span class="w"> </span><span class="nb">cat </span>result
<span class="go">Go to the store and buy some more.
</span></code></pre></div></div>

<p>Fifty-one builds, one after another<sup id="fnref:cost"><a href="#fn:cost" class="footnote" rel="footnote" role="doc-noteref">2</a></sup>. Evaluation knows about only the first one. Nix discovers each of the other 50 by building the one before it. 🍺</p>

<figure class="graphviz" style="--graphviz-height: 6rem"><img src="https://fzakaria.com/assets/figures/4366f56f823ef5be.svg" alt="Figure" width="878" height="44">
</figure>

<blockquote class="alert alert-note">
  <p><strong>Aside</strong>
Hey, didn’t an <a href="/2026/09/20/a-build-graph-that-rolls-dice">earlier post</a> have dynamic derivation chains 500 deep?!</p>

  <p>Yes! The difference is whether a derivation <em>outputs</em> the next one or <em>depends</em> on it. A derivation whose output is another derivation gets one more <code class="language-plaintext highlighter-rouge">.drv</code> appended to the name. The dice chain linked each step to the next as a dependency, and a dependency keeps its own name, so no name ever had more than two <code class="language-plaintext highlighter-rouge">.drv</code>s in it.</p>
</blockquote>

<p>Back to the original question: can we query the deriver of the output derivation to get the initial derivation? Yes, we can.</p>

<p>Let’s put <code class="language-plaintext highlighter-rouge">nix-store --query --deriver</code> in a loop that walks from the result all the way back to the top.</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span><span class="nv">p</span><span class="o">=</span><span class="si">$(</span><span class="nb">readlink </span>result<span class="si">)</span>
<span class="gp">$</span><span class="w"> </span><span class="k">while</span> <span class="o">[</span> <span class="s2">"</span><span class="nv">$p</span><span class="s2">"</span> <span class="o">!=</span> unknown-deriver <span class="o">]</span><span class="p">;</span> <span class="k">do</span>
<span class="gp">    echo "$</span>p<span class="s2">"
</span><span class="gp">    p=$</span><span class="s2">(nix-store --query --deriver "</span><span class="nv">$p</span><span class="s2">")
</span><span class="gp">  done &gt;</span><span class="w"> </span><span class="s2">chain.txt
</span><span class="go">
</span><span class="gp">$</span><span class="w"> </span><span class="nb">wc</span> <span class="nt">-l</span> &lt; chain.txt
<span class="go">52

</span><span class="gp">$</span><span class="w"> </span><span class="nb">head</span> <span class="nt">-4</span> chain.txt
<span class="go">/nix/store/kp2aln1pr2cy4gn9qs8vzkq850blj60i-beer
/nix/store/kb16larpavss7y26ivyib5mgc23gicn6-beer.drv
/nix/store/0vr55qvmaswc2vkjvy4i2blcgc6phv85-beer.drv.drv
/nix/store/flj05chf2yyn5bxsjq41if7mihcjjqkp-beer.drv.drv.drv
</span></code></pre></div></div>

<p>We have the result plus 51 derivations. 💪</p>

<p>Since every derivation in the chain was built, every one has a build log, and you can ask any of them to sing its verse again.</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix log <span class="s2">"</span><span class="si">$(</span><span class="nb">sed</span> <span class="nt">-n</span> 26p chain.txt<span class="si">)</span><span class="s2">"</span>
<span class="go">24 bottles of beer on the wall, 24 bottles of beer.
Take one down, pass it around, 23 bottles of beer on the wall.
</span></code></pre></div></div>

<p>I’m very excited for the future of dynamic derivations. <a href="https://github.com/tomberek">tomberek</a> is <a href="https://discourse.nixos.org/t/dynamic-derivations-dynamic-build-graphs-next-steps/79409/">leading a working-group</a> to finalize the feature and are currently meeting weekly. With dynamic derivations, Nix will be able to compete with other build systems in terms of speed and flexibility and <em>take over the world</em>.</p>

<p><a href="https://ghuntley.com/patch/">Patch the world</a>. Nix the world.</p>

<p style="--image-width: 20rem"><a href="/assets/images/dyn_drv_pinky_brain_meme.png"><img src="/assets/images/dyn_drv_pinky_brain_meme.png" alt="Pinky and the Brain meme: Pinky asks &quot;What are we doing tonight, Brain?&quot; and the caption below reads &quot;Taking over the world with dynamic derivations&quot;" /></a></p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:recursive-nix">
      <p>The builder writes the next derivation by hand in <a href="/2025/03/23/nix-derivations-by-hand">ATerm</a>, so there is no recursive Nix and no <code class="language-plaintext highlighter-rouge">nix-instantiate</code> involved. <a href="#fnref:recursive-nix" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:cost">
      <p>A single trivial build takes about 1.5 seconds on my laptop, so the cost of building 51 derivations is about 75 seconds largely due to substituter lookups. If you disable substituters <code class="language-plaintext highlighter-rouge">--option substituters ''</code>, the builds take about 1.3 seconds in total. <a href="#fnref:cost" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[Have you heard about dynamic derivations?]]></summary></entry><entry><title type="html">Worshipping at the altar of Brendan Gregg</title><link href="https://fzakaria.com/2026/11/12/worshipping-at-the-altar-of-brendan-gregg" rel="alternate" type="text/html" title="Worshipping at the altar of Brendan Gregg" /><published>2026-11-12T10:00:00-08:00</published><updated>2026-11-12T10:00:00-08:00</updated><id>https://fzakaria.com/2026/11/12/worshipping-at-the-altar-of-brendan-gregg</id><content type="html" xml:base="https://fzakaria.com/2026/11/12/worshipping-at-the-altar-of-brendan-gregg"><![CDATA[<p>Okay, I am the first to admit that I’m a bit manic with AI. When you are working on a problem that has endless possibilities, it is difficult to constrain yourself to a limited set of features.</p>

<p>Can I just add one more?</p>

<p style="--image-width: 12rem"><a href="/assets/images/rewind_time_hypno_gregg.png"><img src="/assets/images/rewind_time_hypno_gregg.png" alt="Brendan Gregg with black and white spirals for eyes, in front of a giant purple hypnosis spiral" /></a></p>

<p>I have been amazed at all the fun and useful things that a deterministic VM like <a href="https://rewindvm.dev">Rewind</a> enables. I have been using it to help <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">find heisenbugs</a>, to make <a href="/2026/11/07/making-profile-guided-optimization-reproducible">profile-guided optimization reproducible</a>, and to make <a href="/2026/11/09/what-if-every-nix-build-were-bit-reproducible">Nix builds bit-reproducible</a>. But the most fun has been using it to understand performance.</p>

<p>Turns out that performance is yet another area where Rewind shines. I have been using it to analyze the critical path of builds.</p>

<p>What is the critical path?</p>

<p>The critical path is the longest chain of dependent work in a program. It is the minimum time that the program can take to complete, regardless of how many resources you throw at it. The only way to make a program faster is to shorten the critical path.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/a231bbfec4e2b599.svg" alt="Five tasks. A runs first. B, C and D start when A ends and run side by side. E starts when all three have ended. C is the longest, so B and D finish early and wait. The critical path, A then C then E, is highlighted: no number of CPUs makes the run shorter than that chain." width="620" height="160">
</figure>

<p>If you worship at the altar of Brendan Gregg, you know he spent years turning performance analysis from a dark art into a science. This is a small offering to him. 🤲</p>

<p>I added a new <code class="language-plaintext highlighter-rouge">rewind time</code> command to Rewind that analyzes a recording and tells you where the time went and what would make the run finish sooner. You can drill into any part of that answer and see the source lines responsible for it. It’s like <a href="https://www.brendangregg.com/flamegraphs.html">Brendan Gregg’s flame graphs</a> but <del>on steroids</del> for the critical path and with a debugger attached.<sup id="fnref:ideas"><a href="#fn:ideas" class="footnote" rel="footnote" role="doc-noteref">1</a></sup></p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
New to Rewind? Start with <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">a flaky build you only catch once</a> and <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a></p>
</blockquote>

<p>Let’s see how it works by analyzing the critical path of a <a href="https://github.com/libuv/libuv">libuv</a> build and test run. The build and test suite takes 78 seconds inside Rewind, and even with 64 cores it still takes 47 seconds. Why?</p>

<p>The usual answer is to look at a CPU profile, and in this case a CPU profile would be almost useless. For two thirds of those 47 seconds, the work the build is waiting on is not computing at all: it is <em>asleep</em>. 💤💤💤</p>

<h2 id="where-the-time-goes">Where the time goes</h2>

<p>Every <code class="language-plaintext highlighter-rouge">rewind time</code> starts with two numbers:</p>

<div data-mark="3,4" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind <span class="nb">time </span>7a29e716
<span class="go">libuv-1.51.0
    78.0 s  elapsed on the VM's one CPU
    47.4 s  critical path: the least it can take on any number of CPUs
            67% asleep (epoll_pwait 23.1 s, clock_nanosleep 8.53 s, futex 100 ms), 33% computing
</span></code></pre></div></div>

<p>The first is how long the run took on the VM’s one virtual CPU. The second is the <strong>critical path</strong>: the longest chain of work where each step had to wait for the one before.</p>

<p>No number of CPUs makes a run shorter than its critical path, so the gap between the two numbers is all that parallelism can buy you.</p>

<p style="--image-width: 16rem"><a href="/assets/images/rewind_time_drake_meme.png"><img src="/assets/images/rewind_time_drake_meme.png" alt="Drake meme. Drake turns away from &quot;Buy a 64-core build machine&quot; and points approvingly at &quot;Read the critical path first&quot;." /></a></p>

<p>The line under the two numbers applies Gregg’s <a href="https://www.brendangregg.com/tsamethod.html">thread state analysis</a>. Here the biggest state is asleep: 23 seconds in <code class="language-plaintext highlighter-rouge">epoll_pwait</code> and 8.5 in <code class="language-plaintext highlighter-rouge">clock_nanosleep</code>.</p>

<p>A sleeping thread is invisible to a CPU profiler. Gregg’s answer is <a href="https://www.brendangregg.com/offcpuanalysis.html">off-CPU analysis</a>: look at where threads block, not only where they compute.</p>

<p>On a live machine, off-CPU analysis is hard. Linux can trace which thread woke which, and Gregg built <a href="https://www.brendangregg.com/blog/2016-02-01/linux-wakeup-offwake-profiling.html">wakeup and off-wake profiling</a> on top of that, but you have to be tracing before the slow run happens, the tracing has a cost, and most of the sleeps you capture are noise. Rewind already logs every context switch because it needs them to replay, and now it records every wakeup and who caused it too. All that <em>juicy</em> information is in every recording. 🤤</p>

<p>Here is the whole output for libuv:</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind <span class="nb">time </span>7a29e716
<span class="go">libuv-1.51.0
    78.0 s  elapsed on the VM's one CPU
    47.4 s  critical path: the least it can take on any number of CPUs
            67% asleep (epoll_pwait 23.1 s, clock_nanosleep 8.53 s, futex 100 ms), 33% computing

The critical path by phase
    3.54 s  configurePhase  ██
    1.67 s  buildPhase      █
    42.0 s  checkPhase      █████████████████████
     99 ms  5 other phases

The critical path by process
   on path      pid  process, with what it started
    47.4 s       34  init › bash -e source-stdenv.sh default-builder.sh
    41.9 s     4076  ├─ make -j8 SHELL=bash-5.3p3/bin/bash VERBOSE=y check
    36.4 s     4910  │  ├─ make › bash › lt-run-tests
    3.38 s     5412  │  │  ├─ lt-run-tests hrtime hrtime  asleep in clock_nanosleep 3.38 s
    2.00 s     5013  │  │  ├─ lt-run-tests delayed_accept delayed_accept  asleep in epoll_pwait 2.00 s
    1.62 s     5126  │  │  ├─ lt-run-tests fs_event_watch_dir fs_event_watch_dir  asleep in epoll_pwait 1.62 s
    1.60 s     5103  │  │  ├─ lt-run-tests fs_event_close_in_callback fs_event_close_in…  asleep in epoll_pwait 1.60 s
    1.60 s     5508  │  │  ├─ lt-run-tests metrics_idle_time metrics_idle_time  asleep in epoll_pwait 1.00 s, computing 600 ms
    1.24 s     6095  │  │  ├─ lt-run-tests tcp_write_ready tcp_write_ready
    1.14 s     5510  │  │  ├─ lt-run-tests metrics_idle_time_thread metrics_idle_time_t…  asleep in epoll_pwait 1.00 s
    1.10 s     5132  │  │  ├─ lt-run-tests fs_event_watch_file_current_dir fs_event_wat…  asleep in epoll_pwait 1.10 s
    22.6 s           │  │  └─ 279 more
    5.59 s     4077  │  └─ make test/run-tests
    2.22 s     4183  │     ├─ gcc -fPIC -fstack-clash-protection -O2 -U_FORTIFY_SOURCE …
    2.10 s     4189  │     │  └─ cc1 /build/source/test/test-fs.c
    3.35 s           │     └─ 20 more
    1.99 s       68  ├─ sh ./autogen.sh
    1.99 s           │  └─ 9 more
    1.67 s     2642  ├─ make -j8 SHELL=bash-5.3p3/bin/bash
    1.67 s           │  └─ 5 more
    1.53 s      403  └─ bash ./configure --disable-static --disable-dependency-tracking…
    1.47 s              └─ 581 more

What would shorten it
    sooner      pid  if this took no time
    36.1 s           every lt-run-tests, 600 processes
    6.66 s           every cc1, 283 processes
    3.38 s     5412  75 sleeps in clock_nanosleep: lt-run-tests hrtime hrtime
    2.00 s     5013  2 sleeps in epoll_pwait: lt-run-tests delayed_accept delayed_accept
    1.76 s     4189  cc1 /build/source/test/test-fs.c
    1.62 s     5126  30 sleeps in epoll_pwait: lt-run-tests fs_event_watch_dir fs_event_watc…
    1.60 s     5103  16 sleeps in epoll_pwait: lt-run-tests fs_event_close_in_callback fs_ev…
    1.60 s     5508  lt-run-tests metrics_idle_time metrics_idle_time
    1.22 s           every perl, 9 processes
    1.14 s     5510  lt-run-tests metrics_idle_time_thread metrics_idle_time_thread

Look closer
  rewind time 7a29e716 --in PID             one process: its threads, sleeps and waits
  rewind time 7a29e716 --folded             the path for flamegraph.pl or speedscope.app
  rewind time 7a29e716 --perfetto F         every process on a timeline, for ui.perfetto.dev
</span></code></pre></div></div>

<p>The second table is the path as a <strong>tree of processes</strong> based on Gregg’s <a href="https://www.brendangregg.com/ColonyGraphs/execution.html">colony graph</a> idea. Each line is a process with everything it started, and its time on the critical path.<sup id="fnref:ps"><a href="#fn:ps" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></p>

<p>In this build, <code class="language-plaintext highlighter-rouge">make check</code> needs 41.9 of the total 47.4 seconds, and 36.4 of that is <code class="language-plaintext highlighter-rouge">lt-run-tests</code>, libuv’s test runner. The test runner invokes 287 tests each spending 1-3 seconds.</p>

<p>All of those tests are on the path, and the path is a single chain, so the runner ran them one after another. Worse, most of each test is spent asleep, waiting on timers.</p>

<p class="aside">Drag can be less than time on the path.</p>

<p>The last table answers a different question: how much sooner would the run finish if this part took no time? The critical path method calls this <em>drag</em>.</p>

<p>For the truly magical part, we can jump to any part of the path and see what was happening, invoke <code class="language-plaintext highlighter-rouge">gdb</code> and fork the run at that moment. A profiler hands you a stack, sampled at some moment you can never go back to. Every frame in <code class="language-plaintext highlighter-rouge">rewind time</code> is a moment in a recording, and Rewind can replay the run to it.</p>

<p><code class="language-plaintext highlighter-rouge">--in</code> looks inside one process,<sup id="fnref:pid"><a href="#fn:pid" class="footnote" rel="footnote" role="doc-noteref">3</a></sup> so let’s dive into the <code class="language-plaintext highlighter-rouge">hrtime</code> test that spent 3.38 seconds asleep in <code class="language-plaintext highlighter-rouge">clock_nanosleep</code>:</p>

<div data-mark="11" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind <span class="nb">time </span>7a29e716 <span class="nt">--in</span> hrtime
<span class="go">lt-run-tests hrtime hrtime (pid 5412)
    3.38 s  on the critical path with what it started, 7% of the 47.4 s path
            100% asleep (clock_nanosleep 3.38 s), &lt;1% computing

What would shorten it
    sooner      pid  if this took no time
    3.38 s           75 sleeps in clock_nanosleep

Look closer
  rewind where 7a29e716 115894 --pid 5412   the source line the first row's time starts at
  rewind time 7a29e716 --perfetto F         every process on a timeline
</span></code></pre></div></div>

<p>Since this test spent 100% of its time asleep, the step provided on the last line is where it began. <code class="language-plaintext highlighter-rouge">rewind where</code> replays the run to that step and asks gdb where the thread was:</p>

<div data-mark="6" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind where 7a29e716 115894 <span class="nt">--pid</span> 5412
<span class="go">process 5412 (lt-run-tests), thread 5412, at step 115894
</span><span class="gp">#</span>2 uv_sleep <span class="o">(</span>src/unix/core.c:1869<span class="o">)</span>
<span class="go">    1867
    1868    do
</span><span class="gp">&gt;</span><span class="w">   </span>1869      rc <span class="o">=</span> nanosleep<span class="o">(</span>&amp;timeout, &amp;timeout<span class="o">)</span><span class="p">;</span>
<span class="gp">    1870    while (rc == -1 &amp;&amp; errno == EINTR);</span><span class="w">
</span><span class="go">    1871
arguments:
  msec = 45
locals:
  timeout = {tv_sec = 0, tv_nsec = 45000000}
</span><span class="gp">  rc = &lt;optimized out&gt;</span><span class="w">
</span><span class="gp">  __PRETTY_FUNCTION__ = &lt;error: Cannot access memory at address 0x7fb172519ae8&gt;</span><span class="w">
</span><span class="gp">called from #</span>3 run_test_hrtime <span class="o">(</span><span class="nb">test</span>/test-hrtime.c:39<span class="o">)</span>
<span class="gp">called from #</span>4 __libc_start_call_main <span class="o">(</span>../sysdeps/nptl/libc_start_call_main.h:58<span class="o">)</span>
</code></pre></div></div>

<p>🎯 We can see that the test is calling <code class="language-plaintext highlighter-rouge">uv_sleep(45)</code> from line 39 of <code class="language-plaintext highlighter-rouge">test/test-hrtime.c</code>, and that it is sleeping for 45 milliseconds.
It does that 75 times for a total of 3.38 seconds.<sup id="fnref:purpose"><a href="#fn:purpose" class="footnote" rel="footnote" role="doc-noteref">4</a></sup></p>

<p style="--image-width: 22rem"><a href="/assets/images/rewind_time_pigeon_meme.png"><img src="/assets/images/rewind_time_pigeon_meme.png" alt="Is this a pigeon meme: a man labelled &quot;Me&quot; points at a butterfly labelled &quot;75 calls to uv_sleep(45)&quot; and asks &quot;Is this a CPU bottleneck?&quot;" /></a></p>

<p>As the cherry on top: the run is deterministic, so step 115,894 is the same instruction every time you replay it. You can open <code class="language-plaintext highlighter-rouge">rewind gdb</code> at that step and investigate to your heart’s content.</p>

<p>The Rewind app’s <em>Time</em> tab shows the same answers. The path becomes a flame graph, colored the way Gregg colors his <a href="https://www.brendangregg.com/FlameGraphs/offcpuflamegraphs.html">off-CPU flame graphs</a>: computing is warm, asleep is blue, and a process shades from one to the other by how much of its time it slept.</p>

<p style="--image-width: 34rem"><a href="/assets/images/rewind-time-overview.png"><img src="/assets/images/rewind-time-overview-crop.png" alt="The Rewind app's Time tab for libuv: 78.0 s elapsed on the VM's one CPU and a 47.4 s critical path, 67% asleep. Under them the path in order as a bar, the check phase, the path as a flame graph with lt-run-tests' tests in a row, and what would shorten it, with every lt-run-tests at 36.1 s first, each row marked in the color of its frames" /></a></p>

<p>Clicking a frame picks it and moves the playhead there, so the build log, the process tree and the files all show that moment; clicking a process again zooms into it. When you pick a blue frame, the app replays the run to that part’s longest sleep and shows the stack where it slept:</p>

<p style="--image-width: 34rem"><a href="/assets/images/rewind-time-where.png"><img src="/assets/images/rewind-time-where-crop.png" alt="The Time tab zoomed into lt-run-tests, with the hrtime test's sleep picked. The card says asleep in clock_nanosleep 3.38 s, 75 sleeps, the longest 45 ms from step 115,923 on thread 5412, and where its longest sleep was: two frames in libc.so.6, then uv_sleep at src/unix/core.c:1869, nanosleep(&amp;timeout, &amp;timeout), called from run_test_hrtime at test/test-hrtime.c:39, uv_sleep(45)" /></a></p>

<p>Under the stack, <em>Show source</em> opens the source panel at that moment on that thread, and <em>Open gdb here</em> opens gdb in a fork of the run at the sleep:</p>

<p><a href="/assets/images/rewind-time-gdb.png"><img src="/assets/images/rewind-time-gdb-crop.png" alt="gdb in the app's terminal pane at step 115,923, in thread 5412: frame 2 is uv_sleep with msec=45 at src/unix/core.c:1869, print msec gives 45, and up shows run_test_hrtime at test/test-hrtime.c:39, uv_sleep(45)" /></a></p>

<p>If you’d rather use tools you already know, <code class="language-plaintext highlighter-rouge">rewind time</code> can emit the data in their formats: folded stacks for <a href="https://github.com/brendangregg/FlameGraph">flamegraph.pl</a> and <a href="https://www.speedscope.app">speedscope</a>, or a Perfetto trace for <a href="https://ui.perfetto.dev">ui.perfetto.dev</a>.</p>

<p class="aside">The flame graph below is the real flamegraph.pl output: click a frame to zoom in, or <a href="/assets/images/rewind-time-libuv-flamegraph.svg">open it on its own</a>.</p>

<figure>
<object data="/assets/images/rewind-time-libuv-flamegraph.svg" type="image/svg+xml" aria-label="A flame graph of libuv's critical path made by flamegraph.pl from rewind time --folded: checkPhase is most of the width, with lt-run-tests' tests in a row of blue asleep frames, and configurePhase and the test compiles in warm colors at the right" style="display:block;width:100%;aspect-ratio:1200/318">
  <img src="/assets/images/rewind-time-libuv-flamegraph.svg" alt="A flame graph of libuv's critical path made by flamegraph.pl from rewind time --folded: checkPhase is most of the width, with lt-run-tests' tests in a row of blue asleep frames, and configurePhase and the test compiles in warm colors at the right" />
</object>
</figure>

<h2 id="kneeling-at-the-altar">Kneeling at the altar</h2>

<p>Every idea here predates Rewind. Gregg has been drawing off-CPU and wakeup flame graphs for over a decade, and build systems have reported critical path information potentially even longer.<sup id="fnref:bazel"><a href="#fn:bazel" class="footnote" rel="footnote" role="doc-noteref">5</a></sup> I have been inspired by his work since I first dabbled in <a href="https://ebpf.io/">eBPF</a>, back when <a href="https://www.brendangregg.com/flamegraphs.html">flame graphs</a> were new. 🙇</p>

<p>What Rewind adds is the data. <em>Lots of it.</em></p>

<p>Rewind has that data because it can’t replay without it. On a single CPU the only thing that changes from run to run is the scheduler, so every recording already logs every context switch.</p>

<p>This changes the economics of performance analysis. On a live machine, you have to trace before the run, and tracing has a cost. You can only trace a few runs, and you have to pick which ones. Rewind traces every run, so you can analyze any of them later, and do so exactly.</p>

<p>It has just been a <del>manic fever</del> joy to take ideas I have admired for years, point them at a deterministic VM, and watch them work in ways that are hard or impossible on a normal machine.</p>

<p>Please accept <code class="language-plaintext highlighter-rouge">rewind time</code> as my offering at the altar of Brendan Gregg.</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:ideas">
      <p>All the ideas for the command are either inspired by or directly influenced by <a href="https://www.brendangregg.com/">Brendan Gregg’s work</a>. Kneel before Zod! <a href="#fnref:ideas" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:ps">
      <p>A <code class="language-plaintext highlighter-rouge">ps</code> snapshot might miss short-lived process invocations; the recording has every fork, regardless of how brief. <a href="#fnref:ps" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:pid">
      <p>It can take a pid, a program or a word of the command line. <a href="#fnref:pid" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:purpose">
      <p>Turns out that the test sleeps on purpose: it is checking how far <code class="language-plaintext highlighter-rouge">uv_hrtime</code> moves across a sleep. There is nothing to optimize in this case. <a href="#fnref:purpose" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:bazel">
      <p><a href="https://bazel.build/advanced/performance/build-performance-metrics">Bazel’s critical path analysis</a> is a great example of this, and it has been around for years. <a href="#fnref:bazel" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[Okay, I am the first to admit that I’m a bit manic with AI. When you are working on a problem that has endless possibilities, it is difficult to constrain yourself to a limited set of features.]]></summary></entry><entry><title type="html">What if every Nix build were bit-reproducible?</title><link href="https://fzakaria.com/2026/11/09/what-if-every-nix-build-were-bit-reproducible" rel="alternate" type="text/html" title="What if every Nix build were bit-reproducible?" /><published>2026-11-09T10:00:00-08:00</published><updated>2026-11-09T10:00:00-08:00</updated><id>https://fzakaria.com/2026/11/09/what-if-every-nix-build-were-bit-reproducible</id><content type="html" xml:base="https://fzakaria.com/2026/11/09/what-if-every-nix-build-were-bit-reproducible"><![CDATA[<p>The holy grail of build systems and package managers is bit-reproducible<sup id="fnref:bit"><a href="#fn:bit" class="footnote" rel="footnote" role="doc-noteref">1</a></sup> builds. This is such a desired trait that nearly every Linux distribution has a <a href="https://reproducible-builds.org/who/projects/">reproducible builds project</a> to track the progress and validity of their builds.</p>

<p>Why is bit-reproducibility so important? Trust. You can trust that the software you are running has not been tampered with and is the same as what the developers intended if you can verify that when built from source, the output is identical.</p>

<p>Making software bit-reproducible though is hard. There are a lot of ways that can introduce non-determinism into a build: timestamps, random seeds, thread scheduling, and more. Most distributions that have achieved “reproducible builds” have done so for only a subset of their packages, usually those that comprise the core of the ISO or distribution.</p>

<p>Nix’s default model, the <a href="/2025/03/08/demystifying-nix-s-intensional-model">extensional model</a> (input-addressed), famously works around the need for bit-reproducibility by hashing the inputs to a build and using that hash as the store path. This lets the build be repeatable even if the output is not bit-for-bit identical. It is an incredibly pragmatic solution to making builds repeatable, but it does not solve the problem of trust. We are still trusting the outputs uploaded to <a href="https://cache.nixos.org">cache.nixos.org</a> have not been tampered with.</p>

<p>Nix also has an experimental <a href="/2025/03/08/demystifying-nix-s-intensional-model">content-addressed model</a> (intensional model) where the <code class="language-plaintext highlighter-rouge">/nix/store</code> paths are based on the content of the output, but crucially, it does not guarantee that the builds are bit-reproducible.</p>

<p>This leaves us with an undesirable situation regardless of the model. For the extensional model, the smallest change in the inputs changes the store path which causes a cascade of rebuilds. For the intensional model, a single derivation can produce multiple different outputs.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/1baa8f0f3392bf03.svg" alt="Two panels. On the left, the extensional model: a chain of four packages, glibc, zlib, openssl and curl, each depending on the one before. One byte changes in glibc, and the store path under every package in the chain is struck out and replaced with a new one. On the right, the intensional model: one derivation, hello.drv, built from the same inputs, fans out to three outputs with three different store paths, built at three different times." width="680" height="300">
</figure>

<p>What if every build could be bit-reproducible? What would that mean for Nix and the extensional model?</p>

<p>I have been working on <a href="https://rewindvm.dev">Rewind</a>, a deterministic virtual machine. It runs builds in a deterministic environment, which so far has mostly been used to investigate bugs. I have been thinking about what else a platform that runs builds deterministically makes possible.</p>

<p>I started this thought by exploring how to <a href="/2026/11/07/making-profile-guided-optimization-reproducible">make profile-guided optimization reproducible</a> but I was just scratching the surface.</p>

<h2 id="the-machine-is-an-input">The machine is an input</h2>

<p>When we try to make a build bit-reproducible, we usually go hunting for the sources of non-determinism: timestamps, random seeds, thread order. These are inputs the derivation does not account for, so they are not hashed into the store path.</p>

<p>A simpler approach is to run the whole build inside a deterministic machine.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/df9d5f1008967c2e.svg" alt="On the left a die, an alarm clock and a tangle of thread tumble around loose, labelled as what a build implicitly depends on. An arrow leads to the right, where the same three objects sit still inside a parcel of bubble wrap with a shipping label that reads epoch 1790985600, seed 0, schedule 0, to /nix/store. The parcel is labelled making the implicit explicit." width="680" height="300">
</figure>

<p><a href="https://edolstra.github.io/pubs/phd-thesis.pdf">Eelco’s thesis</a> says outright that the extensional model assumes the builder is impure (§5.7).</p>

<blockquote>
  <p>Build operations in general are not pure: the contents that a builder stores in the output path can depend on impure factors such as the system time. […] Thus, while any derivation can have a potentially infinite set of output path contents that can be produced by an execution of its builder, we view the elements of that set as interchangeable.</p>

  <p>But this is a model—an assumption about builders.</p>
</blockquote>

<p>Running a build within <a href="https://rewindvm.dev">Rewind</a> captures all of the implicit inputs to a build and makes them explicit, which makes any build bit-reproducible. 🤯</p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
New to Rewind? Start with <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">a flaky build you only catch once</a> and <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a></p>
</blockquote>

<p>We can wrap any derivation in Rewind with a Nix function. <a href="https://github.com/fzakaria/rewindvm/blob/main/nix/lib.nix"><code class="language-plaintext highlighter-rouge">inRewind</code></a> takes the machine’s inputs and a derivation, and returns the same derivation with its builder running inside Rewind:<sup id="fnref:kvm"><a href="#fn:kvm" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></p>

<div class="language-nix highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span>
  <span class="kn">inherit</span> <span class="p">(</span><span class="nv">rewind</span><span class="o">.</span><span class="nv">lib</span><span class="o">.</span><span class="nv">x86_64-linux</span><span class="p">)</span> <span class="nv">inRewind</span><span class="p">;</span>
  <span class="nv">deterministic</span> <span class="o">=</span> <span class="nv">inRewind</span> <span class="p">{</span>
    <span class="nv">epoch</span> <span class="o">=</span> <span class="mi">1790985600</span><span class="p">;</span>
    <span class="nv">seed</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="nv">schedule</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="p">};</span>
<span class="kn">in</span>
<span class="nv">deterministic</span> <span class="nv">pkgs</span><span class="o">.</span><span class="nv">hello</span>
</code></pre></div></div>

<p>It works on any derivation and the resulting derivation is bit-reproducible every time.<sup id="fnref:guarantee"><a href="#fn:guarantee" class="footnote" rel="footnote" role="doc-noteref">3</a></sup></p>

<p>Let’s look at a simple example of a build that is not bit-reproducible, and how when wrapped in Rewind, it becomes bit-reproducible.</p>

<p>Here is a simple C program that prints a greeting and depends on a library. The derivation adds a build id and a build time to the output similar to what release builds often do to “stamp” their builds. The build id and build time are two common sources of non-determinism in builds.</p>

<div class="language-nix highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span>
  <span class="nv">build</span> <span class="o">=</span>
    <span class="k">if</span> <span class="nv">machine</span> <span class="o">==</span> <span class="s2">"rewind"</span> <span class="k">then</span>
      <span class="nv">inRewind</span> <span class="p">{</span> <span class="nv">epoch</span> <span class="o">=</span> <span class="mi">1790985600</span><span class="p">;</span> <span class="nv">seed</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nv">schedule</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">else</span>
      <span class="p">(</span><span class="nv">drv</span><span class="p">:</span> <span class="nv">drv</span><span class="p">);</span>
  <span class="nv">extra</span> <span class="o">=</span> <span class="nv">lib</span><span class="o">.</span><span class="nv">optionalAttrs</span> <span class="nv">ca</span> <span class="p">{</span> <span class="nv">__contentAddressed</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span> <span class="p">};</span>
<span class="kn">in</span>
<span class="kr">rec</span> <span class="p">{</span>
  <span class="nv">greet</span> <span class="o">=</span> <span class="nv">build</span> <span class="p">(</span>
    <span class="nv">pkgs</span><span class="o">.</span><span class="nv">runCommandCC</span> <span class="s2">"greet"</span> <span class="nv">extra</span> <span class="s2">''</span><span class="err">
</span><span class="s2">      cp </span><span class="si">${</span><span class="sx">./greet.h</span><span class="si">}</span><span class="s2"> greet.h; cp </span><span class="si">${</span><span class="sx">./greet.c</span><span class="si">}</span><span class="s2"> greet.c</span><span class="err">
</span><span class="s2">      mkdir -p $out</span><span class="err">
</span><span class="s2">      cc -c greet.c -o $out/greet.o \</span><span class="err">
</span><span class="s2">        -DBUILD_ID="\"$(cat /proc/sys/kernel/random/uuid)\"" \</span><span class="err">
</span><span class="s2">        -DBUILT_AT="\"$(date -u +%FT%TZ)\""</span><span class="err">
</span><span class="s2">    ''</span>
  <span class="p">);</span>

  <span class="nv">hello</span> <span class="o">=</span> <span class="nv">build</span> <span class="p">(</span>
    <span class="nv">pkgs</span><span class="o">.</span><span class="nv">runCommandCC</span> <span class="s2">"hello"</span> <span class="nv">extra</span> <span class="s2">''</span><span class="err">
</span><span class="s2">      cp </span><span class="si">${</span><span class="sx">./greet.h</span><span class="si">}</span><span class="s2"> greet.h; cp </span><span class="si">${</span><span class="sx">./main.c</span><span class="si">}</span><span class="s2"> main.c</span><span class="err">
</span><span class="s2">      mkdir -p $out/bin</span><span class="err">
</span><span class="s2">      cc main.c </span><span class="si">${</span><span class="nv">greet</span><span class="si">}</span><span class="s2">/greet.o -o $out/bin/hello</span><span class="err">
</span><span class="s2">    ''</span>
  <span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p class="aside">We have wrapped the derivation in a function to control whether the build runs in Rewind or not, and whether the build is content-addressed or not.</p>

<p>Built on the host under the input-addressed model, <code class="language-plaintext highlighter-rouge">greet</code> fails <code class="language-plaintext highlighter-rouge">--check</code>:</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> greet <span class="nt">--arg</span> ca <span class="nb">false</span> <span class="nt">--check</span>
<span class="go">error: derivation '/nix/store/2hm8ram0…-greet.drv' may not be deterministic:
output "/nix/store/kjx5rzjk…-greet" differs
</span></code></pre></div></div>

<p>Built in Rewind, the same derivation passes:</p>

<div data-mark="3,4,8,9,18" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> greet <span class="nt">--arg</span> ca <span class="nb">false</span> <span class="nt">--argstr</span> machine rewind
<span class="go">building '/nix/store/bxh3c25a…-greet.drv'...
inRewind: run c7be39a9ea6be3de exited:0 after 2157 steps
/nix/store/lrx579rx…-greet

</span><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> greet <span class="nt">--arg</span> ca <span class="nb">false</span> <span class="nt">--argstr</span> machine rewind <span class="nt">--check</span>
<span class="go">checking outputs of '/nix/store/bxh3c25a…-greet.drv'...
inRewind: run c7be39a9ea6be3de exited:0 after 2157 steps
/nix/store/lrx579rx…-greet

</span><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> hello <span class="nt">--arg</span> ca <span class="nb">false</span> <span class="nt">--argstr</span> machine rewind
<span class="go">building '/nix/store/1bkqfsg3…-hello.drv'...
inRewind: run 54b543a1c6b65b46 exited:0 after 2439 steps
/nix/store/y8r98q35…-hello

</span><span class="gp">$</span><span class="w"> </span>./result/bin/hello
<span class="go">hello, world
build aabe0f2b-f5d1-477f-b3b8-3e7f1755dc0f at 2026-10-03T00:00:00Z
</span></code></pre></div></div>

<p class="aside">The UUID still comes from the kernel’s random pool and the time still comes from the clock. They are the same on every build because the pool’s seed and the clock’s start are initialized from the same values.</p>

<p>Nice! We just got a build that is bit-reproducible even if it’s not content-addressed.</p>

<p>You can find more details of the library and even making Rewind a Nix <code class="language-plaintext highlighter-rouge">external-builder</code> on <a href="https://rewindvm.dev/nix-builds.html">Rewind’s Nix build reference</a>.</p>

<p>What does that mean for the content-addressed model?</p>

<p>Since the outputs are not bit-reproducible, the same derivation gets a different <code class="language-plaintext highlighter-rouge">/nix/store</code> path on each rebuild.<sup id="fnref:two"><a href="#fn:two" class="footnote" rel="footnote" role="doc-noteref">4</a></sup></p>

<div data-mark="3,7,10,13" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> hello <span class="nt">--arg</span> ca <span class="nb">true</span> <span class="nt">--store</span> ./store-a
<span class="gp">resolved derivation: '/nix/store/5v566cv6…-hello.drv' -&gt;</span><span class="w"> </span><span class="s1">'/nix/store/83qn27rk…-hello.drv'</span>...
<span class="go">/nix/store/rwaisri0…-hello

</span><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> hello <span class="nt">--arg</span> ca <span class="nb">true</span> <span class="nt">--store</span> ./store-b
<span class="gp">resolved derivation: '/nix/store/5v566cv6…-hello.drv' -&gt;</span><span class="w"> </span><span class="s1">'/nix/store/0rjbw8s8…-hello.drv'</span>...
<span class="go">/nix/store/wvy9zby9…-hello

</span><span class="gp">$</span><span class="w"> </span>nix realisation info <span class="nt">-f</span> <span class="nb">.</span> greet <span class="nt">--arg</span> ca <span class="nb">true</span> <span class="nt">--store</span> ./store-a
<span class="gp">rbzv0mbw…-greet.drv^out -&gt;</span><span class="w"> </span>bryxd8dy…-greet
<span class="go">
</span><span class="gp">$</span><span class="w"> </span>nix realisation info <span class="nt">-f</span> <span class="nb">.</span> greet <span class="nt">--arg</span> ca <span class="nb">true</span> <span class="nt">--store</span> ./store-b
<span class="gp">rbzv0mbw…-greet.drv^out -&gt;</span><span class="w"> </span>hh2v12cs…-greet
</code></pre></div></div>

<p>Producing multiple variants is problematic and the thesis notes the consequence (§6.4.1): you can end up with a closure that contains more than one variant of the same derivation.</p>

<blockquote>
  <p>The fact that a derivation can resolve to any number of output paths due to impurity, leads to the problem that we might end up with a closure that contains more than one element from the output equivalence class of a derivation.</p>
</blockquote>

<p>With <code class="language-plaintext highlighter-rouge">inRewind</code>, both stores build the same bytes and print the same path:<sup id="fnref:nix-version"><a href="#fn:nix-version" class="footnote" rel="footnote" role="doc-noteref">5</a></sup></p>

<div data-mark="4,9,12,15" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> hello <span class="nt">--arg</span> ca <span class="nb">true</span> <span class="nt">--argstr</span> machine rewind <span class="nt">--store</span> ./store-a
<span class="go">inRewind: run 4d9de4235038d6d0 exited:0 after 2158 steps
inRewind: run 3a2797f47898d7ce exited:0 after 2438 steps
/nix/store/daqfk0jm…-hello

</span><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> hello <span class="nt">--arg</span> ca <span class="nb">true</span> <span class="nt">--argstr</span> machine rewind <span class="nt">--store</span> ./store-b
<span class="go">inRewind: run 4d9de4235038d6d0 exited:0 after 2158 steps
inRewind: run 3a2797f47898d7ce exited:0 after 2438 steps
/nix/store/daqfk0jm…-hello

</span><span class="gp">$</span><span class="w"> </span>nix realisation info <span class="nt">-f</span> <span class="nb">.</span> greet <span class="nt">--arg</span> ca <span class="nb">true</span> <span class="nt">--argstr</span> machine rewind <span class="nt">--store</span> ./store-a
<span class="gp">q6i384y2…-greet.drv^out -&gt;</span><span class="w"> </span>kvjqc292…-greet
<span class="go">
</span><span class="gp">$</span><span class="w"> </span>nix realisation info <span class="nt">-f</span> <span class="nb">.</span> greet <span class="nt">--arg</span> ca <span class="nb">true</span> <span class="nt">--argstr</span> machine rewind <span class="nt">--store</span> ./store-b
<span class="gp">q6i384y2…-greet.drv^out -&gt;</span><span class="w"> </span>kvjqc292…-greet
</code></pre></div></div>

<p>One derivation, one path, in every store.</p>

<p>Bit-reproducible outputs also mean cache hits across machines. If the bytes are the same, the content address is the same, and a path one machine built is a hit for every other: early cutoff optimization ftw!</p>

<h2 id="both-panels-collapse">Both panels collapse</h2>

<p>When we make every build bit-reproducible, the two models collapse into one. What does this mean for the extensional model?</p>

<p>The extensional model was a wonderful pragmatic solution to a world where determinism was not guaranteed but it came at a cost: a single change in the inputs cascades through every downstream derivation. Adoption to content-addressed derivations has been slow similarly because producing multiple outputs makes it hard to reason about the closure of a derivation. When we have guaranteed bit-reproducibility, both problems disappear.</p>

<p>Having a stable platform with which to build software reproducibly might completely change the toil of working to make software reproducible and change the economics of whether to leverage content-addressed derivations.</p>

<p>The usefulness of a reproducible environment is not well explored and I think there are other interesting use cases for it. One that I’m exploring is to use it to make the act of performing a benchmark reproducible.</p>

<blockquote class="alert alert-note">
  <p><strong>Aside</strong>
The cost is that the machine is now an input, Rewind included. Upgrade Rewind and every wrapped derivation rebuilds. Build on an Intel machine and you get a different, equally reproducible, output than on AMD.</p>
</blockquote>

<p>A tool that was designed for bug investigation and reproducibility of builds might have a larger impact on the software ecosystem than I had originally thought. It is a tool that can be used to make software more trustworthy, and all the wonderful beefits that come with it.</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:bit">
      <p>It’s lame that I have to keep clarifying it as “bit” reproducible but the term is overloaded. <a href="#fnref:bit" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:kvm">
      <p>Rewind is a KVM-based virtual machine, so it requires a host with KVM support. It also requires the <code class="language-plaintext highlighter-rouge">rewind-amd</code> or <code class="language-plaintext highlighter-rouge">rewind-intel</code> system feature to be advertised by the host. <a href="#fnref:kvm" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:guarantee">
      <p>On the same Rewind version and the same CPU vendor. Fixed-output derivations are refused, because they need the network and the VM has none. <a href="#fnref:guarantee" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:two">
      <p>Two stores are used to illustrate buids on different machines. <a href="#fnref:two" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:nix-version">
      <p>Nix 2.35 changed how it hashes an output that mentions its own path, so the content address of such an output depends on the Nix version. <a href="#fnref:nix-version" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[The holy grail of build systems and package managers is bit-reproducible1 builds. This is such a desired trait that nearly every Linux distribution has a reproducible builds project to track the progress and validity of their builds. Why is bit-reproducibility so important? Trust. You can trust that the software you are running has not been tampered with and is the same as what the developers intended if you can verify that when built from source, the output is identical. Making software bit-reproducible though is hard. There are a lot of ways that can introduce non-determinism into a build: timestamps, random seeds, thread scheduling, and more. Most distributions that have achieved “reproducible builds” have done so for only a subset of their packages, usually those that comprise the core of the ISO or distribution. Nix’s default model, the extensional model (input-addressed), famously works around the need for bit-reproducibility by hashing the inputs to a build and using that hash as the store path. This lets the build be repeatable even if the output is not bit-for-bit identical. It is an incredibly pragmatic solution to making builds repeatable, but it does not solve the problem of trust. We are still trusting the outputs uploaded to cache.nixos.org have not been tampered with. Nix also has an experimental content-addressed model (intensional model) where the /nix/store paths are based on the content of the output, but crucially, it does not guarantee that the builds are bit-reproducible. This leaves us with an undesirable situation regardless of the model. For the extensional model, the smallest change in the inputs changes the store path which causes a cascade of rebuilds. For the intensional model, a single derivation can produce multiple different outputs. Extensional model input-addressed one byte changes glibc zlib openssl curl x7mq2v… 9kd0zl… p3vn8a… c1rw5y… ba4ks1… h0wq7f… 6jtm9d… rz2pl8… rebuilt rebuilt rebuilt rebuilt One input changes, every path downstream changes Intensional model content-addressed same inputs hello.drv /nix/store/q7xm… built Mon 14:02 /nix/store/d04c… built Tue 09:48 /nix/store/9f2k… built Wed 17:31 One derivation, many different outputs What if every build could be bit-reproducible? What would that mean for Nix and the extensional model? I have been working on Rewind, a deterministic virtual machine. It runs builds in a deterministic environment, which so far has mostly been used to investigate bugs. I have been thinking about what else a platform that runs builds deterministically makes possible. I started this thought by exploring how to make profile-guided optimization reproducible but I was just scratching the surface. The machine is an input When we try to make a build bit-reproducible, we usually go hunting for the sources of non-determinism: timestamps, random seeds, thread order. These are inputs the derivation does not account for, so they are not hashed into the store path. A simpler approach is to run the whole build inside a deterministic machine. What a build implicitly depends on inRewind epoch 1790985600 seed 0 schedule 0 TO: /nix/store Making the implicit explicit Eelco’s thesis says outright that the extensional model assumes the builder is impure (§5.7). Build operations in general are not pure: the contents that a builder stores in the output path can depend on impure factors such as the system time. […] Thus, while any derivation can have a potentially infinite set of output path contents that can be produced by an execution of its builder, we view the elements of that set as interchangeable. But this is a model—an assumption about builders. Running a build within Rewind captures all of the implicit inputs to a build and makes them explicit, which makes any build bit-reproducible. 🤯 Aside: New to Rewind? Start with a flaky build you only catch once and dafuq is a deterministic VM? We can wrap any derivation in Rewind with a Nix function. inRewind takes the machine’s inputs and a derivation, and returns the same derivation with its builder running inside Rewind:2 let inherit (rewind.lib.x86_64-linux) inRewind; deterministic = inRewind { epoch = 1790985600; seed = 0; schedule = 0; }; in deterministic pkgs.hello It works on any derivation and the resulting derivation is bit-reproducible every time.3 Let’s look at a simple example of a build that is not bit-reproducible, and how when wrapped in Rewind, it becomes bit-reproducible. Here is a simple C program that prints a greeting and depends on a library. The derivation adds a build id and a build time to the output similar to what release builds often do to “stamp” their builds. The build id and build time are two common sources of non-determinism in builds. let build = if machine == "rewind" then inRewind { epoch = 1790985600; seed = 0; schedule = 0; } else (drv: drv); extra = lib.optionalAttrs ca { __contentAddressed = true; }; in rec { greet = build ( pkgs.runCommandCC "greet" extra '' cp ${./greet.h} greet.h; cp ${./greet.c} greet.c mkdir -p $out cc -c greet.c -o $out/greet.o \ -DBUILD_ID="\"$(cat /proc/sys/kernel/random/uuid)\"" \ -DBUILT_AT="\"$(date -u +%FT%TZ)\"" '' ); hello = build ( pkgs.runCommandCC "hello" extra '' cp ${./greet.h} greet.h; cp ${./main.c} main.c mkdir -p $out/bin cc main.c ${greet}/greet.o -o $out/bin/hello '' ); } We have wrapped the derivation in a function to control whether the build runs in Rewind or not, and whether the build is content-addressed or not. Built on the host under the input-addressed model, greet fails --check: $ nix-build -A greet --arg ca false --check error: derivation '/nix/store/2hm8ram0…-greet.drv' may not be deterministic: output "/nix/store/kjx5rzjk…-greet" differs Built in Rewind, the same derivation passes: $ nix-build -A greet --arg ca false --argstr machine rewind building '/nix/store/bxh3c25a…-greet.drv'... inRewind: run c7be39a9ea6be3de exited:0 after 2157 steps /nix/store/lrx579rx…-greet $ nix-build -A greet --arg ca false --argstr machine rewind --check checking outputs of '/nix/store/bxh3c25a…-greet.drv'... inRewind: run c7be39a9ea6be3de exited:0 after 2157 steps /nix/store/lrx579rx…-greet $ nix-build -A hello --arg ca false --argstr machine rewind building '/nix/store/1bkqfsg3…-hello.drv'... inRewind: run 54b543a1c6b65b46 exited:0 after 2439 steps /nix/store/y8r98q35…-hello $ ./result/bin/hello hello, world build aabe0f2b-f5d1-477f-b3b8-3e7f1755dc0f at 2026-10-03T00:00:00Z The UUID still comes from the kernel’s random pool and the time still comes from the clock. They are the same on every build because the pool’s seed and the clock’s start are initialized from the same values. Nice! We just got a build that is bit-reproducible even if it’s not content-addressed. You can find more details of the library and even making Rewind a Nix external-builder on Rewind’s Nix build reference. What does that mean for the content-addressed model? Since the outputs are not bit-reproducible, the same derivation gets a different /nix/store path on each rebuild.4 $ nix-build -A hello --arg ca true --store ./store-a resolved derivation: '/nix/store/5v566cv6…-hello.drv' -&gt; '/nix/store/83qn27rk…-hello.drv'... /nix/store/rwaisri0…-hello $ nix-build -A hello --arg ca true --store ./store-b resolved derivation: '/nix/store/5v566cv6…-hello.drv' -&gt; '/nix/store/0rjbw8s8…-hello.drv'... /nix/store/wvy9zby9…-hello $ nix realisation info -f . greet --arg ca true --store ./store-a rbzv0mbw…-greet.drv^out -&gt; bryxd8dy…-greet $ nix realisation info -f . greet --arg ca true --store ./store-b rbzv0mbw…-greet.drv^out -&gt; hh2v12cs…-greet Producing multiple variants is problematic and the thesis notes the consequence (§6.4.1): you can end up with a closure that contains more than one variant of the same derivation. The fact that a derivation can resolve to any number of output paths due to impurity, leads to the problem that we might end up with a closure that contains more than one element from the output equivalence class of a derivation. With inRewind, both stores build the same bytes and print the same path:5 $ nix-build -A hello --arg ca true --argstr machine rewind --store ./store-a inRewind: run 4d9de4235038d6d0 exited:0 after 2158 steps inRewind: run 3a2797f47898d7ce exited:0 after 2438 steps /nix/store/daqfk0jm…-hello $ nix-build -A hello --arg ca true --argstr machine rewind --store ./store-b inRewind: run 4d9de4235038d6d0 exited:0 after 2158 steps inRewind: run 3a2797f47898d7ce exited:0 after 2438 steps /nix/store/daqfk0jm…-hello $ nix realisation info -f . greet --arg ca true --argstr machine rewind --store ./store-a q6i384y2…-greet.drv^out -&gt; kvjqc292…-greet $ nix realisation info -f . greet --arg ca true --argstr machine rewind --store ./store-b q6i384y2…-greet.drv^out -&gt; kvjqc292…-greet One derivation, one path, in every store. Bit-reproducible outputs also mean cache hits across machines. If the bytes are the same, the content address is the same, and a path one machine built is a hit for every other: early cutoff optimization ftw! Both panels collapse When we make every build bit-reproducible, the two models collapse into one. What does this mean for the extensional model? The extensional model was a wonderful pragmatic solution to a world where determinism was not guaranteed but it came at a cost: a single change in the inputs cascades through every downstream derivation. Adoption to content-addressed derivations has been slow similarly because producing multiple outputs makes it hard to reason about the closure of a derivation. When we have guaranteed bit-reproducibility, both problems disappear. Having a stable platform with which to build software reproducibly might completely change the toil of working to make software reproducible and change the economics of whether to leverage content-addressed derivations. The usefulness of a reproducible environment is not well explored and I think there are other interesting use cases for it. One that I’m exploring is to use it to make the act of performing a benchmark reproducible. Aside The cost is that the machine is now an input, Rewind included. Upgrade Rewind and every wrapped derivation rebuilds. Build on an Intel machine and you get a different, equally reproducible, output than on AMD. A tool that was designed for bug investigation and reproducibility of builds might have a larger impact on the software ecosystem than I had originally thought. It is a tool that can be used to make software more trustworthy, and all the wonderful beefits that come with it. It’s lame that I have to keep clarifying it as “bit” reproducible but the term is overloaded. &#8617; Rewind is a KVM-based virtual machine, so it requires a host with KVM support. It also requires the rewind-amd or rewind-intel system feature to be advertised by the host. &#8617; On the same Rewind version and the same CPU vendor. Fixed-output derivations are refused, because they need the network and the VM has none. &#8617; Two stores are used to illustrate buids on different machines. &#8617; Nix 2.35 changed how it hashes an output that mentions its own path, so the content address of such an output depends on the Nix version. &#8617;]]></summary></entry><entry><title type="html">Making profile-guided optimization reproducible</title><link href="https://fzakaria.com/2026/11/07/making-profile-guided-optimization-reproducible" rel="alternate" type="text/html" title="Making profile-guided optimization reproducible" /><published>2026-11-07T10:00:00-08:00</published><updated>2026-11-07T10:00:00-08:00</updated><id>https://fzakaria.com/2026/11/07/making-profile-guided-optimization-reproducible</id><content type="html" xml:base="https://fzakaria.com/2026/11/07/making-profile-guided-optimization-reproducible"><![CDATA[<p>Profile-guided optimization (PGO) is an easy way to speed up a program, especially if the workload is somewhat stable. In <a href="/2026/05/23/leaving-performance-on-the-table">leaving performance on the table</a>, I built a profile-guided sqlite3 variant for a 1.32x speedup for our <code class="language-plaintext highlighter-rouge">SELECT</code> workloads.</p>

<p>Compilers and interpreters make excellent candidates for PGO, since the training workload looks like the real one: compiling code is compiling code. They also benefit the most from it, since they underpin so many other programs; a small speedup in the compiler or interpreter can have a large effect on the overall system performance.</p>

<p>Despite their benefits, PGO is not widely used in package-managers. For instance, Python and GCC both support profile-guided builds but are explicitly disabled in Nixpkgs (<a href="https://github.com/NixOS/nixpkgs/blob/0ec91f273c5f2edc3ed4e390acdbb18105e285d1/pkgs/development/interpreters/python/cpython/default.nix#L79-L122">Python</a>, <a href="https://github.com/NixOS/nixpkgs/blob/0ec91f273c5f2edc3ed4e390acdbb18105e285d1/pkgs/development/compilers/gcc/default.nix#L204-L206">GCC</a>), and Guix (<a href="https://codeberg.org/guix/guix/src/commit/866708b91c7385e1a49470e31075681fe9d72d20/gnu/packages/python.scm#L974-L977">Python</a>).</p>

<blockquote class="alert alert-note">
  <p><strong>Aside</strong>
Nix and Guix both do not need reproducible builds to stay consistent. Their store paths are input-addressed, meaning the path is derived from the inputs only. They can produce outputs with different bytes claiming the same path, and whichever one reaches the binary cache first is the one everybody downloads.</p>
</blockquote>

<p style="--image-width: 18rem"><a href="/assets/images/rewind_pgo_buttons_meme.png"><img src="/assets/images/rewind_pgo_buttons_meme.png" alt="Two buttons meme: a hand hovers between a button labelled &quot;Fast Python&quot; and one labelled &quot;Reproducible Python&quot;, and a sweating man below is labelled &quot;nixpkgs&quot;" /></a></p>

<p>Why are they disabled? Reproducibility!</p>

<p>Many package managers have reproducible builds as a <u>goal</u>, and <strong>PGO is not reproducible</strong>.</p>

<blockquote>
  <p>When compiling from the same source on independent infrastructure yields bit-by-bit identical results, this gives confidence that the build infrastructure was not compromised and the artifact really does correspond to the source.</p>

  <p>– <a href="https://reproducible.nixos.org/">reproducible.nixos.org</a></p>
</blockquote>

<p>To build a profile-guided program, the compiler first builds it with instrumentation. Running that build on a training workload collects profile data, which is the “profile-guided” part. The compiler then uses the profile to optimize the program in a second build.<sup id="fnref:optimize"><a href="#fn:optimize" class="footnote" rel="footnote" role="doc-noteref">1</a></sup> The problem is that the training run is not reproducible,<sup id="fnref:world"><a href="#fn:world" class="footnote" rel="footnote" role="doc-noteref">2</a></sup> so the profile can differ between builds, and with it the optimized binary.</p>

<p>We want profile-guided builds though, because it is such an easy way to speed up a program. Can we make PGO reproducible so that we can have our cake and eat it too?</p>

<p>I have been building <a href="https://rewindvm.dev">Rewind</a>, a deterministic virtual machine. A program’s execution becomes a pure function of its inputs. I have primarily been using it to investigate and find bugs<sup id="fnref:leaderboard"><a href="#fn:leaderboard" class="footnote" rel="footnote" role="doc-noteref">3</a></sup> or as a way to <a href="/2026/10/23/who-wrote-this-byte">make builds bit-reproducible</a>. It occurred to me that the same properties that make Rewind useful for debugging and reproducible builds can also make PGO reproducible.</p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
New to Rewind? Start with <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">a flaky build you only catch once</a> and <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a></p>
</blockquote>

<p>Here is a program whose profile depends on the order in which its threads run. It hands 100,000 jobs to two workers: one worker always runs <code class="language-plaintext highlighter-rouge">checksum</code> and the other always runs <code class="language-plaintext highlighter-rouge">compress</code>, so how often each function runs depends on which worker takes each job. That depends on the thread schedule, which is non-deterministic, so the profile is non-deterministic too.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">static</span> <span class="kt">void</span> <span class="o">*</span><span class="nf">worker</span><span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span>
<span class="p">{</span>
	<span class="kt">long</span> <span class="n">id</span> <span class="o">=</span> <span class="p">(</span><span class="kt">long</span><span class="p">)</span><span class="n">arg</span><span class="p">,</span> <span class="n">acc</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">job</span><span class="p">;</span> <span class="p">(</span><span class="n">job</span> <span class="o">=</span> <span class="n">take</span><span class="p">())</span> <span class="o">!=</span> <span class="n">DONE</span><span class="p">;)</span> <span class="p">{</span>
		<span class="cm">/* The seed picks which worker checksums and which compresses. */</span>
		<span class="k">if</span> <span class="p">((</span><span class="n">id</span> <span class="o">^</span> <span class="n">seed</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
			<span class="n">acc</span> <span class="o">+=</span> <span class="n">checksum</span><span class="p">(</span><span class="n">job</span> <span class="o">^</span> <span class="n">seed</span><span class="p">);</span>
		<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
			<span class="n">acc</span> <span class="o">+=</span> <span class="n">compress</span><span class="p">((</span><span class="n">job</span> <span class="o">^</span> <span class="n">seed</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mh">0xffff</span><span class="p">);</span>
		<span class="p">}</span>
	<span class="p">}</span>
	<span class="k">return</span> <span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="n">acc</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<details>
  <summary>shuffle.c</summary>
  <div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/* main() hands jobs to two workers through a small queue. Which worker
 * takes a job decides which code path runs, so the profile depends on
 * the schedule. */</span>
<span class="cp">#include</span> <span class="cpf">&lt;pthread.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;sys/random.h&gt;</span><span class="cp">
</span>
<span class="cp">#define JOBS 100000
#define SLOTS 8
#define DONE -1
</span>
<span class="k">static</span> <span class="n">pthread_mutex_t</span> <span class="n">lock</span> <span class="o">=</span> <span class="n">PTHREAD_MUTEX_INITIALIZER</span><span class="p">;</span>
<span class="k">static</span> <span class="n">pthread_cond_t</span> <span class="n">not_empty</span> <span class="o">=</span> <span class="n">PTHREAD_COND_INITIALIZER</span><span class="p">;</span>
<span class="k">static</span> <span class="n">pthread_cond_t</span> <span class="n">not_full</span> <span class="o">=</span> <span class="n">PTHREAD_COND_INITIALIZER</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">int</span> <span class="n">queue</span><span class="p">[</span><span class="n">SLOTS</span><span class="p">],</span> <span class="n">head</span><span class="p">,</span> <span class="n">count</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">unsigned</span> <span class="n">seed</span><span class="p">;</span>

<span class="n">__attribute__</span><span class="p">((</span><span class="n">noinline</span><span class="p">))</span> <span class="k">static</span> <span class="kt">long</span> <span class="nf">checksum</span><span class="p">(</span><span class="kt">long</span> <span class="n">x</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">64</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">*</span> <span class="mi">6364136223846793005L</span> <span class="o">+</span> <span class="mi">1442695040888963407L</span><span class="p">;</span>
	<span class="p">}</span>
	<span class="k">return</span> <span class="n">x</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">__attribute__</span><span class="p">((</span><span class="n">noinline</span><span class="p">))</span> <span class="k">static</span> <span class="kt">long</span> <span class="nf">compress</span><span class="p">(</span><span class="kt">long</span> <span class="n">x</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">while</span> <span class="p">(</span><span class="n">x</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">x</span> <span class="o">=</span> <span class="p">(</span><span class="n">x</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="o">?</span> <span class="mi">3</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span> <span class="o">:</span> <span class="n">x</span> <span class="o">/</span> <span class="mi">2</span><span class="p">;</span>
	<span class="p">}</span>
	<span class="k">return</span> <span class="n">x</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="nf">put</span><span class="p">(</span><span class="kt">int</span> <span class="n">job</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">pthread_mutex_lock</span><span class="p">(</span><span class="o">&amp;</span><span class="n">lock</span><span class="p">);</span>
	<span class="k">while</span> <span class="p">(</span><span class="n">count</span> <span class="o">==</span> <span class="n">SLOTS</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">pthread_cond_wait</span><span class="p">(</span><span class="o">&amp;</span><span class="n">not_full</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">lock</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="n">queue</span><span class="p">[(</span><span class="n">head</span> <span class="o">+</span> <span class="n">count</span><span class="o">++</span><span class="p">)</span> <span class="o">%</span> <span class="n">SLOTS</span><span class="p">]</span> <span class="o">=</span> <span class="n">job</span><span class="p">;</span>
	<span class="n">pthread_cond_signal</span><span class="p">(</span><span class="o">&amp;</span><span class="n">not_empty</span><span class="p">);</span>
	<span class="n">pthread_mutex_unlock</span><span class="p">(</span><span class="o">&amp;</span><span class="n">lock</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span> <span class="nf">take</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">pthread_mutex_lock</span><span class="p">(</span><span class="o">&amp;</span><span class="n">lock</span><span class="p">);</span>
	<span class="k">while</span> <span class="p">(</span><span class="n">count</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">pthread_cond_wait</span><span class="p">(</span><span class="o">&amp;</span><span class="n">not_empty</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">lock</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="kt">int</span> <span class="n">job</span> <span class="o">=</span> <span class="n">queue</span><span class="p">[</span><span class="n">head</span><span class="p">];</span>
	<span class="n">head</span> <span class="o">=</span> <span class="p">(</span><span class="n">head</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">%</span> <span class="n">SLOTS</span><span class="p">;</span>
	<span class="n">count</span><span class="o">--</span><span class="p">;</span>
	<span class="n">pthread_cond_signal</span><span class="p">(</span><span class="o">&amp;</span><span class="n">not_full</span><span class="p">);</span>
	<span class="n">pthread_mutex_unlock</span><span class="p">(</span><span class="o">&amp;</span><span class="n">lock</span><span class="p">);</span>
	<span class="k">return</span> <span class="n">job</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="o">*</span><span class="nf">worker</span><span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span>
<span class="p">{</span>
	<span class="kt">long</span> <span class="n">id</span> <span class="o">=</span> <span class="p">(</span><span class="kt">long</span><span class="p">)</span><span class="n">arg</span><span class="p">,</span> <span class="n">acc</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">job</span><span class="p">;</span> <span class="p">(</span><span class="n">job</span> <span class="o">=</span> <span class="n">take</span><span class="p">())</span> <span class="o">!=</span> <span class="n">DONE</span><span class="p">;)</span> <span class="p">{</span>
		<span class="cm">/* The seed picks which worker checksums and which compresses. */</span>
		<span class="k">if</span> <span class="p">((</span><span class="n">id</span> <span class="o">^</span> <span class="n">seed</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
			<span class="n">acc</span> <span class="o">+=</span> <span class="n">checksum</span><span class="p">(</span><span class="n">job</span> <span class="o">^</span> <span class="n">seed</span><span class="p">);</span>
		<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
			<span class="n">acc</span> <span class="o">+=</span> <span class="n">compress</span><span class="p">((</span><span class="n">job</span> <span class="o">^</span> <span class="n">seed</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mh">0xffff</span><span class="p">);</span>
		<span class="p">}</span>
	<span class="p">}</span>
	<span class="k">return</span> <span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="n">acc</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">pthread_t</span> <span class="n">t</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span>

	<span class="n">getrandom</span><span class="p">(</span><span class="o">&amp;</span><span class="n">seed</span><span class="p">,</span> <span class="k">sizeof</span> <span class="n">seed</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">long</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">pthread_create</span><span class="p">(</span><span class="o">&amp;</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="nb">NULL</span><span class="p">,</span> <span class="n">worker</span><span class="p">,</span> <span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="n">i</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">job</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">job</span> <span class="o">&lt;</span> <span class="n">JOBS</span><span class="p">;</span> <span class="n">job</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">put</span><span class="p">(</span><span class="n">job</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">put</span><span class="p">(</span><span class="n">DONE</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">2</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">pthread_join</span><span class="p">(</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="nb">NULL</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="n">puts</span><span class="p">(</span><span class="s">"done"</span><span class="p">);</span>
	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>  </div>
</details>

<p>A typical Nix derivation does all three PGO steps in its <code class="language-plaintext highlighter-rouge">buildPhase</code>, and keeps the profile in <code class="language-plaintext highlighter-rouge">$out</code> so we can inspect it:</p>

<div class="language-nix highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
  <span class="nv">pkgs</span> <span class="o">?</span> <span class="kr">import</span> <span class="o">&lt;</span><span class="nv">nixpkgs</span><span class="o">&gt;</span> <span class="p">{</span> <span class="p">},</span>
<span class="p">}:</span>
<span class="nv">pkgs</span><span class="o">.</span><span class="nv">stdenv</span><span class="o">.</span><span class="nv">mkDerivation</span> <span class="p">{</span>
  <span class="nv">name</span> <span class="o">=</span> <span class="s2">"shuffle-pgo"</span><span class="p">;</span>
  <span class="nv">src</span> <span class="o">=</span> <span class="sx">./shuffle.c</span><span class="p">;</span>
  <span class="nv">dontUnpack</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>

  <span class="nv">buildPhase</span> <span class="o">=</span> <span class="s2">''</span><span class="err">
</span><span class="s2">    cp $src shuffle.c</span><span class="err">

</span><span class="s2">    # 1. Build with instrumentation.</span><span class="err">
</span><span class="s2">    cc -O2 -pthread -fprofile-generate -c shuffle.c -o shuffle.o</span><span class="err">
</span><span class="s2">    cc -pthread -fprofile-generate shuffle.o -o shuffle</span><span class="err">

</span><span class="s2">    # 2. Train: the run writes its counters to shuffle.gcda.</span><span class="err">
</span><span class="s2">    ./shuffle</span><span class="err">

</span><span class="s2">    # 3. Rebuild using the counters.</span><span class="err">
</span><span class="s2">    cc -O2 -pthread -fprofile-use -c shuffle.c -o shuffle.o</span><span class="err">
</span><span class="s2">    cc -pthread shuffle.o -o shuffle</span><span class="err">
</span><span class="s2">  ''</span><span class="p">;</span>

  <span class="nv">installPhase</span> <span class="o">=</span> <span class="s2">''</span><span class="err">
</span><span class="s2">    install -Dm755 shuffle $out/bin/shuffle</span><span class="err">
</span><span class="s2">    install -Dm644 shuffle.gcda $out/share/shuffle.gcda</span><span class="err">
</span><span class="s2">  ''</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Build it, then ask Nix to build it again and compare:</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-build
<span class="go">/nix/store/3ynxjxlc05afxwk675ysdbvi7vp4vpqm-shuffle-pgo

</span><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">--check</span> <span class="nt">-K</span>
<span class="go">error: derivation '/nix/store/f4522l48yf8wdd488yg4p604xqx1i2z3-shuffle-pgo.drv' may not be deterministic: output "/nix/store/3ynxjxlc05afxwk675ysdbvi7vp4vpqm-shuffle-pgo" differs from "/nix/store/3ynxjxlc05afxwk675ysdbvi7vp4vpqm-shuffle-pgo.check"
</span></code></pre></div></div>

<p>Rebuilding the derivation multiple times and reading the profile shows that the counts are different every time.</p>

<table>
  <thead>
    <tr>
      <th>build</th>
      <th style="text-align: right"><code class="language-plaintext highlighter-rouge">checksum</code> calls</th>
      <th style="text-align: right"><code class="language-plaintext highlighter-rouge">compress</code> calls</th>
      <th>ran first</th>
      <th>binary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>original</td>
      <td style="text-align: right">55,163</td>
      <td style="text-align: right">44,837</td>
      <td><code class="language-plaintext highlighter-rouge">compress</code></td>
      <td><code class="language-plaintext highlighter-rouge">ba528bca18f5</code></td>
    </tr>
    <tr>
      <td>check 1</td>
      <td style="text-align: right">57,725</td>
      <td style="text-align: right">42,275</td>
      <td><code class="language-plaintext highlighter-rouge">checksum</code></td>
      <td><code class="language-plaintext highlighter-rouge">2bb3ff5e19d2</code></td>
    </tr>
    <tr>
      <td>check 2</td>
      <td style="text-align: right">57,066</td>
      <td style="text-align: right">42,934</td>
      <td><code class="language-plaintext highlighter-rouge">compress</code></td>
      <td><code class="language-plaintext highlighter-rouge">ba528bca18f5</code></td>
    </tr>
    <tr>
      <td>check 3</td>
      <td style="text-align: right">57,443</td>
      <td style="text-align: right">42,557</td>
      <td><code class="language-plaintext highlighter-rouge">compress</code></td>
      <td><code class="language-plaintext highlighter-rouge">ba528bca18f5</code></td>
    </tr>
    <tr>
      <td>check 4</td>
      <td style="text-align: right">58,522</td>
      <td style="text-align: right">41,478</td>
      <td><code class="language-plaintext highlighter-rouge">checksum</code></td>
      <td><code class="language-plaintext highlighter-rouge">2bb3ff5e19d2</code></td>
    </tr>
    <tr>
      <td>check 5</td>
      <td style="text-align: right">58,486</td>
      <td style="text-align: right">41,514</td>
      <td><code class="language-plaintext highlighter-rouge">checksum</code></td>
      <td><code class="language-plaintext highlighter-rouge">2bb3ff5e19d2</code></td>
    </tr>
    <tr>
      <td>check 6</td>
      <td style="text-align: right">57,799</td>
      <td style="text-align: right">42,201</td>
      <td><code class="language-plaintext highlighter-rouge">checksum</code></td>
      <td><code class="language-plaintext highlighter-rouge">2bb3ff5e19d2</code></td>
    </tr>
  </tbody>
</table>

<blockquote class="alert alert-note">
  <p><strong>Aside</strong>
Interestingly, only two binaries are produced (<code class="language-plaintext highlighter-rouge">ba528bca18f5</code> and <code class="language-plaintext highlighter-rouge">2bb3ff5e19d2</code>), but the profile is different every time. <code class="language-plaintext highlighter-rouge">-fprofile-use</code> turns on <code class="language-plaintext highlighter-rouge">-fprofile-reorder-functions</code>, which lays functions out in order of first use. We could disable that and get the same binary every time for this toy, but the counts still change, and in a real program they decide inlining and block layout.</p>
</blockquote>

<p>Inside Rewind the run is fixed by its boot clock, seed and thread schedule, so the same inputs give the same profile. To use Rewind, we split the derivation into three separate derivations: one for the instrumented build, one for the training run, and one for the final build. Compiling is already deterministic, so the two compiles remai ordinary derivations. Only the training run in the middle needs a deterministic machine, and that one runs inside Rewind.n</p>

<figure class="graphviz"><img src="https://fzakaria.com/assets/figures/ba61c035b9d2c642.svg" alt="Figure" width="743" height="167">
</figure>

<p>The one part of the deterministic VM the model does not fix is the vendor. Intel and AMD differ in ways that cannot be hidden from the guest, so they are exposed to the program and <em>could</em> change the program execution and therefore the profile. That means the training run must be pinned to a vendor, and the derivation must require that vendor.<sup id="fnref:check"><a href="#fn:check" class="footnote" rel="footnote" role="doc-noteref">4</a></sup></p>

<div class="language-nix highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
  <span class="nv">pkgs</span> <span class="o">?</span> <span class="kr">import</span> <span class="o">&lt;</span><span class="nv">nixpkgs</span><span class="o">&gt;</span> <span class="p">{</span> <span class="p">},</span>
  <span class="nv">rewind</span> <span class="o">?</span>
    <span class="p">(</span><span class="kr">builtins</span><span class="o">.</span><span class="nv">getFlake</span> <span class="s2">"github:fzakaria/rewindvm/v0.12.0"</span><span class="p">)</span>
    <span class="o">.</span><span class="nv">packages</span><span class="o">.</span><span class="p">${</span><span class="nv">pkgs</span><span class="o">.</span><span class="nv">stdenv</span><span class="o">.</span><span class="nv">hostPlatform</span><span class="o">.</span><span class="nv">system</span><span class="p">}</span><span class="o">.</span><span class="nv">default</span><span class="p">,</span>
  <span class="c"># The CPU vendor to train on. Rewind's fixed CPU model keeps the host's</span>
  <span class="c"># vendor, so each vendor trains its own profile.</span>
  <span class="nv">vendor</span> <span class="o">?</span> <span class="s2">"amd"</span><span class="p">,</span>
<span class="p">}:</span>
<span class="kd">let</span>
  <span class="c"># What /proc/cpuinfo calls each vendor.</span>
  <span class="nv">vendorIds</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nv">amd</span> <span class="o">=</span> <span class="s2">"AuthenticAMD"</span><span class="p">;</span>
    <span class="nv">intel</span> <span class="o">=</span> <span class="s2">"GenuineIntel"</span><span class="p">;</span>
  <span class="p">};</span>

  <span class="c"># The training run's inputs: the VM's clock at boot, the seed for its</span>
  <span class="c"># randomness, the thread schedule, and what moves its clock.</span>
  <span class="nv">epoch</span> <span class="o">=</span> <span class="s2">"1790985600"</span><span class="p">;</span>
  <span class="nv">seed</span> <span class="o">=</span> <span class="s2">"0"</span><span class="p">;</span>
  <span class="nv">schedule</span> <span class="o">=</span> <span class="s2">"1"</span><span class="p">;</span>
  <span class="nv">clock</span> <span class="o">=</span> <span class="s2">"branches"</span><span class="p">;</span>

  <span class="c"># a. The program built with instrumentation, natively.</span>
  <span class="nv">instrumented</span> <span class="o">=</span> <span class="nv">pkgs</span><span class="o">.</span><span class="nv">runCommandCC</span> <span class="s2">"shuffle-instrumented"</span> <span class="p">{</span> <span class="p">}</span> <span class="s2">''</span><span class="err">
</span><span class="s2">    cp </span><span class="si">${</span><span class="sx">./shuffle.c</span><span class="si">}</span><span class="s2"> shuffle.c</span><span class="err">
</span><span class="s2">    cc -O2 -pthread -fprofile-generate -c shuffle.c -o shuffle.o</span><span class="err">
</span><span class="s2">    mkdir -p $out/bin</span><span class="err">
</span><span class="s2">    cc -pthread -fprofile-generate shuffle.o -o $out/bin/shuffle</span><span class="err">
</span><span class="s2">  ''</span><span class="p">;</span>

  <span class="c"># b. The training run, inside Rewind. The instrumented program writes</span>
  <span class="c"># its counters to /build/shuffle.gcda, where it was compiled.</span>
  <span class="nv">profile</span> <span class="o">=</span>
    <span class="nv">pkgs</span><span class="o">.</span><span class="nv">runCommand</span> <span class="s2">"shuffle-profile"</span>
      <span class="p">{</span>
        <span class="nv">nativeBuildInputs</span> <span class="o">=</span> <span class="p">[</span>
          <span class="nv">rewind</span>
          <span class="nv">pkgs</span><span class="o">.</span><span class="nv">jq</span>
        <span class="p">];</span>
        <span class="c"># A builder whose Rewind module says this vendor, with KVM.</span>
        <span class="nv">requiredSystemFeatures</span> <span class="o">=</span> <span class="p">[</span>
          <span class="s2">"kvm"</span>
          <span class="s2">"rewind-</span><span class="si">${</span><span class="nv">vendor</span><span class="si">}</span><span class="s2">"</span>
        <span class="p">];</span>
        <span class="nv">closure</span> <span class="o">=</span> <span class="nv">pkgs</span><span class="o">.</span><span class="nv">closureInfo</span> <span class="p">{</span> <span class="nv">rootPaths</span> <span class="o">=</span> <span class="p">[</span> <span class="nv">instrumented</span> <span class="p">];</span> <span class="p">};</span>
      <span class="p">}</span>
      <span class="s2">''</span><span class="err">
</span><span class="s2">        export HOME=$TMPDIR</span><span class="err">

</span><span class="s2">        # Another vendor would train another profile: refuse instead.</span><span class="err">
</span><span class="s2">        if ! grep -q "vendor_id.*: </span><span class="si">${</span><span class="nv">vendorIds</span><span class="o">.</span><span class="p">${</span><span class="nv">vendor</span><span class="p">}</span><span class="si">}</span><span class="s2">$" /proc/cpuinfo; then</span><span class="err">
</span><span class="s2">          echo "this profile trains on </span><span class="si">${</span><span class="nv">vendor</span><span class="si">}</span><span class="s2">; this builder is $(grep -m1 vendor_id /proc/cpuinfo)" &gt;&amp;2</span><span class="err">
</span><span class="s2">          exit 1</span><span class="err">
</span><span class="s2">        fi</span><span class="err">

</span><span class="s2">        # A root filesystem holding the program and its closure.</span><span class="err">
</span><span class="s2">        mkdir -p root/nix/store root/build</span><span class="err">
</span><span class="s2">        xargs -I{} cp -a {} root/nix/store/ &lt; $closure/store-paths</span><span class="err">

</span><span class="s2">        rewind run --root root --cwd /build --json \</span><span class="err">
</span><span class="s2">          --epoch </span><span class="si">${</span><span class="nv">epoch</span><span class="si">}</span><span class="s2"> --seed </span><span class="si">${</span><span class="nv">seed</span><span class="si">}</span><span class="s2"> --schedule </span><span class="si">${</span><span class="nv">schedule</span><span class="si">}</span><span class="s2"> \</span><span class="err">
</span><span class="s2">          --cpu v3-compat --clock </span><span class="si">${</span><span class="nv">clock</span><span class="si">}</span><span class="s2"> \</span><span class="err">
</span><span class="s2">          -- </span><span class="si">${</span><span class="nv">instrumented</span><span class="si">}</span><span class="s2">/bin/shuffle &gt; run.json</span><span class="err">
</span><span class="s2">        jq . run.json &gt;&amp;2</span><span class="err">

</span><span class="s2">        # Read the profile as it was when the run ended.</span><span class="err">
</span><span class="s2">        id=$(jq -r .id run.json)</span><span class="err">
</span><span class="s2">        steps=$(jq -r .steps run.json)</span><span class="err">
</span><span class="s2">        mkdir -p $out</span><span class="err">
</span><span class="s2">        rewind cat --progress off $id $steps /build/shuffle.gcda &gt; $out/shuffle.gcda</span><span class="err">
</span><span class="s2">      ''</span><span class="p">;</span>
<span class="kn">in</span>
<span class="c"># c. The program rebuilt with the profile, natively.</span>
<span class="nv">pkgs</span><span class="o">.</span><span class="nv">runCommandCC</span> <span class="s2">"shuffle"</span> <span class="p">{</span> <span class="nv">passthru</span> <span class="o">=</span> <span class="p">{</span> <span class="kn">inherit</span> <span class="nv">instrumented</span> <span class="nv">profile</span><span class="p">;</span> <span class="p">};</span> <span class="p">}</span> <span class="s2">''</span><span class="err">
</span><span class="s2">  cp </span><span class="si">${</span><span class="sx">./shuffle.c</span><span class="si">}</span><span class="s2"> shuffle.c</span><span class="err">
</span><span class="s2">  cp </span><span class="si">${</span><span class="nv">profile</span><span class="si">}</span><span class="s2">/shuffle.gcda shuffle.gcda</span><span class="err">
</span><span class="s2">  cc -O2 -pthread -fprofile-use -c shuffle.c -o shuffle.o</span><span class="err">
</span><span class="s2">  mkdir -p $out/bin</span><span class="err">
</span><span class="s2">  cc -pthread shuffle.o -o $out/bin/shuffle</span><span class="err">
</span><span class="s2">''</span>
</code></pre></div></div>

<p>Nix puts <code class="language-plaintext highlighter-rouge">/dev/kvm</code> inside the sandbox on a machine that lists <code class="language-plaintext highlighter-rouge">kvm</code> in its <code class="language-plaintext highlighter-rouge">system-features</code>, as NixOS does by default. <code class="language-plaintext highlighter-rouge">kvm</code> alone does not say the machine can train this profile, so the derivation also requires <code class="language-plaintext highlighter-rouge">rewind-amd</code>. A builder can opt-in easily through Rewind’s NixOS module:</p>

<div class="language-nix highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">programs</span><span class="o">.</span><span class="nv">rewind</span> <span class="o">=</span> <span class="p">{</span>
  <span class="nv">enable</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
  <span class="nv">systemFeature</span> <span class="o">=</span> <span class="s2">"amd"</span><span class="p">;</span>
  <span class="c"># AMD only: make the branch counter exact at every boot.</span>
  <span class="nv">amdBranchCounterWorkaround</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Build it, then check both the profile and the final program:</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-build
<span class="go">/nix/store/f1yqkk8a3binrq4iqrm6mdl1p7zp5dvv-shuffle

</span><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> passthru.profile <span class="nt">--check</span>
<span class="go">/nix/store/ywv05plinnpg868b0p66b1lpfjnr9sp1-shuffle-profile

</span><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">--check</span>
<span class="go">/nix/store/f1yqkk8a3binrq4iqrm6mdl1p7zp5dvv-shuffle
</span></code></pre></div></div>

<p>This means our profile-guided build is bit-for-bit reproducible!</p>

<p>The profile is a function of the derivation now along with the other arguments to Rewind: <code class="language-plaintext highlighter-rouge">--epoch</code> <code class="language-plaintext highlighter-rouge">--seed</code> <code class="language-plaintext highlighter-rouge">--schedule</code> <code class="language-plaintext highlighter-rouge">--cpu</code> and <code class="language-plaintext highlighter-rouge">--clock</code>. If any of those change, the profile changes too.</p>

<p>In our example above, we picked <code class="language-plaintext highlighter-rouge">--schedule 1</code> why?</p>

<p>This is a little beyond the reproducible build story, but picking a workload is a bit-of-an-art. You want to pick a workload that resembles production, so that the profile is useful.</p>

<p>Since our toy-example is heavily influenced by the thread schedule, we can try different schedules and see what profile they produce.</p>

<table>
  <thead>
    <tr>
      <th style="text-align: right">schedule</th>
      <th style="text-align: right"><code class="language-plaintext highlighter-rouge">checksum</code> calls</th>
      <th style="text-align: right"><code class="language-plaintext highlighter-rouge">compress</code> calls</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: right">0</td>
      <td style="text-align: right">100,000</td>
      <td style="text-align: right">0</td>
    </tr>
    <tr>
      <td style="text-align: right">1</td>
      <td style="text-align: right">50,004</td>
      <td style="text-align: right">49,996</td>
    </tr>
    <tr>
      <td style="text-align: right">2</td>
      <td style="text-align: right">100,000</td>
      <td style="text-align: right">0</td>
    </tr>
    <tr>
      <td style="text-align: right">3</td>
      <td style="text-align: right">100,000</td>
      <td style="text-align: right">0</td>
    </tr>
  </tbody>
</table>

<p>Three of the four gave every job to one worker, so <code class="language-plaintext highlighter-rouge">compress</code> would never run in training, and a profile from them would tell GCC or Clang that <code class="language-plaintext highlighter-rouge">compress</code> is dead code. Schedule 1 is closer to what we hypothetically expect which is about a 50/50 split.</p>

<p>In a more realistic program, picking any schedule would likely be fine, since the program’s execution is less dependent on the schedule.</p>

<p>Although our profiles are vendor-specific, having a meaningful way forward to having reproducible profile-guided builds can help unlock a lot of easy performance wins.</p>

<p>Fast Python or reproducible Python? Press both buttons.</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:optimize">
      <p>The instrumented program counts which branches it takes, and the second build compiles the program again with those counts. The compiler uses them to decide what to inline, which blocks to lay out together, and which functions are hot or cold. <a href="#fnref:optimize" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:world">
      <p>The training run depends on the machine it runs on: the CPU, the clock, thread scheduling and anything else that changes between builds. <a href="#fnref:world" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:leaderboard">
      <p><a href="https://rewindvm.dev/bugs">Rewind’s bug leaderboard</a> tracks bugs found in the wild. <a href="#fnref:leaderboard" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:check">
      <p>The derivation checks the vendor against <code class="language-plaintext highlighter-rouge">/proc/cpuinfo</code> and refuses to run if it does not match. <a href="#fnref:check" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[Profile-guided optimization (PGO) is an easy way to speed up a program, especially if the workload is somewhat stable. In leaving performance on the table, I built a profile-guided sqlite3 variant for a 1.32x speedup for our SELECT workloads.]]></summary></entry><entry><title type="html">The intensional model in disguise</title><link href="https://fzakaria.com/2026/11/06/the-intensional-model-in-disguise" rel="alternate" type="text/html" title="The intensional model in disguise" /><published>2026-11-06T10:00:00-08:00</published><updated>2026-11-06T10:00:00-08:00</updated><id>https://fzakaria.com/2026/11/06/the-intensional-model-in-disguise</id><content type="html" xml:base="https://fzakaria.com/2026/11/06/the-intensional-model-in-disguise"><![CDATA[<p>Despite how different they look on the surface, Nix, Bazel and buck2 are remarkably similar under the hood. Don’t believe me?
I built a prototype in <a href="/2026/10/17/one-store-two-frontends">one store, two frontends</a> to prove it. Turns out though that the similarities are even deeper than I realized.</p>

<!--more-->

<p>Upon further reflection, I realized that the intensional model is an even more substantial common denominator. What is the intensional model?</p>

<blockquote class="alert alert-tip">
  <p><strong>TIP</strong>
I’ve written before about <a href="/2025/03/08/demystifying-nix-s-intensional-model">Nix’s intensional model</a>, better known as content-addressed (CA) derivations. It has been “experimental” in Nix for years. 🧪</p>
</blockquote>

<p>In the intensional model, outputs are addressed by their <em>content</em>, and actions refer to their inputs by content as well. The extensional model instead addresses an output by the <em>recipe</em> and <em>inputs</em> that produced it. Nix also calls this “content-addressed derivations” (CA derivations). Bazel and buck2 don’t name their model, but they use content-addressing as well.
Consider this coincidence: <a href="https://edolstra.github.io/pubs/phd-thesis.pdf">Eelco’s PhD thesis</a> was published in 2006, the same year that Google started development on Blaze, the predecessor of Bazel [<a href="https://medium.com/better-programming/from-blaze-to-buck2-a-brief-history-of-modern-monorepo-build-systems-563becbcb987">cite</a>].</p>

<p>Let’s take a closer look at the three systems with a simple C example and see how all three implement the intensional model. 🥸</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// greet.h</span>
<span class="kt">void</span> <span class="nf">greet</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">name</span><span class="p">);</span>

<span class="c1">// greet.c</span>
<span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">"greet.h"</span><span class="cp">
</span>
<span class="cm">/* say hi */</span>
<span class="kt">void</span> <span class="nf">greet</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">name</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">"hello, %s</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">name</span><span class="p">);</span>
<span class="p">}</span>

<span class="c1">// main.c</span>
<span class="cp">#include</span> <span class="cpf">"greet.h"</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">greet</span><span class="p">(</span><span class="s">"world"</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In the traditional extensional model (input-addressed), a change anywhere upstream of a build action invalidates the action’s output. This occurs even if the change
is irrelevant to the output, such as a comment change in a source file. In contrast, the intensional model (content-addressed) only invalidates an action’s output if the content of the output itself changes.</p>

<p>In our C example, if we were to change the comment in <code class="language-plaintext highlighter-rouge">greet.c</code> from <code class="language-plaintext highlighter-rouge">say hi</code> to <code class="language-plaintext highlighter-rouge">say hello</code>, the compiled object file <code class="language-plaintext highlighter-rouge">greet.o</code> would still be byte-for-byte identical, as the comment does not affect the compiled output. In the ideal world, the linking of <code class="language-plaintext highlighter-rouge">hello</code> would not need to be redone, as its inputs have not changed in content.</p>

<details>
  <summary>Nix example</summary>
  <div class="language-nix highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span> <span class="nv">pkgs</span> <span class="o">?</span> <span class="kr">import</span> <span class="o">&lt;</span><span class="nv">nixpkgs</span><span class="o">&gt;</span> <span class="p">{},</span> <span class="nv">ca</span> <span class="o">?</span> <span class="kc">false</span> <span class="p">}:</span>
<span class="kd">let</span>
  <span class="nv">extra</span> <span class="o">=</span> <span class="nv">pkgs</span><span class="o">.</span><span class="nv">lib</span><span class="o">.</span><span class="nv">optionalAttrs</span> <span class="nv">ca</span> <span class="p">{</span> <span class="nv">__contentAddressed</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span> <span class="p">};</span>
<span class="kn">in</span> <span class="kr">rec</span> <span class="p">{</span>
  <span class="c"># The `cp` is needed otherwise the source file's store path ends up</span>
  <span class="c"># in the object file, which is a leak of the extensional model.</span>
  <span class="nv">greet</span> <span class="o">=</span> <span class="nv">pkgs</span><span class="o">.</span><span class="nv">runCommandCC</span> <span class="s2">"greet"</span> <span class="nv">extra</span> <span class="s2">''</span><span class="err">
</span><span class="s2">    cp </span><span class="si">${</span><span class="sx">./greet.h</span><span class="si">}</span><span class="s2"> greet.h; cp </span><span class="si">${</span><span class="sx">./greet.c</span><span class="si">}</span><span class="s2"> greet.c</span><span class="err">
</span><span class="s2">    mkdir -p $out</span><span class="err">
</span><span class="s2">    cc -c greet.c -o $out/greet.o</span><span class="err">
</span><span class="s2">  ''</span><span class="p">;</span>
  <span class="nv">hello</span> <span class="o">=</span> <span class="nv">pkgs</span><span class="o">.</span><span class="nv">runCommandCC</span> <span class="s2">"hello"</span> <span class="nv">extra</span> <span class="s2">''</span><span class="err">
</span><span class="s2">    cp </span><span class="si">${</span><span class="sx">./greet.h</span><span class="si">}</span><span class="s2"> greet.h; cp </span><span class="si">${</span><span class="sx">./main.c</span><span class="si">}</span><span class="s2"> main.c</span><span class="err">
</span><span class="s2">    mkdir -p $out/bin</span><span class="err">
</span><span class="s2">    cc main.c </span><span class="si">${</span><span class="nv">greet</span><span class="si">}</span><span class="s2">/greet.o -o $out/bin/hello</span><span class="err">
</span><span class="s2">  ''</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>  </div>
</details>

<p>By default, Nix uses the <em>extensional</em> (input-addressed) model. If we <em>edit the comment</em> and rebuild:</p>

<div data-mark="3" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">-A</span> hello
<span class="go">building '/nix/store/3hwrlpnji5bh5bajdg52s7zbg7ihs6j6-greet.drv'...
building '/nix/store/2k5is7yim1j8pb3qjz89bw45cqzcy2y5-hello.drv'...
/nix/store/122jc3iz6qkrgm907kdz7rrk3lp4qrma-hello
</span></code></pre></div></div>

<p>Everything rebuilt. 😩</p>

<p>The store path in the extensional model is a hash of the <em>recipe</em>, and the recipe for <code class="language-plaintext highlighter-rouge">hello</code> includes the recipe for <code class="language-plaintext highlighter-rouge">greet</code>. Recursion is fun!
Change one byte anywhere upstream and every path downstream changes with it. 🌀</p>

<figure class="graphviz" style="--graphviz-height: 6rem"><img src="https://fzakaria.com/assets/figures/0cb4e88545d5e7ee.svg" alt="Figure" width="571" height="44">
</figure>

<blockquote class="alert alert-warning">
  <p><strong>Warning</strong>
 The two <code class="language-plaintext highlighter-rouge">hello</code> binaries are not even byte-identical: the cc-wrapper puts <code class="language-plaintext highlighter-rouge">$out/lib</code> in the <code class="language-plaintext highlighter-rouge">RUNPATH</code>, so the binary contains its own store path. The extensional model leaks into the bytes. 🙃</p>
</blockquote>

<p>If we enable the build to use content-addressed derivations we observe <code class="language-plaintext highlighter-rouge">greet</code> rebuilt, but <code class="language-plaintext highlighter-rouge">hello</code> did not. 🎉</p>

<div data-mark="3" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nix-build <span class="nt">--extra-experimental-features</span> ca-derivations <span class="nt">-A</span> hello <span class="nt">--arg</span> ca <span class="nb">true</span>
<span class="go">building '/nix/store/qpa1q7g5yjvhdbnfap4y3r2glzyflyv4-greet.drv'...
</span><span class="gp">resolved derivation: '/nix/store/1xnbxrrprs50879ivzmjpv7cbk44w258-hello.drv' -&gt;</span><span class="w"> </span><span class="s1">'/nix/store/rs2j6r2gvz2vi7nfvqj1s3yxx4lqpa3m-hello.drv'</span>...
<span class="go">/nix/store/l2nrycgcg97vrz4nb59icwz9i04ys8jg-hello
</span></code></pre></div></div>

<p>You can read <a href="/2025/03/08/demystifying-nix-s-intensional-model">demystifying Nix’s intensional model</a> for a more detailed explanation of how CA derivations work, but the short version is that Nix rewrites <code class="language-plaintext highlighter-rouge">hello.drv</code> to point at <code class="language-plaintext highlighter-rouge">greet</code>’s <em>content-addressed</em> output instead of <code class="language-plaintext highlighter-rouge">greet.drv</code>. The resolved <code class="language-plaintext highlighter-rouge">rs2j6r…-hello.drv</code> is the same one we built before the edit.</p>

<p>Since no “input” changed, Nix avoids the rebuild.</p>

<p>This is the same behavior as Bazel and buck2, which are intensional by default.</p>

<details>
  <summary>BUILD example</summary>
  <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">cc_library</span><span class="p">(</span>
    <span class="n">name</span> <span class="o">=</span> <span class="sh">"</span><span class="s">greet</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">srcs</span> <span class="o">=</span> <span class="p">[</span><span class="sh">"</span><span class="s">greet.c</span><span class="sh">"</span><span class="p">],</span>
    <span class="n">hdrs</span> <span class="o">=</span> <span class="p">[</span><span class="sh">"</span><span class="s">greet.h</span><span class="sh">"</span><span class="p">],</span>
<span class="p">)</span>

<span class="nf">cc_binary</span><span class="p">(</span>
    <span class="n">name</span> <span class="o">=</span> <span class="sh">"</span><span class="s">hello</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">srcs</span> <span class="o">=</span> <span class="p">[</span><span class="sh">"</span><span class="s">main.c</span><span class="sh">"</span><span class="p">],</span>
    <span class="n">deps</span> <span class="o">=</span> <span class="p">[</span><span class="sh">"</span><span class="s">:greet</span><span class="sh">"</span><span class="p">],</span>
<span class="p">)</span>
</code></pre></div>  </div>
</details>

<p>If we edit the comment and rebuild with Bazel or buck2, we see that the compile ran, but the link was an <em>action cache hit</em>.</p>

<div data-mark="2,8" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>bazel build //:hello <span class="nt">--explain</span><span class="o">=</span>explain.log
<span class="go">INFO: 2 processes: 1 action cache hit, 1 internal, 1 linux-sandbox.

</span><span class="gp">$</span><span class="w"> </span><span class="nb">cat </span>explain.log
<span class="go">Executing action 'Compiling greet.c': action changed since cached execution.

</span><span class="gp">$</span><span class="w"> </span>buck2 build //:hello
<span class="go">Commands: 1 (cached: 0, remote: 0, local: 1)
BUILD SUCCEEDED

</span><span class="gp">$</span><span class="w"> </span>buck2 log what-ran
<span class="go">build  root//:greet (c_compile greet.c (pic))  local  ... clang -c ./greet.c ...
</span></code></pre></div></div>

<p>Bazel and buck2 do not have an input-addressed mode. They always use the intensional model. An action’s key is a hash of its command line (to force rebuilds) and the <em>content digests</em> of its inputs.</p>

<figure class="graphviz" style="--graphviz-height: 6rem"><img src="https://fzakaria.com/assets/figures/6c21e0b9634f31ff.svg" alt="Figure" width="816" height="44">
</figure>

<p>A change only travels as far as the bytes actually change. This optimization is called <em>early cutoff</em>, and it is the whole selling point of the intensional model.</p>

<p>There is a clear mapping between Nix’s CA derivations and Bazel’s action cache.</p>

<table>
  <thead>
    <tr>
      <th>Nix (intensional)</th>
      <th>Bazel / buck2 (REAPI)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>resolved derivation</td>
      <td><code class="language-plaintext highlighter-rouge">Action</code>: command + input digests</td>
    </tr>
    <tr>
      <td>realisation: <code class="language-plaintext highlighter-rouge">drv output → store path</code></td>
      <td>action cache: <code class="language-plaintext highlighter-rouge">action digest → output digests</code></td>
    </tr>
    <tr>
      <td>content-addressed store path</td>
      <td>blob in the CAS</td>
    </tr>
  </tbody>
</table>

<p>A resolved derivation <em>is</em> a Bazel/buck2 action. 🤯</p>

<figure class="graphviz" style="--graphviz-height: 8rem"><img src="https://fzakaria.com/assets/figures/1aa2ae2ca242f9c0.svg" alt="Figure" width="496" height="174">
</figure>

<p>You may see the output paths in Bazel and buck2 and think they are extensional (i.e. <code class="language-plaintext highlighter-rouge">bazel-out/k8-fastbuild/bin/hello</code>), but they are just a convenient place on disk. The real addresses are the digests. <code class="language-plaintext highlighter-rouge">buck2</code> can even make this explicit with <code class="language-plaintext highlighter-rouge">declare_output(has_content_based_path=True)</code>.</p>

<p>Until <a href="/2025/03/11/nix-dynamic-derivations-a-practical-application">dynamic derivations</a> stabilize, people will continue to reach for Bazel and buck2 for the granularity on large builds. The intensional model is a big part of why they are so fast, and Nix has the same model. The two implementations are nearly identical in concept.</p>

<p>Nix described the intensional model in 2006. Google started building on it the same year. Twenty years later, maybe it’s time they compared notes. 🥸</p>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[Despite how different they look on the surface, Nix, Bazel and buck2 are remarkably similar under the hood. Don’t believe me? I built a prototype in one store, two frontends to prove it. Turns out though that the similarities are even deeper than I realized.]]></summary></entry><entry><title type="html">Rewinding by fast-forwarding</title><link href="https://fzakaria.com/2026/11/05/rewinding-by-fast-forwarding" rel="alternate" type="text/html" title="Rewinding by fast-forwarding" /><published>2026-11-05T09:00:00-08:00</published><updated>2026-11-05T09:00:00-08:00</updated><id>https://fzakaria.com/2026/11/05/rewinding-by-fast-forwarding</id><content type="html" xml:base="https://fzakaria.com/2026/11/05/rewinding-by-fast-forwarding"><![CDATA[<p>Debuggers are an incredibly powerful and useful tool, but they mostly show you only the present and let you move forward.<sup id="fnref:rr"><a href="#fn:rr" class="footnote" rel="footnote" role="doc-noteref">1</a></sup> Inspecting the present can help you understand the past, but is that a limitation we must accept?</p>

<p>What if you could travel back in time to see what happened? What if you could see the exact moment a value was written, and who wrote it? What if you could run your debugger <em>backwards</em>?</p>

<p><a href="https://rewindvm.dev">Rewind</a> is a deterministic virtual machine that records a program’s execution once, and then lets you replay it identically, many times. This lets you run the debugger backwards, and see the history of a value in memory, including who last read and wrote it.</p>

<p>Turns out that you can go backwards by fast-forwarding.</p>

<p>Going backwards changes how you debug: you can see how a value got there, not just what it is now. In <a href="/2026/10/23/who-wrote-this-byte">who wrote this byte?</a> <code class="language-plaintext highlighter-rouge">rewind blame</code> found the program that wrote a byte of a file. That was the easy case. Every write to a file goes through the kernel, and Rewind’s kernel logs each one. Writes to memory don’t go through the kernel, so there is no log to read.</p>

<p>So instead we go backwards, <em>by running forwards again</em>. This is how <code class="language-plaintext highlighter-rouge">rewind blame</code> can tell us who last read and wrote a value in memory, and it is the same trick that lets gdb run backwards as well. Let’s see how it works.</p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
New to Rewind? Start with <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">a flaky build you only catch once</a> and <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a></p>
</blockquote>

<h2 id="two-tellers-one-account">Two tellers, one account</h2>

<p>Let’s use the <a href="https://github.com/fzakaria/rewindvm/tree/main/examples/bank"><code class="language-plaintext highlighter-rouge">bank</code></a> example from <a href="/2026/10/07/nix-wrote-half-of-my-debugger">Nix wrote half of my debugger</a>. Two tellers each deposit 10, twenty times, into one account:</p>

<div data-mark="5,10" class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">static</span> <span class="kt">long</span> <span class="n">balance</span><span class="p">;</span>

<span class="k">static</span> <span class="kt">void</span> <span class="nf">deposit</span><span class="p">(</span><span class="kt">int</span> <span class="n">teller</span><span class="p">,</span> <span class="kt">long</span> <span class="n">amount</span><span class="p">)</span>
<span class="p">{</span>
	<span class="kt">long</span> <span class="n">seen</span> <span class="o">=</span> <span class="n">balance</span><span class="p">;</span>
	<span class="kt">char</span> <span class="n">line</span><span class="p">[</span><span class="mi">64</span><span class="p">];</span>
	<span class="kt">int</span> <span class="n">n</span> <span class="o">=</span> <span class="n">snprintf</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="k">sizeof</span> <span class="n">line</span><span class="p">,</span> <span class="s">"teller %d: %ld + %ld</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">teller</span><span class="p">,</span> <span class="n">seen</span><span class="p">,</span> <span class="n">amount</span><span class="p">);</span>

	<span class="k">if</span> <span class="p">(</span><span class="n">write</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">line</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span> <span class="o">==</span> <span class="n">n</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">balance</span> <span class="o">=</span> <span class="n">seen</span> <span class="o">+</span> <span class="n">amount</span><span class="p">;</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In our example, crucially, there is no lock around the read and write of <code class="language-plaintext highlighter-rouge">balance</code>. If the other teller runs in between, one of the deposits is lost.</p>

<p><code class="language-plaintext highlighter-rouge">rewind check</code> runs the program under different thread schedules until one fails:</p>

<div data-mark="6" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind check <span class="nt">--epoch</span> 1790985600 github:fzakaria/rewindvm#bank
<span class="go">schedule   0: exited:0             4547 steps  2ffd6b62eb30  run b1d6981401d5d15f  holds
schedule   1: exited:2             3768 steps    run 36036ed36994d7d8  violates same-outcome, sdk
</span><span class="c">...
</span><span class="go">failing: run 240115d5505149aa, schedule 1 over steps 3245..3246
failing run violates sdk: step 3292: always "balance-adds-up" failed: balance 310, expected 400
</span></code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">check</code> narrows schedule 1’s failure down to steps 3,245 and 3,246 and records that run, <code class="language-plaintext highlighter-rouge">240115d5</code>, which is the one we will dig into. We expected 400 and got 310. Nine deposits are gone. 😬</p>

<h2 id="rewind-blame-at">rewind blame –at</h2>

<p>Our program prints the balance at step 3,291. We can run <code class="language-plaintext highlighter-rouge">rewind blame</code> at that step and the variable<sup id="fnref:expression"><a href="#fn:expression" class="footnote" rel="footnote" role="doc-noteref">2</a></sup> to see who last wrote it:</p>

<div data-mark="4-6" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind blame 240115d5 <span class="nt">--at</span> 3291 balance
<span class="go">balance = 310   8 bytes at 0x56055a0ef030, thread 139, bank.c:69

last written at step 3282 by thread 141 (bank)
</span><span class="gp">  bank.c:41  teller  balance = seen + amount;</span><span class="w">
</span><span class="go">  was 300

other threads just after the write, in step 3282:
  thread 139  bank.c:65  main  __GI___clone3

searched back to step 3210, 1 keyframe window, 1 write, 3.1s
</span></code></pre></div></div>

<p>Rewind goes “backwards” through the run, looking for the last write to that value. We can see that the last write was at step 3,282, by teller 2 (thread 141) on line 41.</p>

<p>But wait, 300 + 10 is 310. That write is fine! 🤔</p>

<p style="--image-width: 22rem"><a href="/assets/images/rewind_spiderman_balance_meme.png"><img src="/assets/images/rewind_spiderman_balance_meme.png" alt="Spider-Man pointing at Spider-Man meme: one Spider-Man labelled &quot;teller 1: I wrote balance&quot;, the other &quot;teller 2: no, I wrote balance&quot;" /></a></p>

<p>The last write is rarely the bug. The money went missing earlier, when a teller wrote a value it had read much earlier. We need to augment <code class="language-plaintext highlighter-rouge">blame</code> with the reads too, to see that.</p>

<h2 id="who-read-it">Who read it?</h2>

<p><code class="language-plaintext highlighter-rouge">--reads</code> lists every read and write of the value, back to the start of the process. Here are the rows around where it goes wrong:</p>

<div data-mark="5,12" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind blame 240115d5 <span class="nt">--at</span> 3291 balance <span class="nt">--reads</span>
<span class="go">  step  thread           access  value               where
</span><span class="c">...
</span><span class="gp">  3244  140 bank         read    110                 bank.c:36  teller  long seen = balance;</span><span class="w">  </span>balance
<span class="gp">  3248  141 bank         read    110                 bank.c:36  teller  long seen = balance;</span><span class="w">  </span>balance
<span class="gp">  3250  140 bank         write   120                 bank.c:41  teller  balance = seen + amount;</span><span class="w">  </span>balance
<span class="gp">  3250  140 bank         read    120                 bank.c:36  teller  long seen = balance;</span><span class="w">  </span>balance
<span class="c">...
</span><span class="gp">  3257  140 bank         write   190                 bank.c:41  teller  balance = seen + amount;</span><span class="w">  </span>balance
<span class="gp">  3257  140 bank         read    190                 bank.c:36  teller  long seen = balance;</span><span class="w">  </span>balance
<span class="gp">  3258  140 bank         write   200                 bank.c:41  teller  balance = seen + amount;</span><span class="w">  </span>balance
<span class="gp">  3263  141 bank         write   120                 bank.c:41  teller  balance = seen + amount;</span><span class="w">  </span>balance
<span class="c">...
</span><span class="go">searched back to step 3210, 1 keyframe window, 40 writes, 41 reads, 1.8s
</span></code></pre></div></div>

<p>Reading the chronology, we can see that teller 2 read the balance at step 3,248, and then teller 1 made nine deposits, taking the balance from 110 to 200. Then at step 3,263 teller 2 wrote its stale value of 120, overwriting the balance and losing the nine deposits (90). 💣</p>

<p>In this example, the bug is obvious, but in a real program it can be hard to find. The <code class="language-plaintext highlighter-rouge">--reads</code> option shows you the whole history of a value, and you can often see where it went wrong without ever setting a breakpoint. You can even see the bug in the plot of the balance over time:</p>

<figure class="plotnine" title="The balance after each of the 40 writes, by step. Teller 1's writes climb from 10 to 200 by step 3,258. Teller 2 read 110 at step 3,248, and at step 3,263 it writes 120, dropping the balance from 200. It then climbs to 310, while the dashed expected line ends at 400."><img src="https://fzakaria.com/assets/figures/dbf8ebde152022a4.svg" alt="The balance after each of the 40 writes, by step. Teller 1's writes climb from 10 to 200 by step 3,258. Teller 2 read 110 at step 3,248, and at step 3,263 it writes 120, dropping the balance from 200. It then climbs to 310, while the dashed expected line ends at 400." width="518" height="245">
</figure>

<p>The example is simple and the fix is obvious: a lock around the read and write. In a real program, the bug can be subtle and the fix complex. Seeing the history of a value, and who last wrote it, can be invaluable in tracking down the root cause.</p>

<h2 id="in-the-app">In the app</h2>

<p>The <a href="https://rewindvm.dev">Rewind app</a> gives the same information but in a more interactive way. The source panel underlines every value that <code class="language-plaintext highlighter-rouge">blame</code> can watch:</p>

<p style="--image-width: 30rem"><a href="/assets/images/rewind-blame-hover.png"><img src="/assets/images/rewind-blame-hover-crop.png" alt="The Rewind app's source panel at bank.c:69, the printf of the balance, with balance underlined and a tooltip: balance = 310. Click to see who last wrote it." /></a></p>

<p>You can click on the value to see who wrote it, and then click <em>Show reads too</em> to see the whole history of that value.</p>

<p style="--image-width: 30rem"><a href="/assets/images/rewind-blame-answer.png"><img src="/assets/images/rewind-blame-answer-crop.png" alt="The app's answer for balance: became 310 at step 3,282, 9 steps before here, written by thread 141 in teller at bank.c:41, balance = seen + amount, was 300, with buttons Go to the write, Show reads too and Blame the earlier value" /></a></p>

<p><em>Show reads too</em> draws every access, one lane per thread. Teller 2’s lone read sits in the middle of teller 1’s deposits, and that one dot is the bug. 🙌</p>

<p style="--image-width: 30rem"><a href="/assets/images/rewind-blame-reads.png"><img src="/assets/images/rewind-blame-reads-crop.png" alt="The app's accesses view for balance: three lanes. Thread 140 has two runs of reads and writes, thread 141 has one read between them and then its own run of reads and writes, and thread 139 reads once at the end. Searched back to step 3,210, 1 keyframe window, 40 writes, 41 reads, 0.9 s" /></a></p>

<h2 id="gdb-backwards">gdb, backwards</h2>

<p>If you would rather drive, <code class="language-plaintext highlighter-rouge">rewind gdb</code> can go backwards too by setting a watchpoint and <code class="language-plaintext highlighter-rouge">reverse-continue</code>. Here it is forked at step 3,264, just after teller 2’s stale write:</p>

<div data-mark="8-9" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind gdb 240115d5 3264
<span class="go">(gdb) watch balance
Hardware watchpoint 1: balance
(gdb) reverse-continue

Thread 3 hit Hardware watchpoint 1: balance

Old value = 120
New value = 200
0x000056055a0ec50d in deposit (teller=2, amount=10) at bank.c:41
</span><span class="gp">41			balance = seen + amount;</span><span class="w">
</span></code></pre></div></div>

<p>You can navigate the stack, inspect variables, and step backwards with <code class="language-plaintext highlighter-rouge">reverse-step</code> and <code class="language-plaintext highlighter-rouge">reverse-next</code>.</p>

<h2 id="rewinding-by-fast-forwarding">Rewinding by fast-forwarding</h2>

<p>How does this all work? How do you run a VM backwards?</p>

<p>You don’t. 😅</p>

<p style="--image-width: 22rem"><a href="/assets/images/rewind_astronaut_reverse_meme.png"><img src="/assets/images/rewind_astronaut_reverse_meme.png" alt="Always has been meme: an astronaut looking at Earth asks &quot;Wait, running backwards is just running forward?&quot; and the astronaut behind him, holding a gun, says &quot;Always has been&quot;" /></a></p>

<p>Rewind replays are completely deterministic: the same run produces the same result every time. Turns out that a simpler way to go backwards is to run forwards again, but stop one instruction sooner than last time. That is all <code class="language-plaintext highlighter-rouge">blame</code> and <code class="language-plaintext highlighter-rouge">reverse-continue</code> do.</p>

<p>Rewind keeps a <em>checkpoint</em> of the machine at the start of a step. It rewinds to that checkpoint and then runs forward back to the step you want to inspect making note of every read and write along the way. If no reads or writes are found, it rewinds to the previous checkpoint and runs forward again. It keeps doing this until it finds the last read or write before the step you want to inspect.<sup id="fnref:cost"><a href="#fn:cost" class="footnote" rel="footnote" role="doc-noteref">3</a></sup></p>

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 830 300" role="img" class="ff" style="display:block;margin-inline:auto;width:100%;height:auto" aria-label="How rewind blame and reverse-continue go back. A timeline of the bank run's steps, with the step asked about, 3291, on the right. Step one, the rewind: restore the latest keyframe before the step. Step two, the fast-forward: replay forward from it to the step with the CPU's debug registers watching balance; each of the 40 writes traps, teller 1's in red from step 3234 to 3258 and teller 2's in teal from 3263 to 3282. The last trap before the step is the answer, step 3282, teller 2, 300 to 310. Only if the window held no trap does the search restore the keyframe before and replay that window.">
<style>
  /* Inline in the post, so these rules reach the whole page: every class is
     prefixed, and colours read the site's tokens, which follow its theme. */
  .ff { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
  .ff-t { font-size: 12px; }
  .ff-s { font-size: 10.5px; }
  .ff-b { font-weight: bold; }
  .ff-ink { fill: var(--ink, #1a1815); }
  .ff-muted { fill: var(--ink-muted, #565046); }
  .ff-faint { fill: var(--ink-faint, #6f685b); }
  .ff-accent { fill: var(--accent, #9e3413); }
  .ff-window { fill: var(--paper-raised, #ebe6da); }
  .ff-before { fill: none; stroke: var(--rule-strong, #c2b9a6); stroke-dasharray: 4 3; }
  .ff-axis { stroke: var(--ink-faint, #6f685b); stroke-width: 1; }
  .ff-line-ink { stroke: var(--ink, #1a1815); }
  .ff-line-accent { stroke: var(--accent, #9e3413); fill: none; }
  .ff-t1 { fill: #b1201d; }
  .ff-t2 { fill: #2f6f73; }
</style>
<defs>
  <marker id="ff-ink-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
    <path d="M0,0 L10,5 L0,10 z" class="ff-ink" />
  </marker>
  <marker id="ff-accent-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
    <path d="M0,0 L10,5 L0,10 z" class="ff-accent" />
  </marker>
</defs>
<!-- The window searched first, and the one before it, faint. -->
<rect x="250" y="166" width="440" height="60" rx="4" class="ff-window" />
<rect x="40" y="166" width="202" height="60" rx="4" class="ff-before" />
<line x1="40" y1="196" x2="690" y2="196" class="ff-axis" />
<!-- Keyframes. -->
<path d="M250,187 l9,9 l-9,9 l-9,-9 z" class="ff-ink" />
<path d="M44,187 l9,9 l-9,9 l-9,-9 z" class="ff-faint" />
<text x="250" y="242" class="ff-s ff-muted" text-anchor="middle">keyframe</text>
<text x="44" y="242" class="ff-s ff-faint" text-anchor="start">keyframe</text>
<!-- The step asked about. -->
<line x1="690" y1="152" x2="690" y2="230" class="ff-line-accent" stroke-width="1.6" />
<text x="700" y="192" class="ff-s ff-b ff-accent">step 3291:</text>
<text x="700" y="207" class="ff-s ff-b ff-accent">who wrote balance?</text>
<!-- ① The rewind: restore the keyframe. -->
<path d="M684,148 C610,18 330,18 256,180" class="ff-line-accent" stroke-width="1.4" stroke-dasharray="5 4" marker-end="url(#ff-accent-arrow)" />
<text x="470.0" y="30" class="ff-t ff-accent" text-anchor="middle"><tspan class="ff-b">1</tspan>  restore the latest keyframe before the step</text>
<!-- ② The fast-forward: replay with the debug registers set. -->
<line x1="262" y1="140" x2="682" y2="140" class="ff-line-ink" stroke-width="1.4" marker-end="url(#ff-ink-arrow)" />
<text x="470.0" y="158" class="ff-t ff-ink" text-anchor="middle"><tspan class="ff-b">2</tspan>  replay forward, debug registers watching balance</text>
<!-- Every write traps; the last before the step is the answer. -->
<circle cx="304.2" cy="196" r="3.4" class="ff-t1" />
<circle cx="310.9" cy="196" r="3.4" class="ff-t1" />
<circle cx="317.7" cy="196" r="3.4" class="ff-t1" />
<circle cx="324.5" cy="196" r="3.4" class="ff-t1" />
<circle cx="331.2" cy="196" r="3.4" class="ff-t1" />
<circle cx="338.0" cy="196" r="3.4" class="ff-t1" />
<circle cx="344.8" cy="196" r="3.4" class="ff-t1" />
<circle cx="351.5" cy="196" r="3.4" class="ff-t1" />
<circle cx="358.3" cy="196" r="3.4" class="ff-t1" />
<circle cx="365.1" cy="196" r="3.4" class="ff-t1" />
<circle cx="371.8" cy="196" r="3.4" class="ff-t1" />
<circle cx="412.5" cy="196" r="3.4" class="ff-t1" />
<circle cx="419.2" cy="196" r="3.4" class="ff-t1" />
<circle cx="426.0" cy="196" r="3.4" class="ff-t1" />
<circle cx="432.8" cy="196" r="3.4" class="ff-t1" />
<circle cx="439.5" cy="196" r="3.4" class="ff-t1" />
<circle cx="446.3" cy="196" r="3.4" class="ff-t1" />
<circle cx="453.1" cy="196" r="3.4" class="ff-t1" />
<circle cx="459.8" cy="196" r="3.4" class="ff-t1" />
<circle cx="466.6" cy="196" r="3.4" class="ff-t1" />
<circle cx="500.5" cy="196" r="3.4" class="ff-t2" />
<circle cx="507.2" cy="196" r="3.4" class="ff-t2" />
<circle cx="514.0" cy="196" r="3.4" class="ff-t2" />
<circle cx="520.8" cy="196" r="3.4" class="ff-t2" />
<circle cx="527.5" cy="196" r="3.4" class="ff-t2" />
<circle cx="534.3" cy="196" r="3.4" class="ff-t2" />
<circle cx="541.1" cy="196" r="3.4" class="ff-t2" />
<circle cx="547.8" cy="196" r="3.4" class="ff-t2" />
<circle cx="554.6" cy="196" r="3.4" class="ff-t2" />
<circle cx="561.4" cy="196" r="3.4" class="ff-t2" />
<circle cx="568.2" cy="196" r="3.4" class="ff-t2" />
<circle cx="574.9" cy="196" r="3.4" class="ff-t2" />
<circle cx="581.7" cy="196" r="3.4" class="ff-t2" />
<circle cx="588.5" cy="196" r="3.4" class="ff-t2" />
<circle cx="595.2" cy="196" r="3.4" class="ff-t2" />
<circle cx="602.0" cy="196" r="3.4" class="ff-t2" />
<circle cx="608.8" cy="196" r="3.4" class="ff-t2" />
<circle cx="615.5" cy="196" r="3.4" class="ff-t2" />
<circle cx="622.3" cy="196" r="3.4" class="ff-t2" />
<circle cx="629.1" cy="196" r="3.4" class="ff-t2" />
<circle cx="629.1" cy="196" r="8" fill="none" class="ff-line-accent" stroke-width="1.6" />
<line x1="629.1" y1="205" x2="629.1" y2="258" class="ff-line-accent" stroke-width="1" />
<text x="623.1" y="272" class="ff-t ff-accent" text-anchor="end"><tspan class="ff-b">3</tspan>  the last trap is the answer: step 3282, teller 2, 300 → 310</text>
<!-- Legend and the fallback. -->
<circle cx="258" cy="286" r="3.4" class="ff-t1" />
<text x="266" y="290" class="ff-s ff-muted">teller 1 writes</text>
<circle cx="378" cy="286" r="3.4" class="ff-t2" />
<text x="386" y="290" class="ff-s ff-muted">teller 2 writes</text>
<text x="141.0" y="190" class="ff-s ff-faint" text-anchor="middle">no trap in the window?</text>
<text x="141.0" y="206" class="ff-s ff-faint" text-anchor="middle">do it again from here</text>
</svg>

<p>Deterministic replay is what makes this work, and it keeps the implementation simple: going back is just going forward again from earlier.</p>

<p>I’ve been having a lot of fun debugging my own programs this way. It’s a bit like time travel without the paradoxes. You can see the whole history of a value, and who wrote it, without setting a breakpoint and restarting the program.</p>

<p>It’s git blame for your program’s memory.  🔍</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:rr">
      <p>Tools like <a href="https://rr-project.org/">rr</a> and <a href="https://undo.io/">Undo</a> record a process and let you run its replay backwards. Rewind records the whole machine, the kernel included, so the same inputs make the same run every time. <a href="#fnref:rr" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:expression">
      <p>The expression can be a variable, a pointer dereference, or a struct field. <a href="#fnref:expression" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:cost">
      <p>A step can be millions of instructions, so this can take a little bit. <a href="#fnref:cost" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[Debuggers are an incredibly powerful and useful tool, but they mostly show you only the present and let you move forward.1 Inspecting the present can help you understand the past, but is that a limitation we must accept? Tools like rr and Undo record a process and let you run its replay backwards. Rewind records the whole machine, the kernel included, so the same inputs make the same run every time. &#8617;]]></summary></entry><entry><title type="html">Why does shuffling the schedule find so many bugs?</title><link href="https://fzakaria.com/2026/11/03/why-does-shuffling-the-schedule-find-so-many-bugs" rel="alternate" type="text/html" title="Why does shuffling the schedule find so many bugs?" /><published>2026-11-03T09:00:00-08:00</published><updated>2026-11-03T09:00:00-08:00</updated><id>https://fzakaria.com/2026/11/03/why-does-shuffling-the-schedule-find-so-many-bugs</id><content type="html" xml:base="https://fzakaria.com/2026/11/03/why-does-shuffling-the-schedule-find-so-many-bugs"><![CDATA[<p>Here is something to think about: bugs are not rare, but rather the orderings of events that trigger them are. What do I mean by this?</p>

<!--more-->

<p>Let’s start with a simple story. When I worked at AWS on RDS (Relational Database Service), we built the control plane for the service using workflows, of course using SWF (Simple Workflow). The workflows would execute a series of steps to create, modify or delete a database instance. Every so often we’d see something that looked impossible: a workflow that seemed to run its steps out of order.</p>

<p>What we actually observed was a pause. A worker would pick up a step and then stop for an unexpectedly long time. While paused it stopped heartbeating, so SWF decided it was dead and reassigned the step to another worker. The new worker finished the step and the workflow moved on. Then the first worker woke up. As far as it could tell no time had passed, so it carried on with the step it was holding, causing havoc in its wake.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/d538c6f3a7d7efa3.svg" alt="A timeline with three lanes: worker 1, SWF and worker 2. Worker 1 runs snapshot, starts apply config, then pauses. SWF hears no heartbeat, times the step out and hands apply config to worker 2, which runs it and then runs reboot. Worker 1 wakes up and finishes apply config after the reboot, and SWF rejects its result. The instance saw snapshot, apply config, reboot, apply config." width="720" height="236">
</figure>

<p>We suddenly realized that we were not adequately testing all the possible schedules of events. The workflow code was correct, but the schedule that triggered the bug was not one we had ever seen in our tests. It was a rare schedule, but it was not a rare bug. So we began adding idempotency tokens to every step and making sure that every step could be run multiple times without breaking anything. It was a lot of work, but it made the system much more robust.</p>

<p>What’s the purpose of this story?</p>

<p>I am building <a href="https://rewindvm.dev">Rewind VM</a>, a deterministic VM. It helps find bugs in software primarily by running the same code under many different schedules.<sup id="fnref:schedule"><a href="#fn:schedule" class="footnote" rel="footnote" role="doc-noteref">1</a></sup> The mere act of shuffling the schedule has found <a href="https://rewindvm.dev/bugs.html">many bugs</a> thus far.</p>

<p>The software under test is not even a distributed system, such as the workflow example above, and yet many of the bugs are still schedule-dependent. No crazy Jepsen test suite needed. How can this be? All these projects have tests that validate the code on every change. Why does shuffling the schedule find so many bugs that all those tests never did?</p>

<p>The bugs aren’t rare; the schedules your tests run are. An idle, fast machine runs the same handful of orderings nearly every time. A test passes because the order never changes, and the code may only ever have handled that one order.</p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
New to Rewind? Start with <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">a flaky build you only catch once</a> and <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a>.</p>
</blockquote>

<p>It takes different schedules or unforeseen long pauses, similar to the workflow story above, to trigger these bugs. The bugs are not rare, but the schedules that trigger them are. How rare are they?</p>

<p>The smallest race I know is <code class="language-plaintext highlighter-rouge">counter++</code> from two threads.</p>

<div class="side-by-side">

  <div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">long</span> <span class="n">counter</span><span class="p">;</span>

<span class="kt">void</span> <span class="nf">increment</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">counter</span><span class="o">++</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>  </div>

  <div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">increment:</span>
    <span class="nf">mov</span>  <span class="nb">rax</span><span class="p">,</span> <span class="p">[</span><span class="nv">counter</span><span class="p">]</span>  <span class="c1">; load</span>
    <span class="nf">add</span>  <span class="nb">rax</span><span class="p">,</span> <span class="mi">1</span>          <span class="c1">; add</span>
    <span class="nf">mov</span>  <span class="p">[</span><span class="nv">counter</span><span class="p">],</span> <span class="nb">rax</span>  <span class="c1">; store</span>
    <span class="nf">ret</span>
</code></pre></div>  </div>

</div>

<p>Two threads run <code class="language-plaintext highlighter-rouge">increment</code> once each. Each thread’s three steps execute in order, but the two threads can interleave. An ordering is a choice of which 3 of the 6 slots belong to thread A, so there are <math xmlns="http://www.w3.org/1998/Math/MathML" display="inline"><mrow><mo>&#x00028;</mo><mfrac linethickness="0"><mrow><mn>6</mn></mrow><mrow><mn>3</mn></mrow></mfrac><mo>&#x00029;</mo><mo>&#x0003D;</mo><mn>20</mn></mrow></math> of them.</p>

<p>We can visualize the 20 choices as paths on a grid. A step right is a step of thread A, a step down is a step of thread B, and every path from the top-left corner to the bottom-right one is one ordering.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/7e57f7a084c36e55.svg" alt="Left: a 3 by 3 grid. Moving right is a step of thread A, moving down a step of thread B, so every path from the top-left corner to the bottom-right corner is one interleaving, 20 in all. The four inner points, where both threads have loaded and neither has stored, are shaded: every path through them loses an update. Only the two paths along the edges, A then B and B then A, avoid them. Right: the 20 orderings listed, each with the counter it ends with. AAABBB and BBBAAA end at 2; the other 18 end at 1." width="720" height="300">
</figure>

<p>The shaded square holds the four points where both threads have loaded the counter and neither has stored it. Any path that enters it ends with the counter at 1, because the second writer stores the stale original value.</p>

<p>Only the two paths along the edges provide the “correct result” of 2, A entirely before B or B entirely before A. That is 18 of 20 orderings that lose an update. If every ordering were equally likely, this race would fire in 9 runs out of 10. 😱</p>

<p>What does this look like on a real machine?</p>

<p>Let’s build a small program that runs the two threads and records the order of their steps. The program is a bit more complicated than the simple <code class="language-plaintext highlighter-rouge">counter++</code> above, because it has to record the order of the steps. It also has to be careful not to introduce any new races in the recording itself. The program leverages Rewind’s <code class="language-plaintext highlighter-rouge">rewind_point()</code> to give Rewind VM a place to switch threads.<sup id="fnref:barrier"><a href="#fn:barrier" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></p>

<details>
  <summary>race.c</summary>

  <div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/*
 * Two threads each add one to a shared counter in three steps: load the
 * counter, add one, store it back. No lock, so a thread that runs between
 * the other's load and store writes a stale value over it.
 *
 * Each step first takes the next slot of a shared atomic sequence and
 * writes its thread's letter there, so the program prints the order the
 * six steps ran in, such as AABABB, and the final counter.
 *
 * rewind_point() between the steps gives Rewind VM a place to switch
 * threads. main() calls it once before the threads start, so the one
 * failed open it makes outside Rewind happens there; on the host the
 * points inside the threads are a load and a branch.
 *
 * Built with -DSTART_BARRIER, both threads wait on a barrier before the
 * first step, so they start as close together as the host allows.
 *
 * The exit status encodes the outcome so `rewind check` reports it
 * without reading output: ordering index (0..19) * 2 + (1 if an update
 * was lost).
 */</span>
<span class="cp">#include</span> <span class="cpf">&lt;pthread.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;stdatomic.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;string.h&gt;</span><span class="cp">
</span>
<span class="cp">#include</span> <span class="cpf">"rewind.h"</span><span class="cp">
</span>
<span class="k">enum</span> <span class="p">{</span> <span class="n">THREADS</span> <span class="o">=</span> <span class="mi">2</span><span class="p">,</span> <span class="n">STEPS</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span> <span class="n">MARKS</span> <span class="o">=</span> <span class="n">THREADS</span> <span class="o">*</span> <span class="n">STEPS</span> <span class="p">};</span>

<span class="k">static</span> <span class="k">volatile</span> <span class="kt">long</span> <span class="n">counter</span><span class="p">;</span>
<span class="k">static</span> <span class="n">atomic_int</span> <span class="n">next_mark</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">char</span> <span class="n">order</span><span class="p">[</span><span class="n">MARKS</span> <span class="o">+</span> <span class="mi">1</span><span class="p">];</span>

<span class="cp">#ifdef START_BARRIER
</span><span class="k">static</span> <span class="n">pthread_barrier_t</span> <span class="n">start</span><span class="p">;</span>
<span class="cp">#endif
</span>
<span class="cm">/* Record that thread `who` is taking its next step. */</span>
<span class="k">static</span> <span class="kt">void</span> <span class="nf">mark</span><span class="p">(</span><span class="kt">char</span> <span class="n">who</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">order</span><span class="p">[</span><span class="n">atomic_fetch_add</span><span class="p">(</span><span class="o">&amp;</span><span class="n">next_mark</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span> <span class="o">=</span> <span class="n">who</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span> <span class="o">*</span><span class="nf">increment</span><span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span>
<span class="p">{</span>
	<span class="kt">char</span> <span class="n">who</span> <span class="o">=</span> <span class="o">*</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="p">)</span><span class="n">arg</span><span class="p">;</span>

<span class="cp">#ifdef START_BARRIER
</span>	<span class="n">pthread_barrier_wait</span><span class="p">(</span><span class="o">&amp;</span><span class="n">start</span><span class="p">);</span>
<span class="cp">#endif
</span>	<span class="n">mark</span><span class="p">(</span><span class="n">who</span><span class="p">);</span>
	<span class="kt">long</span> <span class="n">seen</span> <span class="o">=</span> <span class="n">counter</span><span class="p">;</span> <span class="cm">/* load */</span>
	<span class="n">rewind_point</span><span class="p">();</span>
	<span class="n">mark</span><span class="p">(</span><span class="n">who</span><span class="p">);</span>
	<span class="n">seen</span> <span class="o">=</span> <span class="n">seen</span> <span class="o">+</span> <span class="mi">1</span><span class="p">;</span> <span class="cm">/* add */</span>
	<span class="n">rewind_point</span><span class="p">();</span>
	<span class="n">mark</span><span class="p">(</span><span class="n">who</span><span class="p">);</span>
	<span class="n">counter</span> <span class="o">=</span> <span class="n">seen</span><span class="p">;</span> <span class="cm">/* store */</span>
	<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>

<span class="cm">/* The index of `s` among the 20 orderings of AAABBB, in sorted order. */</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">ordering_index</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">s</span><span class="p">)</span>
<span class="p">{</span>
	<span class="kt">int</span> <span class="n">index</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="mi">64</span><span class="p">;</span> <span class="n">a</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
		<span class="kt">char</span> <span class="n">candidate</span><span class="p">[</span><span class="n">MARKS</span> <span class="o">+</span> <span class="mi">1</span><span class="p">];</span>
		<span class="kt">int</span> <span class="n">as</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">MARKS</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
			<span class="n">candidate</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="n">a</span> <span class="o">&gt;&gt;</span> <span class="p">(</span><span class="n">MARKS</span> <span class="o">-</span> <span class="mi">1</span> <span class="o">-</span> <span class="n">i</span><span class="p">))</span> <span class="o">&amp;</span> <span class="mi">1</span> <span class="o">?</span> <span class="sc">'B'</span> <span class="o">:</span> <span class="sc">'A'</span><span class="p">;</span>
			<span class="n">as</span> <span class="o">+=</span> <span class="n">candidate</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">==</span> <span class="sc">'A'</span><span class="p">;</span>
		<span class="p">}</span>
		<span class="n">candidate</span><span class="p">[</span><span class="n">MARKS</span><span class="p">]</span> <span class="o">=</span> <span class="sc">'\0'</span><span class="p">;</span>
		<span class="k">if</span> <span class="p">(</span><span class="n">as</span> <span class="o">!=</span> <span class="n">STEPS</span><span class="p">)</span> <span class="p">{</span>
			<span class="k">continue</span><span class="p">;</span>
		<span class="p">}</span>
		<span class="k">if</span> <span class="p">(</span><span class="n">strcmp</span><span class="p">(</span><span class="n">candidate</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
			<span class="k">return</span> <span class="n">index</span><span class="p">;</span>
		<span class="p">}</span>
		<span class="n">index</span><span class="o">++</span><span class="p">;</span>
	<span class="p">}</span>
	<span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>

<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
	<span class="k">static</span> <span class="k">const</span> <span class="kt">char</span> <span class="n">names</span><span class="p">[</span><span class="n">THREADS</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span> <span class="sc">'A'</span><span class="p">,</span> <span class="sc">'B'</span> <span class="p">};</span>
	<span class="n">pthread_t</span> <span class="n">threads</span><span class="p">[</span><span class="n">THREADS</span><span class="p">];</span>

	<span class="cm">/* Open /dev/rewind, or find it missing, before any thread runs. */</span>
	<span class="n">rewind_point</span><span class="p">();</span>

<span class="cp">#ifdef START_BARRIER
</span>	<span class="n">pthread_barrier_init</span><span class="p">(</span><span class="o">&amp;</span><span class="n">start</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="n">THREADS</span><span class="p">);</span>
<span class="cp">#endif
</span>	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">THREADS</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">pthread_create</span><span class="p">(</span><span class="o">&amp;</span><span class="n">threads</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="nb">NULL</span><span class="p">,</span> <span class="n">increment</span><span class="p">,</span> <span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">names</span><span class="p">[</span><span class="n">i</span><span class="p">]);</span>
	<span class="p">}</span>
	<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">THREADS</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
		<span class="n">pthread_join</span><span class="p">(</span><span class="n">threads</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="nb">NULL</span><span class="p">);</span>
	<span class="p">}</span>

	<span class="kt">int</span> <span class="n">lost</span> <span class="o">=</span> <span class="n">counter</span> <span class="o">!=</span> <span class="n">THREADS</span><span class="p">;</span>
	<span class="n">printf</span><span class="p">(</span><span class="s">"%s %ld</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">order</span><span class="p">,</span> <span class="n">counter</span><span class="p">);</span>
	<span class="k">return</span> <span class="n">ordering_index</span><span class="p">(</span><span class="n">order</span><span class="p">)</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">+</span> <span class="n">lost</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>  </div>

</details>

<p>I ran both builds, with and without the barrier, 10,000 times each on my laptop, a Ryzen 7 7840U with 16 idle hardware threads.</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span><span class="k">for </span>i <span class="k">in</span> <span class="si">$(</span><span class="nb">seq </span>10000<span class="si">)</span><span class="p">;</span> <span class="k">do</span> ./race<span class="p">;</span> <span class="k">done</span> | <span class="nb">sort</span> | <span class="nb">uniq</span> <span class="nt">-c</span> | <span class="nb">sort</span> <span class="nt">-rn</span>
<span class="go">   9985 AAABBB 2
     15 BBBAAA 2
</span><span class="gp">$</span><span class="w"> </span><span class="k">for </span>i <span class="k">in</span> <span class="si">$(</span><span class="nb">seq </span>10000<span class="si">)</span><span class="p">;</span> <span class="k">do</span> ./race-barrier<span class="p">;</span> <span class="k">done</span> | <span class="nb">sort</span> | <span class="nb">uniq</span> <span class="nt">-c</span> | <span class="nb">sort</span> <span class="nt">-rn</span>
<span class="go">   9957 BBBAAA 2
     39 AAABBB 2
      2 BBAAAB 1
      1 BAAABB 1
      1 BAABAB 1
</span></code></pre></div></div>

<figure class="plotnine" title="Two panels of runs per ordering, on a log scale, across the 20 orderings. With pthread_create alone, 9,985 runs are AAABBB and 15 are BBBAAA. With a barrier, 9,957 are BBBAAA, 39 are AAABBB, and 4 runs spread over three orderings that lose an update. The other orderings never ran."><img src="https://fzakaria.com/assets/figures/96c2e3ebedae9ef3.svg" alt="Two panels of runs per ordering, on a log scale, across the 20 orderings. With pthread_create alone, 9,985 runs are AAABBB and 15 are BBBAAA. With a barrier, 9,957 are BBBAAA, 39 are AAABBB, and 4 runs spread over three orderings that lose an update. The other orderings never ran." width="518" height="346">
</figure>

<p>Across 20,000 runs the idle laptop ran 5 of the 20 orderings and lost an update 4 times.
Interestingly, the barrier was supposed to make them collide. Instead it flipped the order such that 9,957 runs were <code class="language-plaintext highlighter-rouge">BBBAAA</code>.</p>

<p>A busy machine is a little different. With <code class="language-plaintext highlighter-rouge">stress-ng --cpu 16</code> keeping every hardware thread busy, the same two binaries ran 13 and 16 of the orderings, and lost an update in 32 and 66 of 10,000 runs. That’s still fewer than 1 run in 100 losing an update.</p>

<p style="--image-width: 20rem"><a href="/assets/images/rewind_buzz_aaabbb_meme.png"><img src="/assets/images/rewind_buzz_aaabbb_meme.png" alt="X, X everywhere meme: Buzz Lightyear, his arm around a worried Woody, points into the distance: &quot;AAABBB&quot;, &quot;AAABBB everywhere&quot;" /></a></p>

<p>Rewind runs the guest on one virtual CPU and only switches threads at an exit, such as a system call (see <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a>) or a <code class="language-plaintext highlighter-rouge">rewind_point</code> SDK call. This gives Rewind a chance to modify the schedule.</p>

<p>We can then run the same binary with Rewind to see how many of the 20 orderings it can reach.</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind check <span class="nt">--epoch</span> 1790985600 <span class="nt">--root</span> root <span class="nt">--schedules</span> 9999 <span class="se">\</span>
<span class="go">    --all --no-narrow -- /bin/race
</span><span class="c">...
</span><span class="go">schedule 9999: exited:0              354 steps    run 9b248f72f742b07f
1492 of 9999 other schedules ended differently
</span></code></pre></div></div>

<p>Across 10,000 runs Rewind reached 15 of the 20 orderings and lost an update in 1,371 of them. With a barrier it reached all 20 orderings and lost an update in 2,997 of them.</p>

<figure class="plotnine" title="Two panels of runs per ordering, on a log scale, under rewind check. With pthread_create alone, 8,508 runs are AAABBB and the rest spread over 14 more orderings, 1,371 of them losing an update. With a barrier, all 20 orderings appear, from 5,715 runs of AAABBB down to 1 of BABABA, and 2,997 runs lose an update."><img src="https://fzakaria.com/assets/figures/53408b0d14748957.svg" alt="Two panels of runs per ordering, on a log scale, under rewind check. With pthread_create alone, 8,508 runs are AAABBB and the rest spread over 14 more orderings, 1,371 of them losing an update. With a barrier, all 20 orderings appear, from 5,715 runs of AAABBB down to 1 of BABABA, and 2,997 runs lose an update." width="518" height="346">
</figure>

<p>We can observe that Rewind’s perturbations reach more orderings than the host, and that it loses an update more often, which helps us find the bug. The table below summarizes the results:</p>

<table>
  <thead>
    <tr>
      <th>Where</th>
      <th>Start</th>
      <th>Orderings seen</th>
      <th>Runs that lost an update</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>idle laptop</td>
      <td>create</td>
      <td>2 of 20</td>
      <td>0 of 10,000</td>
    </tr>
    <tr>
      <td>idle laptop</td>
      <td>barrier</td>
      <td>5 of 20</td>
      <td>4 of 10,000</td>
    </tr>
    <tr>
      <td>busy laptop</td>
      <td>create</td>
      <td>13 of 20</td>
      <td>32 of 10,000</td>
    </tr>
    <tr>
      <td>busy laptop</td>
      <td>barrier</td>
      <td>16 of 20</td>
      <td>66 of 10,000</td>
    </tr>
    <tr>
      <td>Rewind</td>
      <td>create</td>
      <td>15 of 20</td>
      <td>1,371 of 10,000</td>
    </tr>
    <tr>
      <td>Rewind</td>
      <td>barrier</td>
      <td>20 of 20</td>
      <td>2,997 of 10,000</td>
    </tr>
  </tbody>
</table>

<p>Interleavings, though, are not the only way to trigger bugs. Long pauses are orderings too, and they can be even rarer than interleavings.</p>

<p>A long pause sits at the far edge of the grid. Thread A stops, and everything else takes hundreds of steps before A takes its next one. A path like that runs along one edge of the grid for a long time. A short perturbation hands the other side a few steps, so it rarely walks that far.</p>

<p>Rewind has knobs to make long pauses more likely. The <code class="language-plaintext highlighter-rouge">--stall-max</code> knob raises the maximum stall time, and the <code class="language-plaintext highlighter-rouge">--stall-min</code> knob lowers the minimum stall time. These settings can help explore even more unlikely schedules to discover bugs that only appear under extreme conditions.</p>

<p>It’s kind of surprising that with all the hype around property-based testing, fuzzing, and Jepsen, a simple deterministic VM that shuffles the schedule finds so many bugs.
Our hardware is so fast that we’ve become accustomed to thinking that the order of events is always the same. Adding a little randomness to the schedule can expose bugs that have been hiding in plain sight.</p>

<p>Bugs aren’t rare, but the schedules that trigger them are.</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:schedule">
      <p>I say <em>schedule</em> rather than <em>thread interleaving</em> on purpose. Most of the bugs on that page are races between processes, or between a process and a signal. Only a few are between two threads of one program. <a href="#fnref:schedule" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:barrier">
      <p>The program also has a version that uses a barrier so the threads collide on purpose, which should make the race even more likely. <a href="#fnref:barrier" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[Here is something to think about: bugs are not rare, but rather the orderings of events that trigger them are. What do I mean by this?]]></summary></entry><entry><title type="html">A clock made of branches</title><link href="https://fzakaria.com/2026/11/01/a-clock-made-of-branches" rel="alternate" type="text/html" title="A clock made of branches" /><published>2026-11-01T09:00:00-08:00</published><updated>2026-11-01T09:00:00-08:00</updated><id>https://fzakaria.com/2026/11/01/a-clock-made-of-branches</id><content type="html" xml:base="https://fzakaria.com/2026/11/01/a-clock-made-of-branches"><![CDATA[<p><em>What is time inside a machine you want to replay?</em> 🧘</p>

<p>When building <a href="http://rewindvm.dev/">Rewind</a>, a deterministic VM, you come face-to-face with the idea of how to represent time very quickly. You need a way to measure time inside the guest so that on subsequent replays, the guest sees the same time and makes the same decisions. Time is the ultimate variable.</p>

<!--more-->

<p>You can’t simply record the wall-clock time of the host because time spent between two interception points depends on things outside the guest, like host load, CPU frequency, caches and other processes. Therefore the same guest work can take a different amount of time on the host.</p>

<p>In <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a> I explained how the clock inside <a href="https://rewindvm.dev">Rewind VM</a> moves 5 microseconds per step. More specifically, that clock, <em>exit time</em>, moves only when the guest exits such as from a <code class="language-plaintext highlighter-rouge">syscall</code>. It treats everything the program does between two exits as <strong>instant</strong>. Therefore a program that is CPU bound such as doing nothing but math for a full second between two system calls, sees only 5µs go by. 🤦🏻‍♂️</p>

<p>Rewind has a second clock mode as well, <em>counter time</em>, that tries to account for the work. The clock advances one nanosecond for every <strong>conditional branch</strong> the guest retired.<sup id="fnref:rr"><a href="#fn:rr" class="footnote" rel="footnote" role="doc-noteref">1</a></sup></p>

<p style="--image-width: 20rem"><a href="/assets/images/rewind_morpheus_time_meme.png"><img src="/assets/images/rewind_morpheus_time_meme.png" alt="Matrix Morpheus meme: Morpheus in his sunglasses says &quot;What if I told you time is just counting branches&quot;" /></a></p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
New to Rewind? Start with <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">a flaky build you only catch once</a> and <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a></p>
</blockquote>

<p>Still confused about what I mean by “free” and “branches”? Let’s look at a simple example to distinguish between the two clocks.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/d4be2da3c7c76fbb.svg" alt="A guest makes four exits with work between them: 2,000 branches, then one second of math worth a billion branches, then 3,000 branches. Exit time charges 5 microseconds for each exit and nothing for the work, so the clock reads 20 microseconds at the end. Counter time charges 5 microseconds for each exit plus a nanosecond per branch of work: 2 microseconds, 1 second and 3 microseconds, so the clock reads 1.000025 seconds." width="720" height="250">
</figure>

<p>The counter time tries to account for the work whereas the exit time only advanced the clock on exits.<sup id="fnref:exits"><a href="#fn:exits" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></p>

<p>Why branches, though?</p>

<h2 id="what-is-time-in-a-replayed-machine">What is time in a replayed machine?</h2>

<p>We already understand that we cannot rely on the wall-clock time of the host. We need something to measure that is the same for every run of the same program so that we can equate it to time spent.</p>

<p>What <em>is</em> the same on every run?</p>

<p>The guest’s instruction stream! The CPU is a deterministic machine: the same input, the same registers, the same memory, and the same instructions produce the same next state.</p>

<p>We can measure time by measuring progress through the instruction stream. 💡</p>

<p>Turns out that CPU manufacturers even ship a hardware counter for exactly that. Is it reliable? Let’s see. 🧐</p>

<p>Let’s use this simple program: count down from a billion.</p>

<div class="side-by-side">

  <div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="p">{</span>
  <span class="kt">long</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1000000000</span><span class="p">;</span>
  <span class="k">do</span> <span class="p">{</span>
    <span class="n">i</span><span class="o">--</span><span class="p">;</span>
  <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">i</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>  </div>

  <div class="language-nasm highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">_start:</span>
    <span class="nf">mov</span>  <span class="nb">rcx</span><span class="p">,</span> <span class="mi">1000000000</span>
<span class="nl">.loop:</span>
    <span class="nf">dec</span>  <span class="nb">rcx</span>
    <span class="nf">jnz</span>  <span class="nv">.loop</span>
    <span class="nf">mov</span>  <span class="nb">eax</span><span class="p">,</span> <span class="mi">60</span>    <span class="c1">; exit(0)</span>
    <span class="nf">xor</span>  <span class="nb">edi</span><span class="p">,</span> <span class="nb">edi</span>
    <span class="nf">syscall</span>
</code></pre></div>  </div>

</div>

<p>The assembly equivalent contains a <code class="language-plaintext highlighter-rouge">mov</code>, <strong>a billion</strong> <code class="language-plaintext highlighter-rouge">dec</code>+<code class="language-plaintext highlighter-rouge">jnz</code> (conditional branch) pairs, then three instructions to exit for a total of <strong>2,000,000,004</strong> instructions.</p>

<p>Let’s run it on the CPU twice and count the instructions and conditional branches with <code class="language-plaintext highlighter-rouge">perf stat</code>:</p>

<div data-mark="3,7" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>nasm <span class="nt">-felf64</span> loop.asm <span class="o">&amp;&amp;</span> ld <span class="nt">-o</span> loop loop.o
<span class="gp">$</span><span class="w"> </span>taskset <span class="nt">-c</span> 5 perf <span class="nb">stat</span> <span class="nt">-e</span> instructions:u,ex_ret_cond:u ./loop
<span class="go">     2,000,001,025      instructions:u
     1,000,000,000      ex_ret_cond:u

</span><span class="gp">$</span><span class="w"> </span>taskset <span class="nt">-c</span> 5 perf <span class="nb">stat</span> <span class="nt">-e</span> instructions:u,ex_ret_cond:u ./loop
<span class="go">     2,000,001,054      instructions:u
     1,000,000,000      ex_ret_cond:u
</span></code></pre></div></div>

<p>The same program and input gives the same conditional branch count, but the instruction count is off by a thousand or so. Why?</p>

<p style="--image-width: 16rem"><a href="/assets/images/rewind_panik_instructions_meme.png"><img src="/assets/images/rewind_panik_instructions_meme.png" alt="Panik kalm panik meme: &quot;My clock counts instructions&quot; (panik), &quot;The program can't see interrupts&quot; (kalm), &quot;The instruction counter can&quot; (panik)" /></a></p>

<p>Although this loop is CPU bound and only decrements a register, it is still not isolated from the effects of the outside world. Timers tick, network packets arrive, other cores send inter-processor interrupts (IPIs). The program can’t see any of that, but the instruction counter we are probing can.</p>

<p>I pinned the loop to a single CPU and counted how many interrupts that CPU took during each run, from <code class="language-plaintext highlighter-rouge">/proc/interrupts</code>.</p>

<figure class="plotnine" title="Two panels of 120 runs each, plotting extra counts against the interrupts taken during the run. Instructions sit on a dashed line of one extra per interrupt, from about 60 to 1,300. Conditional branches are zero in every run."><img src="https://fzakaria.com/assets/figures/05fe041b70128dbb.svg" alt="Two panels of 120 runs each, plotting extra counts against the interrupts taken during the run. Instructions sit on a dashed line of one extra per interrupt, from about 60 to 1,300. Conditional branches are zero in every run." width="518" height="230">
</figure>

<p>The dashed line is <em>one extra count per interrupt</em>, and the instruction counter is almost perfectly on it.<sup id="fnref:slope"><a href="#fn:slope" class="footnote" rel="footnote" role="doc-noteref">3</a></sup> 
The conditional branch counter on the other hand, stays at zero no matter how many interrupts land.</p>

<p>Interrupts from the outside-world are not the only thing that can skew the instruction count. The program can also page fault, which is an interrupt too. The instruction counter sees the kernel’s detour to handle the fault, but the program does not.</p>

<blockquote class="alert alert-tip">
  <p><strong>Tip</strong>
Out of the box, AMD Zen also overcounts conditional branches, a few in tens of millions, from a speculation optimization known as SpecLockMap. The fix is to set a particular bit in the PMU MSR, which Rewind does automatically as does <a href="https://github.com/rr-debugger/rr/issues/2034">rr#2034</a>.</p>
</blockquote>

<h2 id="so-what-time-is-it">So, what time is it?</h2>

<p>In order to rewind history, we need a measurement of time that is reliable and deterministic. Our traditional wall-clock time is unreliable due to the effects of the outside world but we do have a reliable measurement of progress through the instruction stream: the conditional branch counter.</p>

<p>Using the conditional branch counter as a proxy for time turns out to be a relatively decent approximation.</p>

<table>
  <thead>
    <tr>
      <th>Clock</th>
      <th>Time inside the VM</th>
      <th>Time on the host</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Exit time</td>
      <td>2.1 s</td>
      <td>15.7 s</td>
    </tr>
    <tr>
      <td>Counter time</td>
      <td>11.7 s</td>
      <td>14.2 s</td>
    </tr>
  </tbody>
</table>

<p>Why do we care about having a “realistic” representation of time?</p>

<p>Plenty of programs read the clock and make decisions with it, so the guest’s clock has to be at least somewhat realistic. Under exit time, computing is “free”. A test that checks some work “finishes within 1 s” always passes. If the bug you’re chasing is a timeout, exit time will never reproduce it. 🙃</p>

<p>Races get skewed too with an unrealistic clock. With exit time, a whole burst of work lands in the same instant, which crowds the threads together, so a race can fire far more often in the VM than it ever would on real hardware.</p>

<p>The closer we can emulate the real world, the more likely we are to reproduce a bug that only happens in the real world. Counter time is a better approximation of the real world than exit time, and it is deterministic, so it is the default clock in Rewind.</p>

<p style="--image-width: 22rem"><a href="/assets/images/rewind_distracted_branches_meme.png"><img src="/assets/images/rewind_distracted_branches_meme.png" alt="Distracted boyfriend meme: the boyfriend, labelled &quot;Rewind's clock&quot;, turns to look at a woman labelled &quot;conditional branches&quot; while his girlfriend, labelled &quot;instructions retired&quot;, glares at him" /></a></p>

<p>Some say time is an illusion. I say it’s a <code class="language-plaintext highlighter-rouge">jnz</code> counter.</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:rr">
      <p>This is the same approach popularized by the <a href="https://rr-project.org/">rr</a> debugger. The <a href="https://arxiv.org/abs/1705.05937">rr paper</a> calls it <em>deterministic time</em>. <a href="#fnref:rr" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:exits">
      <p>The 5µs was my guess at a reasonable cost of a system call and context switch on current hardware. The 1ns is roughly what a conditional branch costs on a current core. <a href="#fnref:exits" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:slope">
      <p>The fit is 0.94 rather than 1 because <code class="language-plaintext highlighter-rouge">/proc/interrupts</code> also catches the interrupts that land while <code class="language-plaintext highlighter-rouge">perf</code> and <code class="language-plaintext highlighter-rouge">taskset</code> start up and tear down, before and after the loop runs. <a href="#fnref:slope" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[What is time inside a machine you want to replay? 🧘 When building Rewind, a deterministic VM, you come face-to-face with the idea of how to represent time very quickly. You need a way to measure time inside the guest so that on subsequent replays, the guest sees the same time and makes the same decisions. Time is the ultimate variable.]]></summary></entry><entry><title type="html">Reading the code is the hard part</title><link href="https://fzakaria.com/2026/10/28/reading-the-code-is-the-hard-part" rel="alternate" type="text/html" title="Reading the code is the hard part" /><published>2026-10-28T10:00:00-07:00</published><updated>2026-10-28T10:00:00-07:00</updated><id>https://fzakaria.com/2026/10/28/reading-the-code-is-the-hard-part</id><content type="html" xml:base="https://fzakaria.com/2026/10/28/reading-the-code-is-the-hard-part"><![CDATA[<p>I have been stress testing <a href="https://rewindvm.dev">Rewind VM</a>, a deterministic VM, to work through the kinks, bugs and <a href="https://en.wikipedia.org/wiki/Eating_your_own_dog_food">dog-fooding</a> the user-experience. Even having developed it myself, I continue to be wild-eye amazed at the magic of what it can do.</p>

<!--more-->

<p>Despite the magic, the ease of claiming to have a bug “reproduced deterministically”, and the ease of narrowing it down to a single step, the hard part is still reading the code and understanding why it failed. Rewind can tell you what went wrong, but it cannot read the code.</p>

<p>This is a particular area that is ripe for AI assistance. Agents can already read the code and often find bugs. Unsurprisingly, when given a wealth of reliable data about what went wrong, they can pinpoint the bug in a way that is much more efficient than reading the code alone. The combination of deterministic runs and AI agents is incredibly powerful. 🪄</p>

<p>Finding the bugs in Rewind is easy. <code class="language-plaintext highlighter-rouge">rewind check</code> replays a test, script, or binary under many different thread schedules until one fails, then narrows the failure down to the single step. That leaves you, though, with a step number and potentially a large codebase, one you are unfamiliar with. The hard part is reading the code and understanding why it failed.</p>

<p style="--image-width: 22rem"><a href="/assets/images/rewind_gru_plan_meme.png"><img src="/assets/images/rewind_gru_plan_meme.png" alt="Gru's plan meme: &quot;rewind check finds a failing schedule&quot;, &quot;It narrows it to step 2682&quot;, &quot;Now I read 3,000 lines of git&quot;, and Gru staring back at &quot;Now I read 3,000 lines of git?&quot;" /></a></p>

<p>Rewind can tell you what went wrong, but it cannot read the code for you. Rewind does however give you, <em>or an agent</em>, a lot of information about what went wrong. I pointed <a href="https://rewindvm.dev">Rewind VM</a> at a cornicopia of tools, and unsurprisingly, it found bugs…<em>many bugs</em>. The best part is that it found them in a way that is reproducible and debuggable, which has led to the agents also easily providing the fixes as well.<sup id="fnref:bugs"><a href="#fn:bugs" class="footnote" rel="footnote" role="doc-noteref">1</a></sup></p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
New to Rewind? Start with <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">a flaky build you only catch once</a> and <a href="/2026/10/24/dafuq-is-a-deterministic-vm">dafuq is a deterministic VM?</a></p>
</blockquote>

<p>This is a small example of a bug that Rewind found in git, and how I used Rewind to find the bug and the line of code that caused it. The bug is in <code class="language-plaintext highlighter-rouge">git notes</code>, which attaches a note to a commit without changing the commit. The bug is that two notes, on two different commits, at the same time, can lose one of the notes.<sup id="fnref:git"><a href="#fn:git" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></p>

<h2 id="the-bug">The bug</h2>

<p><a href="https://git-scm.com/docs/git-notes"><code class="language-plaintext highlighter-rouge">git notes</code></a> attaches a note to a commit without changing the commit.</p>

<p>We can start with an idea for a simple test<sup id="fnref:test"><a href="#fn:test" class="footnote" rel="footnote" role="doc-noteref">3</a></sup>: create two notes, on two different commits, at the same time concurrently.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git notes add <span class="nt">-m</span> <span class="s2">"note 1"</span> HEAD~0 &amp;
git notes add <span class="nt">-m</span> <span class="s2">"note 2"</span> HEAD~1 &amp;
<span class="nb">wait</span>

<span class="c"># both commands exited 0, so both notes should be there</span>
git notes show HEAD~0 <span class="o">&amp;&amp;</span> git notes show HEAD~1
</code></pre></div></div>

<div data-mark="5,7" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind check <span class="nt">--all</span> <span class="nt">--schedules</span> 32 <span class="nt">--property</span> exit-zero .#notes2
<span class="go">schedule   1: exited:1             3167 steps    run e5e5a1ecd0195f8f  violates exit-zero
schedule   2: exited:1             3312 steps    run ea6889e56564e374  violates exit-zero
</span><span class="c">...
</span><span class="go">15 of 32 other schedules violated a property

step 2682 decides it: a request to switch threads there makes the run violate exit-zero
</span></code></pre></div></div>

<p>When executed by Rewind, fifteen of thirty-two schedules lose a git-note, yet every <code class="language-plaintext highlighter-rouge">git notes add</code> still exits successfully.<sup id="fnref:normal"><a href="#fn:normal" class="footnote" rel="footnote" role="doc-noteref">4</a></sup></p>

<p>Now what?</p>

<h2 id="ask-the-runs-not-the-code">Ask the runs, not the code</h2>

<p>A run in Rewind is a full trace of the build: every process, every file it wrote, and any file’s contents at any step, that you replay to any point in time. <strong>That is a lot of data</strong>. Rewind does make it a little simpler to comb through the data though that help narrow the culprit.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/d0b7a17807cc3fe7.svg" alt="Three boxes in a row joined by arrows. One: what ended differently, a file, an output or an exit status. Two: who wrote it, the process and the step, which rewind blame answers. Three: which line wrote it, which rewind where answers." width="720" height="150">
</figure>

<p>None of those three commands knows anything about git, locks or races. They work on any program.</p>

<h3 id="what-ended-differently">What ended differently?</h3>

<p><code class="language-plaintext highlighter-rouge">rewind diff --outputs</code> compares the files the two runs left behind. This is like <a href="https://diffoscope.org/">diffoscope</a> but on steroids 💉: it can compare any two runs, and it can compare the files at any step in the run, not just the final outputs.<sup id="fnref:byte"><a href="#fn:byte" class="footnote" rel="footnote" role="doc-noteref">5</a></sup></p>

<div data-mark="4" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind diff <span class="nt">--outputs</span> 94c59fdf987c4944 ad0de5aec5a0be2d
<span class="go">3 of the 30 files the runs left behind differ:
  /build/r/.git/logs/refs/notes/commits: 36 of 465 bytes differ, first at byte 351
  /build/r/.git/refs/notes/commits: 36 of 41 bytes differ, first at byte 0
  /nix/store/014fz1lj7hmk5h3rzcaw0w4576md3bg9-git-notes2: only in the right run
</span></code></pre></div></div>

<p>Our clue is that <code class="language-plaintext highlighter-rouge">.git/refs/notes/commits</code> is the ref that points at the latest notes commit, and it points at different commits in the two runs.</p>

<h3 id="who-wrote-it-and-what-did-it-read">Who wrote it, and what did it read?</h3>

<p><code class="language-plaintext highlighter-rouge">rewind blame</code> takes two runs and a file:</p>

<div data-mark="5-8" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind blame 94c59fdf987c4944 ad0de5aec5a0be2d /build/r/.git/refs/notes/commits
<span class="go">commits differs at byte 0. git notes (pid 56) wrote that byte at step
2,751 in run 94c59fdf and at step 2,717 in run ad0de5ae.
</span><span class="c">...
</span><span class="go">Likely cause: git notes (pid 56) read /build/r/.git/refs/notes/commits
before git notes (pid 55) changed it at step 2,721 in run 94c59fdf,
and after that change in run ad0de5ae. It read an older version of
the file in run 94c59fdf.
</span></code></pre></div></div>

<p>In this example, Rewind has given us pretty close to the smoking gun. The second <code class="language-plaintext highlighter-rouge">git notes add</code> read the notes before the first one had saved its own, then saved its version over the top: a read-modify-write race.</p>

<p>We can visualize this exact step in the Rewind GUI at the deciding step: both <code class="language-plaintext highlighter-rouge">git notes add</code> processes are alive (top box), and the first is halfway through saving, with its lock file written but not yet renamed into place (bottom box).</p>

<p><a href="/assets/images/rewind-git-notes-race.png"><img src="/assets/images/rewind-git-notes-race-crop.png" alt="The Rewind app at step 2,682 of the failing run: a box around both git notes add processes in the process tree, and a box around refs/notes/commits.lock in the files list" /></a></p>

<h3 id="which-line-wrote-it">Which line wrote it?</h3>

<p>If we have access to debug symbols, which Nixpkgs provides,  <code class="language-plaintext highlighter-rouge">rewind where</code> shows where in git’s own code a process was at a step. Here is pid 56 when it wrote the ref:</p>

<div data-mark="10" class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind where 94c59fdf987c4944 2754 <span class="nt">--pid</span> 56 <span class="nt">--frames</span> 8
<span class="go">process 56 (git), thread 56, at step 2754
</span><span class="c">#1 rename_tempfile (tempfile.c:347)
</span><span class="go">called from #2 commit_lock_file_to (/build/source/lockfile.h:364)
called from #3 commit_lock_file (lockfile.c:358)
called from #4 commit_ref (refs/files-backend.c:1889)
called from #5 files_transaction_finish (refs/files-backend.c:3381)
called from #6 ref_transaction_commit (refs.c:2806)
called from #7 refs_update_ref (refs.c:1592)
called from #8 commit_notes (notes-utils.c:64)
</span></code></pre></div></div>

<p>We can then look at the code at a very specific line, and try to understand why it failed. 
In this case, <a href="https://github.com/git/git/blob/8d1b215c01512b9658d4525c54ff9b9245f9a7e8/notes-utils.c#L64"><code class="language-plaintext highlighter-rouge">notes-utils.c:64</code></a> updates the ref without checking that it still points where it did when the command loaded the notes with a lock.</p>

<p>Three questions, three commands, and I read one line of git. 🤓</p>

<h2 id="who-reads-all-of-this">Who reads all of this?</h2>

<p>The git notes failure is 2,936 steps and 1,937 events in one run, and <code class="language-plaintext highlighter-rouge">rewind check</code> made 33 runs. Going through one run is a lot of work, and going through all thirty-three is unrealistic.</p>

<p>Recently, a friend told me AI has been really useful for parsing the <a href="https://en.wikipedia.org/wiki/CAN_bus">CAN bus</a> of cars. The CAN bus is a firehose of messages from the car from every sensor, every button, every switch, and every light. LLMs have made managing the firehose of data easier.</p>

<p>I see the same emergence in Rewind. The run is also a firehose of events, and similarly, LLMs can help parse the firehose of events and find the bugs. Telling an LLM to investigate a bug with Rewind has been very effective. Narrowing the bug down to a single step and source lines, is especially helpful for an LLM as it keeps the context small and focused. At that point, the LLM can read the code and understand what went wrong, and very likely suggest a fix.</p>

<p>LLMs have a lot of stochasticity built into them. I have found that pairing them with more deterministic technologies such as <a href="https://nixos.org/">Nix</a> and Rewind makes them more effective. I’m very optimistic about the
leveraging the combination of deterministic runs and LLMs to find and fix bugs in large codebases.</p>

<p>LLMs induce many of these bugs but now they can also fix them. 🙃</p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:bugs">
      <p>You can find all the bugs on the <a href="https://rewindvm.dev/bugs.html">bugs page</a>. <a href="#fnref:bugs" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:git">
      <p>I submitted an <a href="https://lore.kernel.org/git/20261028-fz-notes-concurrent-write-v1-1-3d513e1fdbb7@gmail.com/T/#u">upstream patch</a> for the bug as well. <a href="#fnref:git" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:test">
      <p>This test demonstrates the race condition in <code class="language-plaintext highlighter-rouge">git notes</code> when adding notes concurrently. We can easily build this as a Nix derivation using <a href="https://nixos.org/manual/nix/stable/#sec-runcommand"><code class="language-plaintext highlighter-rouge">runCommand</code></a>. <a href="#fnref:test" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:normal">
      <p>On a normal Linux machine, 25 of 30 runs lose one too, so this is not a Rewind-onlybug. <a href="#fnref:normal" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:byte">
      <p>I have a <a href="/2026/10/23/who-wrote-this-byte">lengthier post</a> about how Rewind can help make your build bit-for-bit reproducible. <a href="#fnref:byte" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[I have been stress testing Rewind VM, a deterministic VM, to work through the kinks, bugs and dog-fooding the user-experience. Even having developed it myself, I continue to be wild-eye amazed at the magic of what it can do.]]></summary></entry><entry><title type="html">Dafuq is a deterministic VM?</title><link href="https://fzakaria.com/2026/10/24/dafuq-is-a-deterministic-vm" rel="alternate" type="text/html" title="Dafuq is a deterministic VM?" /><published>2026-10-24T10:00:00-07:00</published><updated>2026-10-24T10:00:00-07:00</updated><id>https://fzakaria.com/2026/10/24/dafuq-is-a-deterministic-vm</id><content type="html" xml:base="https://fzakaria.com/2026/10/24/dafuq-is-a-deterministic-vm"><![CDATA[<p><em>The life of a system call inside Rewind VM.</em></p>

<p>Since I started writing about <a href="https://rewindvm.dev">Rewind VM</a>, the question I get most from friends is not “does it work?” but “how does it <em>actually</em> work?” 🤔</p>

<p>D’uh! <u>It is a virtual machine that only gets interrupted when it asks to be</u>.</p>

<!--more-->

<p style="--image-width: 18rem"><a href="/assets/images/rewind_dafuq_meme.png"><img src="/assets/images/rewind_dafuq_meme.png" alt="Dafuq did I just read meme: Samuel Johnson squints at a book that says &quot;It is a VM that only gets interrupted when it asks to be&quot;, then looks up, baffled: &quot;Dafuq did I just read&quot;" /></a></p>

<p>That seems to not have helped much, so let’s go deeper.</p>

<p>We will follow a tiny C program through the machine and, at each step, look at where non-determinism would have crept in and what Rewind does about it.</p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
If you have not seen Rewind before, start with <a href="/2026/10/03/rewind-vm-a-flaky-build-you-only-catch-once">a flaky build you only catch once</a>.</p>
</blockquote>

<h2 id="life-is-deterministic">Life is deterministic</h2>

<p>CPUs must be deterministic. If they were not, we would have a very bad time trusting them to do anything.</p>

<p>Give a CPU the same registers, the same memory and the same instructions, and it computes the same result.</p>

<p>What does change? Why are machines not deterministic?</p>

<p>They are not closed systems. They interact with the outside world and that interaction is not deterministic. A timer interrupt can land at any instruction or a disk read can complete at any time.</p>

<blockquote class="alert alert-note">
  <p><strong>Aside:</strong>
Computers can’t actually make random numbers. A deterministic machine can only fake it with <em>pseudo</em>-randomness: run the same algorithm from the same seed and you get the same numbers back. The real stuff has to come from the physical world. My favorite example is how Cloudflare keeps <a href="https://www.cloudflare.com/learning/ssl/lava-lamp-encryption/">a wall of 100 lava lamps</a> in its San Francisco office with a camera pointed at it, feeding its encryption keys.</p>
</blockquote>

<p>If we could capture all external influences, we could replay the external world and get the same run again. That is what Rewind does.</p>

<p>Every source from the outside world is either removed or replaced with a value derived from a stored seed. Time, for instance, is a clock managed by Rewind. Interrupts arrive only at points we choose. ⏱️</p>

<p>One more outside influence is easy to miss: other CPUs. On two cores, which thread wins a race comes down to cache misses and pipeline stalls, so Rewind provides a single virtual CPU and the threads take turns on it.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/d9df1991fa0f2dff.svg" alt="Left: two cores run thread A and thread B at the same time, both reach the same lock at nearly the same moment, and which one wins depends on cache timing. Right: Rewind's single virtual CPU runs A, then B, then A, switching only at exits, in the same order every run." width="720" height="190">
</figure>

<h2 id="a-step-is-a-vm-exit">A step is a VM exit</h2>

<p>To control the outside world, Rewind needs moments where the software stops and Rewind can step in. At those moments it writes down what just happened, hands over the current time, or delivers an interrupt. So how do you stop the software at the same place on every run?</p>

<p>One answer is to make the hardware do it. CPUs have performance counters that can interrupt after a set number of instructions. 
Unfortunately, the interrupt may arrive a few instructions late, and the amount varies.<sup id="fnref:intel"><a href="#fn:intel" class="footnote" rel="footnote" role="doc-noteref">1</a></sup></p>

<p>Rewind uses a <em>cooperative</em> approach: let the software tell us when something happens!</p>

<p>Rewind runs the guest under KVM, the hypervisor built into Linux. The guest’s code runs directly on the real CPU until it touches a device. The CPU then stops the guest and hands control to the program running the VM, Rewind’s monitor (<code class="language-plaintext highlighter-rouge">rewind-vmm</code>). That hand-off is a <em>VM exit</em>.</p>

<p>Rewind patches the guest kernel so that whenever it needs something only the outside world has, such as the time, a timer, or “I have nothing to do”, it makes an exit and asks the monitor. Reporting what happened, like a process starting or a line of output, is an exit too.</p>

<p>Each exit the guest makes is called a <strong>step</strong>, and they are numbered starting from boot.</p>

<p>If we <strong>assume</strong> the guest is deterministic up to step <em>N</em>, step <em>N</em> happens at the same instruction on every run.</p>

<p>The monitor’s loop, sketched in Python:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">step</span><span class="p">,</span> <span class="n">clock</span><span class="p">,</span> <span class="n">deadline</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="bp">None</span>

<span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
    <span class="c1"># The guest runs natively until it exits.
</span>    <span class="nb">exit</span> <span class="o">=</span> <span class="n">vcpu</span><span class="p">.</span><span class="nf">run</span><span class="p">()</span>

    <span class="c1"># The host's own business: not a step, and nothing is sent.
</span>    <span class="k">if</span> <span class="nb">exit</span><span class="p">.</span><span class="n">reason</span> <span class="o">==</span> <span class="n">HOST_INTERRUPT</span><span class="p">:</span>
        <span class="k">continue</span>

    <span class="c1"># An exit the guest made. Time moves only here.
</span>    <span class="n">step</span> <span class="o">+=</span> <span class="mi">1</span>
    <span class="n">clock</span> <span class="o">+=</span> <span class="n">QUANTUM</span>

    <span class="c1"># Read the clock, arm a timer, log an event...
</span>    <span class="n">deadline</span> <span class="o">=</span> <span class="nf">handle</span><span class="p">(</span><span class="nb">exit</span><span class="p">,</span> <span class="n">step</span><span class="p">)</span>

    <span class="c1"># Interrupts go in only here, with the guest stopped.
</span>    <span class="k">if</span> <span class="n">deadline</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="n">clock</span> <span class="o">&gt;=</span> <span class="n">deadline</span><span class="p">:</span>
        <span class="n">vcpu</span><span class="p">.</span><span class="nf">inject</span><span class="p">(</span><span class="n">TIMER_INTERRUPT</span><span class="p">)</span>
        <span class="n">deadline</span> <span class="o">=</span> <span class="bp">None</span>
</code></pre></div></div>

<figure>
<img src="https://fzakaria.com/assets/figures/2351cc55e9b61677.svg" alt="Two runs of the same guest in a normal VM and two in Rewind, each drawn as a line of guest instructions with the guest's exits at the same five places. In the normal VM the timer interrupt lands between exits, at a different instruction in each run. In Rewind the interrupt is delivered at an exit, the same step in the recording and in the replay." width="720" height="330">
</figure>

<p>This is true on the first run too. Nothing gets recorded, and a replay just runs the same inputs again.</p>

<p>Three pieces make this work, and your program doesn’t need to know about any of them.</p>

<p><strong>A patched Linux kernel.</strong> The guest kernel is the piece that cooperates. A <a href="https://github.com/fzakaria/rewindvm/blob/main/guest/linux/rewind-guest.patch">small patch</a> teaches it to take its clock, its timer and its idle loop from the monitor instead of from hardware, and to report what processes do: exec, exit, output, files written. The monitor also hides the CPU features that would leak the outside world in, such as the hardware cycle counter and the random number instruction, so the kernel never uses them.</p>

<p><strong>rewind-init.</strong> The special PID 1 is a small program that mounts the input image (a Nix closure or a root filesystem), runs the command, reports its exit status and powers the machine off. The image is mapped straight into guest memory, so reading a file is reading memory, and there is no disk to finish a read at a random moment.</p>

<p><strong>rewind-vmm.</strong> The monitor owns time, decides when interrupts go in, and keeps the trace of everything the kernel reports.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/6d1763f5f4070bc1.svg" alt="Rewind VM's architecture. Inputs, a Nix closure or a root filesystem packed as erofs, go into the guest VM: one vCPU on stock KVM, running natively on the real CPU. Inside it are the build or test processes, rewind-init as PID 1, and a patched Linux kernel with the Rewind platform, whose clock, timer, idle and events go through the host. Each VM exit is one step down to the host's rewind-vmm, which owns time, ordering and memory: a virtual clock from exits and the branch count, an event trace, keyframes in a deduplicated page store, and seeded randomness, so the same inputs and seed give the same run. The monitor sends its interrupt back up only at an exit." width="680" height="600">
</figure>

<h2 id="the-life-of-a-system-call">The life of a system call</h2>

<p>Here is the program. It reads the clock, draws a random number, prints both with the address of a stack variable, sleeps for a second, then reads the clock again.</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;sys/random.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;time.h&gt;</span><span class="cp">
#include</span> <span class="cpf">&lt;unistd.h&gt;</span><span class="cp">
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">struct</span> <span class="n">timespec</span> <span class="n">ts</span><span class="p">;</span>
  <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">r</span><span class="p">;</span>

  <span class="n">clock_gettime</span><span class="p">(</span><span class="n">CLOCK_REALTIME</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">ts</span><span class="p">);</span>
  <span class="n">getrandom</span><span class="p">(</span><span class="o">&amp;</span><span class="n">r</span><span class="p">,</span> <span class="k">sizeof</span> <span class="n">r</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">"time=%ld.%09ld random=%u stack=%p</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">ts</span><span class="p">.</span><span class="n">tv_sec</span><span class="p">,</span> <span class="n">ts</span><span class="p">.</span><span class="n">tv_nsec</span><span class="p">,</span> <span class="n">r</span><span class="p">,</span> <span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">r</span><span class="p">);</span>
  <span class="n">fflush</span><span class="p">(</span><span class="n">stdout</span><span class="p">);</span>

  <span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>

  <span class="n">clock_gettime</span><span class="p">(</span><span class="n">CLOCK_REALTIME</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">ts</span><span class="p">);</span>
  <span class="n">printf</span><span class="p">(</span><span class="s">"time=%ld.%09ld</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">ts</span><span class="p">.</span><span class="n">tv_sec</span><span class="p">,</span> <span class="n">ts</span><span class="p">.</span><span class="n">tv_nsec</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>On my laptop every run prints something new. In Rewind, every run prints the same thing, down to the nanosecond, until you change the seed:</p>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>rewind run <span class="nt">--root</span> root <span class="nt">--</span> /bin/hello
<span class="go">time=1792886400.001006990 random=166963147 stack=0x7fff2bad5e4c
time=1792886401.001132684
rewind: run 85a03383f7d917d9 exited:0 after 432 steps, 1.002s virtual, 1.139s wall (poweroff)

</span><span class="gp">$</span><span class="w"> </span>rewind run <span class="nt">--root</span> root <span class="nt">--</span> /bin/hello
<span class="go">time=1792886400.001006990 random=166963147 stack=0x7fff2bad5e4c
time=1792886401.001132684
rewind: run 85a03383f7d917d9 exited:0 after 432 steps, 1.002s virtual, 0.394s wall (poweroff)

</span><span class="c"># a different seed is a different input, so a different run
</span><span class="gp">$</span><span class="w"> </span>rewind run <span class="nt">--root</span> root <span class="nt">--seed</span> 1 <span class="nt">--</span> /bin/hello
<span class="go">time=1792886400.001006990 random=2117056732 stack=0x7ffdd58e5bdc
time=1792886401.001132680
rewind: run 59c7da84895c210a exited:0 after 432 steps, 1.002s virtual, 0.848s wall (poweroff)
</span></code></pre></div></div>

<p style="--image-width: 22rem"><a href="/assets/images/rewind_same_picture_meme.png"><img src="/assets/images/rewind_same_picture_meme.png" alt="They're the same picture meme: Pam holds up two papers labelled &quot;the run that failed on CI&quot; and &quot;rewind replay of that run&quot;, and says &quot;They're the same picture.&quot;" /></a></p>

<p>Same inputs, same run id, same 432 steps. Oh, and the program slept for a second, yet the whole VM finished in 0.39 seconds. 🤓</p>

<p>Normally, reading the time never enters the kernel: a bit of code in every process reads a hardware counter directly. Rewind hides that counter, so the read goes to the kernel, and the kernel asks the monitor.</p>

<figure>
<img src="https://fzakaria.com/assets/figures/bebabefcc874f6c7.svg" alt="A sequence diagram of clock_gettime in Rewind across four lanes: hello in user space, the guest kernel, KVM in the host kernel, and rewind-vmm on the host. hello makes a system call because there is no hardware counter to read. The guest kernel reads the clock port, which makes KVM exit to rewind-vmm. The monitor counts a step, adds 5 microseconds plus the work done to its clock, leaves the time in memory the guest can read, and sends an interrupt if a timer is due. It resumes the guest, and the kernel returns the time to hello." width="760" height="470">
</figure>

<p>Rewind hides the CPU’s random number instruction, so the only thing
available to the guest kernel is the seed Rewind passes at boot. The kernel’s random number generator is seeded with that value, so every run of the same program with the same seed gets the same random numbers.</p>

<p>Most system calls never leave the guest. The few that need the outside world make an exit, and the monitor writes down what happened. The guest kernel also reports when it is idle, so the monitor can jump its clock to the next timer interrupt.<sup id="fnref:sleep"><a href="#fn:sleep" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></p>

<p>Control those few doors and the guest is deterministic: the outside world shows up at the same step on every run.</p>

<p>So, dafuq is a deterministic VM? Like I said at the start, it’s a VM that only gets interrupted when it asks to be. Hopefully that makes a bit more sense now. 😅</p>

<p style="--image-width: 22rem"><a href="/assets/images/rewind_expanding_brain_meme.png"><img src="/assets/images/rewind_expanding_brain_meme.png" alt="Expanding brain meme: &quot;Re-run the flaky test until it passes&quot;, &quot;Add sleep(1) before the assert&quot;, &quot;Record where every interrupt landed and replay it&quot;, and, brightest, &quot;Only take an interrupt when the guest asks for one&quot;" /></a></p>
<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:intel">
      <p>Intel’s counter is good enough that you can single-step the rest of the way to the exact instruction. I have an AMD laptop. 🙃 <a href="#fnref:intel" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:sleep">
      <p><code class="language-plaintext highlighter-rouge">sleep(N)</code> costs no real time. The monitor jumps its clock straight to the deadline and delivers the timer interrupt. <a href="#fnref:sleep" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Farid Zakaria</name></author><summary type="html"><![CDATA[The life of a system call inside Rewind VM. Since I started writing about Rewind VM, the question I get most from friends is not “does it work?” but “how does it actually work?” 🤔 D’uh! It is a virtual machine that only gets interrupted when it asks to be.]]></summary></entry></feed>