<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-us"><generator uri="https://gohugo.io/" version="0.170.0">Hugo</generator><title type="html">Unsafe on sunshowers</title><subtitle type="html">thoughts and ideas</subtitle><link href="https://sunshowers.io/tags/unsafe/" rel="alternate" type="text/html" title="html"/><link href="https://sunshowers.io/tags/unsafe/index.xml" rel="alternate" type="application/rss+xml" title="rss"/><link href="https://sunshowers.io/tags/unsafe/atom.xml" rel="self" type="application/atom+xml" title="atom"/><updated>2026-11-15T23:03:09+00:00</updated><rights>© Rain 2020-present. Licensed under CC BY-NC-SA 4.0 unless marked otherwise.</rights><author><name>Rain</name></author><id>https://sunshowers.io/tags/unsafe/</id><entry><title type="html">iddqd, or the hardest kind of unsafe Rust</title><link href="https://sunshowers.io/posts/iddqd-unsafe/?utm_source=atom_feed" rel="alternate" type="text/html"/><link href="https://sunshowers.io/posts/on-poisoning/?utm_source=atom_feed" rel="related" type="text/html" title="In defense of lock poisoning in Rust"/><link href="https://sunshowers.io/posts/socketaddrv6-not-roundtrip/?utm_source=atom_feed" rel="related" type="text/html" title="`SocketAddrV6` is not roundtrip serializable"/><link href="https://sunshowers.io/posts/cancelling-async-rust/?utm_source=atom_feed" rel="related" type="text/html" title="Cancelling async Rust"/><link href="https://sunshowers.io/posts/nextest-process-per-test/?utm_source=atom_feed" rel="related" type="text/html" title="Why nextest is process-per-test"/><link href="https://sunshowers.io/posts/open-closed-universes/?utm_source=atom_feed" rel="related" type="text/html" title="Open and closed universes"/><id>https://sunshowers.io/posts/iddqd-unsafe/</id><published>2026-06-02T00:00:00+00:00</published><updated>2026-06-16T00:00:00+00:00</updated><content type="html"><![CDATA[<blockquote>How Oxide&rsquo;s Rust collections library defends against adversarial trait implementations.</blockquote><p><em>Mirrored from the canonical version on the <a href="https://oxide.computer/blog/iddqd-unsafe">Oxide blog</a>.</em></p>
<p><em>Update 2026-06-16</em>: I talked about this post on <em>Oxide and Friends</em>, in an episode titled <em>The Hardest Kind of Unsafe Rust</em>. Check it out on <a href="https://www.youtube.com/watch?v=mdcu3dKMjyg">YouTube</a>, <a href="https://oxide-and-friends.transistor.fm/episodes/the-hardest-kind-of-unsafe-rust">Transistor</a>, or wherever else you get your podcasts.</p>
<hr>
<p>I&rsquo;m the main author of <a href="https://docs.rs/iddqd"><code>iddqd</code></a>, a Rust library for maps (named after the <a href="https://doomwiki.org/wiki/Doom_cheat_codes#All_Doom_engine_versions">Doom cheat code</a>) where keys are borrowed from values. At <a href="https://oxide.computer/">Oxide</a> we use it extensively in <a href="https://github.com/oxidecomputer/omicron">Omicron</a>, our control plane—the software that <a href="https://rfd.shared.oxide.computer/rfd/0048">sits</a> at the heart of every Oxide rack, provisions resources like compute and storage for our customers, and ensures the rack stays up and running over time. <code>iddqd</code> maintains in-memory indexes of the kinds of large records that show up everywhere in a system like that, such as <a href="https://github.com/oxidecomputer/omicron/blob/2e319eb3b9b9fcffb8cee71cffb9cd13397cb316/sled-agent/config-reconciler/src/internal_disks.rs#L602-L637">disks</a> or <a href="https://github.com/oxidecomputer/omicron/blob/2e319eb3b9b9fcffb8cee71cffb9cd13397cb316/nexus/types/src/inventory.rs#L682-L717">sled inventories</a>. As a result, it must be correct: if it misbehaves, our control plane can malfunction in ways that are unpredictable and hard to diagnose.</p>
<p><code>iddqd</code> consists of a fair amount of unsafe code underneath. There&rsquo;s been <a href="https://github.com/oven-sh/bun/issues/30719">some recent concern</a> over the amount of unsafe code in Rust rewrites, so I thought I&rsquo;d write about some of the unsafe code in <code>iddqd</code> and how we try to tame it.</p>
<h2 id="what-problem-does-iddqd-solve">What problem does iddqd solve?</h2>
<p>With Rust&rsquo;s standard library maps, keys are stored separately from values. Let&rsquo;s say you want to store a map of records keyed by an email address. With <a href="https://doc.rust-lang.org/std/collections/struct.BTreeMap.html"><code>std::collections::BTreeMap</code></a>, you might write something like:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// Email is typically a newtype which validates that the email address is well-formed.
</span></span></span><span class="line"><span class="cl"><span class="c1">// In this example, we alias it to String for simplicity.
</span></span></span><span class="line"><span class="cl"><span class="k">type</span> <span class="nc">Email</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">String</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">struct</span> <span class="nc">User</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">name</span>: <span class="nb">String</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">age</span>: <span class="kt">u8</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">users</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">BTreeMap</span>::<span class="o">&lt;</span><span class="n">Email</span><span class="p">,</span><span class="w"> </span><span class="n">User</span><span class="o">&gt;</span>::<span class="n">new</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">users</span><span class="p">.</span><span class="n">insert</span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="s">&#34;alice@example.com&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">User</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">name</span>: <span class="s">&#34;Alice&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w"> </span><span class="n">age</span>: <span class="mi">30</span><span class="w"> </span><span class="p">},</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">users</span><span class="p">.</span><span class="n">insert</span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="s">&#34;bob@example.com&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">User</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">name</span>: <span class="s">&#34;Bob&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w"> </span><span class="n">age</span>: <span class="mi">35</span><span class="w"> </span><span class="p">},</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">);</span><span class="w">
</span></span></span></code></pre></div><p>This approach has what I consider to be a pretty major downside: the key (email) is not stored in the same struct as the value (the rest of the record). How would you handle this? One way is to pass around both the email and the user, for example with <a href="https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.get_key_value"><code>get_key_value</code></a>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">process_user</span><span class="p">(</span><span class="n">email</span>: <span class="kp">&amp;</span><span class="nc">Email</span><span class="p">,</span><span class="w"> </span><span class="n">user</span>: <span class="kp">&amp;</span><span class="nc">User</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="cm">/* ... */</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="p">(</span><span class="n">email</span><span class="p">,</span><span class="w"> </span><span class="n">user</span><span class="p">)</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">users</span><span class="p">.</span><span class="n">get_key_value</span><span class="p">(</span><span class="s">&#34;alice@example.com&#34;</span><span class="p">).</span><span class="n">unwrap</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">process_user</span><span class="p">(</span><span class="n">email</span><span class="p">,</span><span class="w"> </span><span class="n">user</span><span class="p">);</span><span class="w">
</span></span></span></code></pre></div><p>As an extension, you could maybe have a struct which combines both at fetch time:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">struct</span> <span class="nc">UserRecord</span><span class="o">&lt;</span><span class="na">&#39;a</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">email</span>: <span class="kp">&amp;</span><span class="na">&#39;a</span> <span class="nc">Email</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">user</span>: <span class="kp">&amp;</span><span class="na">&#39;a</span> <span class="nc">User</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="p">(</span><span class="n">email</span><span class="p">,</span><span class="w"> </span><span class="n">user</span><span class="p">)</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">users</span><span class="p">.</span><span class="n">get_key_value</span><span class="p">(</span><span class="s">&#34;alice@example.com&#34;</span><span class="p">).</span><span class="n">unwrap</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">record</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">UserRecord</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">email</span><span class="p">,</span><span class="w"> </span><span class="n">user</span><span class="w"> </span><span class="p">};</span><span class="w">
</span></span></span></code></pre></div><p>In practice, this gets quite unwieldy when you have lots of different types of records that need this kind of treatment.</p>
<p>Alternatively, you could duplicate the email across the key and the value:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">struct</span> <span class="nc">User</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">email</span>: <span class="nc">Email</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">name</span>: <span class="nb">String</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">age</span>: <span class="kt">u8</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">users</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">BTreeMap</span>::<span class="o">&lt;</span><span class="n">Email</span><span class="p">,</span><span class="w"> </span><span class="n">User</span><span class="o">&gt;</span>::<span class="n">new</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">email</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">&#34;alice@example.com&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">users</span><span class="p">.</span><span class="n">insert</span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">email</span><span class="p">.</span><span class="n">clone</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">User</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">email</span><span class="p">,</span><span class="w"> </span><span class="n">name</span>: <span class="s">&#34;Alice&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w"> </span><span class="n">age</span>: <span class="mi">30</span><span class="w"> </span><span class="p">},</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">);</span><span class="w">
</span></span></span></code></pre></div><p>But that has the risk that the emails stored in the key and the value fall out of sync.</p>
<p><code>iddqd</code> provides a better alternative. With <a href="https://docs.rs/iddqd/latest/iddqd/struct.IdOrdMap.html"><code>IdOrdMap</code></a>, you can write something like:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">struct</span> <span class="nc">User</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">email</span>: <span class="nc">Email</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">name</span>: <span class="nb">String</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">age</span>: <span class="kt">u8</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="c1">// You implement a trait which tells iddqd how to extract the key from the
</span></span></span><span class="line"><span class="cl"><span class="c1">// record.
</span></span></span><span class="line"><span class="cl"><span class="k">impl</span><span class="w"> </span><span class="n">IdOrdItem</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">User</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// The key type can borrow from the value!
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">type</span> <span class="nc">Key</span><span class="o">&lt;</span><span class="na">&#39;a</span><span class="o">&gt;</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="o">&amp;</span><span class="na">&#39;a</span><span class="w"> </span><span class="n">Email</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">fn</span> <span class="nf">key</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nc">Self</span>::<span class="n">Key</span><span class="o">&lt;</span><span class="nb">&#39;_</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="o">&amp;</span><span class="bp">self</span><span class="p">.</span><span class="n">email</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// This macro expands into a small amount of boilerplate to work around
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// a Rust borrow checker limitation.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="fm">id_upcast!</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="c1">// Then, you can insert records:
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">users</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">IdOrdMap</span>::<span class="o">&lt;</span><span class="n">User</span><span class="o">&gt;</span>::<span class="n">new</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">users</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">.</span><span class="n">insert_unique</span><span class="p">(</span><span class="n">User</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">email</span>: <span class="s">&#34;alice@example.com&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">name</span>: <span class="s">&#34;Alice&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">age</span>: <span class="mi">30</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">})</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">.</span><span class="n">unwrap</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">users</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">.</span><span class="n">insert_unique</span><span class="p">(</span><span class="n">User</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">email</span>: <span class="s">&#34;bob@example.com&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">name</span>: <span class="s">&#34;Bob&#34;</span><span class="p">.</span><span class="n">to_string</span><span class="p">(),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">age</span>: <span class="mi">35</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">})</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">.</span><span class="n">unwrap</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="c1">// And look them up by email:
</span></span></span><span class="line"><span class="cl"><span class="fm">assert_eq!</span><span class="p">(</span><span class="o">&amp;</span><span class="n">users</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#34;alice@example.com&#34;</span><span class="p">).</span><span class="n">unwrap</span><span class="p">().</span><span class="n">name</span><span class="p">,</span><span class="w"> </span><span class="s">&#34;Alice&#34;</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="fm">assert_eq!</span><span class="p">(</span><span class="n">users</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#34;bob@example.com&#34;</span><span class="p">).</span><span class="n">unwrap</span><span class="p">().</span><span class="n">age</span><span class="p">,</span><span class="w"> </span><span class="mi">35</span><span class="p">);</span><span class="w">
</span></span></span></code></pre></div><p>At Oxide, this has proven to be an invaluable pattern: many of the records in our control plane are quite large (think database lookups), and <code>iddqd</code> is a great fit for them. It also comes with several other features that directly address pain points we&rsquo;ve dealt with at Oxide. A few worth calling out:</p>
<ul>
<li><a href="https://docs.rs/iddqd/latest/iddqd/#examples">First-class support</a> for complex keys that borrow from more than one field, without having to resort to <a href="https://github.com/sunshowers-code/borrow-complex-key-example">workarounds like dynamic dispatch</a>.</li>
<li>Maps with <a href="https://docs.rs/iddqd/latest/iddqd/struct.BiHashMap.html">two</a> or <a href="https://docs.rs/iddqd/latest/iddqd/struct.TriHashMap.html">three</a> keys per item, each independently indexing the same record, without the usual pattern of maintaining multiple maps by hand.</li>
<li>Serde implementations that <a href="https://docs.rs/iddqd/latest/iddqd/struct.IdOrdMap.html#impl-Serialize-for-IdOrdMap%3CT%3E">serialize</a> as sequences rather than maps, so that non-string keys can be serialized in JSON<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>. Importantly, these implementations reject duplicate keys. (For backwards compatibility, serialization as maps is <a href="https://docs.rs/iddqd/latest/iddqd/id_ord_map/struct.IdOrdMapAsMap.html">also supported</a>.)</li>
</ul>
<p>Like many of our other crates, <code>iddqd</code> is built for Oxide&rsquo;s needs but is generally useful to the Rust community. You&rsquo;re <a href="https://crates.io/crates/iddqd">welcome</a> to use it in your own projects as well.</p>
<h2 id="on-unsafe-rust">On unsafe Rust</h2>
<p>Before I move on, I want to talk about what it means for <code>unsafe</code> to exist in a memory-safe language. The big concern is <a href="https://doc.rust-lang.org/reference/behavior-considered-undefined.html"><strong>undefined behavior</strong></a> (UB): a program behaves in an unpredictable way because core assumptions made by the language or compiler have been violated. Rust calls an abstraction <em>sound</em> if no safe code can use it to cause UB, and <em>unsound</em> otherwise.</p>
<p>The vast majority of Rust code is safe, which (assuming that any unsafe used by the safe code is sound) means that no UB can occur. However, due to the fundamental undecidability of static analysis (see <a href="https://en.wikipedia.org/wiki/Rice%27s_theorem">Rice&rsquo;s theorem</a>), it is impossible for the Rust compiler—or any kind of algorithm that terminates—to accept all programs without UB and reject all programs with it. Therefore, when writing such an algorithm, its authors have to make a decision: do they reject some programs without UB, accept some programs with UB, or both? The Rust compiler does the first: within the context of safe Rust, it rejects all programs with UB but also some without UB. (This is the correct choice!)</p>
<p>What if your program is in the no-man&rsquo;s-land where it gets rejected even though you know it doesn&rsquo;t have UB? To express those kinds of programs, the Rust compiler provides an escape hatch: the <code>unsafe</code> keyword. By writing it, the author takes responsibility for soundness: they vouch that no safe code can use this to cause UB, and that the compiler should trust them.</p>
<p>What does it mean for some unsafe code to not have UB? Informally, it must follow <a href="https://cacm.acm.org/research/safe-systems-programming-in-rust/">the rules of Rust</a>—all the rules that the compiler proves for safe Rust. Some examples of these rules are:</p>
<ul>
<li>There are no data races.</li>
<li>There must be no reads of uninitialized or freed memory.</li>
<li>There must not ever be multiple aliases of <code>&amp;mut</code> references to the same region of memory.</li>
<li>Immutable data must not be mutated.</li>
</ul>
<p>The rules of Rust are very hard to reason about! I consider them to be significantly harder than C, for example, particularly due to the rules around mutable aliasing<sup id="fnref:2"><a href="#fn:2" class="footnote-ref" role="doc-noteref">2</a></sup>. So judicious use of unsafe Rust usually involves encapsulating it behind a safe abstraction.</p>
<h3 id="unsafe-rust-requires-reasoning-about-safe-rust">Unsafe Rust requires reasoning about safe Rust</h3>
<p>In all but the simplest of cases, it is not possible to be sure that such an abstraction is sound without also reasoning about the surrounding safe Rust. In this section, I&rsquo;ll walk through three examples in increasing order of difficulty.</p>
<p>The first example is the <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.split_at_mut"><code>split_at_mut</code> method</a> on slices. This method splits a mutable slice into two separate parts. <code>split_at_mut</code> is a safe method, but safe Rust lacks the ability to express this kind of partitioning of a slice. Thus, <code>split_at_mut</code> requires unsafe Rust.</p>
<p>The implementation is roughly:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">split_at_mut</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="p">(</span><span class="n">slice</span>: <span class="kp">&amp;</span><span class="nc">mut</span><span class="w"> </span><span class="p">[</span><span class="n">T</span><span class="p">],</span><span class="w"> </span><span class="n">mid</span>: <span class="kt">usize</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="p">[</span><span class="n">T</span><span class="p">],</span><span class="w"> </span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="p">[</span><span class="n">T</span><span class="p">])</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="fm">assert!</span><span class="p">(</span><span class="n">mid</span><span class="w"> </span><span class="o">&lt;=</span><span class="w"> </span><span class="n">slice</span><span class="p">.</span><span class="n">len</span><span class="p">());</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="n">ptr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">slice</span><span class="p">.</span><span class="n">as_mut_ptr</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="n">remaining</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">slice</span><span class="p">.</span><span class="n">len</span><span class="p">()</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">mid</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">unsafe</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">(</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">std</span>::<span class="n">slice</span>::<span class="n">from_raw_parts_mut</span><span class="p">(</span><span class="n">ptr</span><span class="p">,</span><span class="w"> </span><span class="n">mid</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">std</span>::<span class="n">slice</span>::<span class="n">from_raw_parts_mut</span><span class="p">(</span><span class="n">ptr</span><span class="p">.</span><span class="n">add</span><span class="p">(</span><span class="n">mid</span><span class="p">),</span><span class="w"> </span><span class="n">remaining</span><span class="p">),</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>To be sure of the correctness of the unsafe block, you also have to consider several things about the surrounding safe code:</p>
<ul>
<li>that the function was provided a <code>&amp;mut [T]</code>, and not, for example, a <code>&amp;[T]</code></li>
<li>the <code>assert!</code> ensuring that <code>mid</code> is in bounds</li>
<li>the fact that <code>remaining</code> is <code>slice.len() - mid</code>, and not, for example, <code>(slice.len() - mid) + 1</code></li>
</ul>
<p>If any of these invariants (all of which are safe Rust) are not upheld, the safe abstraction becomes unsound.</p>
<p>The next level up is that in many cases you also have to analyze the <em>entire module</em> the unsafe code is present in. Consider this vector type:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">struct</span> <span class="nc">MyVec</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">ptr</span>: <span class="nc">NonNull</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">len</span>: <span class="kt">usize</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">cap</span>: <span class="kt">usize</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">impl</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="n">MyVec</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">get</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">,</span><span class="w"> </span><span class="n">i</span>: <span class="kt">usize</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nb">Option</span><span class="o">&lt;&amp;</span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="bp">self</span><span class="p">.</span><span class="n">len</span><span class="p">).</span><span class="n">then</span><span class="p">(</span><span class="o">||</span><span class="w"> </span><span class="k">unsafe</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="o">&amp;*</span><span class="bp">self</span><span class="p">.</span><span class="n">ptr</span><span class="p">.</span><span class="n">as_ptr</span><span class="p">().</span><span class="n">add</span><span class="p">(</span><span class="n">i</span><span class="p">)</span><span class="w"> </span><span class="p">})</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>The soundness of <code>get</code> relies on <strong>every other method</strong> in the module, safe and unsafe, ensuring that <code>len</code> is correct and in bounds. Encapsulation and privacy (<code>len</code> cannot be mutated from outside the module) are load-bearing here.</p>
<p>The hardest situations, though, are when unsafe code is generic and calls back into user-supplied code. In those cases, the <a href="https://doc.rust-lang.org/nomicon/safe-unsafe-meaning.html">fundamental principle</a> is:</p>
<p><em>Safe Rust code, no matter how pathological or adversarially written, must never cause unsafe code to exhibit undefined behavior.</em></p>
<p>In other words, you no longer have the luxury of analyzing just the safe code you see; you must put yourself in the shoes of an attacker, considering every safe Rust program one could write, and be resilient to <em>all</em> of them. For example, it is possible for user code to misbehave in a way that leads to internal tables or data structures being corrupted. Safe but buggy Rust may cause unsafe Rust to be slower, produce incorrect results, or even panic, but it must not cause UB!</p>
<p>(Why assume the worst? You might argue that well-meaning Rust developers are quite unlikely to write adversarial code. One reason for having a firm rule is that guarding against adversarial code means guarding against innocent mistakes as a corollary; a bright line makes it easier to assign responsibility for protection against UB.)</p>
<p>An example is the <a href="https://doc.rust-lang.org/std/iter/trait.ExactSizeIterator.html"><code>ExactSizeIterator</code></a> trait, which has a <code>len</code> method that returns the exact size of an iterator. A developer might be tempted to take advantage of this in unsafe Rust:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">collect_exact</span><span class="o">&lt;</span><span class="n">T</span><span class="p">,</span><span class="w"> </span><span class="n">I</span>: <span class="nb">ExactSizeIterator</span><span class="o">&lt;</span><span class="n">Item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">T</span><span class="o">&gt;&gt;</span><span class="p">(</span><span class="n">iter</span>: <span class="nc">I</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nc">MyVec</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">iter</span><span class="p">.</span><span class="n">len</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">v</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">MyVec</span>::<span class="n">with_capacity</span><span class="p">(</span><span class="n">n</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="n">i</span><span class="p">,</span><span class="w"> </span><span class="n">item</span><span class="p">)</span><span class="w"> </span><span class="k">in</span><span class="w"> </span><span class="n">iter</span><span class="p">.</span><span class="n">enumerate</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">unsafe</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">std</span>::<span class="n">ptr</span>::<span class="n">write</span><span class="p">(</span><span class="n">v</span><span class="p">.</span><span class="n">ptr</span><span class="p">.</span><span class="n">as_ptr</span><span class="p">().</span><span class="n">add</span><span class="p">(</span><span class="n">i</span><span class="p">),</span><span class="w"> </span><span class="n">item</span><span class="p">);</span><span class="w"> </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">v</span><span class="p">.</span><span class="n">len</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">n</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">v</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>This code does not cause UB if the iterator is well-behaved. But there&rsquo;s no guarantee of such behavior! It is entirely possible to write a broken <code>ExactSizeIterator</code> implementation that returns a bogus result, all in safe Rust:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">struct</span> <span class="nc">BadIterator</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">remaining</span>: <span class="kt">usize</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">impl</span><span class="w"> </span><span class="nb">Iterator</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">BadIterator</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">type</span> <span class="nc">Item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kt">u32</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">fn</span> <span class="nf">next</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="bp">self</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nb">Option</span><span class="o">&lt;</span><span class="kt">u32</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">remaining</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="mi">0</span><span class="p">).</span><span class="n">then</span><span class="p">(</span><span class="o">||</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="bp">self</span><span class="p">.</span><span class="n">remaining</span><span class="w"> </span><span class="o">-=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="mi">42</span><span class="w"> </span><span class="p">})</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">impl</span><span class="w"> </span><span class="nb">ExactSizeIterator</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">BadIterator</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">fn</span> <span class="nf">len</span><span class="p">(</span><span class="o">&amp;</span><span class="bp">self</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="kt">usize</span> <span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="mi">0</span><span class="w"> </span><span class="c1">// but this actually yields `self.remaining` items!
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p><code>collect_exact</code> will write into unallocated memory in this case, so it is unsound in general<sup id="fnref:3"><a href="#fn:3" class="footnote-ref" role="doc-noteref">3</a></sup>.</p>
<p>Another example is the <a href="https://doc.rust-lang.org/std/io/trait.Read.html"><code>std::io::Read</code> trait</a>, where a safe but buggy <code>Read</code> implementation can return the wrong number of bytes read. See <a href="https://github.com/rust-lang/rfcs/blob/master/text/2930-read-buf.md">Rust RFC 2930</a> for more discussion about this.</p>
<p><code>iddqd</code> is in exactly this situation: it consists of generic data structures which call into user-supplied code, so it is working at this highest level of difficulty<sup id="fnref:4"><a href="#fn:4" class="footnote-ref" role="doc-noteref">4</a></sup>.</p>
<h2 id="how-iddqd-works">How iddqd works</h2>
<p><code>iddqd</code>&rsquo;s architecture is pretty straightforward: it uses a combination of a list of items (internally called an <code>ItemSet</code>) and a table with indexes into the slots. For example, <a href="https://docs.rs/iddqd/latest/iddqd/struct.IdHashMap.html"><code>IdHashMap&lt;T&gt;</code></a> consists of:</p>
<ul>
<li>an <code>ItemSet&lt;T&gt;</code>, which (similar to the <a href="https://docs.rs/slab"><code>slab</code> crate</a>) internally has:
<ul>
<li>a <code>Vec&lt;ItemSlot&lt;T&gt;&gt;</code>, where <code>ItemSlot&lt;T&gt;</code> is an enum with two variants:
<ul>
<li><code>Occupied(T)</code></li>
<li><code>Vacant { next: ItemIndex }</code> (where <code>ItemIndex</code> represents an integer index into the <code>Vec&lt;ItemSlot&lt;T&gt;&gt;</code>)</li>
</ul>
</li>
<li>a <code>free_head: ItemIndex</code>, which points to either the most recently freed <code>Vacant</code> slot, or is a sentinel (marked as <code>SENT</code> in the diagrams below) indicating that no free vacant slots are available. (The combination of <code>free_head</code> and the <code>Vacant</code> slots forms a <em>free chain</em>.)</li>
</ul>
</li>
<li>a <a href="https://docs.rs/hashbrown/latest/hashbrown/struct.HashTable.html"><code>hashbrown::HashTable</code></a> over <code>ItemIndex</code> (<code>hashbrown</code> is the fast hash table implementation used by the standard library)</li>
</ul>
<p>For example, an <code>IdHashMap</code> holding three items might look like the diagram below. The top row is the hash table over <code>ItemIndex</code>; the middle row is the <code>Vec&lt;ItemSlot&lt;T&gt;&gt;</code>.</p>

  <figure class="center" >
    
    <img src="/images/iddqd/iddqd-diagram-01.svg"  alt="An IdHashMap holding three items. The top row is a hash table mapping hash(k₁) → 0, hash(k₀) → 3, and hash(k₂) → 4. The middle row is the item vector: slot 0 Occupied(t₁), slot 1 Vacant (next: SENT), slot 2 Vacant (next: 1), slot 3 Occupied(t₀), slot 4 Occupied(t₂). free_head points to slot 2."   />
    
    
  </figure>


<p>Adding a new item consists of checking <code>free_head</code> to see if any <code>Vacant</code> slots are available. If so, we read the <code>next</code> index out of that <code>Vacant</code> slot, overwrite the slot with <code>Occupied(...)</code>, then set <code>free_head</code> to the <code>next</code> value we read. Otherwise, we push a new <code>Occupied</code> slot to the end. Finally, the hash table is updated, fetching the key and computing the hash, then recording the new index in the hash table.</p>
<p>Starting from the state above: Let&rsquo;s say we want to insert a new item <code>t₃</code>. Calling <code>insert(t₃)</code> recycles slot <code>2</code> from the free chain, advances <code>free_head</code> to <code>1</code>, and records the new hash entry:</p>

  <figure class="center" >
    
    <img src="/images/iddqd/iddqd-diagram-02.svg"  alt="The same IdHashMap after inserting t₃. Slot 2 is recycled from the free chain and now holds Occupied(t₃), and a new hash entry hash(k₃) → 2 is added. free_head advances to slot 1."   />
    
    
  </figure>


<p>Removing an item given a key involves this process in reverse: first, consult the hash table using the hash computed from the key, and remove the found index from the hash table. With the index in hand, replace the <code>ItemSlot</code> with <code>Vacant</code>, setting the internal <code>next</code> to the current value of <code>free_head</code>. Finally, set <code>free_head</code> to the index that was just replaced with <code>Vacant</code>.</p>
<p>Continuing from the post-insert state above: Calling <code>remove(k₀)</code> drops the hash entry for <code>k₀</code>, marks slot <code>3</code> as <code>Vacant</code> with its <code>next</code> pointing at the old <code>free_head</code> (<code>1</code>), and updates <code>free_head</code> to <code>3</code>:</p>

  <figure class="center" >
    
    <img src="/images/iddqd/iddqd-diagram-04.svg"  alt="The IdHashMap after removing k₀. The hash entry for k₀ is dropped, slot 3 becomes Vacant with next pointing at the old free_head (1), and free_head updates to 3."   />
    
    
  </figure>


<p>This pattern generalizes to the other map types:</p>
<ul>
<li><a href="https://docs.rs/iddqd/latest/iddqd/struct.IdOrdMap.html"><code>IdOrdMap</code></a> follows a similar structure, except the hash table is replaced with a <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/src/support/btree_table.rs">B-tree index</a><sup id="fnref:5"><a href="#fn:5" class="footnote-ref" role="doc-noteref">5</a></sup>.</li>
<li><a href="https://docs.rs/iddqd/latest/iddqd/struct.BiHashMap.html"><code>BiHashMap</code></a> and <a href="https://docs.rs/iddqd/latest/iddqd/struct.TriHashMap.html"><code>TriHashMap</code></a> store two and three hash tables respectively.</li>
</ul>
<h2 id="unsafe-rust-in-iddqd">Unsafe Rust in iddqd</h2>
<p><code>iddqd</code> has a few different kinds of unsafe Rust within it. Most uses of unsafe follow <a href="https://github.com/oxidecomputer/iddqd/blob/1588c91bb7d120f9175533c0f36fdcf58c84f13c/crates/iddqd/src/support/borrow.rs#L18">well-established patterns</a> also used <a href="https://github.com/rust-lang/rust/blob/c854ac880bf68671f56e6a28e4ff5cb7e92da62c/library/alloc/src/collections/btree/borrow.rs#L14">within Rust&rsquo;s standard library</a>—these are not dependent on user code, and a sufficiently smart borrow checker would make these uses of unsafe unnecessary. But there are a few that stand out.</p>
<p>Perhaps the most challenging one to reason about is mutable iteration over items. For <a href="https://docs.rs/iddqd/latest/iddqd/struct.IdOrdMap.html#method.iter_mut"><code>IdOrdMap::iter_mut</code></a>, iteration is ordered by the key. One might start off by writing something like:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">pub</span><span class="w"> </span><span class="k">struct</span> <span class="nc">IterMut</span><span class="o">&lt;</span><span class="na">&#39;a</span><span class="p">,</span><span class="w"> </span><span class="n">T</span>: <span class="nc">IdOrdItem</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">items</span>: <span class="kp">&amp;</span><span class="na">&#39;a</span> <span class="nc">mut</span><span class="w"> </span><span class="n">ItemSet</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// This is an ordered iterator over the B-tree equivalent to a hash table.
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">iter</span>: <span class="nc">btree_table</span>::<span class="n">Iter</span><span class="o">&lt;</span><span class="na">&#39;a</span><span class="o">&gt;</span><span class="p">,</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">impl</span><span class="o">&lt;</span><span class="na">&#39;a</span><span class="p">,</span><span class="w"> </span><span class="n">T</span>: <span class="nc">IdOrdItem</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="na">&#39;a</span><span class="o">&gt;</span><span class="w"> </span><span class="nb">Iterator</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">IterMut</span><span class="o">&lt;</span><span class="na">&#39;a</span><span class="p">,</span><span class="w"> </span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">type</span> <span class="nc">Item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="o">&amp;</span><span class="na">&#39;a</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">T</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="cp">#[inline]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">fn</span> <span class="nf">next</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="bp">self</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nb">Option</span><span class="o">&lt;</span><span class="bp">Self</span>::<span class="n">Item</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Obtain the next index to return, in order.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="n">index</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="bp">self</span><span class="p">.</span><span class="n">iter</span><span class="p">.</span><span class="n">next</span><span class="p">()</span><span class="o">?</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Fetch the item.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="n">item</span>: <span class="kp">&amp;</span><span class="nc">mut</span><span class="w"> </span><span class="n">T</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="bp">self</span><span class="p">.</span><span class="n">items</span><span class="p">[</span><span class="n">index</span><span class="p">];</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nb">Some</span><span class="p">(</span><span class="n">item</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>But this would immediately return an error:</p>
<pre class="chroma rustc-error"><code><span class="level-error">error</span><span class="bold">: lifetime may not live long enough</span>
<span class="info">   --&gt;</span> crates/iddqd/src/id_ord_map/iter.rs:90:9
<span class="info">    |</span>
<span class="info"> 79 |</span> impl&lt;'a, T: IdOrdItem + 'a&gt; Iterator for IterMut&lt;'a, T&gt; {
<span class="info">    |</span>      <span class="info">-- lifetime `'a` defined here</span>
<span class="info">...</span>
<span class="info"> 83 |</span>     fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
<span class="info">    |</span>             <span class="info">- let's call the lifetime of this reference `'1`</span>
<span class="info">...</span>
<span class="info"> 90 |</span>         Some(item)
<span class="info">    |</span>         <span class="level-error">^^^^^^^^^^ method was supposed to return data with lifetime `'a`</span>
<span class="info">    |</span>                    <span class="level-error">but it is returning data with lifetime `'1`</span></code></pre>
<p>The reason this occurs is that Rust&rsquo;s iterators require that the returned values do not borrow from the iterator itself<sup id="fnref:6"><a href="#fn:6" class="footnote-ref" role="doc-noteref">6</a></sup>. Many uses of iterators do not need this capability—in particular, most for loops only operate on one item at a time:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">items</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">IdOrdMap</span>::<span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span>::<span class="n">new</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="c1">// ... insert some items
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">for</span><span class="w"> </span><span class="n">item</span><span class="w"> </span><span class="k">in</span><span class="w"> </span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="n">items</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">item</span><span class="p">.</span><span class="n">value</span><span class="w"> </span><span class="o">+=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>But Rust&rsquo;s iterators also let you create values that outlive the iterator, via e.g. the <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect"><code>collect</code> combinator</a>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">items</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">IdOrdMap</span>::<span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span>::<span class="n">new</span><span class="p">();</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="c1">// ... insert some items
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">items_mut</span>: <span class="nb">Vec</span><span class="o">&lt;&amp;</span><span class="k">mut</span><span class="w"> </span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">items</span><span class="p">.</span><span class="n">iter_mut</span><span class="p">().</span><span class="n">collect</span><span class="p">();</span><span class="w">
</span></span></span></code></pre></div><p><code>items_mut</code> cannot outlive <code>items</code> itself, but <em>can</em> outlive the iterator returned by <code>items.iter_mut()</code>.</p>
<p>Crucially, this relies on knowing that all of the <code>&amp;mut T</code> returned by the iterator are disjoint—or, in other words, that the iterator never yields the same value twice. (Remember that one of the rules of Rust is that there must never be multiple <code>&amp;mut</code> references to the same memory.) But the Rust borrow checker just sees a succession of accesses into a list, and it has no way of knowing that the indexes are all different. If the human writing the code has knowledge that all of the indexes are different, though, they can use an unsafe pattern called <a href="https://doc.rust-lang.org/stable/std/mem/fn.transmute.html#examples">lifetime extension</a> to tell the borrow checker to let this code through:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">impl</span><span class="o">&lt;</span><span class="na">&#39;a</span><span class="p">,</span><span class="w"> </span><span class="n">T</span>: <span class="nc">IdOrdItem</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="na">&#39;a</span><span class="o">&gt;</span><span class="w"> </span><span class="nb">Iterator</span><span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="n">IterMut</span><span class="o">&lt;</span><span class="na">&#39;a</span><span class="p">,</span><span class="w"> </span><span class="n">T</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">type</span> <span class="nc">Item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="o">&amp;</span><span class="na">&#39;a</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">T</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="cp">#[inline]</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">fn</span> <span class="nf">next</span><span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="bp">self</span><span class="p">)</span><span class="w"> </span>-&gt; <span class="nb">Option</span><span class="o">&lt;</span><span class="bp">Self</span>::<span class="n">Item</span><span class="o">&gt;</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Obtain the next index to return, in order.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="n">index</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="bp">self</span><span class="p">.</span><span class="n">iter</span><span class="p">.</span><span class="n">next</span><span class="p">()</span><span class="o">?</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Fetch the item.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="n">item</span>: <span class="kp">&amp;</span><span class="nc">mut</span><span class="w"> </span><span class="n">T</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="o">&amp;</span><span class="k">mut</span><span class="w"> </span><span class="bp">self</span><span class="p">.</span><span class="n">items</span><span class="p">[</span><span class="n">index</span><span class="p">];</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// Extend the lifetime of the item to &#39;a.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// 
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// SAFETY: The indexes returned by `self.iter` are known to all be different,
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// so successive calls to `IterMut::next` never create mutable aliases to
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// the same memory.
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="kd">let</span><span class="w"> </span><span class="n">item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">unsafe</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">std</span>::<span class="n">mem</span>::<span class="n">transmute</span>::<span class="o">&lt;&amp;</span><span class="k">mut</span><span class="w"> </span><span class="n">T</span><span class="p">,</span><span class="w"> </span><span class="o">&amp;</span><span class="na">&#39;a</span><span class="w"> </span><span class="k">mut</span><span class="w"> </span><span class="n">T</span><span class="o">&gt;</span><span class="p">(</span><span class="n">item</span><span class="p">)</span><span class="w"> </span><span class="p">};</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nb">Some</span><span class="p">(</span><span class="n">item</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><h3 id="a-bug-and-a-fix">A bug and a fix</h3>
<p>In the previous section, we saw how unsafe Rust acts as an escape hatch for facts that the Rust compiler cannot establish by itself—in this case, that the indexes returned by <code>self.iter</code> are all different. But <em>are the indexes actually different</em>? Based on the storage scheme described above, it would seem like that is the case. But this is generic code which calls into user-provided functions, so there&rsquo;s a chance that sufficiently pathological user code can trick the map into storing duplicate indexes.</p>
<p>Let&rsquo;s take one such example we recently found and fixed. Suppose you have an <code>IdOrdMap</code> called <code>items</code> storing five items with integer keys 0 through 4, inserted and stored in order. Here, the top row is the B-tree storing indexes in key order, while the bottom row is the <code>Vec&lt;ItemSlot&lt;T&gt;&gt;</code>:</p>

  <figure class="center" >
    
    <img src="/images/iddqd/iddqd-diagram-05.svg"  alt="An IdOrdMap storing five items with integer keys 0 through 4. The top row is a B-tree of (key, index) pairs in key order; the bottom row is the item vector, with each B-tree entry pointing to its matching Occupied slot."   />
    
    
  </figure>


<p>Now suppose you use the <a href="https://docs.rs/iddqd/latest/iddqd/struct.IdOrdMap.html#method.entry">Entry API</a> (a standard Rust data structure pattern) to fetch an item by index 0:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// In this example, the integer keys are wrapped in another type. We&#39;re going
</span></span></span><span class="line"><span class="cl"><span class="c1">// to swap in a different Ord for Key in the next step.
</span></span></span><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">entry</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">items</span><span class="p">.</span><span class="n">entry</span><span class="p">(</span><span class="n">Key</span><span class="p">(</span><span class="mi">0</span><span class="p">));</span><span class="w">
</span></span></span></code></pre></div><p>This will successfully look up the item stored at index 0 and return an <a href="https://docs.rs/iddqd/latest/iddqd/id_ord_map/struct.OccupiedEntry.html"><code>OccupiedEntry</code></a>. The <code>OccupiedEntry</code> internally stores the fact that the item was found at index 0.</p>
<p>Now, at this point, let&rsquo;s deliberately switch the <code>Ord</code> implementation for <code>Key</code> to always return <a href="https://doc.rust-lang.org/std/cmp/enum.Ordering.html#variant.Equal"><code>Equal</code></a>, no matter the values inside. There are a few different ways to do this in safe Rust, most of which use some form of <a href="https://doc.rust-lang.org/reference/interior-mutability.html">interior mutability</a>. (This is unlikely in ordinary Rust, but <em>that doesn&rsquo;t matter</em>: unsafe generic Rust must handle arbitrarily pathological Rust!)</p>
<p>Now remove the entry from the map using <a href="https://docs.rs/iddqd/latest/iddqd/id_ord_map/struct.OccupiedEntry.html#method.remove"><code>OccupiedEntry::remove</code></a>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">item</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">entry</span><span class="p">.</span><span class="n">remove</span><span class="p">();</span><span class="w">
</span></span></span></code></pre></div><p>At this point, <code>iddqd</code> would attempt to remove <em>index</em> 0 from the B-tree, descending into the tree again but comparing only by <em>key</em><sup id="fnref:7"><a href="#fn:7" class="footnote-ref" role="doc-noteref">7</a></sup>. Because we made comparisons by key always return <code>Equal</code>, the comparison would short-circuit at the first element it compares against. For example, if the first comparison lands on the B-tree entry <code>(key = 2, index = 2)</code>, then that entry would be removed. But the <code>OccupiedEntry</code> was carrying <code>index = 0</code>, so it would also remove item 0 from the item set:</p>

  <figure class="center" >
    
    <img src="/images/iddqd/iddqd-diagram-03.svg"  alt="The IdOrdMap left inconsistent after a buggy removal. The B-tree entry for key=2/index=2 was removed instead of key=0/index=0; slot 0 is now Vacant with free_head = 0 even though its B-tree entry remains, and slot 2 (key=2) is orphaned with nothing pointing to it."   />
    
    
  </figure>


<p>The map is no longer in a consistent state. The index 0 is still in the B-tree index but the corresponding slot in the <code>ItemSet</code> is vacant; meanwhile, item 2 in the <code>ItemSet</code> does not have any pointers to it.</p>
<p>At this point, though, the invariant that there aren&rsquo;t duplicate indexes hasn&rsquo;t been violated. Where it does get violated is with this next step: suppose the <code>Ord</code> implementation now switches back to being honest<sup id="fnref:8"><a href="#fn:8" class="footnote-ref" role="doc-noteref">8</a></sup>, and you insert a new entry with key 1000. Since <code>free_head</code> points to item 0, <code>iddqd</code> will attempt to reuse that slot. It is <em>this</em> step that results in duplicate indexes:</p>

  <figure class="center" >
    
    <img src="/images/iddqd/iddqd-diagram-06.svg"  alt="The IdOrdMap after inserting key=1000 into the reused slot 0. Two B-tree entries, key=0/index=0 and key=1000/index=0, now both point at slot 0, creating duplicate indexes, while slot 2 remains orphaned."   />
    
    
  </figure>


<p>There are now duplicate indexes pointing to the same item, and <code>IterMut</code> becomes unsound.</p>
<p>This was fixed through a combination of two things:</p>
<ol>
<li>
<p><strong>When descending into the B-tree, also check equality against the index.</strong> In other words, if we&rsquo;re looking for a key with a known index in the B-tree, <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/src/support/btree_table.rs#L458-L476">compare against <em>both</em> <code>key</code> and <code>index</code></a>. As covered in the example above, previously, we would just check that the key is the same; the pathological <code>Ord</code> implementation returned <code>Equal</code>, tricking the map into believing that the entry at <code>(key = 2, index = 2)</code> was the one to remove. We changed this to additionally use the index as a tie-breaker. The comparison against <code>(key = 2, index = 2)</code> now resolves to <code>Less</code> (since <code>0 &lt; 2</code>), so the search doesn&rsquo;t spuriously match here.</p>
<p>By construction, the only way the search can now succeed is if the stored index actually equals the one we&rsquo;re looking for.</p>
</li>
<li>
<p><strong>If there are no matches, fall back to a linear scan.</strong> The tie-breaker eliminates spurious matches on the wrong entry, but it doesn&rsquo;t guarantee that the search finds the <em>right</em> entry. (The B-tree is sorted by <em>key</em>, while the tie-breaker compares by <em>index</em>, and in general these two orderings are independent.) If the tree search yields no results, we must still keep the tree and the <code>ItemSet</code> in sync. In that case, we remove the index from the B-tree by <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/src/support/btree_table.rs#L267-L276">doing a linear scan</a> without calling into user code. The remove operation then takes linear rather than logarithmic time, but that is an acceptable tradeoff, since buggy user code is the only way to encounter the fallback.</p>
</li>
</ol>
<p>This is the kind of long-range reasoning that is sometimes required to establish the soundness of a safe abstraction. The overall system relies on all of these moving parts working correctly across arbitrarily complex series of operations.</p>
<h2 id="validating-iddqd">Validating iddqd</h2>
<p>Because <code>iddqd</code> is such a foundational data structure at Oxide, we go through great lengths to validate its correctness, including the soundness of its abstractions. There is a great deal of analytical reasoning performed by experienced Rust authors and reviewers, as described in the section above. But we also empirically validate <code>iddqd</code> along several different dimensions. None of the layers is sufficient by itself, but by rigorously doing all of them we can be more confident that <code>iddqd</code> is correct.</p>
<p>The layers of validation we apply are:</p>
<table>
	<thead>
			<tr>
					<th>Technique</th>
					<th>Catches</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Analytical reasoning</td>
					<td>Soundness errors</td>
			</tr>
			<tr>
					<td>Example-based tests (including doctests)</td>
					<td>Regressions, broken examples</td>
			</tr>
			<tr>
					<td>Pathological tests with Miri</td>
					<td>Adversarial trait impls causing UB</td>
			</tr>
			<tr>
					<td>Model-based tests (PBT with <code>NaiveMap</code> oracle)</td>
					<td>Divergence from oracle over random operation sequences</td>
			</tr>
			<tr>
					<td>Panic safety fault injection</td>
					<td>Invariant violations on mid-operation panics</td>
			</tr>
			<tr>
					<td>LLM adversarial review</td>
					<td>Blind spots in adversarial user code</td>
			</tr>
			<tr>
					<td>Formal verification</td>
					<td>Proofs over arbitrarily adversarial trait impls</td>
			</tr>
	</tbody>
</table>
<p>In this section, I&rsquo;ll provide a brief overview of each layer. Click through the links to see more details and code samples.</p>
<h3 id="analytical-reasoning">Analytical reasoning</h3>
<p>All blocks and patterns of unsafe Rust have been analyzed by at least one human reviewer, and up to three. Thanks to several of my Oxide colleagues for lending their time and expertise to these reviews—these discussions helped sharpen our reasoning considerably.</p>
<p>The reasoning for each unsafe block is captured in a <code>// SAFETY:</code> comment above the block. We use Clippy&rsquo;s <a href="https://rust-lang.github.io/rust-clippy/master/index.html?search=undocumented_unsafe_blocks#undocumented_unsafe_blocks"><code>undocumented_unsafe_blocks</code></a> lint to verify that these comments are present.</p>
<h3 id="example-based-tests">Example-based tests</h3>
<p>The simplest kind of empirical validation is with <strong>example-based tests</strong>: create a map, perform some operations, and ensure that the results of those operations are as expected. <code>iddqd</code> has <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/src/support/btree_table.rs#L639">unit tests for its internals</a> and <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/tests/integration/id_ord_map.rs">integration tests for the public API</a>. These also live as doctests, where they double as documentation.</p>
<h3 id="pathological-tests-with-miri">Pathological tests with Miri</h3>
<p><code>iddqd</code> also has a <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/tests/integration/pathological.rs">battery of <strong>pathological tests</strong></a> which supply buggy implementations of <code>Ord</code> and other traits.</p>
<p>In CI, both regular and pathological tests are run under the <a href="https://github.com/rust-lang/miri/">Miri interpreter</a>, which can detect many classes of undefined behavior. (If you&rsquo;re curious about the details, we run with Miri under both Stacked and <a href="https://www.ralfj.de/blog/2023/06/02/tree-borrows.html">Tree Borrows</a>.) But note that some classes of UB can be detected in the regular test environment as well. For example, in the previous section we established that the tables not containing duplicate indexes is a necessary condition for soundness; this invariant <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/src/support/btree_table.rs#L113-L159">can be verified</a> outside the Miri context as well.</p>
<h3 id="model-based-testing-and-fault-injection">Model-based testing and fault injection</h3>
<p><code>iddqd</code> uses two layers of randomized testing: model-based comparison against a known-correct oracle, and fault injection on top of it.</p>
<p>For data structures, example-based tests alone are generally considered insufficient. A much stronger kind of testing is <strong>model-based testing</strong>, also known as <strong>stateful property-based testing</strong> (stateful PBT): random sequences of operations are applied to an instance of the type, and the results are compared against an <em>oracle</em> that is known to be correct. <code>iddqd</code> has extensive model-based tests against <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd-test-utils/src/naive_map.rs#L9">a <code>NaiveMap</code> oracle</a> that is inefficient but clearly correct. (I&rsquo;ve talked about this style of testing before <a href="https://www.youtube.com/watch?v=CcYK8E1UuJY">on <em>Oxide and Friends</em></a>.)</p>
<p>An extension of model-based testing is <strong>fault injection</strong>, where bugs are randomly inserted into user code. For <code>iddqd</code>, a fruitful avenue for fault injection has been <em>panic safety</em> (or <em>unwind safety</em>): user code panicking in the middle of an operation must not cause the map&rsquo;s invariants to be violated<sup id="fnref:9"><a href="#fn:9" class="footnote-ref" role="doc-noteref">9</a></sup>. We systematically explore fault injection by <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/tests/integration/id_ord_map.rs#L1113-L1255">generating random sequences</a> of map operations, where each operation is associated with a (randomly selected) panic countdown. Each call into user code decrements the countdown by 1; if it reaches 0, the code panics. Randomized panic safety testing found several subtle bugs in <code>iddqd</code> (<a href="https://github.com/oxidecomputer/iddqd/pull/259">example</a>), including some that escalated into unsoundness.</p>
<p>The model-based tests also verify internal invariants after each operation, such as the no-duplicate-index condition described in the previous section. We&rsquo;ve found in practice that model-based tests are too slow to run under Miri, so we verify the invariants on which soundness (and correctness) is known to be dependent instead.</p>
<h3 id="llm-adversarial-review">LLM adversarial review</h3>
<p>Another kind of validation that&rsquo;s recently become available is <strong>LLM-driven adversarial review</strong>. Current-generation frontier models<sup id="fnref:10"><a href="#fn:10" class="footnote-ref" role="doc-noteref">10</a></sup> found several ways to write pathological implementations of user code that would corrupt the map. In <a href="https://github.com/oxidecomputer/iddqd/pull/260">one notable case</a>, an LLM constructed a way for the map&rsquo;s invariants to break on a custom allocator panicking and unwinding. This is a panic safety issue (and a failure mode I hadn&rsquo;t thought about before), but distinct from the existing panic safety tests that only covered panics in regular user code like an <code>Ord</code> implementation.</p>
<p>LLMs can sometimes produce plausible-but-wrong soundness claims. An effective way to guard against that is <a href="https://simonwillison.net/guides/agentic-engineering-patterns/red-green-tdd/">red-green TDD</a>, using Miri as an oracle: For a soundness bug, first have the LLM write a test case demonstrating the bug, running it under Miri to show undefined behavior—the <em>red</em> phase. Then, after fixing the bug, rerun the test to show that it now passes—the <em>green</em> phase.</p>
<h3 id="what-about-formal-methods">What about formal methods?</h3>
<p>To formally verify <code>iddqd</code>, one&rsquo;s first thought would be to use a <a href="https://en.wikipedia.org/wiki/Model_checking">model checker</a> like <a href="https://github.com/model-checking/kani">Kani</a> to establish that the maps don&rsquo;t violate internal invariants. But <code>iddqd</code> is unfortunately a bit too complicated for Kani to handle, and the required proofs blow up beyond what is feasible for the tool.</p>
<p>The <a href="https://creusot.rs/">Creusot</a> deductive verifier can help Rust developers prove their code is free of panics and other errors, but as of this writing it&rsquo;s <a href="https://github.com/creusot-rs/creusot/blob/7a68885eb85a3bea6f65e7cb50b9013e4aa7d1dc/creusot-std/src/std/panicking.rs#L10-L45">unable to prove</a> invariants that must hold even if user code panics or otherwise misbehaves.</p>
<p>The infeasibility of proofs is a common problem with applying formal methods to implementations, so they are often applied to a higher-level specification instead. For <code>iddqd</code>, the closest thing to a specification is <code>NaiveMap</code>, but it can be easily observed to be correct without needing a formal proof.</p>
<p>How do we ensure that the implementation matches the specification? Model-based testing does a lot of heavy lifting here. While they aren&rsquo;t a formal proof that <code>iddqd</code> matches <code>NaiveMap</code>, running model-based tests thousands of times in CI provides fairly high confidence that it does.</p>
<p>We keep an eye on developments in this space; the in-development <a href="https://crates.io/crates/cargo-anneal"><code>cargo-anneal</code></a>, which lets you embed <a href="https://lean-lang.org/">Lean</a> soundness proofs alongside unsafe Rust as doc comments, looks quite interesting.</p>
<p>If you&rsquo;re working on formal verification tooling, <code>iddqd</code> is a great candidate to benchmark against because of its crisp invariants and relatively constrained yet non-trivial scope. We&rsquo;d be especially interested in proofs that hold over arbitrary trait implementations, and of refinement between <code>iddqd</code> and <code>NaiveMap</code>. Please reach out by <a href="https://github.com/oxidecomputer/iddqd/issues/new">filing an issue</a> or <a href="mailto:rain@oxide.computer">emailing me</a>!</p>
<hr>
<p><em>Update 2026-06-16</em>: Since publication, we&rsquo;ve used <a href="https://soteria-tools.com/">Soteria</a> to <a href="https://github.com/oxidecomputer/iddqd/tree/main/crates/iddqd/tests/soteria">verify</a> that <code>iddqd</code>&rsquo;s no-duplicate-index invariant holds under arbitrarily adversarial <code>Hash</code> and <code>Ord</code> implementations. Soteria is similar to Kani in spirit, though with <a href="https://arxiv.org/abs/2511.08729">different internals</a> that make it more compatible with <code>iddqd</code>. Soteria is implemented as a symbolic execution engine that lets you declare points of nondeterminism in your code. (For example, within <code>iddqd</code>, we represent an adversarial <a href="https://github.com/oxidecomputer/iddqd/blob/a794b0a57d18ca3ef5cc261cfbcb6b970301acb4/crates/iddqd/tests/soteria/hasher.rs#L53-L54"><code>Hash</code></a> or <a href="https://github.com/oxidecomputer/iddqd/blob/a794b0a57d18ca3ef5cc261cfbcb6b970301acb4/crates/iddqd/tests/soteria/id_ord_map.rs#L63-L70"><code>Ord</code></a> return value as nondeterministic, since we want to model adversarially bad user code.) Then, it:</p>
<ul>
<li>Compiles the Rust program into a form suitable for formal verification.</li>
<li>Interprets this form until it reaches a point of nondeterminism, treating each such point as a symbol rather than a concrete value.</li>
<li>Branches at each point where control flow depends on a symbol, validating that there is no UB and that the invariants specified by the program are upheld. A lot of the cleverness lies in how the possibility space is collapsed down to something manageable. For example, Soteria doesn&rsquo;t have to enumerate every possible <code>Hash</code> value; rather, it only has to fork in places where control flow depends on the <code>Hash</code> value.</li>
</ul>
<p>For <code>IdOrdMap</code> from the example above, the proof runs against the real B-tree and its unsafe code, and it checks exactly the index tie-breaker and linear search fallback described here. (Remove either of them and the proof fails.)</p>
<p>The benefits and limits of this approach are both apparent. It covers every possible return value at once, but to stay fast enough for CI, we have to restrict the proof to operation sequences of depth 3. (In contrast, the property-based tests generate sequences of hundreds of operations.) So it acts as a complement to the existing layers of validation, not a replacement.</p>
<p>We plan to keep expanding the scope of formal verification within <code>iddqd</code> as the tooling continues to mature.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Writing unsafe generic Rust is extremely difficult. Each invariant that the unsafe code relies upon has to be carefully upheld over arbitrary trait implementations, including adversarial ones. This post covers one such example: how an <code>Ord</code> implementation could be carefully written to trick the map into creating mutable aliases to the same memory, and how we fixed it.</p>
<p>No single technique can hope to catch all bugs, which is why <code>iddqd</code> uses several layers of validation. Humans carefully reasoning about every line of unsafe code goes a long way; example-based, pathological, and randomized tests provide empirical evidence; and frontier models can find new and surprising ways to break code that humans might not have thought of. This is a lot of machinery, but at Oxide <a href="https://oxide.computer/principles">we believe</a> that for foundational infrastructure, this level of rigor is justified. And if you agree, <a href="https://oxide.computer/careers">we&rsquo;re hiring</a>!</p>
<p><em>Diagrams courtesy Ben Leonard. Discuss on <a href="https://news.ycombinator.com/item?id=48371762">Hacker News</a> and <a href="https://lobste.rs/s/6eyhii/iddqd_hardest_kind_unsafe_rust">Lobsters</a>.</em></p>
<div class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1">
<p><code>serde_json</code> also supports integer keys; it serializes and deserializes them as strings.&#160;<a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:2">
<p>In C, the aliasing rules are about <em>accesses</em>: multiple pointers to the same memory are fine, as long as you don&rsquo;t have a data race on them or violate <a href="https://blog.regehr.org/archives/1307">strict aliasing</a>. In Rust, it is UB for multiple <code>&amp;mut</code> references to the same memory to ever <em>exist</em>, even if they&rsquo;re not actively being mutated simultaneously.&#160;<a href="#fnref:2" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:3">
<p>An exercise for the reader. There is a second, entirely different, kind of bug in <code>collect_exact</code>: it can leak memory with some user-supplied iterators. This isn&rsquo;t a soundness bug, but it is a bug nonetheless. Try working out how this can happen and why this isn&rsquo;t a soundness bug. (Hint: think about user code panicking.)&#160;<a href="#fnref:3" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:4">
<p>For this discussion we&rsquo;re restricting ourselves to single-threaded Rust, since iddqd is not a concurrent data structure. Concurrency amplifies the difficulty of reasoning about Rust several-fold further.&#160;<a href="#fnref:4" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:5">
<p>The index is built on top of the standard library <code>BTreeMap</code>. This required making <code>BTreeMap</code> work <a href="https://github.com/oxidecomputer/iddqd/blob/dd52024760267ce0a5bcd5b98a745a4b4468ebe5/crates/iddqd/src/support/btree_table.rs#L22-L69">with an external comparator</a> through some further unsafe trickery.&#160;<a href="#fnref:5" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:6">
<p>For a proposed version of an iterator which does let you borrow values from the iterator, see <a href="https://rust-lang.github.io/generic-associated-types-initiative/design_patterns/iterable.html"><code>LendingIterator</code></a>.&#160;<a href="#fnref:6" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:7">
<p>Is this second descent necessary? <a href="https://doc.rust-lang.org/std/collections/btree_map/struct.OccupiedEntry.html"><code>BTreeMap</code>&rsquo;s own <code>OccupiedEntry</code></a> stores a cursor into the map to avoid a second descent, and <code>iddqd</code> could be restructured to hold one. But there are other ways to trigger the same issue without using <code>Entry</code>, for example by using a chaotic <code>Ord</code> implementation that randomly returns <code>Equal</code> at times. I&rsquo;m using <code>Entry</code> here as the clearest way to demonstrate the bug.&#160;<a href="#fnref:7" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:8">
<p>Restoring <code>Ord</code> is necessary here because, with <code>Equal</code>, the duplicate-detection step at the start of <code>insert_unique</code> would short-circuit and reject the insert. The point is that user code is free to misbehave in arbitrary ways, including changing its mind from one call to the next.&#160;<a href="#fnref:8" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:9">
<p>Rust binaries <a href="https://doc.rust-lang.org/rust-by-example/error/abort_unwind.html">can be configured</a> to either unwind (be <a href="https://doc.rust-lang.org/std/panic/fn.catch_unwind.html">recovered from</a>) or abort (tear down the process). Panic safety only matters with <code>panic = 'unwind'</code>. At Oxide, we ship our system software with <code>panic = 'abort'</code>. However, libraries cannot assume <code>abort</code> and <a href="https://sunshowers.io/posts/on-poisoning/#just-ship-with-panic--abort"><em>must</em> work with <code>unwind</code></a>.&#160;<a href="#fnref:9" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:10">
<p>Claude Opus 4.7 and GPT-5.5.&#160;<a href="#fnref:10" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</div>
]]></content><category scheme="https://sunshowers.io/tags/rust" term="rust" label="rust"/><category scheme="https://sunshowers.io/tags/unsafe" term="unsafe" label="unsafe"/></entry></feed>