<?xml version="1.0" encoding="UTF-8"?>
<rss  xmlns:atom="http://www.w3.org/2005/Atom" 
      xmlns:media="http://search.yahoo.com/mrss/" 
      xmlns:content="http://purl.org/rss/1.0/modules/content/" 
      xmlns:dc="http://purl.org/dc/elements/1.1/" 
      version="2.0">
<channel>
<title>bthek1_blog</title>
<link>https://bthek1.github.io/bthek1_blog/</link>
<atom:link href="https://bthek1.github.io/bthek1_blog/index.xml" rel="self" type="application/rss+xml"/>
<description>Long-form write-ups from the rest of this collection: what actually worked, what cost an evening, and the numbers behind both.</description>
<image>
<url>https://bthek1.github.io/bthek1_blog/Logo.svg</url>
<title>bthek1_blog</title>
<link>https://bthek1.github.io/bthek1_blog/</link>
</image>
<generator>quarto-1.11.9</generator>
<lastBuildDate>Wed, 11 Nov 2026 00:00:00 GMT</lastBuildDate>
<item>
  <title>Guardrails for 22 Docs Repos</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/docs_fleet_guardrails.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>How the sites are stitched into one website is in <a href="../posts/federated_docs_site.html">Running a Federated Docs Site</a>, and what the repo has held over two years is in <a href="../posts/two_years_knowledge_repo.html">Two Years of a Knowledge Repo</a>. This post is about the other side: the checks that decide what is allowed to reach those sites, and the commands that tell me the state of 22 repos without opening 22 terminals.</p>
</blockquote>
<p>The short version: <strong>every guardrail that held was a command that prints a number. Every one that failed was a convention I meant to follow.</strong></p>
<hr>
<section id="the-premise-that-was-wrong" class="level2">
<h2 class="anchored" data-anchor-id="the-premise-that-was-wrong">The premise that was wrong</h2>
<p>The working assumption for two years was simple. A private repo keeps its contents private, and a <code>p_</code> filename prefix keeps a notebook off the site. In September I checked both with an anonymous <code>curl</code>, and neither held.</p>
<ul>
<li><strong>A private repo does not give you a private site.</strong> GitHub Pages serves a site to anyone, whatever the repo’s visibility. Every private repo in the fleet that had a Pages site returned <code>200</code> to an unauthenticated request. <code>gh repo view --json visibility</code> tells you about the repo and nothing about the site.</li>
<li><strong><code>p_</code> was navigation, not a boundary.</strong> The sidebar rule <code>auto: "[0-9]*.ipynb"</code> only lists numbered notebooks, so a <code>p_</code> page was missing from the menu. But <code>nbdev-docs</code> still rendered it and pushed it. It was live at its direct URL, listed in <code>sitemap.xml</code>, and indexed by the site’s own search box.</li>
<li><strong>The inverse was worse.</strong> A few notebooks with personal figures in them had ordinary numeric names, so they were not only published but linked in the sidebar.</li>
</ul>
<p>The fix for the second point is one block in the shared <code>_quarto.yml</code>: a <code>project.render</code> list that excludes <code>p_*.ipynb</code> by glob. Now Quarto never renders the page at all. The first point has no setting. Anything that must stay private has to live somewhere that has no deploy workflow, and the documents that fell in that category moved to a separate private repo with no Pages site.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/36_publish_guardrails.svg" class="img-fluid figure-img"></p>
<figcaption>The checks between a notebook and the public web, and the status board over all submodules</figcaption>
</figure>
</div>
<hr>
</section>
<section id="stored-outputs-are-published-too" class="level2">
<h2 class="anchored" data-anchor-id="stored-outputs-are-published-too">Stored outputs are published too</h2>
<p>This was the leak that started it, and it is the least obvious one.</p>
<p>Quarto renders the outputs a notebook <strong>already holds</strong>. It does not run the notebook. So if a code cell once printed some numbers, and I later rewrote the cell to stop printing them, the old numbers are still in the <code>.ipynb</code> JSON under the new code, and they are still on the site. The source looked clean in review. The page did not.</p>
<p>Two rules came out of that:</p>
<ul>
<li><strong>Clear outputs that are not the point.</strong> A concept notebook with <code>skip_exec: true</code> is never executed, so any output it carries is stale by definition.</li>
<li><strong>Any scanner must read outputs as well as source.</strong> A <code>grep</code> over the code cells would have passed the leaking notebook.</li>
</ul>
<hr>
</section>
<section id="just-scan-a-secret-scanner-people-will-actually-run" class="level2">
<h2 class="anchored" data-anchor-id="just-scan-a-secret-scanner-people-will-actually-run"><code>just scan</code>: a secret scanner people will actually run</h2>
<p><code>just scan</code> walks all 22 submodules and reads file contents, not git metadata. It reports three counts per submodule:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Count</th>
<th>Meaning</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>published</strong></td>
<td>A hit in a file the site renders right now (a non-<code>p_</code> <code>.ipynb</code> or <code>.md</code>). This is on the public web.</td>
</tr>
<tr class="even">
<td><strong>tracked</strong></td>
<td>A hit in a file that is only in git. A smaller problem.</td>
</tr>
<tr class="odd">
<td><strong>binary docs</strong></td>
<td>PDFs, spreadsheets and databases. They cannot be scanned without a parser, so they are counted, not judged.</td>
</tr>
</tbody>
</table>
<p>It <strong>exits 1 on any published finding</strong>. <code>--strict</code> also fails on tracked ones, and <code>--detail</code> lists each hit.</p>
<p>What it looks for, by category: private key material, vendor tokens with known prefixes (cloud, Git hosting, chat, LLM APIs), password hashes, government ID numbers, long hex secrets next to words like <code>token</code> or <code>api_key</code>, credentials assigned as literals, and a column of five or more real email addresses (a user table, not a contact line). For notebooks it reads cell sources plus <strong>text outputs</strong>, and it skips <code>image/*</code> payloads. That skip is not only speed: megabytes of base64 plot data look like high-entropy secrets to a regex.</p>
<hr>
</section>
<section id="the-false-positive-problem-decided-whether-it-would-be-used" class="level2">
<h2 class="anchored" data-anchor-id="the-false-positive-problem-decided-whether-it-would-be-used">The false-positive problem decided whether it would be used</h2>
<p>The first version of the credential rule reported <strong>23 published findings. 22 were code.</strong> A docs fleet about Django, Stripe and Grafana is full of lines like these:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">password <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> forms.CharField(widget<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>forms.PasswordInput)</span>
<span id="cb1-2">api_key <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> settings.STRIPE_SECRET_KEY</span></code></pre></div></div>
<p>The one real finding was a live API token, and it was invisible in that list. A scanner with 22 false alarms out of 23 is a scanner nobody reads, so the second version judges the <strong>value</strong> the pattern captured, not just the keyword:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> looks_secret(v):</span>
<span id="cb2-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">len</span>(v) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">16</span>:                                     <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span></span>
<span id="cb2-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> re.fullmatch(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[A-Za-z0-9_</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\-</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">+/=.~]</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, v):    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># an expression</span></span>
<span id="cb2-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> re.fullmatch(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[A-Z0-9_]</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, v):                  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ENV_VAR_NAME</span></span>
<span id="cb2-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> re.fullmatch(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[A-Za-z_][</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\w</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">.]</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, v) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">and</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"."</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> v:<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># settings.API_KEY</span></span>
<span id="cb2-6">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> re.search(<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[*x]</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{4,}</span><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">|</span><span class="ch" style="color: #20794D;
background-color: null;
font-style: inherit;">\.</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{3,}</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, v):                <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># already masked</span></span>
<span id="cb2-7">    classes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>(<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>(re.search(c, v)) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> c <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> (<span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[a-z]</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">[A-Z]</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>, <span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">r"</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">\d</span><span class="vs" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>))</span>
<span id="cb2-8">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> classes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span></span></code></pre></div></div>
<p>A real generated secret is a plain literal that mixes lower case, upper case and digits. A word, an expression, an environment variable name or a masked example does not. A doc that has to show a secret-shaped string on purpose marks that line with <code>scan:allow</code>.</p>
<p>The known limit is stated in the tool’s docs rather than hidden: an entropy test cannot catch a short password a human chose and wrote in prose. Chasing that would fire on every page that contains the word “password”. Those are found by reading.</p>
<p>Today the summary line is <code>22 submodules: 4 with findings, 17 clean, 1 without nbs</code>, and every one of those findings is in the tracked or binary column. <strong>Zero published.</strong></p>
<hr>
</section>
<section id="just-nblint-a-standard-is-a-number-per-rule" class="level2">
<h2 class="anchored" data-anchor-id="just-nblint-a-standard-is-a-number-per-rule"><code>just nblint</code>: a standard is a number per rule</h2>
<p>The same month I wrote down a notebook standard: a title cell with <code># H1</code>, a <code>&gt;</code> description and correctly spelled skip directives, one <code>##</code> section per cell, diagrams as SVG files, ASCII-only code, timezone-aware datetimes, no stale outputs, and an index page that links every public notebook. A standard on paper drifts. So <code>just nblint</code> turns it into a table, one row per rule, each tagged with the phase of the cleanup issue that drives it to zero.</p>
<p>The baseline on 2026-11-11 was taken over 677 notebooks in 20 nbdev submodules. Selected rows, before and now:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Rule</th>
<th>Baseline (notebooks)</th>
<th>Now</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Plain <code>```mermaid</code> fence (raw source on the site)</td>
<td>15</td>
<td>0</td>
</tr>
<tr class="even">
<td>Title cell has no <code># H1</code></td>
<td>3</td>
<td>0</td>
</tr>
<tr class="odd">
<td>Title cell is a code cell</td>
<td>19</td>
<td>0</td>
</tr>
<tr class="even">
<td>Title cell has no <code>&gt;</code> description</td>
<td>11</td>
<td>0</td>
</tr>
<tr class="odd">
<td>Concept notebook without <code>skip_showdoc</code></td>
<td>11</td>
<td>0</td>
</tr>
<tr class="even">
<td>Non-ASCII characters in code cells</td>
<td>24</td>
<td>0</td>
</tr>
<tr class="odd">
<td>Naive <code>now()</code> / <code>utcnow()</code></td>
<td>3</td>
<td>0</td>
</tr>
<tr class="even">
<td>Filename with a space or <code>&amp;</code></td>
<td>18</td>
<td>0</td>
</tr>
<tr class="odd">
<td><code>##</code> cell without a trailing <code>---</code></td>
<td>366</td>
<td>0</td>
</tr>
<tr class="even">
<td>Braced <code>{mermaid}</code> not yet an SVG</td>
<td>27</td>
<td>2</td>
</tr>
<tr class="odd">
<td><code>skip_exec</code> notebook carrying outputs</td>
<td>87</td>
<td>91</td>
</tr>
<tr class="even">
<td>Notebook over 3 MB</td>
<td>29</td>
<td>29</td>
</tr>
</tbody>
</table>
<p>The last two rows are deliberately left as a measured backlog rather than hidden. Stripping 1,700-odd stale outputs is a large, mechanical change of its own, and it was scoped out of this round.</p>
<p>By default <code>nblint</code> always exits 0: <strong>it measures, it does not gate.</strong> <code>--strict</code> turns it into a gate when a rule is at zero and should stay there.</p>
<hr>
</section>
<section id="things-the-linter-found-that-reading-never-did" class="level2">
<h2 class="anchored" data-anchor-id="things-the-linter-found-that-reading-never-did">Things the linter found that reading never did</h2>
<ul>
<li><strong>nbdev silently ignores misspelled directives.</strong> <code>Skip_exec</code>, <code>skip_doc</code> and similar typos were sitting in title cells, and nbdev treats an unknown key as nothing. No warning, just a notebook that executes or documents when it should not. That became its own rule, which flags any title-cell key that looks like a skip directive but is not one exactly.</li>
<li><strong>A title cell that starts with <code>---</code> breaks the whole repo.</strong> Quarto parses it as YAML front matter, and <code>nbdev-test</code> fails every notebook, not just that one.</li>
<li><strong>The linter’s own test fixtures tripped it.</strong> A fixture that contains a non-ASCII character or a naive <code>now()</code> gets flagged in the linter’s own notebook. The fixtures now build those strings at runtime.</li>
<li><strong>Renames rot links quietly.</strong> A follow-up audit of this blog found <strong>69 of 93</strong> internal links to the docs sites were dead, from renamed sites, moved pages and slugs that drop their number prefix. Each was replaced only with a URL that returned 200, and a re-audit found zero dead links.</li>
</ul>
<hr>
</section>
<section id="one-walker-for-22-submodules" class="level2">
<h2 class="anchored" data-anchor-id="one-walker-for-22-submodules">One walker for 22 submodules</h2>
<p>The status commands came first, and they are what make the other two cheap to run. Every fleet recipe in the <code>justfile</code> (<code>status</code>, <code>gss</code>, <code>update</code>, <code>sync</code>, <code>upload</code>, <code>push</code>, <code>copy_quarto</code>, <code>scan</code>, <code>nblint</code>) is now one line that calls a <code>fleet</code> command in my <code>nbdevAuto</code> package. One walker backs all of them, so they share one output style and one rule:</p>
<p><strong>A submodule that has nothing to report does not get a line. It gets counted.</strong> On a fleet with one dirty repo, <code>just upload</code> prints a single summary like <code>21 submodules: 1 uploaded, 19 clean, 1 without nbs</code> instead of 21 lines that all say “nothing to do”. The noise I removed is what lets the one line that matters be seen.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Command</th>
<th>Question it answers</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>just status</code> / <code>just gss</code></td>
<td>Which submodules are dirty, and what changed in each</td>
</tr>
<tr class="even">
<td><code>just report</code></td>
<td>Dirty, behind or ahead, plus CI and Pages state</td>
</tr>
<tr class="odd">
<td><code>just ci</code></td>
<td>Per submodule: last CI run, Pages deploy, Pages build, <code>main</code> sha</td>
</tr>
<tr class="even">
<td><code>just scan</code></td>
<td>Is anything secret or personal on the public web</td>
</tr>
<tr class="odd">
<td><code>just nblint</code></td>
<td>How far is each rule from zero</td>
</tr>
</tbody>
</table>
<p>Moving the loops into Python took the <code>justfile</code> from 406 to 321 lines with no loop logic left in it. Two things stay in bash on purpose: <code>init</code>, which runs on a fresh clone before Python is installed, and a git-only fallback for <code>report</code>. That fallback matters: with a working environment, <code>report --offline</code> takes about 0.15 s, while the pure bash version has to fetch every remote and took about 54 s.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Guardrail</th>
<th>What it replaced</th>
<th>What it prints</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>project.render</code> excludes <code>p_*</code></td>
<td>A sidebar rule that only hid the link</td>
<td>Nothing to check: the page is never built</td>
</tr>
<tr class="even">
<td>Separate private repo, no deploy workflow</td>
<td>“It is a private repo”</td>
<td>Nothing: there is no site</td>
</tr>
<tr class="odd">
<td><code>just scan</code></td>
<td>Remembering not to paste secrets</td>
<td>Published / tracked / binary per submodule, exit 1 on published</td>
</tr>
<tr class="even">
<td><code>just nblint</code></td>
<td>A standard written in a docs file</td>
<td>Notebooks and items per rule, per phase</td>
</tr>
<tr class="odd">
<td><code>fleet</code> walker</td>
<td>22 terminals and <code>git status</code></td>
<td>One summary line, plus a line only for submodules that need attention</td>
</tr>
</tbody>
</table>
<p>Repo visibility, filename conventions and code review all felt like guardrails, and the anonymous <code>curl</code> showed that none of them were. <strong>The checks that held are the ones that print a number</strong>, and every new rule I write down now gets a row in one of these tables.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Infrastructure</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/docs_fleet_guardrails.html</guid>
  <pubDate>Wed, 11 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>The Deadlock Only Load Found</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/fastapi_port_pool_deadlock.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The repo is my own experiment, SAAS_experimental: a questionnaire application started from my <a href="https://github.com/bthek1/django_react_template">django_react_template</a> starter and split into two Django REST services, <code>catalog</code> (users, tokens, questionnaire and battery types) and <code>instances</code> (the questionnaires themselves). It runs on Proxmox LXC containers with a k6 load generator, the same kind of harness as the <a href="../posts/k3s_load_testing.html">k3s post</a> and the <a href="../posts/postgres_vs_mongodb.html">Postgres vs MongoDB post</a>. It is a home lab with synthetic load, and every number below should be read as that.</p>
</blockquote>
<p>The order of work is the part worth copying: <strong>pin the behaviour first, port second, measure third, delete last.</strong> Each step had its own GitHub issue, and none started before the previous one was green.</p>
<hr>
<section id="what-was-ported-and-what-was-not" class="level2">
<h2 class="anchored" data-anchor-id="what-was-ported-and-what-was-not">What was ported, and what was not</h2>
<p>Only <code>catalog</code> moved, about 1.5k lines of Django. <code>instances</code> stayed on Django. Three decisions kept the comparison honest:</p>
<ul>
<li><strong>Sync first.</strong> Plain <code>def</code> endpoints and a sync SQLAlchemy session. It is a port, not a redesign, so the load test measures the framework and not a switch to async. Async is a separate, separately measured change.</li>
<li><strong>No schema change.</strong> SQLAlchemy models map onto the tables Django created. Alembic’s first revision is that schema, and existing databases are <code>stamp</code>ed, not migrated. Django could run against the same database again at any point until it was deleted.</li>
<li><strong>Same secrets on the wire.</strong> Passwords stay in Django’s <code>pbkdf2_sha256$&lt;iterations&gt;$&lt;salt&gt;$&lt;hash&gt;</code> format, verified with <code>hashlib</code> at Django 6.0’s iteration count, so a rollback still logs everyone in. Tokens keep simplejwt’s claims, RS256 and lifetimes, so <code>instances</code> verifies them with no change.</li>
</ul>
<p>The stack is the standard one: FastAPI, Pydantic v2, pydantic-settings, SQLAlchemy 2.0 on psycopg3, Alembic, PyJWT, and uvicorn workers under gunicorn. The <a href="../posts/fastapi_for_django_developers.html">FastAPI for Django developers post</a> covers that stack itself.</p>
<hr>
</section>
<section id="pin-the-behaviour-before-rewriting-anything" class="level2">
<h2 class="anchored" data-anchor-id="pin-the-behaviour-before-rewriting-anything">Pin the behaviour before rewriting anything</h2>
<p><code>catalog</code> had 2.1k lines of tests, but they used DRF’s <code>APIClient</code> and the Django ORM. None of them could check a FastAPI service. So the first plan wrote a new suite that imports neither framework. It starts the service under test as a real server on a free port, next to a stub <code>instances</code> built on the standard library’s <code>http.server</code>, and talks to it only with <code>httpx</code>. A boundary test fails if the suite ever imports service code.</p>
<p>It had to be green against Django before a line of FastAPI existed. Then I broke Django on purpose (removed one field from a serializer) and checked that the suite failed.</p>
<p>Writing it turned up behaviour the frontend depends on that nobody had written down:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Behaviour</th>
<th>Django REST Framework</th>
<th>FastAPI default</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Validation error</td>
<td><strong>400</strong> <code>{"field": ["message"]}</code></td>
<td>422 <code>{"detail": [...]}</code></td>
</tr>
<tr class="even">
<td>Page shape</td>
<td><code>{count, next, previous, results}</code>, absolute URLs</td>
<td>none</td>
</tr>
<tr class="odd">
<td>API vs event timestamps</td>
<td><code>...123456Z</code> vs <code>...123456+00:00</code></td>
<td>one format</td>
</tr>
<tr class="even">
<td><code>/internal/</code> without a token</td>
<td><strong>403</strong> (no authenticator there)</td>
<td>usually 401</td>
</tr>
<tr class="odd">
<td><code>previous</code> on page 2</td>
<td>the list URL without <code>page=1</code></td>
<td>not applicable</td>
</tr>
</tbody>
</table>
<p>Each row became a test. The FastAPI version was done when the same suite passed against it. It ended at <strong>84 of 84 on both targets</strong>.</p>
<hr>
</section>
<section id="functional-tests-passed.-the-first-real-deploy-did-not." class="level2">
<h2 class="anchored" data-anchor-id="functional-tests-passed.-the-first-real-deploy-did-not.">Functional tests passed. The first real deploy did not.</h2>
<p>The parity suite runs on SQLite. The first deploy to the LXC stack ran on Postgres, and <code>migrate</code> failed: the databases were created as <code>SQL_ASCII</code>, and psycopg returned text as bytes. Django had been hiding this all along, because it sets <code>client_encoding=utf8</code> and <code>TimeZone=UTC</code> on every connection. The FastAPI engine now does the same, and the schema test’s throwaway database is <code>SQL_ASCII</code> too, so the test fails without the fix.</p>
<p>That is a small version of the whole story. <strong>The things a framework does for you are part of its behaviour, and a port has to find each one.</strong></p>
<hr>
</section>
<section id="the-first-measurement-could-not-tell-them-apart" class="level2">
<h2 class="anchored" data-anchor-id="the-first-measurement-could-not-tell-them-apart">The first measurement could not tell them apart</h2>
<p>The existing k6 scenarios are mostly <code>instances</code> traffic. At a fixed 200 req/s, <code>catalog</code> received only 26 to 34 req/s at about 3% CPU on both implementations. Its own request groups differed by fractions of a millisecond: <code>questionnaire-type-list</code> had a mean of 2.9 ms on Django and 3.2 ms on FastAPI in the mixed run. Whole-run numbers were <code>instances</code>’ numbers.</p>
<p>That is a real result, and it is easy to misread as “same performance”. It only says that <code>catalog</code> was not the bottleneck. The stress runs were more useful, because one of them broke.</p>
<hr>
</section>
<section id="the-deadlock" class="level2">
<h2 class="anchored" data-anchor-id="the-deadlock">The deadlock</h2>
<p>One stress run (<code>stress-20261111T080102Z</code>) ended with <strong>93 HTTP 502s, all on <code>catalog</code></strong>, in waves 30 seconds apart, and they continued for 2 minutes after k6 had stopped. The log said:</p>
<pre><code>QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30</code></pre>
<p>The cause is two pools that wait on each other.</p>
<ul>
<li>FastAPI runs every sync dependency and every sync endpoint on a thread from AnyIO’s thread pool. That pool has <strong>40</strong> threads by default.</li>
<li>SQLAlchemy keeps <strong>15</strong> connections per worker (pool size 5 plus overflow 10).</li>
<li>The auth dependency, <code>current_user</code>, runs on one thread, loads the user and returns. The endpoint then needs a <strong>second</strong> trip to the thread pool. The request session lives for the whole request, so the connection stays checked out while the request waits for that second thread.</li>
</ul>
<p>Under load, all 15 connections end up held by requests that are queued for a thread. All 40 threads are running requests that are blocked waiting for a connection. Nothing can move until the pool checkouts time out after 30 seconds. Then the gateway returns 502s, the cycle forms again, and you get waves.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/37_pool_deadlock.svg" class="img-fluid figure-img"></p>
<figcaption>The deadlock: threads wait for connections, and connections are held by requests that wait for threads</figcaption>
</figure>
</div>
<p>The fix is one line at the end of the dependency. <code>expire_on_commit</code> is off, so the <code>User</code> object stays usable after the commit:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> current_user(request: Request, session: Annotated[Session, Depends(get_session)]) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> User:</span>
<span id="cb2-2">    ...</span>
<span id="cb2-3">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Hand the connection back before the endpoint waits for a thread, or a busy</span></span>
<span id="cb2-4">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># worker deadlocks: every thread waits for a connection that a request waiting</span></span>
<span id="cb2-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># for a thread holds.</span></span>
<span id="cb2-6">    session.commit()</span>
<span id="cb2-7">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> user</span></code></pre></div></div>
<hr>
</section>
<section id="a-deadlock-test-that-runs-in-a-second" class="level2">
<h2 class="anchored" data-anchor-id="a-deadlock-test-that-runs-in-a-second">A deadlock test that runs in a second</h2>
<p>A load test found it. A load test is a poor regression test, because it takes an hour and needs a lab. So the test shrinks both pools until the cycle forms with a handful of requests: <strong>2 threads, 1 connection, 8 concurrent requests</strong>.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@pytest.fixture</span></span>
<span id="cb3-2"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> one_connection(tmp_path, monkeypatch):</span>
<span id="cb3-3">    engine <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> create_engine(</span>
<span id="cb3-4">        <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"sqlite:///</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>tmp_path <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">'pool.sqlite3'</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb3-5">        connect_args<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"check_same_thread"</span>: <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>},</span>
<span id="cb3-6">        poolclass<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>QueuePool, pool_size<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, max_overflow<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>, pool_timeout<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">3</span>,</span>
<span id="cb3-7">    )</span>
<span id="cb3-8">    ...</span>
<span id="cb3-9"></span>
<span id="cb3-10"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> _concurrent_requests(token: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span>) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span>]:</span>
<span id="cb3-11">    anyio.to_thread.current_default_thread_limiter().total_tokens <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span></span>
<span id="cb3-12">    transport <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> httpx.ASGITransport(app<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>create_app(), raise_app_exceptions<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb3-13">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> httpx.AsyncClient(transport<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>transport, base_url<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"http://testserver"</span>,</span>
<span id="cb3-14">                                 headers<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Authorization"</span>: <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"Bearer </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>token<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>}) <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> client:</span>
<span id="cb3-15">        responses <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> asyncio.gather(<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>(client.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/api/accounts/me/"</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> _ <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">range</span>(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span>)))</span>
<span id="cb3-16">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> [r.status_code <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> responses]</span>
<span id="cb3-17"></span>
<span id="cb3-18"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> test_concurrent_requests_do_not_starve_the_pool(one_connection):</span>
<span id="cb3-19">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">assert</span> asyncio.run(_concurrent_requests(one_connection)) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">==</span> [<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">8</span></span></code></pre></div></div>
<p>It returned 500s before the fix and passes after it. The technique generalises: <strong>a resource bug that needs 600 req/s to show up usually needs only 2 of each resource in a test.</strong> Make the pools tiny and the race becomes certain.</p>
<hr>
</section>
<section id="the-second-pool-bug-found-by-verifying-the-first" class="level2">
<h2 class="anchored" data-anchor-id="the-second-pool-bug-found-by-verifying-the-first">The second pool bug, found by verifying the first</h2>
<p>The rerun after the fix failed in a new way. At the start of the read stress (23 failures) and the soak (101 failures), every k6 user logged in at once. Each login held a connection through the pbkdf2 password hash, which takes long by design, and a login burst starved the pool.</p>
<p>Three changes fixed it:</p>
<ul>
<li><code>authenticate</code> commits before it hashes.</li>
<li><code>create_user</code> hashes before its first query.</li>
<li>AnyIO’s thread limit is set to the pool size, 15, in the app’s lifespan. A thread can then never wait for a connection, because there are never more threads than connections.</li>
</ul>
<p>Two more tests in the same file cover this. The login test makes the hash sleep 0.5 s, runs 4 logins on 2 threads, and sets a 1 s pool timeout. If the connection is held through the hash, the logins queue past the timeout. A third test asserts that the thread limit equals the pool size.</p>
<hr>
</section>
<section id="measuring-catalog-on-its-own" class="level2">
<h2 class="anchored" data-anchor-id="measuring-catalog-on-its-own">Measuring <code>catalog</code> on its own</h2>
<p>With the deadlocks fixed, FastAPI matched Django on the mixed traffic. That still said little, because <code>catalog</code> sat at 3 to 8% CPU in every run. So a follow-up plan added a k6 scenario that loads only <code>catalog</code>: lists, details, <code>/me</code>, token refresh, and create, update and delete of a type. Django was deployed again from the last commit that had it, and the two ran back to back.</p>
<p>The first FastAPI runs were much worse than Django:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th></th>
<th>Django</th>
<th>FastAPI, first runs</th>
<th>FastAPI, fixed</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>CRUD knee</td>
<td>~409 to ~431 req/s</td>
<td>~176 to ~183</td>
<td><strong>~532 to ~594</strong></td>
</tr>
<tr class="even">
<td>At ~240 req/s: p95 / <code>catalog</code> CPU</td>
<td>27.6 ms / 41%</td>
<td>not measured</td>
<td><strong>16.5 ms / 25%</strong></td>
</tr>
<tr class="odd">
<td>Login knee</td>
<td>~17.0/s</td>
<td>~11.1/s</td>
<td>~16.8/s</td>
</tr>
</tbody>
</table>
<p>Two more bugs explained the gap, and both were things Django’s libraries had done for me:</p>
<ul>
<li><strong>The signing key was parsed on every token.</strong> PyJWT parses a PEM string for each signature: 25 ms of CPU, against 0.19 ms with a loaded key object. <code>token-refresh</code> took 65 ms against Django’s 2.8 ms. The fix caches the loaded key with <code>lru_cache</code>.</li>
<li><strong>A new <code>httpx</code> client for every call to <code>instances</code>.</strong> That cost 3.6 ms against 0.42 ms per call, and it leaked memory: workers grew from about 135 to about 275 MiB each in 5 minutes. One shared client per process fixed both. Anonymous memory had doubled from 416 to 836 MiB in 5 minutes before the fix. After it, it stayed flat: 414 to 443 MiB.</li>
</ul>
<p>Each fix has a test that fails without it.</p>
<hr>
</section>
<section id="the-final-numbers" class="level2">
<h2 class="anchored" data-anchor-id="the-final-numbers">The final numbers</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Measurement</th>
<th>Django</th>
<th>FastAPI</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Parity suite</td>
<td>84 / 84</td>
<td>84 / 84</td>
</tr>
<tr class="even">
<td>Mixed traffic stress knee</td>
<td>~575 to ~614 req/s</td>
<td>~600 req/s</td>
</tr>
<tr class="odd">
<td>Read-mostly stress knee</td>
<td>~495 to ~526 req/s</td>
<td>~518 req/s</td>
</tr>
<tr class="even">
<td>1 h soak at ~352 req/s</td>
<td>held (2026-11-06 run)</td>
<td><strong>0 failed of 1,268,223</strong>, p95 22.1 ms</td>
</tr>
<tr class="odd">
<td><code>catalog</code> alone, CRUD knee</td>
<td>~409 to ~431 req/s</td>
<td>~532 to ~594 req/s</td>
</tr>
<tr class="even">
<td><code>catalog</code> alone, ~240 req/s</td>
<td>p95 27.6 ms, CPU 41%</td>
<td>p95 16.5 ms, CPU 25%</td>
</tr>
<tr class="odd">
<td>Login knee</td>
<td>~17.0/s</td>
<td>~16.8/s</td>
</tr>
<tr class="even">
<td>Memory</td>
<td>baseline</td>
<td>~100 to 170 MiB more</td>
</tr>
<tr class="odd">
<td><code>token</code> p95 in a re-login burst</td>
<td>3.8 s</td>
<td>6.4 s</td>
</tr>
</tbody>
</table>
<p>In the mixed and read stress runs, both implementations broke on <code>instances</code> at 80 to 90% CPU, not on <code>catalog</code>. The soak had zero <code>QueuePool</code> timeouts in <code>catalog</code>’s log.</p>
<p>FastAPI is not free. It uses more memory, and a burst of logins is slower, because it runs up to 15 password hashes per worker at once where Django ran 4. Every stress run on both ended the same way: k6 adding users who all log in at the same moment. So the knees understate what <code>catalog</code> serves to users who are already logged in.</p>
<hr>
</section>
<section id="then-delete-django" class="level2">
<h2 class="anchored" data-anchor-id="then-delete-django">Then delete Django</h2>
<p>Only after the numbers were recorded did the Django <code>catalog</code> go, migrations included. The parity suite lost its <code>--target</code> option and became <code>catalog</code>’s API test suite. The repo-level tests changed to guard the new contracts:</p>
<ul>
<li><code>test_catalog_schema.py</code> compares Alembic’s first revision with a frozen dump of the Django-built schema, and tests adopting a Django-built database.</li>
<li><code>test_catalog_compat.py</code> checks that hashes and tokens made by FastAPI work in <code>instances</code>’ Django, with seed ids frozen from Django’s.</li>
<li>A boundary test fails if <code>catalog</code> imports Django. A search for <code>manage.py</code> or a Django import in <code>backend/catalog</code> finds nothing.</li>
</ul>
<p>The final checks: <code>catalog</code> 97 tests, parity 84, <code>instances</code> 243 and the repo tests 132 all passed, then a k6 smoke run on the deploy passed 640 of 640 checks.</p>
<hr>
</section>
<section id="what-this-is-not" class="level2">
<h2 class="anchored" data-anchor-id="what-this-is-not">What this is not</h2>
<p><code>catalog</code> is a small, CRUD-shaped service, and it is not the hot path. The rewrite says nothing about porting a large Django app with admin-heavy workflows. The admin did get worse: sqladmin cannot edit ordered inline items or reset passwords the way Django’s admin could. The load is synthetic, from one generator, on a home lab.</p>
<p>The FastAPI version runs sync endpoints only, so these numbers say nothing about async FastAPI. The work lives on the <code>feature/FastAPI</code> branch and is not merged into <code>main</code> yet. Django’s own tables (<code>django_session</code>, <code>django_migrations</code> and others) are still in the database, waiting for a follow-up Alembic migration. <code>instances</code> still builds a new <code>httpx</code> client per call to <code>catalog</code>, the same bug fixed above in the other direction.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Step</th>
<th>What it caught</th>
<th>Lesson</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Black-box parity suite</td>
<td>Undocumented DRF contracts (400 shape, page URLs, 403 vs 401)</td>
<td>Pin behaviour before you change the code under it</td>
</tr>
<tr class="even">
<td>First real deploy</td>
<td><code>SQL_ASCII</code> databases Django had hidden</td>
<td>A framework’s defaults are part of its behaviour</td>
</tr>
<tr class="odd">
<td>Mixed-traffic stress</td>
<td>Thread pool vs connection pool deadlock</td>
<td>Never hold a connection across a wait for a thread</td>
</tr>
<tr class="even">
<td>Verifying that fix</td>
<td>Logins holding a connection through the hash</td>
<td>Rerun the load test after every fix, not only the unit test</td>
</tr>
<tr class="odd">
<td><code>catalog</code>-only scenario</td>
<td>PEM parsed per token, <code>httpx</code> client per call</td>
<td>Load the component itself, or you measure its neighbours</td>
</tr>
</tbody>
</table>
<p>Functional tests proved the port did the same things. Only load proved it could do them at the same time. All four performance bugs were invisible at one request per second, and each now has a test that runs in seconds.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Software</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/fastapi_port_pool_deadlock.html</guid>
  <pubDate>Wed, 11 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>FastAPI for Django Developers</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/fastapi_for_django_developers.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>I have written Django for years (see <a href="../posts/django_deep_cuts.html">Django Deep Cuts</a>). This post comes from moving one small service in a side project from Django REST Framework to FastAPI, and from the two reference notebooks I wrote while doing it: <a href="https://bthek1.github.io/Back_End/FastAPI/fastapi_stack.html">FastAPI Stack</a> and <a href="https://bthek1.github.io/Back_End/FastAPI/sqlalchemy_alembic.html">SQLAlchemy and Alembic</a>. Those are the full reference. This is the opinionated short version.</p>
</blockquote>
<p>The surprise was not that FastAPI is hard. It is small and pleasant. The surprise was how many decisions Django had been making on my behalf, silently and correctly, for years. FastAPI hands every one of them back. Each bug I hit lived in a decision I did not know I was now making.</p>
<hr>
<section id="the-map" class="level2">
<h2 class="anchored" data-anchor-id="the-map">The map</h2>
<p>Most of Django has a direct counterpart. The rows that matter are the ones where the right-hand side is “you build it”.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Django / DRF</th>
<th>FastAPI stack</th>
<th>Who decides now</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>settings.py</code></td>
<td><code>pydantic-settings</code> <code>Settings</code></td>
<td>You, but it is typed</td>
</tr>
<tr class="even">
<td><code>models.Model</code></td>
<td>SQLAlchemy <code>DeclarativeBase</code> subclass</td>
<td>You name the constraints</td>
</tr>
<tr class="odd">
<td><code>makemigrations</code> / <code>migrate</code></td>
<td><code>alembic revision --autogenerate</code> / <code>alembic upgrade head</code></td>
<td>You read every draft</td>
</tr>
<tr class="even">
<td><code>ModelSerializer</code></td>
<td>Pydantic models, one per shape</td>
<td>You choose what leaves</td>
</tr>
<tr class="odd">
<td><code>ViewSet</code> + <code>DefaultRouter</code></td>
<td>Functions on an <code>APIRouter</code></td>
<td>Same as before</td>
</tr>
<tr class="even">
<td><code>request.user</code>, <code>permission_classes</code></td>
<td>A <code>CurrentUser</code> dependency that raises <code>401</code>/<code>403</code></td>
<td>Same as before</td>
</tr>
<tr class="odd">
<td>Connection per request, <code>ATOMIC_REQUESTS</code></td>
<td>A session dependency you write</td>
<td><strong>You</strong></td>
</tr>
<tr class="even">
<td><code>select_related</code> / <code>prefetch_related</code></td>
<td><code>joinedload</code> / <code>selectinload</code></td>
<td><strong>You, or it is an error</strong></td>
</tr>
<tr class="odd">
<td><code>drf-spectacular</code></td>
<td>Built in: <code>/docs</code></td>
<td>Nobody, it is free</td>
</tr>
<tr class="even">
<td>Django admin</td>
<td>Nothing built in (<code>sqladmin</code> is closest)</td>
<td>You</td>
</tr>
<tr class="odd">
<td>Celery</td>
<td>Celery, unchanged</td>
<td>Same as before</td>
</tr>
</tbody>
</table>
<p>The diagram shows one request through the new stack, with the six places (A to F) where a Django habit broke something.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/35_fastapi_traps.svg" class="img-fluid figure-img"></p>
<figcaption>One FastAPI request, the long-lived engine and Alembic, with six numbered traps</figcaption>
</figure>
</div>
<hr>
</section>
<section id="async-def-is-a-promise-you-have-to-keep" class="level2">
<h2 class="anchored" data-anchor-id="async-def-is-a-promise-you-have-to-keep">1. <code>async def</code> is a promise you have to keep</h2>
<p>In Django every view runs in its own worker thread or process, so a slow call only blocks itself. In FastAPI the choice of keyword decides where your code runs.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>You write</th>
<th>FastAPI runs it</th>
<th>Use it when</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>async def</code></td>
<td>On the event loop, in the main thread</td>
<td>Everything slow inside is <code>await</code>ed</td>
</tr>
<tr class="even">
<td><code>def</code></td>
<td>In a thread pool (40 threads by default)</td>
<td>You call anything blocking</td>
</tr>
</tbody>
</table>
<p>A blocking call inside <code>async def</code> stalls the event loop. While it waits, <strong>every other request in that process waits too</strong>. The bug does not show in a unit test. It shows as latency that climbs with load for no visible reason.</p>
<div id="23cc7d18" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># wrong: requests.get blocks the event loop for every request in the process</span></span>
<span id="cb1-2"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@router.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/rate"</span>)</span>
<span id="cb1-3"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> rate():</span>
<span id="cb1-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> requests.get(FX_URL).json()</span>
<span id="cb1-5"></span>
<span id="cb1-6"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># right: await an async client, or drop the async keyword and let it use a thread</span></span>
<span id="cb1-7"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@router.get</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/rate"</span>)</span>
<span id="cb1-8"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> rate(client: HttpDep):</span>
<span id="cb1-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> (<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> client.get(FX_URL)).json()</span></code></pre></div></div>
</div>
<p>My rule: write <code>async def</code> only when every slow call inside is awaited. Otherwise write <code>def</code> and let FastAPI find a thread. CPU-heavy work blocks either way, so it goes to <code>anyio.to_thread.run_sync</code> or to Celery.</p>
<hr>
</section>
<section id="lazy-loading-is-an-error-now" class="level2">
<h2 class="anchored" data-anchor-id="lazy-loading-is-an-error-now">2. Lazy loading is an error now</h2>
<p>In Django, <code>post.author</code> quietly runs a query. At worst it is an N+1. In async SQLAlchemy the same attribute read <strong>raises <code>MissingGreenlet</code></strong>, because a plain attribute access cannot <code>await</code> the IO it needs.</p>
<p>The fix is to say what you will touch as part of the query. The two loaders map straight onto what you already know:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>SQLAlchemy</th>
<th>SQL it runs</th>
<th>Django nearest</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>joinedload(Post.author)</code></td>
<td><code>LEFT OUTER JOIN</code> in the same query</td>
<td><code>select_related</code></td>
</tr>
<tr class="even">
<td><code>selectinload(User.posts)</code></td>
<td>A second <code>SELECT ... WHERE id IN (...)</code></td>
<td><code>prefetch_related</code></td>
</tr>
<tr class="odd">
<td><code>lazy="raise"</code></td>
<td>Nothing. Access raises at once</td>
<td>No equivalent</td>
</tr>
</tbody>
</table>
<div id="e2ff6fe3" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> User(Base):</span>
<span id="cb2-2">    posts: Mapped[<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">list</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Post"</span>]] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> relationship(back_populates<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"author"</span>, lazy<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"raise"</span>)</span>
<span id="cb2-3"></span>
<span id="cb2-4">stmt <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> select(User).options(selectinload(User.posts))</span>
<span id="cb2-5">users <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (<span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> session.scalars(stmt)).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">all</span>()</span></code></pre></div></div>
</div>
<p><strong>Put <code>lazy="raise"</code> on every relationship.</strong> Then a missing loader fails in your tests, with a message that names the attribute, instead of failing in production. I now think this is better than Django’s default. The N+1 that Django lets you ship by accident cannot be written at all.</p>
<hr>
</section>
<section id="the-session-is-yours-to-scope" class="level2">
<h2 class="anchored" data-anchor-id="the-session-is-yours-to-scope">3. The session is yours to scope</h2>
<p>Django opens a connection per request and closes it after. With <code>ATOMIC_REQUESTS</code> it even wraps the request in a transaction. In FastAPI you write that scoping yourself, and there are two halves to get right.</p>
<p>The <strong>engine</strong> owns the connection pool. Create it once per process, at import. An engine per request is a pool per request. The <strong>session</strong> is one unit of work. Create one per request, through a dependency:</p>
<div id="3356de15" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">engine <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> create_async_engine(settings.database_url, pool_pre_ping<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb3-2">SessionLocal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> async_sessionmaker(engine, expire_on_commit<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span>
<span id="cb3-3"></span>
<span id="cb3-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> get_session() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> AsyncIterator[AsyncSession]:</span>
<span id="cb3-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> SessionLocal() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> session:</span>
<span id="cb3-6">        <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">yield</span> session</span>
<span id="cb3-7"></span>
<span id="cb3-8">SessionDep <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Annotated[AsyncSession, Depends(get_session)]</span></code></pre></div></div>
</div>
<p>Three details I missed at first:</p>
<ul>
<li><strong><code>expire_on_commit=False</code>.</strong> The default expires every attribute on commit. In async code the next attribute read then needs IO, which is section 2 again.</li>
<li><strong>Dependencies are cached per request.</strong> If the endpoint and <code>get_current_user</code> both ask for <code>SessionDep</code>, they share one session and one transaction. That is what you want.</li>
<li><strong>A connection is checked out from the first query until the session commits or closes.</strong> A dependency that queries and then hands control to something that waits, keeps its connection the whole time. Under enough load, every pooled connection can be held by code that is waiting for something else. Commit, or close, as soon as a dependency has what it needs. (That one became a real deadlock under load testing. It gets its own post.)</li>
</ul>
<hr>
</section>
<section id="serializers-became-response-models-and-they-are-now-the-only-guard" class="level2">
<h2 class="anchored" data-anchor-id="serializers-became-response-models-and-they-are-now-the-only-guard">4. Serializers became response models, and they are now the only guard</h2>
<p>A DRF <code>ModelSerializer</code> with <code>fields = [...]</code> is an allow-list. You never think about it. In FastAPI, if you return an ORM object from an endpoint with no <code>response_model</code>, nothing stands between the row and the client. That includes <code>password_hash</code>.</p>
<p>Write one Pydantic model per direction and declare the output one on every endpoint:</p>
<div id="af7fb930" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> ItemCreate(BaseModel):</span>
<span id="cb4-2">    title: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> Field(min_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>, max_length<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">200</span>)</span>
<span id="cb4-3"></span>
<span id="cb4-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> ItemRead(BaseModel):</span>
<span id="cb4-5">    model_config <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> ConfigDict(from_attributes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb4-6">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">int</span></span>
<span id="cb4-7">    title: <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">str</span></span>
<span id="cb4-8"></span>
<span id="cb4-9"><span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">@router.post</span>(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"/items"</span>, response_model<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>ItemRead, status_code<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">201</span>)</span>
<span id="cb4-10"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> create_item(body: ItemCreate, session: SessionDep, user: CurrentUser): ...</span></code></pre></div></div>
</div>
<p>Error shapes change too. Pydantic and DRF word validation errors differently. A client that parses DRF’s <code>{"title": ["This field may not be blank."]}</code> gets a different body from FastAPI unless you add an exception handler that keeps the old shape. If anything outside your repo calls the API, decide that on day one.</p>
<hr>
</section>
<section id="name-your-constraints-before-the-first-migration" class="level2">
<h2 class="anchored" data-anchor-id="name-your-constraints-before-the-first-migration">5. Name your constraints before the first migration</h2>
<p>Django names every index and constraint for you and remembers the names. SQLAlchemy without a naming convention lets PostgreSQL invent them, and then Alembic cannot refer to them in a later migration. Adding the convention later means a migration that renames every constraint you already have.</p>
<div id="39e83ce4" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1">NAMING_CONVENTION <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb5-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ix"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ix_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(column_0_label)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb5-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"uq"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"uq_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(table_name)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(column_0_name)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb5-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ck"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ck_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(table_name)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(constraint_name)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb5-5">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fk"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"fk_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(table_name)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(column_0_name)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(referred_table_name)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb5-6">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pk"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pk_</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">%(table_name)s</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb5-7">}</span>
<span id="cb5-8"></span>
<span id="cb5-9"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">class</span> Base(DeclarativeBase):</span>
<span id="cb5-10">    metadata <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> MetaData(naming_convention<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>NAMING_CONVENTION)</span></code></pre></div></div>
</div>
<p>Two more things Django did silently: it <strong>indexes every foreign key</strong>, and SQLAlchemy does not (add <code>index=True</code>). And use <code>DateTime(timezone=True)</code> everywhere, then write <code>datetime.now(UTC)</code>, never a naive datetime.</p>
<hr>
</section>
<section id="autogenerate-is-a-draft-not-a-migration" class="level2">
<h2 class="anchored" data-anchor-id="autogenerate-is-a-draft-not-a-migration">6. Autogenerate is a draft, not a migration</h2>
<p><code>makemigrations</code> asks you “did you rename this field?”. Alembic’s autogenerate does not ask. A renamed column comes out as <strong>drop the old column, add a new one</strong>, and the data goes with the drop. It runs cleanly and looks fine on an empty dev database.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Change</th>
<th>What autogenerate writes</th>
<th>What you write instead</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Rename a column</td>
<td>Drop plus add. <strong>Data lost</strong></td>
<td><code>op.alter_column(..., new_column_name=...)</code></td>
</tr>
<tr class="even">
<td>Move or transform data</td>
<td>Nothing</td>
<td><code>op.execute(...)</code> in its own revision</td>
</tr>
<tr class="odd">
<td>Add a PostgreSQL <code>ENUM</code> value</td>
<td>Nothing</td>
<td><code>ALTER TYPE ... ADD VALUE</code></td>
</tr>
<tr class="even">
<td>Enable pgvector</td>
<td>Nothing</td>
<td><code>CREATE EXTENSION IF NOT EXISTS vector</code></td>
</tr>
<tr class="odd">
<td>A model module not imported in <code>env.py</code></td>
<td><strong>Drops its table</strong></td>
<td>Import every model module in <code>env.py</code></td>
</tr>
</tbody>
</table>
<p>For data migrations the Django rule carries over, with less help. Django gives you <code>apps.get_model()</code> to get the historical model. Alembic has nothing, so describe the columns inline and never import your ORM models:</p>
<div id="b7a3a1f7" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb6" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb6-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> upgrade() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb6-2">    op.add_column(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"post"</span>, sa.Column(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slug"</span>, sa.String(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">220</span>), nullable<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>))</span>
<span id="cb6-3">    post <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> sa.table(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"post"</span>, sa.column(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>, sa.String), sa.column(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slug"</span>, sa.String))</span>
<span id="cb6-4">    op.execute(post.update().values(slug<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>sa.func.lower(sa.func.replace(post.c.title, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">" "</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"-"</span>))))</span>
<span id="cb6-5">    op.alter_column(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"post"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"slug"</span>, nullable<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">False</span>)</span></code></pre></div></div>
</div>
<p>That is also the safe shape for a new required column on a table that has rows: add it nullable, fill it, then set <code>NOT NULL</code>. Read every generated revision before you apply it. That habit is the whole of Alembic safety.</p>
<hr>
</section>
<section id="migrations-are-a-deploy-step-not-a-startup-step" class="level2">
<h2 class="anchored" data-anchor-id="migrations-are-a-deploy-step-not-a-startup-step">7. Migrations are a deploy step, not a startup step</h2>
<p>It is tempting to call <code>alembic upgrade head</code> in FastAPI’s <code>lifespan</code>, the way some Django images run <code>migrate</code> in the entrypoint. With more than one replica they start together and race the schema. Run the migration as its own step, before the new app containers start.</p>
<p>During a rolling deploy, old and new code run against the same schema for a while. So each migration must work with <strong>both</strong> versions. That is <em>expand and contract</em>: add the new column, deploy code that writes both, backfill, and drop the old column in a later release. A rename is three releases, not one.</p>
<p>One PostgreSQL detail: building an index locks writes on the table, and <code>CREATE INDEX CONCURRENTLY</code> cannot run inside a transaction. Alembic wraps each revision in one, so step outside it:</p>
<div id="d2739528" class="cell">
<div class="code-copy-outer-scaffold"><div class="sourceCode cell-code" id="cb7" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb7-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> upgrade() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-&gt;</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>:</span>
<span id="cb7-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> op.get_context().autocommit_block():</span>
<span id="cb7-3">        op.create_index(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ix_post_title"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"post"</span>, [<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"title"</span>], postgresql_concurrently<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span></code></pre></div></div>
</div>
<hr>
</section>
<section id="when-i-would-still-pick-django" class="level2">
<h2 class="anchored" data-anchor-id="when-i-would-still-pick-django">When I would still pick Django</h2>
<p>Most of the time. Many CRUD models, a staff admin, one deployable unit: that is most business software, and Django does it with fewer decisions to get wrong. Its admin alone is worth weeks.</p>
<p>I pick FastAPI when the service is small and API-only, spends its time waiting on IO (streaming LLM output, proxying other APIs, WebSockets), or serves an ML model. Both sit happily behind the same React SPA, the same PostgreSQL and the same Celery, so it is a per-service choice, not a rewrite. The tooling around both is the same <code>uv</code> and <code>ruff</code> setup from <a href="../posts/modern_python_stack_2026.html">The Modern Python Stack</a>.</p>
<p>What makes the port safe is not the framework. It is a black-box test suite that runs the same HTTP requests against the old and the new service and compares the answers. With that in place, each of the decisions above becomes a test failure instead of a production surprise.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>#</th>
<th>Django did it for you</th>
<th>In FastAPI + SQLAlchemy, do this</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>1</td>
<td>Every view had its own thread</td>
<td><code>async def</code> only if every slow call is awaited, else <code>def</code></td>
</tr>
<tr class="even">
<td>2</td>
<td>Lazy loading just worked</td>
<td><code>lazy="raise"</code> everywhere, <code>joinedload</code> / <code>selectinload</code> per query</td>
</tr>
<tr class="odd">
<td>3</td>
<td>Connection per request</td>
<td>One engine per process, one session per request, <code>expire_on_commit=False</code>, release connections early</td>
</tr>
<tr class="even">
<td>4</td>
<td>Serializer field allow-lists</td>
<td>A <code>response_model</code> on every endpoint, one Pydantic model per direction</td>
</tr>
<tr class="odd">
<td>5</td>
<td>Named constraints, indexed foreign keys</td>
<td>A naming convention on day one, <code>index=True</code> on foreign keys</td>
</tr>
<tr class="even">
<td>6</td>
<td><code>makemigrations</code> asked about renames</td>
<td>Read every autogenerated revision; <code>sa.table()</code> in data migrations</td>
</tr>
<tr class="odd">
<td>7</td>
<td><code>migrate</code> before start</td>
<td>Migrate as a deploy step; expand and contract</td>
</tr>
</tbody>
</table>
<p>FastAPI is not harder than Django. It is more honest about what a web service has to decide. Once you have made those seven decisions on purpose, the result is small, fast and easy to read, and every one of them is a line you can point at.</p>
<p>Full reference: <a href="https://bthek1.github.io/Back_End/FastAPI/fastapi_stack.html">FastAPI Stack</a> and <a href="https://bthek1.github.io/Back_End/FastAPI/sqlalchemy_alembic.html">SQLAlchemy and Alembic</a>.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Software</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/fastapi_for_django_developers.html</guid>
  <pubDate>Tue, 10 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>One Paper Gateway, Two Traders</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/shared_ibkr_gateway.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The app is a Django REST + React + Celery dashboard with a separate trader process that talks to Interactive Brokers (IBKR) through IB Gateway, the headless version of their trading terminal. <strong>It trades a paper account only.</strong> Every check below was run against paper, on a home lab, with no real money anywhere near it.</p>
</blockquote>
<p>Until this week the whole thing ran on my dev machine. The goal was a deployed stack that runs all the time, so the stored stock data builds up, while dev keeps trading on the same paper account. One rule from IBKR shaped every decision after it: <strong>one session per username.</strong></p>
<hr>
<section id="the-constraint-one-login-one-session" class="level2">
<h2 class="anchored" data-anchor-id="the-constraint-one-login-one-session">The constraint: one login, one session</h2>
<p>IBKR allows one logged-in session per username. The Gateway container is set to <code>EXISTING_SESSION_DETECTED_ACTION=primary</code>, which logs off any other session. So if dev and the deployed stack each ran a Gateway, starting dev would silently log the deployed one off.</p>
<p>The way out is that one Gateway accepts up to 32 API clients, each with its own client ID. So there is one Gateway, and two traders connect to it as clients:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th></th>
<th>Deployed trader</th>
<th>Dev trader</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Client ID</td>
<td>1</td>
<td>2</td>
</tr>
<tr class="even">
<td>Peer client IDs (ignored)</td>
<td>2</td>
<td>1</td>
</tr>
<tr class="odd">
<td>Market data lines</td>
<td>60</td>
<td>30</td>
</tr>
<tr class="even">
<td>Database and Redis</td>
<td>its own</td>
<td>its own</td>
</tr>
<tr class="odd">
<td>Background stock loading</td>
<td>on</td>
<td>off</td>
</tr>
</tbody>
</table>
<p>The dev side also sets <code>IB_GATEWAY_SHARED=true</code>, and with that set <code>just gateway-up</code> refuses to start a local Gateway. The mistake that would log the shared session off now needs someone to edit a file first.</p>
<hr>
</section>
<section id="four-machines-from-pulumi-configured-by-ansible" class="level2">
<h2 class="anchored" data-anchor-id="four-machines-from-pulumi-configured-by-ansible">Four machines from Pulumi, configured by Ansible</h2>
<p>The Gateway got its own machine, so there are four LXC containers on one <a href="../posts/proxmox_home_lab.html">Proxmox</a> node:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
<col style="width: 20%">
</colgroup>
<thead>
<tr class="header">
<th>Machine</th>
<th>Cores</th>
<th>RAM</th>
<th>Disk</th>
<th>Runs</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>ibkr-obs</code></td>
<td>2</td>
<td>4 GB</td>
<td>100 GB</td>
<td>Grafana, Prometheus, Loki</td>
</tr>
<tr class="even">
<td><code>ibkr-db</code></td>
<td>2</td>
<td>2 GB</td>
<td>60 GB</td>
<td>Postgres 16</td>
</tr>
<tr class="odd">
<td><code>ibkr-gateway</code></td>
<td>2</td>
<td>2 GB</td>
<td>16 GB</td>
<td>IB Gateway, and nothing else</td>
</tr>
<tr class="even">
<td><code>ibkr-app</code></td>
<td>2</td>
<td>4 GB</td>
<td>40 GB</td>
<td>the Compose stack: nginx, gunicorn, Celery, trader, Redis, tunnel</td>
</tr>
</tbody>
</table>
<p><a href="../posts/pulumi_vs_terraform.html">Pulumi</a> (Python, <code>pulumi_proxmoxve</code>) creates them, copying the container pattern from another project of mine. A few rules carried over because they had already saved me once:</p>
<ul>
<li><strong>A local <code>file://</code> state backend, set per command through <code>PULUMI_BACKEND_URL</code>.</strong> Never <code>pulumi login</code>: it is global, and the other project’s recipes depend on it.</li>
<li><strong><code>protect=True</code> and <code>retain_on_delete=True</code> on every container, and no destroy recipe.</strong></li>
<li><strong>No addresses in tracked files.</strong> The stack config with the IPs is git-ignored, with a tracked <code>.example</code> next to it.</li>
</ul>
<p>The first preview said <code>+ 5 to create</code> (the stack and four containers). <code>pulumi up</code> created them in 17 s. The second preview said <code>5 unchanged</code>, and so did the other project’s stack. That second preview is the real test.</p>
<p><a href="../posts/terraform_ansible_home_lab.html">Ansible</a> then configures each machine: Postgres with a <code>pg_hba</code> that admits only the app host, Docker and the Compose plugin, the Gateway machine’s SSH rules and firewall, and Alloy on all four for metrics and logs. Secrets come from an Ansible Vault. The IBKR login sits in a second Vault file that is git-ignored, because the repo rule is that broker credentials are never committed, not even encrypted.</p>
<hr>
</section>
<section id="why-the-gateway-gets-a-machine-of-its-own" class="level2">
<h2 class="anchored" data-anchor-id="why-the-gateway-gets-a-machine-of-its-own">Why the Gateway gets a machine of its own</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/33_shared_gateway_topology.svg" class="img-fluid figure-img"></p>
<figcaption>The deployed and dev traders reach one paper Gateway through restricted SSH tunnels</figcaption>
</figure>
</div>
<p>Three reasons, in order of how much they mattered:</p>
<ol type="1">
<li><strong>Deploying or rebooting <code>ibkr-app</code> no longer drops dev’s connection.</strong> If the Gateway lived on the app host, every deploy would take dev down too.</li>
<li><strong>A Gateway problem cannot take memory from the app.</strong> The Gateway is a Java process, and its 2 GB is a starting guess to check in Grafana after a week.</li>
<li><strong>The machine that holds the broker login runs nothing else.</strong> That makes “who can reach the API port” a short question to answer.</li>
</ol>
<hr>
</section>
<section id="the-tws-api-has-no-login-so-the-network-is-the-authentication" class="level2">
<h2 class="anchored" data-anchor-id="the-tws-api-has-no-login-so-the-network-is-the-authentication">The TWS API has no login, so the network is the authentication</h2>
<p>The Gateway’s API (the TWS API) has no authentication and no encryption. Anything that can open a TCP connection to it can place orders. So the whole security design is about who can reach that port.</p>
<p>On <code>ibkr-gateway</code> the API is published on <code>127.0.0.1:4002</code> only. It is never on the LAN. From the dev machine, <code>nc -z</code> to port 4002 on both <code>ibkr-gateway</code> and <code>ibkr-app</code> fails.</p>
<p>On <code>ibkr-app</code> the problem is the other containers. In the old dev Compose file every container could reach the Gateway, including the Celery workers that download data from outside. A compromised worker could have traded. The prod file has a Docker network called <code>gateway</code> with <code>internal: true</code> and exactly two members, the trader and the tunnel. Everything else reaches IBKR only by sending a command to the trader through Redis.</p>
<p>That was checked from inside the running containers, not just in the YAML. From <code>web</code>, <code>celery_worker</code> and <code>nginx</code>, the name <code>gateway-tunnel</code> does not resolve. From <code>web</code> and <code>celery_stocks</code>, a connection to the tunnel’s IP on 4002 times out. From <code>trader</code>, the name resolves. A test (<code>test_only_the_trader_reaches_the_tunnel</code>) pins the network membership so a later edit cannot quietly widen it.</p>
<p>Two smaller rules in the same file: no <code>env_file</code> (every service lists its variables, so a local run cannot pull the dev <code>.env</code> into prod containers), and <code>${VAR:?}</code> on <code>SECRET_KEY</code>, <code>ALLOWED_HOSTS</code> and <code>DATABASE_URL</code>, so <code>docker compose config</code> fails without them.</p>
<hr>
</section>
<section id="an-ssh-key-that-can-open-one-port-and-nothing-else" class="level2">
<h2 class="anchored" data-anchor-id="an-ssh-key-that-can-open-one-port-and-nothing-else">An SSH key that can open one port and nothing else</h2>
<p>Both traders reach the Gateway the same way: an SSH local forward as a user called <code>gateway-tunnel</code>. On the deployed side it is an <code>autossh</code> container. On dev it is a <code>just gateway-tunnel</code> recipe. Each side has its own key, so either can be revoked alone.</p>
<p>Each line in that user’s <code>authorized_keys</code> starts like this:</p>
<pre class="text"><code>restrict,port-forwarding,permitopen="127.0.0.1:4002" ssh-ed25519 AAAA... deploy</code></pre>
<p>And <code>sshd_config</code> repeats the limits for the user, so a wrong key line cannot loosen them:</p>
<pre class="text"><code>Match User gateway-tunnel
    AllowTcpForwarding local
    PermitOpen 127.0.0.1:4002
    PermitTTY no
    X11Forwarding no
    ForceCommand /usr/sbin/nologin</code></pre>
<p><code>restrict</code> turns off everything (PTY, agent forwarding, X11, user rc files), and <code>port-forwarding</code> turns back on the one thing needed. <code>permitopen</code> limits that to a single destination. Password login is off for every user on the machine.</p>
<p>The checks, run with each real key:</p>
<ul>
<li><code>ssh gateway-tunnel@ibkr-gateway id</code> returns “This account is currently not available”. No shell.</li>
<li><code>-L ...:127.0.0.1:22</code> is refused by the server: “administratively prohibited”.</li>
<li><code>-L ...:127.0.0.1:4002</code> is accepted.</li>
<li><code>sshd -T</code> for the user shows <code>allowtcpforwarding local</code>, <code>permitopen 127.0.0.1:4002</code>, <code>permittty no</code> and <code>forcecommand /usr/sbin/nologin</code>.</li>
<li>From <code>ibkr-db</code>, TCP to port 22 on <code>ibkr-gateway</code> times out, because nftables lets SSH in from the two trader hosts only.</li>
</ul>
<p>One nftables detail worth knowing: the role replaces only its own table. It never runs <code>flush ruleset</code>, which would also delete the tables Docker writes for its own networking.</p>
<hr>
</section>
<section id="teaching-each-trader-to-ignore-the-other" class="level2">
<h2 class="anchored" data-anchor-id="teaching-each-trader-to-ignore-the-other">Teaching each trader to ignore the other</h2>
<p>The trader was written on the assumption that it was the only client on the account. Reconciliation compares IBKR’s open orders with its own database, and any order it does not know becomes an <code>unknown_broker_order</code> event, which sends an alert email. With a peer on the same account, every dev order would page the deployed stack, and the other way round.</p>
<p>The fix is a list of peer client IDs. Reconciliation drops orders by <code>order.clientId</code> and fills by <code>execution.clientId</code> before matching, with one debug line per pass. The order event stream skips a peer’s status, execution and commission events the same way. Orders from any other client still get reported: client 0 (an order placed in the desktop terminal) and client 98 (scripts).</p>
<p>Market data needed a budget. Each trader had a hard cap of 90 lines out of IBKR’s 100 per user, so two of them could ask for 180. The cap is now a setting, split 60 for deploy and 30 for dev.</p>
<p>Some things are shared on purpose, because the account is for testing, and they are written down rather than fixed:</p>
<ul>
<li><code>cancel_all</code> uses IBKR’s global cancel, which cancels the peer’s orders too.</li>
<li>The daily loss limit reads the whole account’s P&amp;L, so a dev loss can halt deploy.</li>
<li><code>READ_ONLY_API</code> is per Gateway, so dev cannot be read-only while deploy trades.</li>
</ul>
<p>The live check, with both traders connected at the same time: a buy of 1 share of F at $0.50 from dev, far from the market, submitted and then cancelled. On deploy, that produced <strong>0 <code>unknown_broker_order</code> events and 0 alert emails.</strong> (The first attempt, 1 share of AAPL at $1, never reached IBKR: the trader’s own risk check rejected it for going over the maximum position. That is the risk check working.)</p>
<hr>
</section>
<section id="idempotence-was-most-of-the-work" class="level2">
<h2 class="anchored" data-anchor-id="idempotence-was-most-of-the-work">Idempotence was most of the work</h2>
<p>The measurable goal was that a second <code>pulumi preview</code> and a second <code>just deploy</code> both report no changes. Getting Ansible there took more fixes than the deploy itself, and each one was a small lie about state:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Symptom</th>
<th>Cause</th>
<th>Fix</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>A <code>setlocale</code> warning on every remote command, and <code>synchronize</code> reporting a change every run</td>
<td>My workstation forwards <code>LC_ALL</code> over SSH, and the containers lacked that locale</td>
<td>The <code>docker</code> role generates the locale</td>
</tr>
<tr class="even">
<td><code>docker compose pull</code> reported a change every run</td>
<td>It prints “Pulled” even when nothing changed</td>
<td>Compare the image ID before and after</td>
</tr>
<tr class="odd">
<td>The observability stack restarted every run</td>
<td>Git checkout rewrites modification times, and rsync compared those</td>
<td>rsync compares checksums</td>
</tr>
<tr class="even">
<td>The app was unpacked and rebuilt every run</td>
<td>No record of what was deployed</td>
<td>A <code>DEPLOYED</code> file with the commit; same commit skips the build</td>
</tr>
<tr class="odd">
<td>A change reported after every reboot</td>
<td>Proxmox rewrites <code>/etc/resolv.conf</code> at boot</td>
<td>Stop managing that file; Pulumi sets DNS</td>
</tr>
</tbody>
</table>
<p>After those, the second <code>just deploy</code> gives <code>changed=0</code> on all four machines. A full deploy of a new commit took 3 min 7 s.</p>
<hr>
</section>
<section id="the-cutover-and-what-it-found" class="level2">
<h2 class="anchored" data-anchor-id="the-cutover-and-what-it-found">The cutover, and what it found</h2>
<p>The cutover was a written list: halt trading on dev, cancel open orders, turn off strategies, stop the dev trader and its Gateway, dump the dev database, restore it on <code>ibkr-db</code>, run migrations, confirm deploy reads halted, then start the Gateway on its own machine and watch reconciliation.</p>
<p>The dump was 3 MB. After the restore the counts matched dev exactly: 53 orders, 6 fills, 195 audit events and 11,767 stocks, still halted. The deployed trader connected through the tunnel in about 45 s.</p>
<p>Then four things went wrong, which is why the cutover was done halted:</p>
<ul>
<li><strong>Reconciliation never finished.</strong> With the Gateway in read-only API mode, IBKR refuses the open-orders request (error 321), so every pass timed out and the trader sat in “Reconciling”. Read-only had to be turned off, as it already was on dev.</li>
<li><strong>The Gateway first started with an empty login.</strong> The dev <code>.env</code> held <code>IBKR_USERNAME=${PAPER_LOGIN}</code>, and the script that copied it into the Vault did not expand the variable. The Vault held the literal text.</li>
<li><strong>Every <code>web</code> restart gave 502s until nginx restarted.</strong> nginx resolves a <code>proxy_pass</code> hostname once at startup and keeps the old container IP. Using Docker’s resolver with a variable in <code>proxy_pass</code> makes it look up <code>web</code> on each request; after <code>web</code> moved IP, nginx followed within 1 s.</li>
<li><strong>The trader logged the full paper account number.</strong> <code>ib_async</code> logs portfolio items and orders at INFO, and those lines now went to Loki. A log filter now masks account IDs on every handler.</li>
</ul>
<p>The last one is the kind of thing a deployment surfaces that dev never does: the logs existed before, but nobody was shipping them anywhere.</p>
<hr>
</section>
<section id="failure-drills" class="level2">
<h2 class="anchored" data-anchor-id="failure-drills">Failure drills</h2>
<p>Each drill was run on the deployed stack, and the trader container was never restarted by any of them:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Drill</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Restart the Gateway container</td>
<td>“reconnecting”, then “connected” in about 16 s</td>
</tr>
<tr class="even">
<td>Restart the tunnel container</td>
<td>disconnected at 15:35:42, connected and reconciled at 15:35:44</td>
</tr>
<tr class="odd">
<td>Restart <code>sshd</code> on the Gateway host and kill the tunnel session</td>
<td><code>autossh</code> reconnected in about 3 s, 0 container restarts</td>
</tr>
<tr class="even">
<td>Restart Postgres</td>
<td>one burst of pool warnings, then writes resumed</td>
</tr>
<tr class="odd">
<td>Reboot all four machines</td>
<td>all back within about 20 s; halt switch and risk limits intact</td>
</tr>
<tr class="even">
<td>Stop the trader for over 60 s</td>
<td>“Trader is down”, then “Trader is back” alerts sent</td>
</tr>
<tr class="odd">
<td><code>just deploy</code> of a new commit</td>
<td>deployed trader restarts and reconciles; dev stays connected</td>
</tr>
</tbody>
</table>
<p>The Gateway also restarts itself every night. Both traders disconnect at 23:45 UTC, reconnect by 00:04, and reconcile with 0 corrections.</p>
<p>Backups are a nightly <code>pg_dump</code> from a systemd timer, kept 14 days. A dump restored into a scratch database gave the same 53 order rows as live. A backup you have not restored is a hope, not a backup.</p>
<hr>
</section>
<section id="what-this-is-not" class="level2">
<h2 class="anchored" data-anchor-id="what-this-is-not">What this is not</h2>
<p><strong>Paper only, by design.</strong> Before any live account, each side needs its own Gateway and its own login, because <code>READ_ONLY_API</code>, global cancel and the daily loss limit are all shared today. The dashboard runs on plain HTTP on the LAN, has no roles (any login can trade paper), and sign-up is off. Prometheus and Loki answer on the LAN without auth.</p>
<p>Outbound traffic from the Gateway machine is not pinned. Inbound is locked down, but IBKR’s servers are not a stable list of addresses, and apt and image pulls need HTTPS out.</p>
<p>Two checks are weaker than they look. An order from a third client (a script on client 98) never reached the broker, because IBKR held it with warning 2139, so the “other clients are still reported” rule is proven by simulated tests only. And the dev tunnel dropping and reopening was checked with a fake <code>ssh</code>, not a live drop. It all runs on one Proxmox node.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Decision</th>
<th>Why</th>
<th>Evidence</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>One Gateway on its own machine</td>
<td>One session per login; deploys must not drop dev</td>
<td>Both traders connected at once; dev stayed up through a deploy</td>
</tr>
<tr class="even">
<td>An internal Docker network with two members</td>
<td>The TWS API has no auth</td>
<td>Other containers cannot resolve or reach the tunnel</td>
</tr>
<tr class="odd">
<td>A tunnel user limited to one forward</td>
<td>Revocable per key, no shell</td>
<td>“not available” for a shell, “administratively prohibited” for port 22</td>
</tr>
<tr class="even">
<td>Peer client IDs and a line budget</td>
<td>Two traders on one account</td>
<td>0 events and 0 emails from a dev order on deploy</td>
</tr>
<tr class="odd">
<td>Halted cutover with a written list</td>
<td>Four surprises, none of them could trade</td>
<td>Counts matched; reconciled with 0 corrections</td>
</tr>
<tr class="even">
<td>Second run must change nothing</td>
<td>Drift you cannot see is drift you cannot trust</td>
<td><code>changed=0</code> on all four; <code>5 unchanged</code> in Pulumi</td>
</tr>
</tbody>
</table>
<p>The pattern I would reuse anywhere: when a service has no authentication of its own, do not bolt one on. Make the network and the SSH layer the authentication, then test each refusal from the machine that should be refused.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Infrastructure</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/shared_ibkr_gateway.html</guid>
  <pubDate>Sun, 08 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Postgres or MongoDB? I Measured It</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/postgres_vs_mongodb.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The app is my experimental test bed: a Django REST + React SaaS split into two services, <code>catalog</code> and <code>instances</code>, behind one gateway, each with its own database, running in LXC containers on my <a href="../posts/proxmox_home_lab.html">Proxmox</a> lab. It is synthetic load on small containers, and the numbers should be read as that. The load-test method is the one from the <a href="../posts/k3s_load_testing.html">k3s post</a>: the same k6 scenario after every change, and a column for what saturated.</p>
</blockquote>
<p>The question was simple. <code>instances</code> stores questionnaires, and its data is mostly JSON blobs: answers, a snapshot of the questionnaire definition, computed metrics. That is the textbook case for a document database. So does MongoDB beat Postgres on it?</p>
<hr>
<section id="why-instances-and-how-to-make-the-test-fair" class="level2">
<h2 class="anchored" data-anchor-id="why-instances-and-how-to-make-the-test-fair">Why <code>instances</code>, and how to make the test fair</h2>
<p><code>instances</code> was the obvious candidate. Its models carry <code>answers_json</code>, <code>questionnaire_json_snapshot</code> and <code>metrics_json</code>. It has no user table, no Celery and no outbox. And it does about 90% of the app-tier work under load, so a database change shows up in the numbers.</p>
<p><code>catalog</code> stayed on Postgres. It holds auth, the admin, Celery beat and a transactional outbox, all of which assume a relational database.</p>
<p>Three rules kept the comparison about the database and not about a rewrite:</p>
<ul>
<li><strong>Keep the ORM.</strong> <code>django-mongodb-backend</code> 6.0.4 lets Django models run on MongoDB. Views, serializers and most tests stayed unchanged. The engine is a deploy setting.</li>
<li><strong>Same box, same cache.</strong> MongoDB 8.0 got its own container with 2 cores and 1 GB, a one-member replica set (needed for transactions), and a 0.25 GB WiredTiger cache. Postgres 16 keeps <code>shared_buffers</code> at 256 MB, so both engines have the same cache.</li>
<li><strong>Each run from its own reset.</strong> Both engines are seeded with the same deterministic data (20 owners x 200 questionnaires). Every scenario ran on Postgres, then on MongoDB, back to back.</li>
</ul>
<p>Making the code engine-neutral was its own piece of work. MongoDB has no row locks, so the double-submit guard became a conditional <code>update()</code> that works on both engines. Integer auto keys became UUIDs, because the backend refuses integer auto keys. And <code>atomic()</code> became engine-aware.</p>
<hr>
</section>
<section id="the-first-run-collapsed" class="level2">
<h2 class="anchored" data-anchor-id="the-first-run-collapsed">The first run collapsed</h2>
<p>The first MongoDB run at a fixed 200 iterations a second had a <strong>p95 of 5.27 s</strong>, against 9.36 ms on Postgres. It dropped 34,253 iterations, and mongod sat at 98% CPU.</p>
<p>A 500x gap is not “MongoDB is slower”. It is a query doing something it should not. So I turned on mongod’s slow-query log for every operation over 100 ms, with <code>docsExamined</code>. That number, documents read per query, found both problems in a few minutes.</p>
<hr>
</section>
<section id="problem-1-a-unique-index-that-cannot-find-null" class="level2">
<h2 class="anchored" data-anchor-id="problem-1-a-unique-index-that-cannot-find-null">Problem 1: a unique index that cannot find <code>null</code></h2>
<p>In SQL, two <code>NULL</code>s in a unique column do not collide. To copy that, <code>django-mongodb-backend</code> builds <strong>every unique index as a partial index</strong>, filtered to documents where the field exists (<code>{id: {$gte: ""}}</code>).</p>
<p>That has a side effect. A partial index only contains the documents that match its filter, so it <strong>cannot answer a query for <code>null</code></strong>. And <code>select_related("battery")</code> becomes a <code>$lookup</code> on <code>battery.id</code>. For every questionnaire with no battery, the lookup searched for <code>null</code>, could not use the index, and scanned the whole battery collection.</p>
<p>One query examined <strong>2,822,816 documents to return 10 rows.</strong></p>
<p>The fix: for a unique field that can never be null, build a full unique index instead (in the backend wrapper, <code>core/mongodb/base.py</code>), and a migration rebuilds the existing ones. p95 went from 5.27 s to <strong>160 ms</strong>.</p>
<hr>
</section>
<section id="problem-2-the-join-runs-before-the-limit" class="level2">
<h2 class="anchored" data-anchor-id="problem-2-the-join-runs-before-the-limit">Problem 2: the join runs before the limit</h2>
<p>160 ms was still 17x Postgres. The slow-query log showed the second shape. The backend puts each <code>$lookup</code> <strong>before</strong> <code>$sort</code> and <code>$limit</code>. So one page of 25 questionnaires joined all of the owner’s ~3,000 rows, sorted all of them, and then kept 25.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/34_join_before_limit.svg" class="img-fluid figure-img"></p>
<figcaption>Postgres limits before it joins. The generated MongoDB pipeline joined and sorted every row first.</figcaption>
</figure>
</div>
<p>A second cost made it worse. MongoDB timestamps have millisecond precision, so the list had gained an <code>-id</code> tiebreaker for a stable order. The list index ended at <code>created_at</code>, so it could not supply that order, and MongoDB sorted every row instead of reading them in index order.</p>
<p>Postgres has neither problem. Its planner limits before it joins, and it can sort incrementally from an index that covers only the first sort key.</p>
<p>The fix had two parts:</p>
<ul>
<li><strong><code>joined()</code></strong>, a small helper in <code>apps/questionnaires/db.py</code>. On Postgres it is a join. On MongoDB it is a prefetch: fetch the page of 25 first, then fetch their related rows in a second query.</li>
<li><strong>A migration adds <code>-id</code> to the list indexes</strong>, so the sort comes from the index.</li>
</ul>
<p>p95 went from 160 ms to <strong>16.1 ms</strong>. The second fix also changed Postgres’s indexes, so Postgres was re-run too, with no measurable change.</p>
<hr>
</section>
<section id="the-fair-comparison" class="level2">
<h2 class="anchored" data-anchor-id="the-fair-comparison">The fair comparison</h2>
<p>With both fixes in, every scenario ran on both engines. Every scenario finished with 0 failed requests on both.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th></th>
<th>Postgres</th>
<th>MongoDB</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Fixed 200/s, mixed, p95</td>
<td><strong>8.54 ms</strong></td>
<td>16.12 ms</td>
</tr>
<tr class="even">
<td>Fixed 200/s, read-mostly, p95</td>
<td><strong>8.74 ms</strong></td>
<td>10.44 ms</td>
</tr>
<tr class="odd">
<td>Stress knee, mixed</td>
<td><strong>~575 to ~614 req/s</strong></td>
<td>~322 to ~332 req/s</td>
</tr>
<tr class="even">
<td>Stress knee, read-mostly</td>
<td><strong>~495 to ~526 req/s</strong></td>
<td>~404 to ~419 req/s</td>
</tr>
<tr class="odd">
<td>Soak, 1 h at ~350 req/s</td>
<td><strong>held</strong>, 1,266,447 requests, 0 failed</td>
<td><strong>stopped at minute 18</strong> (5 minutes over 1% dropped)</td>
</tr>
<tr class="even">
<td>Respondent / PDF / outage, p95</td>
<td>4.8 / 104 / 4.9 ms</td>
<td>6.8 / 110 / 6.6 ms</td>
</tr>
<tr class="odd">
<td>Catch-up after <code>instances</code> restarts</td>
<td>10 s</td>
<td><strong>5 s</strong></td>
</tr>
<tr class="even">
<td>Storage, 4,000 questionnaires</td>
<td>7.2 MB</td>
<td><strong>3.6 MB</strong></td>
</tr>
</tbody>
</table>
<p>MongoDB won two rows. It catches up faster after a restart, and it stores the data in half the space, because it compresses data and Postgres does not below its TOAST threshold. Its indexes were the same size, since the UUIDs are stored as 32-character strings and a UUID primary key adds a second index beside <code>_id</code>.</p>
<p>It lost every row that measures speed.</p>
<hr>
</section>
<section id="why-mongodb-slows-down-as-the-rows-grow" class="level2">
<h2 class="anchored" data-anchor-id="why-mongodb-slows-down-as-the-rows-grow">Why MongoDB slows down as the rows grow</h2>
<p>The fixed-rate table hides the important part. On MongoDB, database CPU and the slowest group’s p95 <strong>rose every minute at a constant request rate</strong>. In the mixed run the slowest group went from 37 ms at minute 1 to 130 ms at minute 5, while Postgres went from 11 to 17 ms. Each run adds rows, and MongoDB’s remaining costs grow with them.</p>
<p>The soak showed it plainly. mongod’s CPU climbed from 16% to 76% at a constant rate, the slowest p95 passed 150 ms at minute 6 and 400 ms at minute 11, and the run was stopped at minute 18.</p>
<p>The cause is the same shape as problem 2, in the queries I had not fixed. The slow-query log during the soak named them:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Query</th>
<th style="text-align: right;">Slow runs</th>
<th>Docs examined, first to last</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Dashboard recent submissions</td>
<td style="text-align: right;">1,407</td>
<td>1,763 to 7,305</td>
</tr>
<tr class="even">
<td>Dashboard battery status</td>
<td style="text-align: right;">943</td>
<td>1,989 to 5,355</td>
</tr>
<tr class="odd">
<td>Dashboard scores</td>
<td style="text-align: right;">583</td>
<td>524 to 1,265</td>
</tr>
<tr class="even">
<td>Questionnaire list</td>
<td style="text-align: right;">15</td>
<td>6,112 to 7,637</td>
</tr>
</tbody>
</table>
<p>Each dashboard cache miss joins every row in its time window before it keeps 10 or 500. That, and not CPU, set MongoDB’s stress knee: it hit the latency limit with CPU to spare on both containers. Postgres runs the same queries as joins, but its planner limits first.</p>
<hr>
</section>
<section id="the-decision" class="level2">
<h2 class="anchored" data-anchor-id="the-decision">The decision</h2>
<p><strong><code>instances</code> stays on Postgres.</strong> On 2026-11-08 the MongoDB support was removed, and the baseline write-up stays in the repo as the record.</p>
<p>Each remaining slow query could be rewritten for MongoDB the way <code>joined()</code> rewrote the lists: fetch the page, then its related rows. But that is engine-specific code for every dashboard query, on top of the engine-specific paths MongoDB already needed for transactions, the submit guard, list joins and index shapes. All of that buys a database that, after the work, would at best match the one I already have.</p>
<p>“Document-shaped data” was the wrong test. What matters is how the service queries the data. These queries are relational: filter by owner, join to the questionnaire type and battery, sort, page. The JSON blobs ride along, and Postgres <code>jsonb</code> already stores them well.</p>
<p>The most reusable lesson is the debugging one. <strong><code>docsExamined</code> against rows returned</strong> found both problems in minutes. Any ORM that translates to a different engine needs that check, because the translation, not the database, is where the cost hides.</p>
<hr>
</section>
<section id="what-this-is-not" class="level2">
<h2 class="anchored" data-anchor-id="what-this-is-not">What this is not</h2>
<p>One run per engine at fixed rate, two stress runs, one soak each, on a shared host. Small containers (2 cores each) and a small dataset (4,000 questionnaires at seed). It measures <strong>MongoDB through <code>django-mongodb-backend</code> 6.0.4</strong>, not MongoDB with hand-written pipelines. A later version of the backend may place <code>$lookup</code> differently, and the result could change. I did not run a Postgres <code>EXPLAIN</code> with stale statistics to see how badly Postgres degrades in the same situation.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Step</th>
<th>MongoDB p95 (mixed, 200/s)</th>
<th>Lesson</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>As generated by the ORM backend</td>
<td>5.27 s</td>
<td>A 500x gap is a query bug, not an engine trait</td>
</tr>
<tr class="even">
<td>Full unique index for never-null fields</td>
<td>160 ms</td>
<td>Partial indexes cannot find <code>null</code></td>
</tr>
<tr class="odd">
<td>Prefetch instead of join, <code>-id</code> in the index</td>
<td>16.12 ms</td>
<td>Limit before you join; let the index supply the order</td>
</tr>
<tr class="even">
<td>Postgres, same code</td>
<td>8.54 ms</td>
<td>Its planner already does both</td>
</tr>
</tbody>
</table>
<p>Compare engines with the same code, the same cache and the same scenarios, and keep measuring until the gap has a cause you can name. Here the named cause was the shape of the queries, and the queries are relational. So the data stays in Postgres.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Software</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/postgres_vs_mongodb.html</guid>
  <pubDate>Sun, 08 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>87 to 1,400 Requests a Second on k3s</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/k3s_load_testing.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The workload is an existing Django REST + React + Celery application that I did not write. What I built is the platform under it and the performance work on it: a three-node k3s cluster on <a href="../posts/proxmox_home_lab.html">Proxmox</a> VMs provisioned with <a href="../posts/pulumi_vs_terraform.html">Pulumi</a>, a hand-written Helm chart, the load tests, and the backend changes below. It is a home lab with synthetic load, and the numbers should be read as that.</p>
</blockquote>
<p>The method is the only thing here that generalises, so it comes first: <strong>run the same load test after every single change, and write down what saturated.</strong> Not what you expected to saturate. What did.</p>
<hr>
<section id="the-setup" class="level2">
<h2 class="anchored" data-anchor-id="the-setup">The setup</h2>
<ul>
<li><strong>Cluster:</strong> k3s, one server and two agents, each a small VM. Pinned k3s version, verified by sha256.</li>
<li><strong>Outside the cluster, on their own VMs:</strong> Postgres 16 (with a streaming replica added later), Redis, an S3-compatible object store with a private image registry, an nginx edge, Prometheus + Grafana, and a dedicated k6 load generator.</li>
<li><strong>In the cluster:</strong> gunicorn web pods, a Celery worker and beat, a migrate hook Job. HPAs scale web 2 to 6 and worker 1 to 3. Pods run as non-root with a read-only root filesystem, asserted by tests on the rendered chart.</li>
<li><strong>Ingress:</strong> Traefik as a <code>hostNetwork</code> DaemonSet, with k3s’s ServiceLB switched off.</li>
<li><strong>Monitoring:</strong> kube-prometheus-stack with Prometheus in <strong>agent mode</strong>, remote-writing to the Prometheus outside the cluster, with alert rules unit-tested by <code>promtool</code>.</li>
</ul>
<p>The test is a k6 <strong>breakpoint</strong> scenario: each iteration is one GET against one of five public read endpoints chosen at random, starting at 40 requests per second and adding 10 every minute until something gives.</p>
<hr>
</section>
<section id="the-table" class="level2">
<h2 class="anchored" data-anchor-id="the-table">The table</h2>
<p>Every row is the same scenario. Dates are 2026-10-12 to 2026-10-14.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Step</th>
<th>Ceiling (req/s)</th>
<th>What saturated</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Single app VM, 2 vCPU, no Kubernetes</td>
<td>~87</td>
<td>app VM CPU at 97%</td>
</tr>
<tr class="even">
<td>k3s, 3 nodes x 2 vCPU, HPA</td>
<td>~172</td>
<td><strong>database VM CPU at 95%</strong></td>
</tr>
<tr class="odd">
<td>+ <code>CONN_MAX_AGE=60</code></td>
<td>~260</td>
<td>k3s nodes at 98%</td>
</tr>
<tr class="even">
<td>+ two query rewrites</td>
<td>~260</td>
<td>k3s nodes at 98% (database fell 65% to 28%)</td>
</tr>
<tr class="odd">
<td>+ 30 s read cache</td>
<td>&gt;586</td>
<td>nothing (hit the scenario’s 600 cap)</td>
</tr>
<tr class="even">
<td>Pushed to the breaking point</td>
<td>~990</td>
<td>k3s nodes at 98%</td>
</tr>
<tr class="odd">
<td>Nodes resized to 3 vCPU</td>
<td><strong>~1,400</strong></td>
<td>k3s nodes at 98%, database at 1%</td>
</tr>
</tbody>
</table>
<p>The final run served <strong>1,440,980 requests with zero failures</strong>, knee around 1,330 req/s, p95 49 ms.</p>
<hr>
</section>
<section id="kubernetes-moved-the-wall-it-did-not-remove-it" class="level2">
<h2 class="anchored" data-anchor-id="kubernetes-moved-the-wall-it-did-not-remove-it">Kubernetes moved the wall, it did not remove it</h2>
<p>Going from one VM to three nodes doubled the ceiling, from about 87 to about 172. Then the wall was somewhere else entirely: the <strong>database VM</strong>, at 95% CPU, while the cluster had room.</p>
<p>This is the most common way a “we need Kubernetes” project disappoints. Horizontal scaling of the stateless tier is exactly what it is good at, and if the stateless tier was the bottleneck you get a real win. Then the bottleneck becomes whatever you did not scale, usually the database, and adding pods makes that worse, not better.</p>
<hr>
</section>
<section id="conn_max_age-51-for-one-line" class="level2">
<h2 class="anchored" data-anchor-id="conn_max_age-51-for-one-line"><code>CONN_MAX_AGE</code>: +51% for one line</h2>
<p>Django’s default is <code>CONN_MAX_AGE = 0</code>: open a new database connection for every request and close it at the end. At low load that is invisible. At 170 requests a second it means 170 TCP handshakes, authentications and backend process setups a second, on the machine that was already the bottleneck.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">DATABASES[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"default"</span>][<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"CONN_MAX_AGE"</span>] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">60</span></span></code></pre></div></div>
<p>Ceiling from ~172 to ~260. At a fixed 40 req/s, database CPU dropped from 22% to 10%, which says how much of its work had been connection churn rather than queries.</p>
<p>Two caveats that make this a setting to think about rather than paste. Persistent connections are per worker thread, so connections held = pods x workers, and that has to stay under Postgres’s <code>max_connections</code> at the HPA’s <em>maximum</em>, not its minimum. And the honest alternative at larger scale is a pooler such as PgBouncer; at this size the setting is enough.</p>
<hr>
</section>
<section id="the-query-rewrites-that-did-not-raise-the-ceiling" class="level2">
<h2 class="anchored" data-anchor-id="the-query-rewrites-that-did-not-raise-the-ceiling">The query rewrites that did not raise the ceiling</h2>
<p>With the database still busy, <code>pg_stat_statements</code> said two statements were 97% of its time. Both were the same ORM shape: an annotation that counts or maximises over a join, which makes Postgres build the join and then group it back down.</p>
<p>One counted interactions per item by joining through them, grouping about 5,900 rows to return 21. The other took the latest related timestamp with a filtered <code>Max</code>, which ran its subqueries per child row instead of per parent. Both became correlated subqueries:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># before: join, then GROUP BY back down</span></span>
<span id="cb2-2">qs.annotate(likes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Count(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"item__interaction"</span>,</span>
<span id="cb2-3">                        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Q(item__interaction__type<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"like"</span>), distinct<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>))</span>
<span id="cb2-4"></span>
<span id="cb2-5"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># after: one small indexed lookup per returned row</span></span>
<span id="cb2-6">likes <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> (Interaction.objects.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">filter</span>(item<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>OuterRef(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"item"</span>), <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">type</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"like"</span>)</span>
<span id="cb2-7">         .order_by().values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"item"</span>).annotate(n<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Count(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"*"</span>)).values(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"n"</span>))</span>
<span id="cb2-8">qs.annotate(likes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>Coalesce(Subquery(likes), <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>))</span></code></pre></div></div>
<p>The heavier statement went from <strong>11.6 ms to 0.9 ms</strong> idle, and from 36 ms to 1.5 ms under load. Postgres time for the two statements over the run fell from 1,103 s to 209 s. Database CPU at the ceiling fell from 65% to 28%.</p>
<p><strong>And the ceiling did not move.</strong> It stayed at about 260, because <code>CONN_MAX_AGE</code> had already shifted the wall to the k3s nodes. The rewrite was real and worth doing: it bought headroom on the one component that cannot scale horizontally. But if I had only measured latency, I would have written “8x faster queries” and believed the system had got faster. The table is what says otherwise.</p>
<hr>
</section>
<section id="the-read-cache-and-why-it-is-only-fair-to-call-it-a-best-case" class="level2">
<h2 class="anchored" data-anchor-id="the-read-cache-and-why-it-is-only-fair-to-call-it-a-best-case">The read cache, and why it is only fair to call it a best case</h2>
<p>The five endpoints are public reads. So they got a Redis cache with a 30-second TTL, with three rules that matter more than the cache itself:</p>
<ul>
<li><strong>Anonymous viewers only.</strong> Any <code>Authorization</code> header, session or per-user cookie bypasses it, so no one is ever served someone else’s view.</li>
<li><strong>It sits after the throttles and permission checks</strong>, inside the view, so a cache hit never skips rate limiting.</li>
<li><strong>Invalidation by generation number.</strong> Every key includes a generation counter, and any write bumps it in <code>transaction.on_commit</code>. No key enumeration, no stale read after a committed write.</li>
</ul>
<p>Result: the scenario hit its own 600 req/s cap with nothing saturated and p95 at 15 ms. Then, uncapped, about 990.</p>
<p>The honest caveat is in the scenario. k6 sent anonymous GETs to five endpoints, so the hit ratio was <strong>98.8%</strong>, which is the cache’s best case. Real traffic has logged-in users and long-tail URLs. The number says the platform can serve cached reads at this rate. It does not say the application can.</p>
<hr>
</section>
<section id="the-last-40-was-hardware" class="level2">
<h2 class="anchored" data-anchor-id="the-last-40-was-hardware">The last 40% was hardware</h2>
<p>At about 990 req/s the k3s nodes were at 98% CPU and the database was idle. Resizing each node from 2 to 3 vCPU took the ceiling to about 1,400: <strong>+50% cores for about +40% throughput</strong>, which is roughly what you would expect once everything else is out of the way.</p>
<p>That is the right order to do it in. Buying cores at row two would have bought nothing, because the database was the wall.</p>
<p>The next wall is already visible in the numbers. At the ceiling, responses average about 95 KB, which is roughly 1 Gbit/s through the single nginx edge VM. That is untested, and it is the next row of the table.</p>
<hr>
</section>
<section id="what-happens-when-a-node-dies" class="level2">
<h2 class="anchored" data-anchor-id="what-happens-when-a-node-dies">What happens when a node dies</h2>
<p>Throughput is half the question. Two drills, both at a steady 100 req/s:</p>
<ul>
<li><strong>Pod loss:</strong> delete a web pod mid-run. <strong>0 of 64,636 requests failed</strong>, worst request 1.15 s.</li>
<li><strong>Node loss:</strong> hard power-off one worker VM, restart it 4.5 minutes later. <strong>149 of 59,566 failed, 0.25%</strong>, all in the first minute.</li>
</ul>
<p>With default node-health timeouts the node was marked NotReady <strong>57 seconds</strong> after the power cut. Until then the Service still routed to the dead pods: 128 of the failures were Traefik giving up after its 30-second dial timeout, and 21 were k6’s own 60-second timeout. Pods were never rescheduled, because the default eviction delay is five minutes and the node was back in four and a half.</p>
<p>So the real failover time on default settings is “however long until the node is declared dead”, and the fix is on the ingress side (retries with a short dial timeout) or a shorter node grace period. Neither is applied yet; both are written down as not done.</p>
<hr>
</section>
<section id="what-this-is-not" class="level2">
<h2 class="anchored" data-anchor-id="what-this-is-not">What this is not</h2>
<p>Single control-plane node, so the cluster itself is not highly available. No persistent volumes: every stateful thing lives on a VM outside the cluster, deliberately. No TLS, no cert-manager, no GitOps. Synthetic load from one generator. The p95 below the knee varied about 2x between identical runs, which is a good reason to distrust any single latency number here, including mine.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Change</th>
<th>Ceiling</th>
<th>Lesson</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Kubernetes</td>
<td>2x</td>
<td>Scales the stateless tier, then exposes the database</td>
</tr>
<tr class="even">
<td><code>CONN_MAX_AGE</code></td>
<td>+51%</td>
<td>Connection churn was half the database’s work</td>
</tr>
<tr class="odd">
<td>Query rewrites</td>
<td>0%</td>
<td>Real 8x per-query win, but on a component that was no longer the wall</td>
</tr>
<tr class="even">
<td>Read cache</td>
<td>3.8x</td>
<td>Best case by construction; say so</td>
</tr>
<tr class="odd">
<td>More cores</td>
<td>+40%</td>
<td>Only useful once nothing else is the wall</td>
</tr>
</tbody>
</table>
<p>The method is the deliverable: one scenario, run after every change, and a column for <strong>what saturated</strong>. Without that column the query rewrite reads as the biggest win in the project. With it, it reads as what it was: headroom.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Infrastructure</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/k3s_load_testing.html</guid>
  <pubDate>Wed, 14 Oct 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>The Webcam That Stopped the Boot</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/webcam_container_boot.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>In <a href="../posts/webcam_mic_proxmox_lxc.html">A Webcam and Mic in a Proxmox LXC</a> the camera and its microphone went into the container as <code>device_passthrough</code> entries, the same mechanism as the GPU. That post was right about everything that happens once the devices are inside. It was wrong about how to get them there, and it took a reboot to show it.</p>
</blockquote>
<p>On 2026-10-12 the Proxmox host rebooted and the container did not come back:</p>
<pre><code>Device /dev/snd/pcmC2D0c does not exist</code></pre>
<hr>
<section id="two-facts-that-combine" class="level2">
<h2 class="anchored" data-anchor-id="two-facts-that-combine">Two facts that combine</h2>
<p><strong>1. A Proxmox <code>devN</code> passthrough is mandatory.</strong> Each <code>dev0:</code>, <code>dev1:</code> line in the container config names a host device node, and if that node is missing at start, <strong>the container does not start.</strong> For a GPU that is reasonable: no GPU, nothing useful to do. For a USB webcam that is unplugged, or slow to enumerate, it turns a peripheral into a single point of failure for the whole machine.</p>
<p><strong>2. ALSA card numbers are not stable across boots.</strong> The host has two onboard HDA sound controllers plus the camera’s microphone. Which one becomes card 0, 1 or 2 depends on which driver finishes probing first, and that races. The camera’s mic was card 2 on one boot and card 0 on the next. The passthrough named <code>pcmC2D0c</code>, card 2, device 0, capture. After the reboot that node did not exist, because the mic was now <code>pcmC0D0c</code>.</p>
<p>Neither fact alone is a problem. A stable number with a mandatory mount is fine; an unstable number with an optional mount is fine. Together, a routine reboot takes the container down.</p>
<hr>
</section>
<section id="the-fix-optional-bind-mounts" class="level2">
<h2 class="anchored" data-anchor-id="the-fix-optional-bind-mounts">The fix: optional bind mounts</h2>
<p>LXC has its own mechanism underneath Proxmox’s, and it has a flag for exactly this. In <code>/etc/pve/lxc/&lt;vmid&gt;.conf</code>:</p>
<pre><code>lxc.cgroup2.devices.allow: c 116:* rwm
lxc.cgroup2.devices.allow: c 81:* rwm
lxc.mount.entry: /dev/snd dev/snd none bind,optional,create=dir
lxc.mount.entry: /dev/video0 dev/video0 none bind,optional,create=file
lxc.mount.entry: /dev/video1 dev/video1 none bind,optional,create=file</code></pre>
<ul>
<li><strong><code>optional</code></strong> is the whole point: a missing source is skipped, and the container boots without the camera instead of not booting.</li>
<li><strong>Binding the whole <code>/dev/snd</code> directory</strong> rather than individual nodes makes the card number irrelevant. Whatever number the mic gets this boot, it is in there. A mic plugged in after boot shows up too.</li>
<li><strong>The two <code>devices.allow</code> lines</strong> open the device cgroup for the character-device majors involved: 116 for ALSA and 81 for video4linux. A bind mount puts the node in the container’s filesystem; the cgroup rule is what lets it be opened.</li>
</ul>
<hr>
</section>
<section id="permissions-a-udev-rule-scoped-tightly" class="level2">
<h2 class="anchored" data-anchor-id="permissions-a-udev-rule-scoped-tightly">Permissions: a udev rule, scoped tightly</h2>
<p>An unprivileged container maps its users to high UIDs on the host, so a node owned by <code>root:audio</code> with mode 0660 is not openable from inside. The <code>devN</code> mechanism had been setting the mode for us; a bind mount does not.</p>
<p>So a host udev rule sets mode 0666, matched on <strong>the camera’s USB vendor and product ID</strong> and on the ALSA timer, and nothing else. Binding all of <code>/dev/snd</code> means the container can <em>see</em> the host’s other sound cards, but it cannot open them, because only the camera’s nodes are world-accessible. Matching on USB ID rather than on a device path also survives the camera moving ports.</p>
<hr>
</section>
<section id="open-the-mic-by-name-never-by-number" class="level2">
<h2 class="anchored" data-anchor-id="open-the-mic-by-name-never-by-number">Open the mic by name, never by number</h2>
<p>Binding the directory fixes the container. It does not fix code that says <code>hw:0,0</code>, which is still wrong on every boot where the mic lands on another card. ALSA can address a card by its id string instead:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">DEVICE <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"plughw:CARD=U2K,DEV=0"</span>   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the camera's card id, stable across boots</span></span></code></pre></div></div>
<p><code>plughw</code> rather than <code>hw</code> also adds ALSA’s conversion layer, so a request for a sample rate or format the hardware does not offer is converted instead of refused. (The earlier post’s advice still holds: record at the device’s native rate and resample yourself, so you know what conversion happened.)</p>
<p>The same thinking applies to <code>/dev/video0</code> with less help. If another camera enumerates first, the UGREEN becomes <code>video2</code>. The host has a second webcam that is deliberately <em>not</em> passed through, which is exactly the setup in which that can happen. <code>/dev/v4l/by-id/</code> gives stable names, and it is the next thing to move to.</p>
<hr>
</section>
<section id="and-it-no-longer-lives-in-the-iac" class="level2">
<h2 class="anchored" data-anchor-id="and-it-no-longer-lives-in-the-iac">And it no longer lives in the IaC</h2>
<p>The container is declared in Pulumi, and the GPU passthrough stays there as <code>devN</code> entries. The camera lines cannot: Proxmox only allows raw <code>lxc.*</code> keys to be written by <code>root@pam</code>, and the API token the IaC uses is deliberately not root. So the bind mounts live by hand in the container config, and the Pulumi program carries the exact lines as a comment beside the GPU passthrough, with the date and the error that put them there. There is also a unit test asserting that <strong>no capture device</strong> is ever added back as a passthrough, so the mistake cannot be re-made by tidying up.</p>
<p>Hand-maintained config next to IaC is a compromise. A comment that says exactly what is out of band, and a test that stops the managed half drifting back, is the honest version of it.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Device</th>
<th>Mechanism</th>
<th>Why</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>GPU</td>
<td>Proxmox <code>devN</code> passthrough</td>
<td>Mandatory is right: no GPU, nothing to do</td>
</tr>
<tr class="even">
<td>Webcam, mic</td>
<td><code>lxc.mount.entry ... bind,optional</code></td>
<td>A missing peripheral must not stop the machine</td>
</tr>
</tbody>
</table>
<p>The general rule: <strong>a peripheral should never be able to stop a machine from booting</strong>, and <strong>anything numbered at enumeration time will eventually be numbered differently.</strong> Bind optionally, bind the directory, and address devices by a name the hardware carries rather than an order the kernel assigned.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Small Hardware</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/webcam_container_boot.html</guid>
  <pubDate>Mon, 12 Oct 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Adopting Live Infra Into Pulumi</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/pulumi_import_live_infra.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>In <a href="../posts/pulumi_vs_terraform.html">Pulumi vs Terraform</a> I wrote that for a home lab, Terraform remains the right call. The same day, 2026-08-05, I moved the first project off it. By 2026-10-09 most of what I run was declared in Pulumi. That deserves an explanation, and then the part that is actually useful: how to move without destroying anything.</p>
</blockquote>
<hr>
<section id="why-switch-given-that-post" class="level2">
<h2 class="anchored" data-anchor-id="why-switch-given-that-post">Why switch, given that post</h2>
<p>The post’s own decision chart had the answer in it: <em>want unit tests on infra logic? Pulumi.</em> That turned out to be the deciding branch, more than I gave it credit for. The reasons the migration notes actually record:</p>
<ul>
<li><strong>Same language as everything else.</strong> The repos were already Python managed by <code>uv</code>. Pulumi in Python is one toolchain; HCL is a second one.</li>
<li><strong>Tests against mocks.</strong> The VPN stack has unit tests, 27 of them now, that run in CI before every preview. The Proxmox stack has one asserting that the container is <code>protect</code>ed, so nobody can quietly remove the guard.</li>
<li><strong>Same provider underneath.</strong> The Proxmox and AWS providers are bridged from the Terraform ones, so resource schemas and import IDs are identical. Nothing has to be re-learned about the resources themselves.</li>
<li><strong>No SaaS.</strong> State lives in S3 or a local file, so there is no new token to hold.</li>
</ul>
<p>None of those say Terraform was wrong. They are about fit. The post’s conclusion was too strong for my own situation, and this one is the correction.</p>
<hr>
</section>
<section id="the-estate" class="level2">
<h2 class="anchored" data-anchor-id="the-estate">The estate</h2>
<p>A WireGuard VPN exit node on EC2 with everything around it: security group, Elastic IP, IAM role and instance profile for SSM, VPC flow logs, a Route 53 record and health check, SNS topics, six CloudWatch alarms, a dashboard and saved Logs Insights queries. <strong>26 resources</strong>, all live, all serving traffic, applied by GitHub Actions through OIDC.</p>
<p>The constraint: nothing gets recreated. A new EC2 instance means a new host key, new WireGuard state, and every client reconfigured. A new Elastic IP is worse.</p>
<hr>
</section>
<section id="the-mechanism-import_-with-a-lookup-table" class="level2">
<h2 class="anchored" data-anchor-id="the-mechanism-import_-with-a-lookup-table">The mechanism: <code>import_</code> with a lookup table</h2>
<p>Pulumi offers two ways to adopt existing resources: the <code>pulumi import</code> CLI, which generates code, and the <code>import_</code> resource option, which attaches an existing ID to code you have already written. I used the second, because the code was being ported by hand anyway, one resource for one resource:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># adopt.py - deleted once the import landed</span></span>
<span id="cb1-2">LIVE <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {</span>
<span id="cb1-3">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"instance"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"i-0abc..."</span>,</span>
<span id="cb1-4">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"security_group"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"sg-0abc..."</span>,</span>
<span id="cb1-5">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># ... 26 entries</span></span>
<span id="cb1-6">}</span>
<span id="cb1-7"></span>
<span id="cb1-8"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> adopt(key):</span>
<span id="cb1-9">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> LIVE.get(key)</span></code></pre></div></div>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">instance <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> aws.ec2.Instance(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"vpn"</span>,</span>
<span id="cb2-2">    ...,</span>
<span id="cb2-3">    opts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pulumi.ResourceOptions(import_<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>adopt(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"instance"</span>)))</span></code></pre></div></div>
<p><code>import_</code> has a property that makes it safe: <strong>Pulumi refuses the import if the live resource differs from your inputs.</strong> It does not adopt and then “fix”. So a clean preview is not just permission to proceed, it is proof that the code describes reality.</p>
<p>Every resource also gets an <strong>explicit physical name</strong>. Pulumi auto-names resources by appending a random suffix, so an unnamed <code>aws.sns.Topic("alerts")</code> would not match the live topic called <code>alerts</code>, and the plan would be to create a new one.</p>
<hr>
</section>
<section id="what-the-first-preview-wanted-to-do" class="level2">
<h2 class="anchored" data-anchor-id="what-the-first-preview-wanted-to-do">What the first preview wanted to do</h2>
<p>It wanted to <strong>replace the EC2 instance.</strong> The rest of the work was making it stop wanting that.</p>
<p><strong>1. A computed subnet picked a different one.</strong> The Terraform config chose a subnet with a data source. The port used <code>min(subnet_ids)</code>, which is a perfectly reasonable expression that happened to pick a different subnet from the one the instance actually lives in. Changing an instance’s subnet forces replacement. The fix was to pin the subnet in stack config. The lesson is general: anything the old tool <em>computed</em> at plan time has to be re-checked against what it actually <em>chose</em>.</p>
<p><strong>2. Fields the API never returns.</strong> SNS email subscriptions diffed on <code>confirmationTimeoutInMinutes</code> and <code>endpointAutoConfirms</code>. Those are provider-side settings, not properties AWS stores, so an imported subscription reads them back as empty. They went into <code>ignore_changes</code>.</p>
<p><strong>3. Fields Terraform was already ignoring.</strong> The old config had <code>lifecycle { ignore_changes = [ami, user_data, key_name] }</code> on the instance, because a new AMI release should not rebuild the VPN. That has to be carried over explicitly, or the first <code>up</code> after a new Amazon Linux image is a replacement:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">opts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pulumi.ResourceOptions(</span>
<span id="cb3-2">    import_<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>adopt(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"instance"</span>),</span>
<span id="cb3-3">    ignore_changes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"ami"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"userData"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"keyName"</span>])</span></code></pre></div></div>
<p><strong>4. Text that is not ASCII.</strong> Some live alarm descriptions contained an em dash, typed into the console months earlier. The description must match byte for byte or it is an update. The source writes it as a Unicode escape, so the file stays ASCII and the value still matches AWS.</p>
<p>After those four, the preview read <strong>26 import, 0 update, 0 replace, 0 delete</strong>. The only creates were the stack itself and an explicit provider for <code>us-east-1</code>, which billing metrics require.</p>
<hr>
</section>
<section id="landing-it" class="level2">
<h2 class="anchored" data-anchor-id="landing-it">Landing it</h2>
<ol type="1">
<li><strong>Push with <code>import_</code> in place.</strong> CI ran <code>pulumi up</code>: <code>create: 2, import: 26</code>.</li>
<li><strong>Remove every <code>import_</code> and the lookup table</strong>, in a second commit. The IDs now live in Pulumi state.</li>
<li><strong><code>pulumi preview --expect-no-changes</code>.</strong> This is the check that matters, because it fails the command if anything at all would change. It passed: 28 unchanged.</li>
<li><strong>Watch the next two CI runs</strong> report <code>same: 28</code>.</li>
</ol>
<p>Both commits landed on 2026-10-09, eleven minutes apart.</p>
<hr>
</section>
<section id="retiring-terraform-keep-the-state" class="level2">
<h2 class="anchored" data-anchor-id="retiring-terraform-keep-the-state">Retiring Terraform: keep the state</h2>
<p>The tempting last step is deleting <code>terraform.tfstate</code>. I kept it, untouched, next to the new state in the same S3 bucket.</p>
<p>The reasoning: if anyone, including me in six months on a stale checkout, runs <code>terraform apply</code> against the old config, a missing state file makes Terraform think nothing exists and <strong>create a duplicate of everything</strong>. With the state present, the same command is a no-op. Old state is not dead weight. It is what makes the old tool harmless.</p>
<p>The <code>.tf</code> files were removed from the repo. The CI workflow swapped tools without touching auth: the existing OIDC role already had access to the state bucket, so the new workflow assumes the same role. <code>destroy</code> was removed from the manual trigger while I was there.</p>
<hr>
</section>
<section id="the-same-thing-on-proxmox-and-one-more-trap" class="level2">
<h2 class="anchored" data-anchor-id="the-same-thing-on-proxmox-and-one-more-trap">The same thing on Proxmox, and one more trap</h2>
<p>The first migration, the one on 2026-08-05, adopted two Proxmox LXC containers with the CLI (<code>pulumi import proxmoxve:CT/container:Container ...</code>). It hit the same class of problem harder: <strong>three creation-only fields</strong> (the initial user account, the template the container was built from, and its feature flags) that Proxmox never reports back. Every preview wanted to replace both containers. <code>protect=True</code> blocked it, and <code>ignore_changes</code> on those fields fixed it.</p>
<p>Two lessons from that one that I would not have guessed:</p>
<ul>
<li><strong>Hand-editing the exported state did nothing.</strong> The bridged provider diffs against the raw Terraform state it keeps internally, not the <code>inputs</code> you can see. <code>ignore_changes</code> is the supported tool and it is the correct one: these fields only mean anything at creation.</li>
<li><strong>A value-neutral <code>pulumi up</code> restarted both containers.</strong> It wrote provider defaults the import had not recorded (console settings, start-on-boot), and the provider applies those by restarting. About ten seconds of downtime for a change that changed nothing. Do the first real <code>up</code> after an import at a time when a restart is acceptable.</li>
</ul>
<p>The newer stacks bake all of this in from the start, driven by an environment variable so that the same program either adopts or creates:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">opts<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>pulumi.ResourceOptions(</span>
<span id="cb4-2">    provider<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>provider,</span>
<span id="cb4-3">    protect<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>,</span>
<span id="cb4-4">    import_<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>os.environ.get(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"IMPORT_ID"</span>),   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># "&lt;node&gt;/&lt;vmid&gt;" to adopt; unset to create</span></span>
<span id="cb4-5">    ignore_changes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"initialization.userAccount"</span>,</span>
<span id="cb4-6">                    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"operatingSystem.templateFileId"</span>])</span></code></pre></div></div>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>The checklist for adopting live infrastructure into any IaC tool:</p>
<ul>
<li><strong>Set <code>protect</code> before the first preview</strong>, so a plan that wants to replace something stops instead of applying.</li>
<li><strong>Name every resource explicitly.</strong> Auto-naming and import do not mix.</li>
<li><strong>Treat every proposed replacement as a finding.</strong> Find the field. It is nearly always something computed, creation-only, or never reported back.</li>
<li><strong>Carry the old tool’s <code>ignore_changes</code> across.</strong> They were there for a reason.</li>
<li><strong>Prove it with <code>--expect-no-changes</code></strong> after the import options are gone.</li>
<li><strong>Keep the old state.</strong> It is what stops the old tool from duplicating everything.</li>
</ul>
<p>The import took a morning. Almost all of it was the four fields.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Infrastructure</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/pulumi_import_live_infra.html</guid>
  <pubDate>Fri, 09 Oct 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Never Let [0] Decide a Verdict</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/never_trust_first_result.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The <a href="../posts/federated_docs_site.html">federated docs site</a> is twenty repos, each with its own CI run, Pages deploy and Pages build. <code>just ci</code> asks the GitHub API about all of them concurrently, in about 1.5 seconds, and prints one row per repo plus an exit code that other recipes act on. A status tool has one job: when it says red, something is red.</p>
</blockquote>
<p>It said red when nothing was, on 2026-08-26, 2026-09-21 and 2026-10-05.</p>
<hr>
<section id="the-endpoints-order-is-not-a-contract" class="level2">
<h2 class="anchored" data-anchor-id="the-endpoints-order-is-not-a-contract">1. 2026-08-26: the endpoint’s order is not a contract</h2>
<p>The report called <code>ML/ML_methods</code> <strong>CI FAILURE</strong> and linked a real run: a genuine <code>test.yaml</code> run on <code>main</code> of that repo. It was <strong>run number 96, from 2026-02-17</strong>. The newest was run 107, from 2026-08-16, and it had succeeded. So had the Pages deploy.</p>
<p>The code asked for exactly one run and believed it:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">r <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> gh.rest.actions.async_list_workflow_runs(owner, repo, wf, branch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"main"</span>, per_page<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)</span>
<span id="cb1-2">run <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> r.parsed_data.workflow_runs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span></code></pre></div></div>
<p>The list-workflow-runs endpoint is eventually consistent, and while it usually returns newest first, nothing promises it. A one-item page is the worst way to consume an unreliable order, because it removes the only evidence you could have used to notice: there is nothing to compare the answer to.</p>
<p>It also did not reproduce. Twenty sequential calls and six full concurrent passes over the fleet all returned 107. A bug you cannot reproduce is still a bug when the code has no defence against it.</p>
<p>The fix costs nothing extra. Ask for a page and pick by a field that <em>means</em> “newest”:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> newest_run(runs):</span>
<span id="cb2-2">    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">"The newest run in `runs`, by `run_number`, which is monotonic per workflow."</span></span>
<span id="cb2-3">    numbered <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> [r <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> runs <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">getattr</span>(r, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"run_number"</span>, <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">is</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>]</span>
<span id="cb2-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">max</span>(numbered, key<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> r: r.run_number) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> numbered <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">else</span> runs[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]</span></code></pre></div></div>
<p>Same single request with <code>per_page=10</code>, and the page’s order can no longer change the verdict. The unit test feeds it a deliberately mis-ordered page.</p>
<hr>
</section>
<section id="a-state-in-flight-is-not-a-state" class="level2">
<h2 class="anchored" data-anchor-id="a-state-in-flight-is-not-a-state">2. 2026-09-21: a state in flight is not a state</h2>
<p>The second one was quieter. <code>just ci</code> exited 1 on a fleet that was fine, and no row in the table said FAILURE. A few minutes later the same command exited 0.</p>
<p>The CI and deploy columns already knew that <code>in_progress</code> and <code>queued</code> are not results. The Pages <em>build</em> column did not:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># before: anything that is not "built" counts as red</span></span>
<span id="cb3-2"><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">any</span>(r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"built"</span>] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"built"</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> rows)</span></code></pre></div></div>
<p><code>building</code> is a state every healthy Pages deploy passes through. Run the check during that window and a healthy repo counts as failed, but the table renders <code>building</code> as an ordinary word, so the exit code and the table disagree and the reader cannot see why.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">RUNNING <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> {<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"in_progress"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"queued"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"requested"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"waiting"</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"pending"</span>,</span>
<span id="cb4-2">           <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"building"</span>}  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># "building" is the Pages build in flight</span></span>
<span id="cb4-3"></span>
<span id="cb4-4"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> has_failure(rows):</span>
<span id="cb4-5">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">bool</span>(failures(rows)) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">any</span>(r[<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"built"</span>] <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> (<span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">None</span>, <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"built"</span>, <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span>RUNNING) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> r <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> rows)</span></code></pre></div></div>
<p>Note what the fix does <em>not</em> do. It does not switch to an allow-list of bad states. A state the code has never seen still counts as red, because a new API value is something to look at, not something to wave through.</p>
<hr>
</section>
<section id="the-maximum-of-a-bad-page-is-still-bad" class="level2">
<h2 class="anchored" data-anchor-id="the-maximum-of-a-bad-page-is-still-bad">3. 2026-10-05: the maximum of a bad page is still bad</h2>
<p>Then <code>DL/DL_methods</code> came back <strong>FAILURE</strong> with <code>newest_run</code> in place. The branch query returned a page whose highest run number was <strong>#143, from 2026-05-13, a failure</strong>. The newest run was #161, and it had succeeded.</p>
<p><code>max()</code> by run number fixed the <em>order</em> of a page. It cannot fix a page that does not contain the right run at all. Taking the best element of the wrong set still gives you a wrong answer, just a more confident one.</p>
<p>The question being asked was never really “what is the newest run on this branch”. It was “did the commit <code>main</code> points at build”. The API can answer that directly:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb5" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb5-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> head_sha:</span>
<span id="cb5-2">    r <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> gh.rest.actions.async_list_workflow_runs(</span>
<span id="cb5-3">        owner, repo, wf, head_sha<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>head_sha, per_page<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb5-4">    runs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> r.parsed_data.workflow_runs</span>
<span id="cb5-5"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">not</span> runs:   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># a commit with no run yet: fall back to the branch page</span></span>
<span id="cb5-6">    r <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> gh.rest.actions.async_list_workflow_runs(</span>
<span id="cb5-7">        owner, repo, wf, branch<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>branch, per_page<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">10</span>)</span>
<span id="cb5-8">    runs <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> r.parsed_data.workflow_runs</span></code></pre></div></div>
<p>The tool already fetched the remote <code>main</code> sha for another column, so this is no extra round trip in the common case. And a query keyed on the commit cannot be answered with some other commit’s run, however the backend’s index is behaving that day.</p>
<hr>
</section>
<section id="the-pattern" class="level2">
<h2 class="anchored" data-anchor-id="the-pattern">The pattern</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/29_proxy_question_fixes.svg" class="img-fluid figure-img"></p>
<figcaption>Taking the first run on one page was wrong order, the max run number on ten runs was wrong page, so the fix queries by head_sha, and treating any build not built as red was a transient state, so the fix excludes the running set and keeps unknown as red.</figcaption>
</figure>
</div>
<p>All three are the same mistake at different layers: <strong>an answer that was arbitrary or temporary, read as a result.</strong> The first trusted an order, the second trusted a moment, the third trusted a set.</p>
<p>The fixes share a shape too. Each one stopped asking a proxy question and asked the real one:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Proxy question</th>
<th>Real question</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>What is first on this page?</td>
<td>Which run has the highest run number?</td>
</tr>
<tr class="even">
<td>Is the build state exactly <code>built</code>?</td>
<td>Has the build <em>finished</em> badly?</td>
</tr>
<tr class="odd">
<td>What is the newest run on <code>main</code>?</td>
<td>Did <em>this commit</em> build?</td>
</tr>
</tbody>
</table>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>For any health check that turns an API response into red or green:</p>
<ul>
<li><strong>Never let <code>[0]</code> of a paged response decide.</strong> Ask for several and select by a field that means what you want.</li>
<li><strong>Separate “not finished” from “failed”,</strong> and keep unknown states red rather than green.</li>
<li><strong>Key the query on the thing you care about.</strong> If the question is about a commit, ask about the commit.</li>
</ul>
<p>And the meta-lesson, which cost an exit code three times: a false red is not harmless just because a human looks at it. A tool that cries wolf trains you to stop reading its output, and then the real FAILURE gets ignored with the rest.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Software</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/never_trust_first_result.html</guid>
  <pubDate>Mon, 05 Oct 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>From Visual Odometry to SLAM</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/vo_to_slam.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The <a href="../posts/bugs_plausible_output.html">previous post</a> was about getting <a href="https://github.com/bthek1/ros2_pi">ros2_pi</a> to run end to end: one webcam, ORB + PnP odometry, neural depth on CUDA, TSDF fusion into a live mesh. That is <strong>visual odometry</strong>. Every pose is estimated relative to recent frames, so error accumulates and nothing ever corrects it. Walk around a room and come back to the start, and the map does not close.</p>
</blockquote>
<p>SLAM is the step that fixes that: recognise a place you have been before, and use it to correct everything in between. This post covers that step, from 2026-09-25 to 2026-10-02, and the rule I held to throughout: <strong>a feature is claimed only when the measurement separates it from the baseline.</strong></p>
<hr>
<section id="first-a-number-to-beat" class="level2">
<h2 class="anchored" data-anchor-id="first-a-number-to-beat">First, a number to beat</h2>
<p>“The mesh looks better” is not a measurement. So before adding anything, the pipeline was pointed at the <strong>TUM RGB-D fr1/desk</strong> sequence: 613 frames of a handheld camera over a desk, with ground truth from a 100 Hz motion-capture system. <code>evo_ape</code> aligns the estimated trajectory to ground truth and reports the absolute trajectory error (ATE).</p>
<p>Monocular depth has no absolute scale, so the alignment is <strong>Sim(3)</strong>: rotation, translation <em>and</em> scale. Baseline visual odometry over seven runs: <strong>ATE 0.27 to 0.36 m.</strong> A rotation-only control, which ignores translation, cannot be aligned at all, which is a useful confirmation that the metric discriminates.</p>
<p>Building the benchmark found a bug before it measured anything. Rotating TUM’s <em>own ground truth</em> into the camera’s optical frame and scoring it against itself gave a relative error of 0.654 m. A trajectory compared with itself should score zero. Body frame versus optical frame: the first real run read 0.768 m in the wrong frame and 0.150 m in the right one. Every number after this depends on that being right.</p>
<hr>
</section>
<section id="two-features-that-were-built-and-not-claimed" class="level2">
<h2 class="anchored" data-anchor-id="two-features-that-were-built-and-not-claimed">Two features that were built and not claimed</h2>
<p><strong>A local map.</strong> Instead of tracking against the last keyframe only, track against a map of recent landmarks. Standard practice, and it should help. Measured: <strong>0.46 to 0.50 m, worse than the 0.28 to 0.46 m baseline.</strong> The diagnosis was that Depth Anything’s scale differs by <strong>15 to 21% between keyframes</strong>, so landmarks triangulated from one keyframe’s depth do not agree with the next one’s. A local map built on inconsistent scale averages disagreement.</p>
<p><strong>Local bundle adjustment</strong> with g2o. The median looked good: <strong>0.259 m against 0.429 m</strong> without it. But at three runs each, BA’s worst run (0.418) overlapped no-BA’s best (0.318). Worse, the baseline with <em>unchanged code</em> ranged 0.28 to 0.46 m one day and 0.44 to 0.47 m the next. The run-to-run spread was bigger than the effect.</p>
<p>Both are in the code, both default off, and neither is claimed. A median that a re-run could reverse is not a result. It is a reason to run more, and the issue stays open until the distributions separate.</p>
<hr>
</section>
<section id="place-recognition-without-a-vocabulary" class="level2">
<h2 class="anchored" data-anchor-id="place-recognition-without-a-vocabulary">Place recognition, without a vocabulary</h2>
<p>The usual tool is a bag-of-words vocabulary such as DBoW2. It is not packaged for either ROS 2 distribution this runs on, so the first version is brute force, run on a low-priority thread:</p>
<ol type="1">
<li><strong>Exclude the obvious.</strong> Skip keyframes younger than 3 seconds, or sharing more than 5 tracked features with the query. Those are not revisits, they are the recent past.</li>
<li><strong>Match descriptors</strong> by Hamming distance with a 0.8 ratio test, and keep the top 3 candidate keyframes.</li>
<li><strong>RANSAC</strong> a relative pose, requiring at least 12 inliers.</li>
<li><strong>Guided matching:</strong> project the candidate’s landmarks into the query with that pose and search within 8 pixels. <strong>Accept at 30 or more.</strong></li>
</ol>
<p>Step 4 is what makes it trustworthy. On a real revisit, blind matching found 15 to 18 correspondences, which is in the range a false match can also reach. Guided matching found <strong>127 to 134.</strong> The separation between a true revisit and a lookalike is in the geometry, not the descriptors.</p>
<p>Scored against motion capture: <strong>zero wrong-place closures</strong> across the evaluation runs. A wrong loop closure is far worse than a missed one, because the pose graph will faithfully bend the whole map to agree with it, so this is the number that matters most.</p>
<hr>
</section>
<section id="the-pose-graph" class="level2">
<h2 class="anchored" data-anchor-id="the-pose-graph">The pose graph</h2>
<p>One vertex per keyframe, as an SE(3) pose. Two kinds of edge:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Edge</th>
<th>Uncertainty</th>
<th>Source</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Odometry</td>
<td>7 deg/s, 0.15 m/s</td>
<td>The tracker’s measured drift rate</td>
</tr>
<tr class="even">
<td>Loop closure</td>
<td>3 deg, 0.06 m, Huber kernel</td>
<td>The guided-match pose</td>
</tr>
</tbody>
</table>
<p>The odometry sigmas are <strong>measured</strong>, not tuned. That matters because the optimiser’s whole job is to decide how much to trust each edge, and it can only do that if the numbers mean something. The Huber kernel limits the damage any single bad closure can do.</p>
<p>The graph is re-solved after each closure, in <strong>0.7 to 0.9 ms.</strong> The correction is published the ROS way: the tracker keeps publishing <code>odom -&gt; base_link</code>, and a real, moving <code>map -&gt; odom</code> transform carries the correction, with the same timestamp. Before this, <code>map -&gt; odom</code> was a static identity.</p>
<p><strong>Keyframe ATE: 0.118 to 0.153 m with loop closure, against 0.361 to 0.533 m without.</strong> Three runs each, and the two ranges do not overlap: there is a 0.21 m gap between the worst run with it and the best run without. That is the one claimed in this post.</p>
<hr>
</section>
<section id="using-the-correction-and-knowing-when-you-are-lost" class="level2">
<h2 class="anchored" data-anchor-id="using-the-correction-and-knowing-when-you-are-lost">Using the correction, and knowing when you are lost</h2>
<p>A corrected trajectory is only half the point if the mesh was built at the uncorrected poses. So the TSDF is <strong>rebuilt at the corrected keyframe poses.</strong> Against a reference rebuilt at motion-capture poses, the surface distance dropped from 0.66 to 0.90 m with odometry alone to <strong>0.51 to 0.53 m</strong> corrected.</p>
<p>Then failure. Cover the lens, and a tracker that does not know it is lost will keep fusing garbage into the map. There is now an explicit <strong>LOST</strong> state, entered within 5 depth frames, during which <strong>nothing is fused.</strong> The control run, with the state disabled, integrated 514 to 622 million voxel updates of nonsense.</p>
<p>And recovery: from a saved map, the pipeline <strong>relocalises after 2 LOST frames to 0.18 m median, 0.25 m worst.</strong> The control is a recording from a <em>different room</em>: 819 relocalisation queries, <strong>zero accepted.</strong> The first time this gate passed, it passed over nothing: the test sequence was already LOST before the lens cap went on, so there was nothing to recover from. A pass with nothing to recover from proves nothing, and that run does not count.</p>
<hr>
</section>
<section id="what-this-is-and-is-not" class="level2">
<h2 class="anchored" data-anchor-id="what-this-is-and-is-not">What this is, and is not</h2>
<p>Honest scope, as the repo states it:</p>
<ul>
<li><strong>Keyframe ATE, not online ATE.</strong> The number above is the graph’s final keyframe poses. The per-frame trajectory the TSDF actually integrates at, with the correction as it stood at each moment, is not yet scored. Until it is, loop closure ships <strong>off by default.</strong></li>
<li><strong>One benchmark sequence.</strong> fr1/desk is short and well textured.</li>
<li><strong>Monocular depth is relative.</strong> Scale breathes by about 4%, anything past about 6 m is clipped, and a blank wall defeats it entirely.</li>
<li><strong>The pose graph cannot catch a large false closure on its own.</strong> A 5 m false loop in the unit tests goes straight through. The defence is upstream, in step 4 of place recognition.</li>
<li><strong>The mesh is a good room. It is not a survey.</strong></li>
</ul>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Feature</th>
<th>Result</th>
<th>Claimed?</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Local map</td>
<td>Worse than baseline (scale disagreement)</td>
<td>No</td>
</tr>
<tr class="even">
<td>Local bundle adjustment</td>
<td>Better median, overlapping runs</td>
<td>No</td>
</tr>
<tr class="odd">
<td>Place recognition</td>
<td>0 wrong closures</td>
<td>Yes</td>
</tr>
<tr class="even">
<td>Pose graph</td>
<td>ATE 0.12 to 0.15 m vs 0.36 to 0.53 m</td>
<td>Yes</td>
</tr>
<tr class="odd">
<td>LOST + relocalisation</td>
<td>0.18 m median, 0 false accepts</td>
<td>Yes</td>
</tr>
</tbody>
</table>
<p>Two things I would carry to any perception project. <strong>Get a ground-truth benchmark before the feature</strong>, because without one, everything that makes the mesh look nicer looks like progress. And <strong>report the spread, not the median.</strong> The bundle adjustment number was a better median and a non-result, and the only thing that showed it was running the baseline twice.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Robotics and ML</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/vo_to_slam.html</guid>
  <pubDate>Fri, 02 Oct 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Bugs That Produce Plausible Output</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/bugs_plausible_output.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p><a href="https://github.com/bthek1/ros2_pi">ros2_pi</a> turns one webcam on a Raspberry Pi 5 into a live triangle mesh of a room. The Pi captures and streams over Wi-Fi; a GPU machine detects ORB keypoints, estimates 6-DoF camera pose with PnP, runs Depth Anything V2 through ONNX Runtime on CUDA, fuses depth into a TSDF volume, extracts a surface with marching cubes, and streams the mesh to a hand-written WebGL dashboard. The code started on 2026-09-08. On <strong>2026-09-19</strong> the whole chain ran end to end for the first time. It is the C++ successor to an earlier Python version, <a href="https://github.com/bthek1/piros2"><code>piros2</code></a>, and it is a learning project, not production.</p>
</blockquote>
<p>The rule from the start: <strong>every performance claim is printed by a script that asserts on it.</strong> Each pipeline stage has a gate under <code>tools/gates/</code> that runs the real system on a recorded clip and fails on a number. These are the bugs those gates found, and the thing they have in common.</p>
<hr>
<section id="six-days-of-correct-looking-3d-from-one-inverted-rotation" class="level2">
<h2 class="anchored" data-anchor-id="six-days-of-correct-looking-3d-from-one-inverted-rotation">1. Six days of correct-looking 3D from one inverted rotation</h2>
<p>On the day the PnP odometry landed, its gate failed on a simple check: <strong>pan the camera right, and the published camera pose turns left.</strong></p>
<p>Everything else had looked fine for six days. The frame moved when the camera moved. The residual check passed, because it measures alignment error and is blind to sign. The rotation-fit unit test checked everything about the estimate except the direction of its inverse. And the reconstruction looked like a room, because <strong>a TSDF built from consistently mirrored poses still produces a surface.</strong> Mirrored poses are self-consistent. Every frame agrees with every other frame about the wrong answer.</p>
<p>The root cause was one line. The pose update composed the point motion <code>M</code> where it needed the camera motion <code>M^-1</code>:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode cpp code-with-copy"><code class="sourceCode cpp"><span id="cb1-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// in camera_step(): the camera moves opposite to the points it observes</span></span>
<span id="cb1-2"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> point_motion<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>inv<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">();</span></span></code></pre></div></div>
<p>The fix was a transpose. The measured effect, as the gap between the fused surface and a reference built from the same frames: <strong>1.344 m before, 0.446 m after.</strong> A 3x improvement in the thing the project exists to produce, from a bug that no visual inspection had flagged.</p>
<p>A <code>CameraStep</code> test suite now closes that loop, so the direction of the inverse is asserted rather than assumed.</p>
<hr>
</section>
<section id="cuda-was-installed-working-and-not-being-used" class="level2">
<h2 class="anchored" data-anchor-id="cuda-was-installed-working-and-not-being-used">2. CUDA was installed, working, and not being used</h2>
<p>Depth inference ran at <strong>517 ms a frame</strong> inside the pipeline. A standalone probe, same libraries, same flags, same model, ran at <strong>51 ms</strong> on the GPU. No error. One log line, easy to miss, named a CUDA library that could not be loaded, and ONNX Runtime fell back to the CPU provider without complaint.</p>
<p>The difference was who owned the executable. In ROS 2, nodes are loaded as shared libraries into <code>component_container_isolated</code>, which is someone else’s binary. The CUDA execution provider is itself <code>dlopen</code>ed by ONNX Runtime, and a <code>dlopen</code>ed library resolves its dependencies through its own <code>RPATH</code>, its loader chain, and the <em>main executable’s</em> paths. The CUDA libraries were installed without root, in a pinned location, and found through my library’s search path.</p>
<p>The trap: modern linkers emit <code>DT_RUNPATH</code> by default, not <code>DT_RPATH</code>, and <strong><code>RUNPATH</code> is not inherited down a <code>dlopen</code> chain.</strong> It applies to the library’s own direct dependencies and stops there. Measured in a standalone executable to be sure: the same build with <code>RUNPATH</code> ran at 236.6 ms on CPU, and with <code>RPATH</code> at 51.2 ms on CUDA.</p>
<p>Two fixes, belt and braces: link with <code>-Wl,--disable-new-dtags</code> so the old inheriting <code>RPATH</code> is emitted, and explicitly <code>dlopen</code> the CUDA libraries by absolute path before creating the session, so they are already resident when the provider asks for them.</p>
<p>The gate now asserts the <strong>provider name</strong> as well as the time. Depth must report <code>CUDAExecutionProvider</code> and come in under an 80 ms budget. Final: <strong>55.1 ms mean, 17.4 Hz.</strong></p>
<hr>
</section>
<section id="a-zero-copy-test-that-measured-the-one-case-that-cannot-fail" class="level2">
<h2 class="anchored" data-anchor-id="a-zero-copy-test-that-measured-the-one-case-that-cannot-fail">3. A zero-copy test that measured the one case that cannot fail</h2>
<p>ROS 2 intra-process communication can hand a message between nodes in the same process without copying it. The gate checks this directly: subscribers record the address of the buffer they received, and the gate compares it with the address the publisher sent.</p>
<p>First run: <strong>429 of 429</strong> buffers matched. Then a second consumer was added for an unrelated reason, and the next run read <strong>0 of 574.</strong></p>
<p><code>rclcpp</code> moves a published <code>unique_ptr</code> into the <strong>last</strong> subscription that takes ownership, and copies it for every other one. With one subscriber, there is no “other one”, so the test passes whatever the subscribers declare. The configuration being tested was the only configuration in which the test could not fail.</p>
<p>The fix was for subscribers to take <code>ConstSharedPtr</code>, which lets every consumer share the one buffer, and for the gate to <strong>require at least two consumers.</strong> The control run turns intra-process communication off and must match almost nothing. A passing run now reads 504 of 504 with it on, and 0 of 395 with it off.</p>
<hr>
</section>
<section id="the-smaller-ones-same-shape" class="level2">
<h2 class="anchored" data-anchor-id="the-smaller-ones-same-shape">4. The smaller ones, same shape</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Gate result</th>
<th>What was actually happening</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Keypoint cost <strong>0.00 ms</strong>, PASS</td>
<td>The gate grepped the last <code>stats</code> line, which now came from the depth node’s idle window. Gates select by node name and require cost &gt; 0</td>
</tr>
<tr class="even">
<td>Keypoints just inside the 8 ms budget</td>
<td>The whole workspace was building at <code>-O0</code>. 7.90 ms became 5.99 ms at <code>-O2</code></td>
</tr>
<tr class="odd">
<td>An 11-point regression in match rate</td>
<td>The gate compared a 20 s window against the average of a 60 s clip. Not a regression. Counting 0/0 frames as zero was worth another 5 points</td>
</tr>
<tr class="even">
<td>12% of fused frames colourless</td>
<td>The executor runs callbacks in registration order, so depth sometimes arrived before its colour frame</td>
</tr>
<tr class="odd">
<td>Teardown gate PASS</td>
<td><code>timeout</code> put <code>ros2 launch</code> in a process group that Ctrl-C never reached, and the gate signalled only one of the two recipes it should have checked</td>
</tr>
</tbody>
</table>
<p>Not one of these is a crash. Each one produced a number, and the number was plausible.</p>
<hr>
</section>
<section id="what-a-gate-looks-like" class="level2">
<h2 class="anchored" data-anchor-id="what-a-gate-looks-like">What a gate looks like</h2>
<p>The depth gate is the template. Run one is the real pipeline and asserts:</p>
<ul>
<li>the provider is <code>CUDAExecutionProvider</code>,</li>
<li>mean cost is under 80 ms and the rate over 10 Hz,</li>
<li>every output frame is byte-identical to its source frame (no stale or reordered pairs),</li>
<li>zero NaN or out-of-range depths, and at least 85% coverage of the clip.</li>
</ul>
<p>Run two is the <strong>adversarial control</strong>: the same binary with <code>use_cuda:=false</code>. It must report the CPU provider, and it <strong>must fail the budget.</strong></p>
<blockquote class="blockquote">
<p>A budget that the thing it excludes can meet is not an assertion.</p>
</blockquote>
<p>That one line is the whole idea. A threshold that a known-bad configuration also passes discriminates nothing, and the only way to know is to run the bad configuration on purpose. The zero-copy gate’s control is intra-process communication switched off, and it must match almost nothing.</p>
<hr>
</section>
<section id="the-measured-pipeline" class="level2">
<h2 class="anchored" data-anchor-id="the-measured-pipeline">The measured pipeline</h2>
<p>Every number below is printed by a gate, on the same recorded clip, on a GTX 1660 SUPER.</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>Stage</th>
<th>Measured</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Capture (Pi 5, 720p MJPEG over Wi-Fi)</td>
<td>44 to 59 Hz, kernel-stamped</td>
</tr>
<tr class="even">
<td>Decode</td>
<td>1.90 ms / frame, zero-copy to every consumer</td>
</tr>
<tr class="odd">
<td>ORB keypoints (x500)</td>
<td>5.99 ms against an 8 ms budget</td>
</tr>
<tr class="even">
<td>PnP odometry</td>
<td>1.42 px mean reprojection over 97 inliers</td>
</tr>
<tr class="odd">
<td>Depth (CUDA)</td>
<td>55.1 ms mean, 58.2 ms p95, against 80 ms</td>
</tr>
<tr class="even">
<td>TSDF fusion (15 mm voxels)</td>
<td>15.3 ms against 20 ms</td>
</tr>
<tr class="odd">
<td>Marching cubes</td>
<td>790,668 triangles in 2.8 s, decimated to 120,000</td>
</tr>
<tr class="even">
<td>Dashboard</td>
<td>10 Hz stats for 0.77% of pipeline throughput</td>
</tr>
</tbody>
</table>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>The expensive bugs in a perception pipeline are not the ones that crash. They are the ones where the output is internally consistent: mirrored poses that agree with each other, a CPU fallback that is merely slow, a zero-copy test in the one configuration that cannot copy.</p>
<p>So the question to ask of every check is not “does it pass” but <strong>“what does this not touch?”</strong>, and the cheapest way to answer it is to run a configuration you know is wrong and confirm the check fails. If it does not, it was never checking anything.</p>
<p>The next step for this pipeline is closing the loop, which is what turns visual odometry into SLAM.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Robotics and ML</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/bugs_plausible_output.html</guid>
  <pubDate>Sat, 19 Sep 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Training GNNs on WebGPU</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/gnns_on_webgpu.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p><a href="https://github.com/bthek1/model_playground">model_playground</a> runs ML models in the browser, on the visitor’s GPU. It is live at <a href="https://playground.benedictthekkel.com">playground.benedictthekkel.com</a>. Most of it deploys pretrained models through Transformers.js and ONNX Runtime Web, and none of that is my kernel code. This post is about the part that is: the graph neural network pages, built between 2026-09-12 and 2026-09-16, where training runs on WGSL compute shaders I wrote by hand.</p>
</blockquote>
<hr>
<section id="one-shader-for-three-architectures" class="level2">
<h2 class="anchored" data-anchor-id="one-shader-for-three-architectures">One shader for three architectures</h2>
<p>GCN, GraphSAGE and GIN look different on paper. In the forward pass they are the same operation: for each node, a scaled sum of its own features and its neighbours’ features. They differ only in the scales.</p>
<p>So there is one aggregation shader, over the adjacency in CSR form, one invocation per node:</p>
<pre class="wgsl"><code>for (var f = 0u; f &lt; dims.nFeat; f = f + 1u) {
  var acc = selfScale * x[base + f];
  for (var e = start; e &lt; end; e = e + 1u) {
    let j = colIdx[e];
    acc = acc + beta[j] * x[j * dims.nFeat + f];
  }
  out[base + f] = outScale * acc;
}</code></pre>
<p>GCN’s symmetric normalisation, SAGE’s mean and GIN’s sum are all choices of <code>selfScale</code>, <code>beta</code> and <code>outScale</code>. And because the self-looped adjacency is symmetric, <strong>the backward pass is the same dispatch</strong> with two scale vectors swapped. One shader, both directions, three models.</p>
<p>Around it, five more small shaders: a naive matmul in 16x16 workgroups with no tiling, elementwise ops, transpose, scale, and a point-cloud renderer used elsewhere. 275 lines of WGSL in all. GAT is the exception: its attention coefficients are learned per edge, so it runs on a CPU propagator.</p>
<p>The dataset ships as CSR too. Cora’s 2,708 nodes and 1,433 features are 15.5 MB as dense float32; as a sparse structure it is 161 KB.</p>
<hr>
</section>
<section id="how-you-know-the-kernels-are-right" class="level2">
<h2 class="anchored" data-anchor-id="how-you-know-the-kernels-are-right">How you know the kernels are right</h2>
<p>Two checks, at different layers:</p>
<ul>
<li><strong>Kernel parity.</strong> The GPU aggregation runs against a CPU reference implementation, in a real browser, and the worst element-wise error must be under <code>1e-5</code>. Dropping the self-loop as a deliberate fault sends it to 0.87, so the test can actually fail.</li>
<li><strong>Finite-difference gradient checks</strong> on every hand-written backward pass: GCN, SAGE, GIN and GAT at one, two and three layers, with and without dropout. They are evaluated at a point with non-zero bias, so no pre-activation sits exactly on ReLU’s kink, where the numerical gradient is meaningless.</li>
</ul>
<p>While wiring those up I found that <strong>every WebGPU end-to-end test in the repo had been silently skipping itself, on every machine.</strong> The suite probed for <code>navigator.gpu</code> before navigating, from <code>about:blank</code>. WebGPU is only exposed in a secure context, and <code>about:blank</code> in that harness was not one, so the probe always said “no GPU” and every spec politely skipped. Green CI, zero coverage. A skip is a result too, and it is worth asserting on how many tests actually ran.</p>
<hr>
</section>
<section id="oversmoothing-the-metric-was-wrong-first" class="level2">
<h2 class="anchored" data-anchor-id="oversmoothing-the-metric-was-wrong-first">Oversmoothing: the metric was wrong first</h2>
<p>Stack enough GCN layers and every node’s representation converges toward the same vector. That is oversmoothing, and the page has a slider for depth so you can watch it happen.</p>
<p>The first measure I used was the obvious one: <strong>mean pairwise cosine similarity over all node pairs.</strong> If representations converge, that should climb with depth. It came out as</p>
<pre><code>0.720, 0.643, 0.663, 0.579, 0.677</code></pre>
<p>which is not a trend. The metric was answering the wrong question. Oversmoothing is a <em>local</em> phenomenon first: connected nodes become indistinguishable. Unrelated nodes on opposite sides of the graph can stay far apart for a long time while every neighbourhood collapses internally.</p>
<p>The replacement measures <strong>similarity between adjacent nodes, on row-normalised representations</strong>, which is the Dirichlet energy up to a constant. With it, the picture is monotonic and matches the accuracy:</p>
<table class="caption-top table">
<thead>
<tr class="header">
<th>GCN layers</th>
<th>Test accuracy</th>
<th>Neighbour similarity</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>2</td>
<td>0.776</td>
<td>0.947</td>
</tr>
<tr class="even">
<td>4</td>
<td>0.687</td>
<td>0.958</td>
</tr>
<tr class="odd">
<td>6</td>
<td>0.496</td>
<td>0.973</td>
</tr>
<tr class="even">
<td>8</td>
<td>0.518</td>
<td>0.978</td>
</tr>
</tbody>
</table>
<p>Accuracy is itself not monotonic (8 layers edges 6), which is a reminder that one run per depth is noise-sensitive. The similarity column is the one that moves cleanly.</p>
<p>GIN at 8 layers is a different failure wearing the same symptom: 0.064 accuracy. That is not smoothing. GIN sums neighbours without normalising, the sums overflow, and ReLU zeroes everything downstream. <strong>Every representation is dead.</strong> So the page reports the dead fraction separately and names the failure when more than half the units are dead, instead of letting a single accuracy number blame the wrong cause.</p>
<hr>
</section>
<section id="link-prediction-the-leak-that-improves-the-score" class="level2">
<h2 class="anchored" data-anchor-id="link-prediction-the-leak-that-improves-the-score">Link prediction: the leak that improves the score</h2>
<p>Link prediction hides some edges, trains on the rest, and asks the model to score the hidden edges above random non-edges. The trap is that <strong>a GNN encoder reads the graph</strong>. If a held-out edge is still in the adjacency the encoder aggregates over, the model is not predicting it. It is looking at it. The expected symptom is an AUC around 0.99, a number that looks like success.</p>
<p>So the split was written to make that impossible before any model was trained on it. Four things have to be true, and the first one is the only one most write-ups mention:</p>
<ol type="1">
<li><strong>Remove both directed copies</strong> of each held-out edge. CSR stores an undirected edge twice.</li>
<li><strong>Recompute the degrees from the training graph.</strong> GCN normalises by <img src="https://latex.codecogs.com/png.latex?D%5E%7B-1/2%7D">. A degree vector computed on the full graph still encodes the held-out edge, as a count, in every message that touches its endpoints.</li>
<li><strong>Never hold out an edge that would isolate a node.</strong> On Cora, up to 485 degree-1 nodes would be stranded with nothing to aggregate. Those edges stay in training.</li>
<li><strong>Sample negatives against the full graph</strong>, so a “negative” is never secretly a held-out positive.</li>
</ol>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode ts code-with-copy"><code class="sourceCode typescript"><span id="cb3-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> (<span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> e <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">of</span> order) {</span>
<span id="cb3-2">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (nTest <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> wantTest <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&amp;&amp;</span> nVal <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&gt;=</span> wantVal) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">break</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-3">  <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> u <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> edges[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> e]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> v <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> edges[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">2</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">*</span> e <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">+</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span>
<span id="cb3-4">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Removing this would leave an endpoint with nothing to aggregate over.</span></span>
<span id="cb3-5">  <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> (degree[u] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span> <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">||</span> degree[v] <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">&lt;=</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>) { rescued<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">++;</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">continue</span><span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span> }</span>
<span id="cb3-6">  degree[u]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--;</span> degree[v]<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">--;</span></span>
<span id="cb3-7">  <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// ...</span></span>
<span id="cb3-8">}</span>
<span id="cb3-9"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">// Negatives are drawn against the *full* graph</span></span>
<span id="cb3-10"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">const</span> testNeg <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">sampleNegatives</span>(rowPtr<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> colIdx<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> nNodes<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> nTest<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">,</span> rand)<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">;</span></span></code></pre></div></div>
<p>And the end-to-end test asserts a <strong>band</strong>, not a floor: test AUC above 0.85 and <strong>below 0.985</strong>. A score that high on Cora is not a better model. It is the leak coming back, and the test fails on it.</p>
<p>The hyperparameters mattered more than I expected. Reusing the node-classification recipe gave 0.737. The graph auto-encoder recipe gave 0.879, then 0.906 at 250 epochs, and <strong>0.925 with 0.2 dropout</strong>, which is what ships. For reference, the published GAE result on Cora is 0.910, so this is in the right place rather than suspiciously above it. GPU and CPU paths agree to within 0.003.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>None of the three stories is about WGSL. The kernels were checked by parity and gradient tests and were right. Every real problem was in what the numbers <em>meant</em>:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Number</th>
<th>What was wrong</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Pairwise cosine vs depth</td>
<td>Measured a global property of a local failure</td>
</tr>
<tr class="even">
<td>GIN accuracy at depth 8</td>
<td>Blamed smoothing for overflow and dead ReLUs</td>
</tr>
<tr class="odd">
<td>Link-prediction AUC</td>
<td>Would reward leakage, so it is bounded above in the test</td>
</tr>
<tr class="even">
<td>Green WebGPU test suite</td>
<td>Nothing had run</td>
</tr>
</tbody>
</table>
<p>The habit that catches all four is the same: before trusting a metric, ask what the wrong answer would look like, and make sure a test can tell the two apart.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Robotics and ML</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/gnns_on_webgpu.html</guid>
  <pubDate>Wed, 16 Sep 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Machine Safety for Software Engineers</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/machine_safety_as4024.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>If you write software that moves something physical, at some point somebody asks whether the machine is safe, and means something specific and legal by it. This is the shape of that answer in Australia.</p>
</blockquote>
<p>AS/NZS 4024 is the Australian and New Zealand <em>Safety of machinery</em> series: not one document but a family of 26 parts, each an adoption, usually modified, of an ISO or EN standard. If you already know ISO 13849, ISO 12100 and IEC 60204-1, this is the same content under local numbering.</p>
<hr>
<section id="it-is-not-law-and-that-is-the-interesting-part" class="level2">
<h2 class="anchored" data-anchor-id="it-is-not-law-and-that-is-the-interesting-part">It is not law, and that is the interesting part</h2>
<p>Standards Australia is not a regulator. Standards are voluntary. They become effectively mandatory only when legislation references them, and AS 4024 is largely <strong>not</strong> called up directly in the WHS Regulations.</p>
<p>What actually binds a machine builder in Queensland:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Instrument</th>
<th>What it does</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>WHS Act 2011 (Qld) ss. 22-26</strong></td>
<td>Upstream duties on designers, manufacturers, importers, suppliers and installers of plant. This is the clause that catches you as a builder or integrator</td>
</tr>
<tr class="even">
<td><strong>WHS Regulation 2011 (Qld) Ch. 5 Pt 3</strong></td>
<td>Plant: guarding, emergency stops, controls, isolation, maintenance</td>
</tr>
<tr class="odd">
<td><strong>Code of Practice: Managing the risks of plant</strong></td>
<td>Admissible in proceedings as evidence of what was known and reasonably practicable</td>
</tr>
</tbody>
</table>
<p>So the relationship is this: <strong>AS 4024 is how you demonstrate you met the “reasonably practicable” test.</strong> Conform to it and you have a defensible position. Ignore it and the prosecution’s expert cites it against you. That is the whole of it.</p>
<p>Jurisdiction matters if you sell interstate: Victoria is still under the OHS Act 2004 rather than the model WHS laws, and WA harmonised only in 2022. The duty applies in each jurisdiction of supply, not just where you built the thing.</p>
<hr>
</section>
<section id="the-trap-two-methodologies-in-the-same-series" class="level2">
<h2 class="anchored" data-anchor-id="the-trap-two-methodologies-in-the-same-series">The trap: two methodologies in the same series</h2>
<p>This is the part that catches people, because both are current documents with current numbers and they encode <strong>incompatible ways of designing a safety function</strong>.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Part</th>
<th>Approach</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>1501/1502</strong> (2006, reconfirmed 2014)</td>
<td>The old EN 954-1 method. Purely architectural: pick <strong>Category B, 1, 2, 3 or 4</strong> from a risk graph. No reliability data, no probability</td>
<td>Withdrawn internationally in 2011</td>
</tr>
<tr class="even">
<td><strong>1503:2014</strong></td>
<td>ISO 13849-1:2006. <strong>Performance Level PLa-PLe</strong>, combining architecture <em>plus</em> component reliability and diagnostic coverage</td>
<td>What you should use</td>
</tr>
</tbody>
</table>
<p>Category-only design was dropped internationally for a concrete reason: it lets you build a Category 3 circuit out of unreliable components and call it safe, because the method never asks how often the parts fail.</p>
<p><strong>Practical tell:</strong> if a supplier quotes you “Category 3” with no Performance Level attached, they are working from a twenty-year-old mental model. Push back before it is designed in.</p>
<hr>
</section>
<section id="how-performance-levels-actually-work" class="level2">
<h2 class="anchored" data-anchor-id="how-performance-levels-actually-work">How Performance Levels actually work</h2>
<p><strong>Step 1: determine the required PL for each safety function</strong>, from a risk graph with three inputs.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Input</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>S</strong> severity</td>
<td>S1 slight and reversible, S2 serious, irreversible or fatal</td>
</tr>
<tr class="even">
<td><strong>F</strong> frequency and duration of exposure</td>
<td>F1 seldom, F2 frequent or continuous</td>
</tr>
<tr class="odd">
<td><strong>P</strong> possibility of avoidance</td>
<td>P1 possible under specific conditions, P2 scarcely possible</td>
</tr>
</tbody>
</table>
<p>S2 + F2 + P2 lands on <strong>PLe</strong>. A guarded pinch point with occasional access is typically PLd. Clearing a jam on a hydraulic press is PLe every time, because all three inputs are at their worst.</p>
<p><strong>Step 2: design to hit it.</strong> PL is a function of the architecture (Category B through 4), the component reliability, the diagnostic coverage, and the resistance to common-cause failure. It is not a label you assert; it is an outcome you calculate and then validate.</p>
<p>Note the direction of the work: the required PL comes from the <em>hazard</em>, before you have chosen any components. Choosing a relay and then reverse-engineering a justification is the wrong order and reads as such in an incident investigation.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/22_pl_design_loop.svg" class="img-fluid figure-img"></p>
<figcaption>Each hazard goes through the S, F and P risk graph to a required PL, then the design is validated against 1502 and 13849-2 and reworked until the achieved PL meets the required PL, after which the file is documented.</figcaption>
</figure>
</div>
<hr>
</section>
<section id="the-calculation-you-will-actually-do" class="level2">
<h2 class="anchored" data-anchor-id="the-calculation-you-will-actually-do">The calculation you will actually do</h2>
<p>Most of the series is read once. The safety-distance parts get used repeatedly, because the question “how far away does the guard have to be” comes up on every job.</p>
<ul>
<li><strong>1801:2014</strong> (from ISO 13857): safety distances to prevent upper and lower limbs reaching hazard zones.</li>
<li><strong>1803:2019</strong> (from ISO 13854): minimum gaps to avoid crushing parts of the body.</li>
</ul>
<p>The logic is that a guard is only as good as the time it buys. If the machine takes 200 ms to stop and a hand moves at 1.6 m/s, the guard has to sit far enough back that the hand cannot arrive before the motion ends. Reach-through, reach-over and reach-around are separate cases with separate tables.</p>
<p>This is the part software people underestimate, because it is the part where the answer is a number in millimetres rather than an architecture.</p>
<hr>
</section>
<section id="the-series-roughly-grouped" class="level2">
<h2 class="anchored" data-anchor-id="the-series-roughly-grouped">The series, roughly grouped</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Range</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>1100, 1201, 1303</strong></td>
<td>Application guide, general design principles, risk assessment (ISO 12100, ISO/TR 14121-2)</td>
</tr>
<tr class="even">
<td><strong>1204</strong></td>
<td>Electrical equipment of machines (IEC 60204-1)</td>
</tr>
<tr class="odd">
<td><strong>1501/1502/1503</strong></td>
<td>Safety-related parts of control systems: the old categories, validation, and the modern PL method</td>
</tr>
<tr class="even">
<td><strong>1601-1604</strong></td>
<td>Guards, interlocking devices, prevention of unexpected start-up, emergency stop</td>
</tr>
<tr class="odd">
<td><strong>1701-1704, 1801, 1803</strong></td>
<td>Human body measurements, access openings, safety distances, crush gaps</td>
</tr>
<tr class="even">
<td><strong>1901-1907</strong></td>
<td>Displays, controls, actuators, markings, auditory and visual warnings</td>
</tr>
<tr class="odd">
<td><strong>3xxx</strong></td>
<td>Machine-specific: presses, milling and boring, conveyors</td>
</tr>
</tbody>
</table>
<hr>
</section>
<section id="what-catches-control-engineers" class="level2">
<h2 class="anchored" data-anchor-id="what-catches-control-engineers">What catches control engineers</h2>
<ul>
<li><strong>Designing to a Category instead of a PL.</strong> Covered above; it is the big one.</li>
<li><strong>Treating the e-stop as the safety function.</strong> An emergency stop is a complementary protective measure, not a substitute for guarding. It requires someone to already be reacting.</li>
<li><strong>Forgetting unexpected start-up.</strong> 1603 exists because the hazard is often not the running machine but the one that restarts while somebody is inside it.</li>
<li><strong>Skipping validation.</strong> The design half (1503) and the validation half (1502 / ISO 13849-2) are separate documents for a reason. An unvalidated calculated PL is a claim, not a result.</li>
</ul>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>The mental shift for a software engineer is that “safe” here is not a property you argue for after the fact. It is a required Performance Level derived from the hazard, a design that demonstrably achieves it, and a validation file that says so.</p>
<p>Start at <strong>1100</strong> for the map and <strong>1201</strong> for risk assessment, use <strong>1503</strong> and never 1501, and expect to spend real time in <strong>1801</strong>. Full notes, including the series table and the jurisdiction detail, are in <a href="https://bthek1.github.io/Hardware_Tools/"><strong>Hardware Tools</strong></a>, alongside the <a href="https://bthek1.github.io/Hardware_Tools/">PLC</a> and SCADA material this sits next to.</p>
<div class="callout callout-style-default callout-warning callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Warning
</div>
</div>
<div class="callout-body-container callout-body">
<p>These are engineering notes, not legal advice, and the legislation differs by state. For a machine going into service, get the safety file reviewed by someone who does this professionally.</p>
</div>
</div>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Hardware and Industry</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/machine_safety_as4024.html</guid>
  <pubDate>Tue, 11 Aug 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Compliance Is a Sales Function</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/compliance_sales_function.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The clearest way I can put it: <strong>the security work is worth doing regardless; the certificate is what unblocks the deal.</strong> Those are two different projects with two different success criteria, and treating them as one is how a company spends $60k on SOC 2 and still ships a tenant-isolation bug.</p>
</blockquote>
<p>Neither half is optional. But if you cannot say which one you are currently doing, you will do both badly.</p>
<hr>
<section id="what-a-certificate-actually-asserts" class="level2">
<h2 class="anchored" data-anchor-id="what-a-certificate-actually-asserts">What a certificate actually asserts</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Framework</th>
<th>What it is</th>
<th>When you need it</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>SOC 2 Type II</strong></td>
<td>An AICPA attestation. An auditor’s <em>opinion</em> on your controls over an observation window. Not a certification</td>
<td>US buyers, mid-market and up. The default ask in North America</td>
</tr>
<tr class="even">
<td><strong>ISO/IEC 27001:2022</strong></td>
<td>A certifiable ISMS standard. An accredited body issues a three-year certificate with annual surveillance</td>
<td>Australian, European and enterprise buyers</td>
</tr>
</tbody>
</table>
<p>Read the definitions closely and the framing follows. SOC 2 is an opinion about whether the controls you described were operating over a window. It is not a statement that your software is free of vulnerabilities, and it was never designed to be.</p>
<p>That is not a criticism of the frameworks. It is what they are for. The mistake is on the buyer’s side and the seller’s side equally: treating an attestation about process as evidence about product.</p>
<hr>
</section>
<section id="the-order-of-operations-that-actually-works" class="level2">
<h2 class="anchored" data-anchor-id="the-order-of-operations-that-actually-works">The order of operations that actually works</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/23_compliance_order.svg" class="img-fluid figure-img"></p>
<figcaption>Compliance runs in order from legal obligations, which cannot be skipped, through security engineering and the evidence it produces, to certification when a deal requires it and finally an unblocked deal.</figcaption>
</figure>
</div>
<p>The failure mode is starting at D. A compliance programme run as a sales project produces a binder that describes controls somebody intends to implement, and an audit window spent hurriedly making the binder true.</p>
<p>Run in the right order, the certificate is mostly a packaging exercise over work you already did.</p>
<hr>
</section>
<section id="the-part-that-binds-you-whether-or-not-you-certify" class="level2">
<h2 class="anchored" data-anchor-id="the-part-that-binds-you-whether-or-not-you-certify">The part that binds you whether or not you certify</h2>
<p>For anything handling health data in Australia, the legal baseline is stricter than most founders assume, and it applies from day one.</p>
<ul>
<li><strong>Health information is <em>sensitive information</em></strong> under the Privacy Act’s APP 3. Collection requires consent and a direct connection to your functions, and the bar for use, disclosure and cross-border transfer is materially higher than for ordinary personal information.</li>
<li><strong>The small business exemption does not save you.</strong> The under-$3M-turnover exemption is voided if you provide a health service or hold health records. A pre-revenue startup holding patient-reported outcomes is a full APP entity immediately. This is the single most commonly missed obligation in Australian health tech.</li>
<li><strong>There is no controller/processor split.</strong> Unlike GDPR, if you hold the information you are an APP entity in your own right. You cannot contract your way into being a mere processor, and both you and the clinic have independent obligations over the same record.</li>
<li><strong>Notifiable Data Breaches</strong>: assess a suspected eligible breach within 30 days, and if serious harm is likely and you cannot remediate, notify the OAIC and the affected individuals. Health data almost always clears the serious-harm threshold. Thirty days sounds generous until you are mid-incident, so write the runbook first.</li>
<li><strong>APP 8 makes you accountable for your offshore recipients’ acts as if they were your own.</strong> In practice: host in an Australian region and document every subprocessor’s residency. “Our vendor is US-based but SOC 2 certified” is not an answer under APP 8, which is the cleanest illustration of the whole thesis.</li>
</ul>
<p>That last point is worth sitting with. A buyer’s procurement team may accept a certificate. The statute does not.</p>
<hr>
</section>
<section id="the-reform-state-because-it-is-moving" class="level2">
<h2 class="anchored" data-anchor-id="the-reform-state-because-it-is-moving">The reform state, because it is moving</h2>
<p>Tranche 1 of the Privacy Act reform passed in late 2024. The piece with the sharpest commercial edge is the <strong>statutory tort for serious invasion of privacy</strong>, which commenced 10 June 2025: individuals can sue directly, independent of any regulator action, with no turnover threshold. Automated decision-making transparency requirements follow in December 2026.</p>
<p>Tranche 2 remains a Government commitment rather than enacted law, with no bill passed and no timetable. Expected scope includes a “fair and reasonable” test independent of consent, GDPR-style rights including erasure, a broader definition of personal information, and removal of the employee and small-business exemptions.</p>
<p>The engineering implication is simple enough to act on now: <strong>design the data model assuming erasure and export will become mandatory.</strong> Retrofitting deletion into a schema that assumed permanence is one of the more painful migrations available.</p>
<hr>
</section>
<section id="one-thing-to-check-rather-than-assume" class="level2">
<h2 class="anchored" data-anchor-id="one-thing-to-check-rather-than-assume">One thing to check rather than assume</h2>
<p>If your product does anything more than deliver questionnaires and report outcomes, check whether it is <strong>Software as a Medical Device</strong> under the TGA. Pure administrative and record-keeping software normally falls inside the exclusions. The moment you add scoring that flags a clinical action, risk stratification, or anything recommending treatment, you may be in the SaMD regime.</p>
<p>That is a regulatory conversation rather than an engineering one, and it changes your entire quality-management burden. Get a written opinion early, when it is a question, rather than late, when it is a finding.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>Three sentences:</p>
<ol type="1">
<li><strong>Legal obligations bind you today</strong>, certificate or not, and for health data in Australia they are stricter than the startup folklore suggests.</li>
<li><strong>Security engineering is worth doing on its own merits</strong>, and it produces the evidence a certification needs as a by-product.</li>
<li><strong>The certificate is a sales artefact.</strong> Buy it when a deal requires it, and be honest that this is why.</li>
</ol>
<p>The trouble starts when the third sentence is mistaken for the second. Full notes, including the framework comparison and the Australian legal detail, are in <a href="https://bthek1.github.io/Web_development/"><strong>Web Development</strong></a>.</p>
<div class="callout callout-style-default callout-note callout-titled">
<div class="callout-header d-flex align-content-center">
<div class="callout-icon-container">
<i class="callout-icon"></i>
</div>
<div class="callout-title-container flex-fill">
Note
</div>
</div>
<div class="callout-body-container callout-body">
<p>Engineering notes, not legal advice. Privacy law is being actively reformed; check the current state before relying on any of it.</p>
</div>
</div>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Product</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/compliance_sales_function.html</guid>
  <pubDate>Tue, 11 Aug 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Which Diagram Answers Which Question</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/which_diagram.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>Most bad architecture diagrams are not badly drawn. They are answering three questions at once, so a load balancer, a Python module and a domain class end up as identical boxes on the same page.</p>
</blockquote>
<p>UML has notation for architecture and almost nobody uses it. The reason is not fashion. <strong>UML’s architecture diagrams have no concept of zoom level</strong>, so a single diagram becomes unreadable at exactly the moment it becomes important. The notations that won each fix that by picking one axis and staying on it.</p>
<hr>
<section id="pick-by-axis" class="level2">
<h2 class="anchored" data-anchor-id="pick-by-axis">Pick by axis</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Notation</th>
<th>Organising axis</th>
<th>The question it owns</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>Sequence</strong></td>
<td>Time, down the page</td>
<td>Who calls whom, in what order, and what happens when a call fails</td>
</tr>
<tr class="even">
<td><strong>State machine</strong></td>
<td>The lifecycle of one entity</td>
<td>What states can this be in, and which transitions are legal</td>
</tr>
<tr class="odd">
<td><strong>Activity / flowchart</strong></td>
<td>Control flow of one procedure</td>
<td>What are the branches and loops in this job</td>
</tr>
<tr class="even">
<td><strong>ER</strong></td>
<td>Tables and relationships</td>
<td>What is the data shape</td>
</tr>
<tr class="odd">
<td><strong>C4</strong></td>
<td>Level of abstraction</td>
<td>What are the moving pieces, at the zoom level you asked about</td>
</tr>
<tr class="even">
<td><strong>Data flow</strong></td>
<td>Where data goes and which boundaries it crosses</td>
<td>What could an attacker do here</td>
</tr>
<tr class="odd">
<td><strong>Network topology</strong></td>
<td>Addresses, segments, firewall zones</td>
<td>Can this host actually reach that one</td>
</tr>
</tbody>
</table>
<p>A useful diagnostic for the behavioural three: <strong>count the nouns.</strong> Many participants exchanging messages means sequence. One noun moving through a lifecycle means state machine. No nouns, just steps and decisions, means activity.</p>
<hr>
</section>
<section id="c4-and-the-advice-that-makes-it-work" class="level2">
<h2 class="anchored" data-anchor-id="c4-and-the-advice-that-makes-it-work">C4, and the advice that makes it work</h2>
<p>Simon Brown’s C4 model is the pragmatic replacement for most UML architecture diagrams, and its entire contribution is insisting that <strong>one diagram holds one zoom level</strong>.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
<col style="width: 25%">
</colgroup>
<thead>
<tr class="header">
<th>Level</th>
<th>Boxes are</th>
<th>Audience</th>
<th>Redraw when</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>1. Context</strong></td>
<td>Your system, its users, the systems it talks to</td>
<td>Anyone, including non-technical</td>
<td>A new external integration appears</td>
</tr>
<tr class="even">
<td><strong>2. Container</strong></td>
<td>Separately deployable things: apps, services, databases, queues</td>
<td>Engineers and ops</td>
<td>A service or datastore is added</td>
</tr>
<tr class="odd">
<td><strong>3. Component</strong></td>
<td>Major building blocks inside one container</td>
<td>Engineers on that container</td>
<td>Rarely, and only where internals are non-obvious</td>
</tr>
<tr class="even">
<td><strong>4. Code</strong></td>
<td>Classes</td>
<td>Almost nobody</td>
<td>Never. Generate it if you truly need it</td>
</tr>
</tbody>
</table>
<p><strong>Draw levels 1 and 2, then stop.</strong> A context diagram and a container diagram cover nearly every architecture conversation that actually happens. Level 3 earns its place for the one or two containers with surprising internals. Level 4 is what your IDE does.</p>
<hr>
</section>
<section id="the-one-to-skip" class="level2">
<h2 class="anchored" data-anchor-id="the-one-to-skip">The one to skip</h2>
<p><strong>Communication diagrams</strong> carry the same information as a sequence diagram laid out spatially, and answer nothing a sequence diagram does not answer better. Distributed bugs are almost always ordering bugs, and sequence is the only common notation that puts ordering on an axis.</p>
<p><strong>Use case diagrams</strong> are mostly ceremony: stick figures connected to ovals, restating a list you already had in prose.</p>
<p>Which suggests a general test.</p>
<hr>
</section>
<section id="the-ceremony-test" class="level2">
<h2 class="anchored" data-anchor-id="the-ceremony-test">The ceremony test</h2>
<p>Before drawing anything, ask: <strong>what decision changes based on this picture?</strong></p>
<p>If the honest answer is “none, but the template has a section for it”, you are producing ceremony. A diagram earns its place when it either surfaces something the prose cannot (ordering, a state you forgot was reachable, a trust boundary nobody had noticed) or settles an argument.</p>
<p>The corollary is that a diagram which merely restates the code is worse than no diagram, because it now needs maintaining and will silently go wrong.</p>
<hr>
</section>
<section id="keep-three" class="level2">
<h2 class="anchored" data-anchor-id="keep-three">Keep three</h2>
<p>If you only keep three, keep <strong>sequence</strong>, <strong>ER</strong>, and <strong>C4 container</strong>.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/24_three_diagrams.svg" class="img-fluid figure-img"></p>
<figcaption>A sequence diagram answers how an interaction works, an ER diagram answers what the data shape is, and a C4 container diagram answers what the moving pieces are.</figcaption>
</figure>
</div>
<p>Those cover roughly 90% of what a diagram gets asked. All three are expressible in Mermaid, which means they live in the repository next to the code and get reviewed in the same pull request. That matters more than which notation you picked, because the failure mode of diagrams is not wrong notation. It is going stale.</p>
<hr>
</section>
<section id="two-worth-knowing-about-beyond-the-three" class="level2">
<h2 class="anchored" data-anchor-id="two-worth-knowing-about-beyond-the-three">Two worth knowing about beyond the three</h2>
<p><strong>Data flow diagrams</strong> are the basis for STRIDE threat modelling. Once trust boundaries are explicit, “what could an attacker do here” becomes a question you can walk systematically rather than brainstorm.</p>
<p><strong>Timing diagrams</strong> matter the moment you touch hardware. Signals on a wire, with time on an axis, is not something the software notations cover.</p>
<p>Full write-ups, organised by what each family is for and with copy-paste Mermaid throughout, are in <a href="https://bthek1.github.io/Software_Tools/"><strong>Software Tools</strong></a>.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>Choose by the question, not by the notation you happen to know. Keep one zoom level per diagram. Prefer text-based diagrams that live beside the code, because a diagram’s real enemy is drift, not expressiveness.</p>
<p>And when a template asks for a diagram nobody will make a decision from, leave it out.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Software</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/which_diagram.html</guid>
  <pubDate>Tue, 11 Aug 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Pulumi vs Terraform</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/pulumi_vs_terraform.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The <a href="../posts/terraform_ansible_home_lab.html">home lab is provisioned with Terraform and configured with Ansible</a>, and that split still holds. This is the other half of the question: having picked declarative provisioning, does the language it is written in matter?</p>
</blockquote>
<p>Short version: <strong>Pulumi is Terraform’s model with a real programming language in front of it.</strong> Declarative resource graph, provider plugins, state file, preview and apply. You write Python, TypeScript, Go, C# or Java instead of HCL.</p>
<p>Most providers are auto-bridged from the Terraform providers, so the resource surface and schema are near-identical, warts included. Error messages occasionally leak HCL-isms, which tells you exactly how thin the layer is.</p>
<hr>
<section id="the-shape-of-it" class="level2">
<h2 class="anchored" data-anchor-id="the-shape-of-it">The shape of it</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pulumi</span>
<span id="cb1-2"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> pulumi_aws <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> aws</span>
<span id="cb1-3"></span>
<span id="cb1-4">bucket <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> aws.s3.BucketV2(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"assets"</span>)</span>
<span id="cb1-5">aws.s3.BucketVersioningV2(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"assets-versioning"</span>,</span>
<span id="cb1-6">    bucket<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>bucket.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>,</span>
<span id="cb1-7">    versioning_configuration<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"status"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"Enabled"</span>})</span>
<span id="cb1-8"></span>
<span id="cb1-9">pulumi.export(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"bucket_name"</span>, bucket.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">id</span>)</span></code></pre></div></div>
<p>You write a program; running it registers resources with the engine over gRPC. The engine diffs the desired graph against state and calls the providers. <strong>Stacks</strong> are environments, each with its own state and config file, and <code>pulumi config set --secret</code> encrypts per stack.</p>
<p>If that looks like Terraform with different syntax, it is, and that is the point. The differences are not in the model.</p>
<hr>
</section>
<section id="the-thing-that-will-trip-you-up-outputt" class="level2">
<h2 class="anchored" data-anchor-id="the-thing-that-will-trip-you-up-outputt">The thing that will trip you up: <code>Output[T]</code></h2>
<p>Resource properties are not values. They are <code>Output[T]</code>: a future that also carries dependency edges and a secret flag. You cannot branch on one or interpolate it into an f-string.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># wrong - Output is not a str</span></span>
<span id="cb2-2">url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"https://</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>bucket<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>bucket_domain_name<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span></span>
<span id="cb2-3"></span>
<span id="cb2-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># right</span></span>
<span id="cb2-5">url <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pulumi.Output.concat(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"https://"</span>, bucket.bucket_domain_name)</span>
<span id="cb2-6"></span>
<span id="cb2-7"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># multiple inputs</span></span>
<span id="cb2-8">conn <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> pulumi.Output.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">all</span>(db.address, db.port).<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">apply</span>(</span>
<span id="cb2-9">    <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span> a: <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"postgres://</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>a[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">:</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>a[<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>]<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">/app"</span>)</span></code></pre></div></div>
<p>During <code>preview</code>, unresolved values are <code>unknown</code>, so anything computed inside <code>.apply()</code> is invisible in the plan. Creating resources inside an <code>apply</code> is worse again: you lose preview fidelity and dependency clarity.</p>
<p>This is the single biggest source of Pulumi frustration, and it is the tax for having a real language. HCL avoids it by not letting you write the expression in the first place.</p>
<hr>
</section>
<section id="what-is-genuinely-better" class="level2">
<h2 class="anchored" data-anchor-id="what-is-genuinely-better">What is genuinely better</h2>
<p><strong>The Automation API.</strong> Embed the engine as a library and drive stacks programmatically, with no CLI and no shelling out.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> pulumi <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> automation <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> auto</span>
<span id="cb3-2"></span>
<span id="cb3-3">stack <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> auto.create_or_select_stack(</span>
<span id="cb3-4">    stack_name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"tenant-</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>clinic_id<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>,</span>
<span id="cb3-5">    project_name<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"tenant-infra"</span>,</span>
<span id="cb3-6">    program<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">lambda</span>: define_tenant(clinic_id))</span>
<span id="cb3-7">up <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> stack.up(on_output<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>)</span></code></pre></div></div>
<p>For a SaaS that provisions per-tenant infrastructure, this is the feature. Per-tenant stacks driven from a management command or a background task, with real error handling, is a different class of thing from templating HCL and shelling out to <code>terraform apply</code>.</p>
<p><strong>Testing.</strong> Mock the provider layer and unit-test your infrastructure logic: assert on tags, naming conventions, policy compliance. Terraform has nothing comparable that does not involve a <code>plan</code> round-trip.</p>
<p><strong>Components.</strong> <code>ComponentResource</code> subclasses are real classes with constructors, inheritance and typed arguments, and they can be packaged and consumed from another language. Substantially better than modules for abstraction.</p>
<p><strong>Loops and conditionals.</strong> No <code>count</code> or <code>for_each</code> gymnastics. You write a loop.</p>
<hr>
</section>
<section id="what-is-at-parity-or-worse" class="level2">
<h2 class="anchored" data-anchor-id="what-is-at-parity-or-worse">What is at parity, or worse</h2>
<p>State backends work the same way: Pulumi Cloud by default, but <code>s3://</code>, <code>gs://</code>, <code>azblob://</code> and <code>file://</code> all work. Self-hosting costs you drift detection, RBAC, deployments and the console, which is a real trade rather than a free one.</p>
<p>The ecosystem is smaller. When the bridged provider misbehaves, there are fewer people who have hit it before you, and the search results are about the Terraform provider underneath.</p>
<hr>
</section>
<section id="choosing" class="level2">
<h2 class="anchored" data-anchor-id="choosing">Choosing</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/21_pulumi_or_terraform.svg" class="img-fluid figure-img"></p>
<figcaption>Pick Pulumi with the Automation API if provisioning runs from inside an app or infra logic needs unit tests, Terraform or OpenTofu if the team already knows HCL, and either one chosen for ecosystem size otherwise.</figcaption>
</figure>
</div>
<p>For a home lab, Terraform remains the right call: the ecosystem is bigger, the examples are everywhere, and there is no application driving provisioning. The Automation API argument only starts paying once infrastructure is something your product creates rather than something you create for your product.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>Do not switch for the language. HCL is limited, but the limits are also what keeps a plan readable, and <code>Output[T]</code> gives back much of the awkwardness you thought you were escaping.</p>
<p>Switch for the <strong>Automation API</strong> if you provision from inside an application, or for <strong>testability</strong> if your infrastructure logic has enough branching to be worth asserting on. Otherwise this is a preference, not an upgrade. Fuller notes are in <a href="https://bthek1.github.io/Web_development/"><strong>Web Development</strong></a>.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Infrastructure</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/pulumi_vs_terraform.html</guid>
  <pubDate>Wed, 05 Aug 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>asyncio After 3.11</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/asyncio_311.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>Most asyncio material online predates Python 3.11. That matters more than a version bump usually does, because <code>TaskGroup</code>, <code>asyncio.timeout()</code> and <code>task.uncancel()</code> did not add convenience. They changed which patterns are correct.</p>
</blockquote>
<p>3.11 is the meaningful floor. Below it you are writing defensive <code>gather</code> code; above it you mostly are not.</p>
<hr>
<section id="the-mental-model-in-three-consequences" class="level2">
<h2 class="anchored" data-anchor-id="the-mental-model-in-three-consequences">The mental model, in three consequences</h2>
<p>One OS thread runs an event loop holding a queue of ready callbacks. Coroutines run until they hit an <code>await</code> that actually suspends, then hand control back.</p>
<p>That gives you three facts which between them explain almost every asyncio bug:</p>
<ol type="1">
<li><strong><code>await</code> is the only preemption point.</strong> Between two awaits your code is atomic; nothing else in the loop runs. This is a design tool, not just trivia. You often do not need a lock, because there is no interleaving unless you await inside the critical section.</li>
<li><strong>Blocking blocks everything.</strong> A <code>time.sleep(1)</code> or a CPU-bound loop freezes every task, timer and socket read in the process. There is no preemptive scheduler to rescue you.</li>
<li><strong>Concurrency is not parallelism.</strong> asyncio gives you thousands of concurrent IO operations on one core, and zero CPU parallelism.</li>
</ol>
<p>Which yields the right question when reaching for it: <strong>am I waiting on things, or computing things?</strong> Waiting means asyncio. Computing means processes.</p>
<hr>
</section>
<section id="await-does-not-create-concurrency" class="level2">
<h2 class="anchored" data-anchor-id="await-does-not-create-concurrency"><code>await</code> does not create concurrency</h2>
<p>The most common misunderstanding, and it is worth being blunt about:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1">coro <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> fetch(url)                   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># NOT running. Just an object.</span></span>
<span id="cb1-2">result <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> coro                 <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># runs it inline - sequential</span></span>
<span id="cb1-3">task <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> asyncio.create_task(coro)    <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># schedules it - concurrent</span></span></code></pre></div></div>
<p><code>await a(); await b()</code> is strictly sequential. Concurrency requires scheduling both <strong>first</strong>, then awaiting.</p>
<table class="caption-top table">
<colgroup>
<col style="width: 50%">
<col style="width: 50%">
</colgroup>
<thead>
<tr class="header">
<th>Type</th>
<th>What it is</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Coroutine</td>
<td>The object returned by calling an <code>async def</code>. Inert until awaited or wrapped</td>
</tr>
<tr class="even">
<td>Task</td>
<td>A coroutine scheduled on the loop. Has a name, can be cancelled, tracks state</td>
</tr>
<tr class="odd">
<td>Future</td>
<td>A low-level “result eventually” placeholder. Libraries create these, you rarely do</td>
</tr>
</tbody>
</table>
<hr>
</section>
<section id="the-footgun-fire-and-forget-tasks-vanish" class="level2">
<h2 class="anchored" data-anchor-id="the-footgun-fire-and-forget-tasks-vanish">The footgun: fire-and-forget tasks vanish</h2>
<p>The event loop holds only <strong>weak</strong> references to tasks. A task with no strong reference elsewhere can be garbage collected mid-execution, and it simply stops. No error, no warning.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># BROKEN - may vanish partway through</span></span>
<span id="cb2-2">asyncio.create_task(background_work())</span>
<span id="cb2-3"></span>
<span id="cb2-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># Correct - keep a strong reference until it finishes</span></span>
<span id="cb2-5">_background <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>()</span>
<span id="cb2-6"></span>
<span id="cb2-7"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> spawn(coro):</span>
<span id="cb2-8">    t <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> asyncio.create_task(coro)</span>
<span id="cb2-9">    _background.add(t)</span>
<span id="cb2-10">    t.add_done_callback(_background.discard)</span>
<span id="cb2-11">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">return</span> t</span></code></pre></div></div>
<p>This is the bug that produces “it works locally and drops requests in production”, because whether the collector runs at the wrong moment is a load-dependent accident.</p>
<hr>
</section>
<section id="what-3.11-changed" class="level2">
<h2 class="anchored" data-anchor-id="what-3.11-changed">What 3.11 changed</h2>
<p><strong><code>TaskGroup</code></strong> replaces most <code>gather</code> usage. The difference is failure semantics: if one child raises, the group cancels its siblings and propagates an <code>ExceptionGroup</code>. With <code>gather</code> you had to remember <code>return_exceptions</code>, then sort the results yourself, and cancellation of the others was your problem.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> asyncio.TaskGroup() <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">as</span> tg:</span>
<span id="cb3-2">    tg.create_task(fetch(a))</span>
<span id="cb3-3">    tg.create_task(fetch(b))</span>
<span id="cb3-4"><span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># both done here, or the group raised and cancelled the rest</span></span></code></pre></div></div>
<p>It also fixes the reference problem above: the group holds its tasks.</p>
<p><strong><code>asyncio.timeout()</code></strong> is a context manager rather than a wrapper, so it composes with a block of work instead of a single awaitable.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">async</span> <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">with</span> asyncio.timeout(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">5</span>):</span>
<span id="cb4-2">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> step_one()</span>
<span id="cb4-3">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">await</span> step_two()</span></code></pre></div></div>
<p><strong><code>task.uncancel()</code></strong> makes nested cancellation scopes work correctly, which is the machinery that lets the other two behave properly when timeouts and groups are nested.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/20_asyncio_before_after.svg" class="img-fluid figure-img"></p>
<figcaption>Before Python 3.11, gather with return_exceptions and wait_for needed manual result sorting and manual sibling cancellation, while from 3.11 TaskGroup and async with timeout cancel siblings and raise an ExceptionGroup for you.</figcaption>
</figure>
</div>
<hr>
</section>
<section id="practical-consequences" class="level2">
<h2 class="anchored" data-anchor-id="practical-consequences">Practical consequences</h2>
<ul>
<li><strong>Default to <code>TaskGroup</code>.</strong> Reach for <code>gather</code> only when you genuinely want independent results and no sibling cancellation, and say so in a comment, because a reader will assume you meant <code>TaskGroup</code>.</li>
<li><strong>Catch <code>ExceptionGroup</code>, not <code>Exception</code>.</strong> The <code>except*</code> syntax exists for this. Code that catches <code>Exception</code> around a task group will miss things.</li>
<li><strong>Never let a blocking call in.</strong> <code>run_in_executor</code> or a process pool for CPU work; there is no partial credit here.</li>
<li><strong>Treat pre-3.11 examples as archaeology.</strong> The patterns are not wrong so much as manual reimplementations of what the language now does properly.</li>
</ul>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>If you learned asyncio before 3.11, the update is small to read and large in effect: <strong><code>TaskGroup</code> for structure, <code>async with asyncio.timeout()</code> for deadlines, <code>except*</code> for the errors that come back.</strong> Most of the defensive scaffolding around <code>gather</code> can go.</p>
<p>And keep a strong reference to anything you fire and forget, because that one is still waiting for you regardless of version. Full reference, with the cancellation and synchronisation detail, is in <a href="https://bthek1.github.io/Python_Libs/"><strong>Python Libraries</strong></a>.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Software</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/asyncio_311.html</guid>
  <pubDate>Tue, 28 Jul 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>A Webcam and Mic in a Proxmox LXC</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/webcam_mic_proxmox_lxc.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The goal was simple: point a camera at something and have a model tell me what it is, live, in a notebook. The machine is an unprivileged <strong>LXC container on Proxmox</strong>, and the camera is a USB webcam plugged into the host. Every number here was measured on that box, not guessed.</p>
</blockquote>
<p>Nothing in this chain is hard. There are just five separate places it quietly does the wrong thing instead of failing.</p>
<hr>
<section id="the-camera-does-not-bring-its-microphone" class="level2">
<h2 class="anchored" data-anchor-id="the-camera-does-not-bring-its-microphone">1. The camera does not bring its microphone</h2>
<p>A USB webcam presents as <strong>two unrelated kinds of device node</strong>, and passing one through does not pass the other:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Half</th>
<th>Node</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>Camera</td>
<td><code>/dev/video0</code></td>
<td>UVC capture, MJPEG and YUYV, up to 2592x1520</td>
</tr>
<tr class="even">
<td>Camera metadata</td>
<td><code>/dev/video1</code></td>
<td>Not a capture node. Opening it fails with <code>VIDIOC_G_INPUT</code></td>
</tr>
<tr class="odd">
<td>Microphone</td>
<td><code>/dev/snd/pcmC0D0c</code> + <code>controlC0</code></td>
<td>ALSA card 0</td>
</tr>
</tbody>
</table>
<p>They are separate entries in the Terraform <code>device_passthrough</code> list. Adding the video nodes and forgetting the sound nodes is the single most likely reason a demo that “should work” does not, and the error you get is about the microphone being absent rather than about passthrough.</p>
<p>Two more things worth knowing before you start debugging the wrong layer:</p>
<ul>
<li><strong>Device numbers are not stable across replug.</strong> Re-seat the camera, or attach a second one first, and <code>video0</code> can become <code>video2</code>. Check on the <em>host</em> before applying.</li>
<li><strong><code>/proc/asound/cards</code> lies.</strong> procfs is not namespaced for sound, so inside the container it cheerfully lists the host’s sound cards even when the container has no <code>/dev/snd</code> at all. The only honest test is <code>ls -l /dev/snd/</code>.</li>
</ul>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode bash code-with-copy"><code class="sourceCode bash"><span id="cb1-1"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">ls</span> <span class="at" style="color: #657422;
background-color: null;
font-style: inherit;">-l</span> /dev/video<span class="pp" style="color: #AD0000;
background-color: null;
font-style: inherit;">*</span> /dev/snd/     <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># the actual test</span></span>
<span id="cb1-2"><span class="fu" style="color: #4758AB;
background-color: null;
font-style: inherit;">cat</span> /proc/asound/cards          <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># shows the HOST's cards. Ignore it.</span></span></code></pre></div></div>
<hr>
</section>
<section id="auto-exposure-is-a-frame-rate-control" class="level2">
<h2 class="anchored" data-anchor-id="auto-exposure-is-a-frame-rate-control">2. Auto-exposure is a frame-rate control</h2>
<p>The camera reports 30 FPS. In a dim room it delivers 15, because the sensor lengthens exposure time to get a usable image and the frame rate is what pays for it.</p>
<p>You can pin it, at the cost of doing your own exposure:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">cap.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(cv2.CAP_PROP_AUTO_EXPOSURE, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">1</span>)   <span class="co" style="color: #5E5E5E;
background-color: null;
font-style: inherit;"># 1 = manual, 3 = aperture priority (default)</span></span>
<span id="cb2-2">cap.<span class="bu" style="color: null;
background-color: null;
font-style: inherit;">set</span>(cv2.CAP_PROP_EXPOSURE, <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">150</span>)</span></code></pre></div></div>
<p>The sharp edge: this is a <strong>device-level setting that persists across processes</strong>. It outlives the Python process that set it, so a debugging session that leaves the camera in manual mode will confuse you tomorrow. Set it back to <code>3</code> when you are done.</p>
<hr>
</section>
<section id="cap_prop_buffersize-halves-your-frame-rate-and-buys-nothing" class="level2">
<h2 class="anchored" data-anchor-id="cap_prop_buffersize-halves-your-frame-rate-and-buys-nothing">3. <code>CAP_PROP_BUFFERSIZE</code> halves your frame rate and buys nothing</h2>
<p>This is the one I would not have guessed. The usual advice for “my frames are stale” is to shrink the capture buffer to 1. On the V4L2 backend that <strong>halves the delivered frame rate and does not make frames any fresher</strong>.</p>
<p>Measured at 640x480 MJPG:</p>
<hr>
<div id="2f1887cc" class="cell">
<div class="cell-output cell-output-display">

<script>
    require.config({
        paths: {
            'echarts':'https://cdn.jsdelivr.net/gh/pyecharts/pyecharts-assets@f2328d558550046fc5449672a6850e848e141590/assets/v6/echarts.min'
        }
    });
</script>

        <div id="a4506649a16d4dedb12e149256f1884b" style="width:780px; height:400px;"></div>

<script>
        require(['echarts'], function(echarts) {
                var chart_a4506649a16d4dedb12e149256f1884b = echarts.init(
                    document.getElementById('a4506649a16d4dedb12e149256f1884b'), 'white', {renderer: 'canvas', locale: 'ZH'});
                var option_a4506649a16d4dedb12e149256f1884b = {
    "animation": true,
    "animationThreshold": 2000,
    "animationDuration": 1000,
    "animationEasing": "cubicOut",
    "animationDelay": 0,
    "animationDurationUpdate": 300,
    "animationEasingUpdate": "cubicOut",
    "animationDelayUpdate": 0,
    "aria": {
        "enabled": false
    },
    "series": [
        {
            "type": "bar",
            "name": "FPS",
            "legendHoverLink": true,
            "data": [
                15.0,
                7.5,
                30.0,
                15.0
            ],
            "realtimeSort": false,
            "showBackground": false,
            "stackStrategy": "samesign",
            "cursor": "pointer",
            "barMinHeight": 0,
            "barCategoryGap": "20%",
            "barGap": "30%",
            "large": false,
            "largeThreshold": 400,
            "seriesLayoutBy": "column",
            "datasetIndex": 0,
            "clip": true,
            "zlevel": 0,
            "z": 2,
            "label": {
                "show": true,
                "position": "top",
                "margin": 8,
                "richInheritPlainLabel": true,
                "valueAnimation": false
            },
            "itemStyle": {
                "color": "#5470c6"
            },
            "rippleEffect": {
                "show": true,
                "brushType": "stroke",
                "scale": 2.5,
                "period": 4
            }
        },
        {
            "type": "bar",
            "name": "ms per read",
            "legendHoverLink": true,
            "data": [
                66.8,
                133.5,
                33.3,
                66.7
            ],
            "realtimeSort": false,
            "showBackground": false,
            "stackStrategy": "samesign",
            "cursor": "pointer",
            "barMinHeight": 0,
            "barCategoryGap": "20%",
            "barGap": "30%",
            "large": false,
            "largeThreshold": 400,
            "seriesLayoutBy": "column",
            "datasetIndex": 0,
            "clip": true,
            "zlevel": 0,
            "z": 2,
            "label": {
                "show": true,
                "position": "top",
                "margin": 8,
                "richInheritPlainLabel": true,
                "valueAnimation": false
            },
            "itemStyle": {
                "color": "#91cc75"
            },
            "rippleEffect": {
                "show": true,
                "brushType": "stroke",
                "scale": 2.5,
                "period": 4
            }
        }
    ],
    "legend": [
        {
            "data": [
                "FPS",
                "ms per read"
            ],
            "selected": {},
            "show": true,
            "top": "8%",
            "padding": 5,
            "itemGap": 10,
            "itemWidth": 25,
            "itemHeight": 14,
            "backgroundColor": "transparent",
            "borderColor": "#ccc",
            "borderRadius": 0,
            "pageButtonItemGap": 5,
            "pageButtonPosition": "end",
            "pageFormatter": "{current}/{total}",
            "pageIconColor": "#2f4554",
            "pageIconInactiveColor": "#aaa",
            "pageIconSize": 15,
            "animationDurationUpdate": 800,
            "selector": false,
            "selectorPosition": "auto",
            "selectorItemGap": 7,
            "selectorButtonGap": 10,
            "triggerEvent": false
        }
    ],
    "tooltip": {
        "show": true,
        "trigger": "axis",
        "triggerOn": "mousemove|click",
        "axisPointer": {
            "type": "line"
        },
        "showContent": true,
        "alwaysShowContent": false,
        "showDelay": 0,
        "hideDelay": 100,
        "enterable": false,
        "confine": false,
        "appendToBody": false,
        "transitionDuration": 0.4,
        "displayTransition": true,
        "textStyle": {
            "fontSize": 14,
            "richInheritPlainLabel": true
        },
        "borderWidth": 0,
        "padding": 5,
        "order": "seriesAsc"
    },
    "xAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "nameTruncate": {},
            "nameMoveOverlap": true,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "silent": false,
            "triggerEvent": false,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": false
                }
            },
            "animation": true,
            "animationThreshold": 2000,
            "animationDuration": 1000,
            "animationEasing": "cubicOut",
            "animationDelay": 0,
            "animationDurationUpdate": 300,
            "animationEasingUpdate": "cubicOut",
            "animationDelayUpdate": 0,
            "data": [
                "auto exp\nno BUFFERSIZE",
                "auto exp\nBUFFERSIZE=1",
                "manual exp\nno BUFFERSIZE",
                "manual exp\nBUFFERSIZE=1"
            ]
        }
    ],
    "yAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "nameTruncate": {},
            "nameMoveOverlap": true,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "silent": false,
            "triggerEvent": false,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": false
                }
            },
            "animation": true,
            "animationThreshold": 2000,
            "animationDuration": 1000,
            "animationEasing": "cubicOut",
            "animationDelay": 0,
            "animationDurationUpdate": 300,
            "animationEasingUpdate": "cubicOut",
            "animationDelayUpdate": 0
        }
    ],
    "title": [
        {
            "show": true,
            "text": "Two settings, four frame rates",
            "target": "blank",
            "subtext": "640x480 MJPG, measured on knowledge-lab",
            "subtarget": "blank",
            "padding": 5,
            "itemGap": 10,
            "textAlign": "auto",
            "textVerticalAlign": "auto",
            "triggerEvent": false
        }
    ]
};
                chart_a4506649a16d4dedb12e149256f1884b.setOption(option_a4506649a16d4dedb12e149256f1884b);
        });
    </script>
</div>
</div>
<p>Both settings compose, and between them they span a <strong>4x range in frame rate</strong> on identical hardware and identical code. Manual exposure with no buffer tweak is 30 FPS; auto-exposure with <code>BUFFERSIZE=1</code> is 7.5.</p>
<p>Resolution, meanwhile, barely matters: at 1280x720 the read still costs about 67 ms. JPEG-encoding a 640x480 side-by-side pair for display costs 1.4 ms. <strong>The camera is the bottleneck, not your code</strong>, which is a useful thing to establish early because it stops you optimising the wrong half.</p>
<hr>
</section>
<section id="there-is-no-gui-so-cv2.imshow-is-out" class="level2">
<h2 class="anchored" data-anchor-id="there-is-no-gui-so-cv2.imshow-is-out">4. There is no GUI, so <code>cv2.imshow</code> is out</h2>
<p>The container has no display, and you are looking at JupyterLab over HTTP anyway. Live video goes through <code>IPython.display</code> handles that you update in place:</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb3" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb3-1">view   <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> display(IPyImage(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>_jpeg(blank)), display_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb3-2">status <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> display(Pretty(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"starting..."</span>), display_id<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb3-3"></span>
<span id="cb3-4"><span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">while</span> ...:</span>
<span id="cb3-5">    view.update(IPyImage(data<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>_jpeg(pair_view(raw, annotated))))</span>
<span id="cb3-6">    status.update(Pretty(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"frame </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>n<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">  </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>fps<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:.1f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> FPS  </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>info<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">"</span>))</span></code></pre></div></div>
<p>Measured end to end, camera through annotation through JPEG through display: <strong>30 FPS</strong>. The display path is not what limits a live demo.</p>
<p>Four details that turn a demo into something usable:</p>
<ul>
<li><strong>Raw on the left, model output on the right.</strong> The model’s contribution should be visible rather than asserted.</li>
<li><strong>Use <code>Pretty(...)</code>, not a bare string.</strong> IPython renders a plain string through <code>repr()</code>, so you get your status line wrapped in quotes.</li>
<li><strong>Catch <code>KeyboardInterrupt</code></strong> so the stop button ends the loop cleanly, and release the camera in <code>finally</code>. A demo that raises mid-loop and keeps <code>/dev/video0</code> open means the next run cannot start.</li>
<li><strong>Bound the loop with a time budget.</strong> An unbounded <code>while True</code> in a notebook is a cell nobody can stop safely.</li>
</ul>
<p>And warm up about ten frames before timing or inferring anything. The first frames come back dark while auto-exposure settles, so without a warm-up both your model output and your FPS number are measured on garbage.</p>
<hr>
</section>
<section id="the-audio-side-disagrees-with-itself-about-sample-rates" class="level2">
<h2 class="anchored" data-anchor-id="the-audio-side-disagrees-with-itself-about-sample-rates">5. The audio side disagrees with itself about sample rates</h2>
<p>Two traps here, and the second one is silent.</p>
<p><strong>The PortAudio device name is not the ALSA card id.</strong> Card id <code>U2K</code> shows up to PortAudio as <code>UGREEN camera 2K: USB Audio (hw:0,0)</code>. Match on the card id and you fall through to “first input device”, which may be <code>sysdefault</code>, which may not be the mic you meant.</p>
<p><strong>Record at the device’s native rate and resample yourself.</strong> This mic runs at 44.1 kHz; the speech models want 16 kHz. Asking ALSA for a rate the hardware does not offer is the usual cause of audio that transcribes like speech played too fast or too slow.</p>
<p>Then the part that produces no error at all:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Pipeline</th>
<th>Rate</th>
<th>Accepts a dict?</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>automatic-speech-recognition</code></td>
<td>16 kHz</td>
<td>yes</td>
</tr>
<tr class="even">
<td><code>audio-classification</code> (AST)</td>
<td>16 kHz</td>
<td>yes, and it <strong>resamples for you</strong></td>
</tr>
<tr class="odd">
<td><code>zero-shot-audio-classification</code> (CLAP)</td>
<td>48 kHz</td>
<td><strong>no</strong> - rejects dicts, and assumes a bare array is already at 48 kHz</td>
</tr>
</tbody>
</table>
<p>Hand CLAP 16 kHz audio and it raises nothing. It scores a signal playing at a third of its true speed and returns confident nonsense. If a cell feeds two models, keep a copy at each rate.</p>
<p>The general form of the rule: do not assume, ask the feature extractor.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb4" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb4-1">AutoFeatureExtractor.from_pretrained(model_id).sampling_rate</span></code></pre></div></div>
<hr>
</section>
<section id="fail-loudly-and-never-fake-the-stream" class="level2">
<h2 class="anchored" data-anchor-id="fail-loudly-and-never-fake-the-stream">Fail loudly, and never fake the stream</h2>
<p>Whisper hallucinates fluent sentences out of digital silence, so a muted capture does not fail. It produces a confident transcript of nothing. So every take reports its level, in dBFS, and both ends are checked:</p>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Peak</th>
<th>Meaning</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><code>&lt; 1e-4</code></td>
<td>muted capture</td>
<td>raise</td>
</tr>
<tr class="even">
<td><code>&lt; 0.05</code></td>
<td>quiet, degrades every model</td>
<td>warn and scale up</td>
</tr>
<tr class="odd">
<td><code>&gt; 1.0</code></td>
<td>overloaded, float32 overshoots full scale</td>
<td>warn and normalise</td>
</tr>
</tbody>
</table>
<p>Observed peaks on this mic swing between -36 and +1.5 dBFS between takes, so both ends are real cases rather than theoretical ones.</p>
<p>The broader rule I settled on: <strong>if the device is missing, raise.</strong> Do not fall back to a static image, a dataset sample, or simulated noise. A silent fallback makes a broken capture path render as a successful run, which is strictly worse than an error.</p>
<hr>
</section>
<section id="the-chain-end-to-end" class="level2">
<h2 class="anchored" data-anchor-id="the-chain-end-to-end">The chain, end to end</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/19_camera_mic_chain.svg" class="img-fluid figure-img"></p>
<figcaption>On the Proxmox host /dev/video0 passes through to OpenCV V4L2 and /dev/snd/pcmC0D0c passes through separately to sounddevice and librosa resampling inside the unprivileged LXC, both feeding a transformers pipeline that renders to an IPython display handle.</figcaption>
</figure>
</div>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>Every one of these failed by doing something reasonable instead of raising: passthrough that half worked, a sensor trading frame rate for exposure, a buffer flag that made things worse, a display call with no display, and a model quietly accepting the wrong sample rate.</p>
<p>If you take three things: <strong>video and audio are separate passthroughs</strong>, <strong>do not set <code>CAP_PROP_BUFFERSIZE</code></strong>, and <strong>ask the feature extractor for its sample rate rather than assuming 16 kHz</strong>. The working code lives in the Audio and Computer Vision notebooks of <a href="https://bthek1.github.io/DL_tasks/"><strong>DL_tasks</strong></a>, and the container that hosts it is built by the <a href="../posts/terraform_ansible_home_lab.html">Terraform and Ansible setup</a>.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Small Hardware</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/webcam_mic_proxmox_lxc.html</guid>
  <pubDate>Fri, 24 Jul 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>What Fits on a 12 GB GPU</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/what_fits_12gb_gpu.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>Almost everything written about running models assumes you rented the GPU. This is the other case: one RTX 3060 with <strong>12 GB of VRAM</strong>, in a container with <strong>20 GB of system RAM</strong>, running every task in <a href="https://bthek1.github.io/DL_tasks/"><strong>DL_tasks</strong></a>.</p>
</blockquote>
<p>Working through 53 task notebooks on that box taught me that the question “will this model fit” has three different answers, and the one everybody quotes is the least likely to stop you.</p>
<hr>
<section id="three-budgets-not-one" class="level2">
<h2 class="anchored" data-anchor-id="three-budgets-not-one">Three budgets, not one</h2>
<table class="caption-top table">
<colgroup>
<col style="width: 33%">
<col style="width: 33%">
<col style="width: 33%">
</colgroup>
<thead>
<tr class="header">
<th>Budget</th>
<th>Size here</th>
<th>What blows it</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><strong>VRAM</strong></td>
<td>12 GB</td>
<td>Model weights plus activations</td>
</tr>
<tr class="even">
<td><strong>System RAM</strong></td>
<td>20 GB, minus ~2 GB for OS and JupyterLab</td>
<td>CPU offload, and un-freed intermediates</td>
</tr>
<tr class="odd">
<td><strong>Download / disk</strong></td>
<td>~15-40 GB free</td>
<td>Repo size, which is <em>not</em> param count</td>
</tr>
</tbody>
</table>
<p>The habit is to check the first one and assume the rest follow. They do not. Most of the times I got stuck, VRAM was fine and one of the other two was the problem.</p>
<hr>
</section>
<section id="the-easy-rule-params-times-two-bytes" class="level2">
<h2 class="anchored" data-anchor-id="the-easy-rule-params-times-two-bytes">The easy rule: params times two bytes</h2>
<p>In fp16 every parameter is 2 bytes, so weights alone are <code>params x 2</code> bytes. Activations, KV cache and CUDA context sit on top, so in practice budget the weights at roughly two thirds of VRAM and leave the rest.</p>
<p>On 12 GB that means <strong>anything past about 3B parameters in fp16 does not fit</strong>, and you either pick a smaller checkpoint or quantize.</p>
<hr>
<div id="00ff60e7" class="cell">
<div class="cell-output cell-output-display">

<script>
    require.config({
        paths: {
            'echarts':'https://cdn.jsdelivr.net/gh/pyecharts/pyecharts-assets@f2328d558550046fc5449672a6850e848e141590/assets/v6/echarts.min'
        }
    });
</script>

        <div id="07773204ecf9467d8f0ebea8108c2c7e" style="width:760px; height:380px;"></div>

<script>
        require(['echarts'], function(echarts) {
                var chart_07773204ecf9467d8f0ebea8108c2c7e = echarts.init(
                    document.getElementById('07773204ecf9467d8f0ebea8108c2c7e'), 'white', {renderer: 'canvas', locale: 'ZH'});
                var option_07773204ecf9467d8f0ebea8108c2c7e = {
    "animation": true,
    "animationThreshold": 2000,
    "animationDuration": 1000,
    "animationEasing": "cubicOut",
    "animationDelay": 0,
    "animationDurationUpdate": 300,
    "animationEasingUpdate": "cubicOut",
    "animationDelayUpdate": 0,
    "aria": {
        "enabled": false
    },
    "series": [
        {
            "type": "bar",
            "name": "fp16 weights (GB)",
            "legendHoverLink": true,
            "data": [
                1.0,
                3.0,
                6.0,
                14.0,
                26.0
            ],
            "realtimeSort": false,
            "showBackground": false,
            "stackStrategy": "samesign",
            "cursor": "pointer",
            "barMinHeight": 0,
            "barCategoryGap": "20%",
            "barGap": "30%",
            "large": false,
            "largeThreshold": 400,
            "seriesLayoutBy": "column",
            "datasetIndex": 0,
            "clip": true,
            "zlevel": 0,
            "z": 2,
            "label": {
                "show": true,
                "position": "top",
                "margin": 8,
                "formatter": "{c} GB",
                "richInheritPlainLabel": true,
                "valueAnimation": false
            },
            "markLine": {
                "silent": false,
                "precision": 2,
                "label": {
                    "show": true,
                    "margin": 8,
                    "richInheritPlainLabel": true,
                    "valueAnimation": false
                },
                "data": [
                    {
                        "name": "12 GB VRAM",
                        "yAxis": 12
                    }
                ]
            },
            "itemStyle": {
                "color": "#5470c6"
            },
            "rippleEffect": {
                "show": true,
                "brushType": "stroke",
                "scale": 2.5,
                "period": 4
            }
        }
    ],
    "legend": [
        {
            "data": [
                "fp16 weights (GB)"
            ],
            "selected": {},
            "show": true,
            "padding": 5,
            "itemGap": 10,
            "itemWidth": 25,
            "itemHeight": 14,
            "backgroundColor": "transparent",
            "borderColor": "#ccc",
            "borderRadius": 0,
            "pageButtonItemGap": 5,
            "pageButtonPosition": "end",
            "pageFormatter": "{current}/{total}",
            "pageIconColor": "#2f4554",
            "pageIconInactiveColor": "#aaa",
            "pageIconSize": 15,
            "animationDurationUpdate": 800,
            "selector": false,
            "selectorPosition": "auto",
            "selectorItemGap": 7,
            "selectorButtonGap": 10,
            "triggerEvent": false
        }
    ],
    "tooltip": {
        "show": true,
        "trigger": "axis",
        "triggerOn": "mousemove|click",
        "axisPointer": {
            "type": "line"
        },
        "showContent": true,
        "alwaysShowContent": false,
        "showDelay": 0,
        "hideDelay": 100,
        "enterable": false,
        "confine": false,
        "appendToBody": false,
        "transitionDuration": 0.4,
        "displayTransition": true,
        "textStyle": {
            "fontSize": 14,
            "richInheritPlainLabel": true
        },
        "borderWidth": 0,
        "padding": 5,
        "order": "seriesAsc"
    },
    "xAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "nameTruncate": {},
            "nameMoveOverlap": true,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "silent": false,
            "triggerEvent": false,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": false
                }
            },
            "animation": true,
            "animationThreshold": 2000,
            "animationDuration": 1000,
            "animationEasing": "cubicOut",
            "animationDelay": 0,
            "animationDurationUpdate": 300,
            "animationEasingUpdate": "cubicOut",
            "animationDelayUpdate": 0,
            "data": [
                "0.5B",
                "1.5B",
                "3B",
                "7B",
                "13B"
            ]
        }
    ],
    "yAxis": [
        {
            "name": "GB",
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "nameTruncate": {},
            "nameMoveOverlap": true,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "silent": false,
            "triggerEvent": false,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": false
                }
            },
            "animation": true,
            "animationThreshold": 2000,
            "animationDuration": 1000,
            "animationEasing": "cubicOut",
            "animationDelay": 0,
            "animationDurationUpdate": 300,
            "animationEasingUpdate": "cubicOut",
            "animationDelayUpdate": 0
        }
    ],
    "title": [
        {
            "show": true,
            "text": "fp16 weights vs the 12 GB ceiling",
            "target": "blank",
            "subtext": "params x 2 bytes; activations sit on top",
            "subtarget": "blank",
            "padding": 5,
            "itemGap": 10,
            "textAlign": "auto",
            "textVerticalAlign": "auto",
            "triggerEvent": false
        }
    ]
};
                chart_07773204ecf9467d8f0ebea8108c2c7e.setOption(option_07773204ecf9467d8f0ebea8108c2c7e);
        });
    </script>
</div>
</div>
</section>
<section id="the-rule-that-actually-bites-download-size-is-not-param-count" class="level2">
<h2 class="anchored" data-anchor-id="the-rule-that-actually-bites-download-size-is-not-param-count">The rule that actually bites: download size is not param count</h2>
<p>This is the one that cost me the most time, and it has nothing to do with whether the model runs.</p>
<p>Generative video pipelines ship a <strong>text encoder</strong> alongside the model doing the interesting work, and the encoder is frequently stored in fp32 while everything else is fp16. The encoder then dwarfs the thing it serves.</p>
<p>Wan 2.1 is marketed as a 1.3B video model. Its UMT5-XXL text encoder is 5.6B parameters stored in fp32, which is 22.7 GB, roughly 90% of a 29 GB download. The DiT you actually came for is a rounding error next to it.</p>
<hr>
<div id="c149caa6" class="cell">
<div class="cell-output cell-output-display">

<script>
    require.config({
        paths: {
            'echarts':'https://cdn.jsdelivr.net/gh/pyecharts/pyecharts-assets@f2328d558550046fc5449672a6850e848e141590/assets/v6/echarts.min'
        }
    });
</script>

        <div id="2590ff1a2caf4ec0bf9b0ac328fa0c84" style="width:760px; height:400px;"></div>

<script>
        require(['echarts'], function(echarts) {
                var chart_2590ff1a2caf4ec0bf9b0ac328fa0c84 = echarts.init(
                    document.getElementById('2590ff1a2caf4ec0bf9b0ac328fa0c84'), 'white', {renderer: 'canvas', locale: 'ZH'});
                var option_2590ff1a2caf4ec0bf9b0ac328fa0c84 = {
    "animation": true,
    "animationThreshold": 2000,
    "animationDuration": 1000,
    "animationEasing": "cubicOut",
    "animationDelay": 0,
    "animationDurationUpdate": 300,
    "animationEasingUpdate": "cubicOut",
    "animationDelayUpdate": 0,
    "aria": {
        "enabled": false
    },
    "series": [
        {
            "type": "bar",
            "name": "fp32 text encoder (GB)",
            "legendHoverLink": true,
            "data": [
                22.7,
                19.0,
                9.5
            ],
            "realtimeSort": false,
            "showBackground": false,
            "stackStrategy": "samesign",
            "cursor": "pointer",
            "barMinHeight": 0,
            "barCategoryGap": "20%",
            "barGap": "30%",
            "large": false,
            "largeThreshold": 400,
            "seriesLayoutBy": "column",
            "datasetIndex": 0,
            "clip": true,
            "zlevel": 0,
            "z": 2,
            "label": {
                "show": true,
                "position": "top",
                "margin": 8,
                "formatter": "{c} GB",
                "richInheritPlainLabel": true,
                "valueAnimation": false
            },
            "markLine": {
                "silent": false,
                "precision": 2,
                "label": {
                    "show": true,
                    "margin": 8,
                    "richInheritPlainLabel": true,
                    "valueAnimation": false
                },
                "data": [
                    {
                        "name": "~8 GB self-imposed cap",
                        "yAxis": 8
                    }
                ]
            },
            "itemStyle": {
                "color": "#ee6666"
            },
            "rippleEffect": {
                "show": true,
                "brushType": "stroke",
                "scale": 2.5,
                "period": 4
            }
        }
    ],
    "legend": [
        {
            "data": [
                "fp32 text encoder (GB)"
            ],
            "selected": {},
            "show": true,
            "padding": 5,
            "itemGap": 10,
            "itemWidth": 25,
            "itemHeight": 14,
            "backgroundColor": "transparent",
            "borderColor": "#ccc",
            "borderRadius": 0,
            "pageButtonItemGap": 5,
            "pageButtonPosition": "end",
            "pageFormatter": "{current}/{total}",
            "pageIconColor": "#2f4554",
            "pageIconInactiveColor": "#aaa",
            "pageIconSize": 15,
            "animationDurationUpdate": 800,
            "selector": false,
            "selectorPosition": "auto",
            "selectorItemGap": 7,
            "selectorButtonGap": 10,
            "triggerEvent": false
        }
    ],
    "tooltip": {
        "show": true,
        "trigger": "axis",
        "triggerOn": "mousemove|click",
        "axisPointer": {
            "type": "line"
        },
        "showContent": true,
        "alwaysShowContent": false,
        "showDelay": 0,
        "hideDelay": 100,
        "enterable": false,
        "confine": false,
        "appendToBody": false,
        "transitionDuration": 0.4,
        "displayTransition": true,
        "textStyle": {
            "fontSize": 14,
            "richInheritPlainLabel": true
        },
        "borderWidth": 0,
        "padding": 5,
        "order": "seriesAsc"
    },
    "xAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "nameTruncate": {},
            "nameMoveOverlap": true,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "silent": false,
            "triggerEvent": false,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": false
                }
            },
            "animation": true,
            "animationThreshold": 2000,
            "animationDuration": 1000,
            "animationEasing": "cubicOut",
            "animationDelay": 0,
            "animationDurationUpdate": 300,
            "animationEasingUpdate": "cubicOut",
            "animationDelayUpdate": 0,
            "data": [
                "Wan 2.1\n(UMT5-XXL)",
                "LTX-Video\n(T5-XXL)",
                "CogVideoX\n(T5-XXL)"
            ]
        }
    ],
    "yAxis": [
        {
            "name": "GB",
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "nameTruncate": {},
            "nameMoveOverlap": true,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "silent": false,
            "triggerEvent": false,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": false
                }
            },
            "animation": true,
            "animationThreshold": 2000,
            "animationDuration": 1000,
            "animationEasing": "cubicOut",
            "animationDelay": 0,
            "animationDurationUpdate": 300,
            "animationEasingUpdate": "cubicOut",
            "animationDelayUpdate": 0
        }
    ],
    "title": [
        {
            "show": true,
            "text": "The text encoder is the download",
            "target": "blank",
            "subtext": "fp32 encoders shipped with video pipelines",
            "subtarget": "blank",
            "padding": 5,
            "itemGap": 10,
            "textAlign": "auto",
            "textVerticalAlign": "auto",
            "triggerEvent": false
        }
    ]
};
                chart_2590ff1a2caf4ec0bf9b0ac328fa0c84.setOption(option_2590ff1a2caf4ec0bf9b0ac328fa0c84);
        });
    </script>
</div>
</div>
</section>
<section id="two-things-that-do-not-save-you" class="level2">
<h2 class="anchored" data-anchor-id="two-things-that-do-not-save-you">Two things that do not save you</h2>
<p><strong><code>load_in_4bit</code> does not shrink the download.</strong> bitsandbytes quantizes <em>after</em> the full fp32 weights have been fetched and read. It halves what you need at run time, which is real and useful, but the disk and the wait are unchanged. To download less you need a repo that <em>stores</em> fp16 or bf16.</p>
<p><strong><code>variant="fp16"</code> helps, but only where an fp16 variant exists.</strong> Image pipelines like SD 1.5 and SDXL publish 40-75 GB repos stuffed with format duplicates, and <code>from_pretrained(..., variant="fp16")</code> correctly fetches just the fp16 shards, a few GB. A text encoder that is only published in fp32 has no fp16 variant to select, so it arrives in full regardless.</p>
<p>Put those together and you get the failure mode: you pick a small model, you pass every memory-saving flag you know, and you still pull 29 GB.</p>
<hr>
</section>
<section id="check-before-you-commit-a-runnable-cell" class="level2">
<h2 class="anchored" data-anchor-id="check-before-you-commit-a-runnable-cell">Check before you commit a runnable cell</h2>
<p>Metadata is free. There is no reason to discover a 29 GB download by starting it.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">from</span> huggingface_hub <span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> HfApi</span>
<span id="cb1-2"></span>
<span id="cb1-3">info <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> HfApi().repo_info(repo, files_metadata<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="va" style="color: #111111;
background-color: null;
font-style: inherit;">True</span>)</span>
<span id="cb1-4">gb <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">sum</span>((s.size <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>) <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">for</span> s <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">in</span> info.siblings) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e9</span></span></code></pre></div></div>
<p>Then look at <em>where</em> the bytes are. A <code>text_encoder/</code> folder of 20 GB is the tell, and it tells you whether the size is avoidable (fp16 variant available) or not (fp32 only).</p>
<p>The rule I settled on: <strong>a runnable cell downloads at most about 8 GB.</strong> Anything bigger goes in a comparison table with prose, or behind a <code>RUN_HEAVY = False</code> flag that prints what it would cost. Nobody opening a notebook should trigger a 29 GB pull by pressing shift-enter.</p>
<hr>
</section>
<section id="datasets-have-the-same-trap-worse" class="level2">
<h2 class="anchored" data-anchor-id="datasets-have-the-same-trap-worse">Datasets have the same trap, worse</h2>
<p><code>load_dataset("repo", split="val")</code> downloads <strong>every data file in the repo</strong>, then slices. Asking for a 0.9 GB validation split can pull 24 GB of training shards and fill the disk before it gives you anything.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1">val <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> load_dataset(</span>
<span id="cb2-2">    <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"parquet"</span>,</span>
<span id="cb2-3">    data_files<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>{<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"val"</span>: <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"hf://datasets/&lt;repo&gt;/data/val-*.parquet"</span>},</span>
<span id="cb2-4">    split<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span><span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"val"</span>, cache_dir<span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span>HF_CACHE,</span>
<span id="cb2-5">)</span></code></pre></div></div>
<p>Also worth knowing: raw Hub blobs land in <code>~/.cache/huggingface/hub</code> regardless of <code>cache_dir</code>, which only controls the built Arrow cache. So a runaway download escapes whatever directory you thought you had confined it to.</p>
<hr>
</section>
<section id="the-working-checklist" class="level2">
<h2 class="anchored" data-anchor-id="the-working-checklist">The working checklist</h2>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/18_gpu_fit_checklist.svg" class="img-fluid figure-img"></p>
<figcaption>A candidate model is quantized or swapped if params times 2 bytes exceeds about 8 GB, becomes a runnable cell if its repo size is under about 8 GB, and otherwise uses the fp16 variant to become runnable or, if the big files are fp32 only, becomes a table and prose instead.</figcaption>
</figure>
</div>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>The parameter count tells you whether a model will <strong>run</strong>. It tells you almost nothing about whether you can <strong>get</strong> it. On a small box those are separate questions and the second one is the one that ruins an afternoon.</p>
<p>Three habits fixed it for me: size the weights before writing the cell, call <code>repo_info</code> before writing a download, and treat anything over ~8 GB as documentation rather than something a reader can execute. The full task-by-task working is in <a href="https://bthek1.github.io/DL_tasks/"><strong>DL_tasks</strong></a>, and the memory side of the same problem is in <a href="../posts/malloc_trim_rss.html">the post on <code>malloc_trim</code></a>.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Small Hardware</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/what_fits_12gb_gpu.html</guid>
  <pubDate>Sun, 12 Jul 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>The Memory Leak That Isn’t a Leak</title>
  <dc:creator>Benedict Thekkel</dc:creator>
  <link>https://bthek1.github.io/bthek1_blog/posts/malloc_trim_rss.html</link>
  <description><![CDATA[ 





<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
<blockquote class="blockquote">
<p>The setup: a container with <strong>20 GB of system RAM</strong> and an RTX 3060 with <strong>12 GB of VRAM</strong>. A notebook that loads several diffusion pipelines in sequence, frees each one before loading the next, and still dies around the third or fourth.</p>
</blockquote>
<p>Every <code>del</code> was correct. <code>gc.collect()</code> ran. <code>torch.cuda.empty_cache()</code> ran. VRAM was flat. System RAM went up anyway, section after section, until the OOM killer took the container rather than the kernel.</p>
<p>It looks exactly like a Python leak. It is not one.</p>
<hr>
<section id="two-things-combine" class="level2">
<h2 class="anchored" data-anchor-id="two-things-combine">Two things combine</h2>
<p><strong>1. <code>enable_model_cpu_offload()</code> parks weights in system RAM, not VRAM.</strong></p>
<p>It is the right call for keeping VRAM flat: only the executing submodule sits on the GPU, everything else waits in host memory. But that means every pipeline you load this way holds its full weight set in the 20 GB of system RAM until it is released. A diffusers pipeline is 2-7 GB there.</p>
<p>So the memory you carefully kept off the GPU is now competing for the budget you did not think you were spending.</p>
<p><strong>2. glibc does not return freed memory to the operating system.</strong></p>
<p>After <code>del pipe; gc.collect()</code> the Python objects genuinely are gone. But glibc keeps the freed blocks in its own arenas so it can reuse them, and <strong>RSS stays high</strong>. Because successive models are different sizes, the reuse is imperfect, so RSS does not plateau. It ratchets.</p>
<p>The container’s memory limit is enforced against RSS. So does the OOM killer. Python’s opinion that the objects are gone is not relevant to either of them.</p>
<hr>
</section>
<section id="the-fix-is-one-line" class="level2">
<h2 class="anchored" data-anchor-id="the-fix-is-one-line">The fix is one line</h2>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb1" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb1-1"><span class="im" style="color: #00769E;
background-color: null;
font-style: inherit;">import</span> ctypes, ctypes.util</span>
<span id="cb1-2"></span>
<span id="cb1-3">ctypes.CDLL(ctypes.util.find_library(<span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"c"</span>) <span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">or</span> <span class="st" style="color: #20794D;
background-color: null;
font-style: inherit;">"libc.so.6"</span>).malloc_trim(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)</span></code></pre></div></div>
<p><code>malloc_trim(0)</code> hands the arenas back to the OS. Measured on this box, loading Stable Diffusion 1.5 in fp16 with CPU offload three times, and reading RSS after each free:</p>
<hr>
<div id="a0cf0c18" class="cell">
<div class="cell-output cell-output-display">

<script>
    require.config({
        paths: {
            'echarts':'https://cdn.jsdelivr.net/gh/pyecharts/pyecharts-assets@f2328d558550046fc5449672a6850e848e141590/assets/v6/echarts.min'
        }
    });
</script>

        <div id="694259899ef644ee8140a3bdcd8516c5" style="width:760px; height:400px;"></div>

<script>
        require(['echarts'], function(echarts) {
                var chart_694259899ef644ee8140a3bdcd8516c5 = echarts.init(
                    document.getElementById('694259899ef644ee8140a3bdcd8516c5'), 'white', {renderer: 'canvas', locale: 'ZH'});
                var option_694259899ef644ee8140a3bdcd8516c5 = {
    "animation": true,
    "animationThreshold": 2000,
    "animationDuration": 1000,
    "animationEasing": "cubicOut",
    "animationDelay": 0,
    "animationDurationUpdate": 300,
    "animationEasingUpdate": "cubicOut",
    "animationDelayUpdate": 0,
    "aria": {
        "enabled": false
    },
    "series": [
        {
            "type": "bar",
            "name": "del + gc + empty_cache (GB)",
            "legendHoverLink": true,
            "data": [
                2.0,
                2.48,
                null
            ],
            "realtimeSort": false,
            "showBackground": false,
            "stackStrategy": "samesign",
            "cursor": "pointer",
            "barMinHeight": 0,
            "barCategoryGap": "20%",
            "barGap": "30%",
            "large": false,
            "largeThreshold": 400,
            "seriesLayoutBy": "column",
            "datasetIndex": 0,
            "clip": true,
            "zlevel": 0,
            "z": 2,
            "label": {
                "show": true,
                "position": "top",
                "margin": 8,
                "formatter": "{c}",
                "richInheritPlainLabel": true,
                "valueAnimation": false
            },
            "itemStyle": {
                "color": "#ee6666"
            },
            "rippleEffect": {
                "show": true,
                "brushType": "stroke",
                "scale": 2.5,
                "period": 4
            }
        },
        {
            "type": "bar",
            "name": "+ malloc_trim(0) (GB)",
            "legendHoverLink": true,
            "data": [
                1.11,
                1.23,
                1.25
            ],
            "realtimeSort": false,
            "showBackground": false,
            "stackStrategy": "samesign",
            "cursor": "pointer",
            "barMinHeight": 0,
            "barCategoryGap": "20%",
            "barGap": "30%",
            "large": false,
            "largeThreshold": 400,
            "seriesLayoutBy": "column",
            "datasetIndex": 0,
            "clip": true,
            "zlevel": 0,
            "z": 2,
            "label": {
                "show": true,
                "position": "top",
                "margin": 8,
                "formatter": "{c}",
                "richInheritPlainLabel": true,
                "valueAnimation": false
            },
            "itemStyle": {
                "color": "#91cc75"
            },
            "rippleEffect": {
                "show": true,
                "brushType": "stroke",
                "scale": 2.5,
                "period": 4
            }
        }
    ],
    "legend": [
        {
            "data": [
                "del + gc + empty_cache (GB)",
                "+ malloc_trim(0) (GB)"
            ],
            "selected": {},
            "show": true,
            "top": "12%",
            "padding": 5,
            "itemGap": 10,
            "itemWidth": 25,
            "itemHeight": 14,
            "backgroundColor": "transparent",
            "borderColor": "#ccc",
            "borderRadius": 0,
            "pageButtonItemGap": 5,
            "pageButtonPosition": "end",
            "pageFormatter": "{current}/{total}",
            "pageIconColor": "#2f4554",
            "pageIconInactiveColor": "#aaa",
            "pageIconSize": 15,
            "animationDurationUpdate": 800,
            "selector": false,
            "selectorPosition": "auto",
            "selectorItemGap": 7,
            "selectorButtonGap": 10,
            "triggerEvent": false
        }
    ],
    "tooltip": {
        "show": true,
        "trigger": "axis",
        "triggerOn": "mousemove|click",
        "axisPointer": {
            "type": "line"
        },
        "showContent": true,
        "alwaysShowContent": false,
        "showDelay": 0,
        "hideDelay": 100,
        "enterable": false,
        "confine": false,
        "appendToBody": false,
        "transitionDuration": 0.4,
        "displayTransition": true,
        "textStyle": {
            "fontSize": 14,
            "richInheritPlainLabel": true
        },
        "borderWidth": 0,
        "padding": 5,
        "order": "seriesAsc"
    },
    "xAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "nameTruncate": {},
            "nameMoveOverlap": true,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "silent": false,
            "triggerEvent": false,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": false
                }
            },
            "animation": true,
            "animationThreshold": 2000,
            "animationDuration": 1000,
            "animationEasing": "cubicOut",
            "animationDelay": 0,
            "animationDurationUpdate": 300,
            "animationEasingUpdate": "cubicOut",
            "animationDelayUpdate": 0,
            "data": [
                "after free #1",
                "after free #2",
                "after free #3"
            ]
        }
    ],
    "yAxis": [
        {
            "name": "RSS (GB)",
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "nameTruncate": {},
            "nameMoveOverlap": true,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "silent": false,
            "triggerEvent": false,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": false
                }
            },
            "animation": true,
            "animationThreshold": 2000,
            "animationDuration": 1000,
            "animationEasing": "cubicOut",
            "animationDelay": 0,
            "animationDurationUpdate": 300,
            "animationEasingUpdate": "cubicOut",
            "animationDelayUpdate": 0
        }
    ],
    "title": [
        {
            "show": true,
            "text": "RSS after each free, SD 1.5 loaded three times",
            "target": "blank",
            "subtext": "third red bar is missing because the run did not survive to report it",
            "subtarget": "blank",
            "padding": 5,
            "itemGap": 10,
            "textAlign": "auto",
            "textVerticalAlign": "auto",
            "triggerEvent": false
        }
    ]
};
                chart_694259899ef644ee8140a3bdcd8516c5.setOption(option_694259899ef644ee8140a3bdcd8516c5);
        });
    </script>
</div>
</div>
<p>Without the trim, RSS climbs: 2.00 GB, then 2.48 GB, then still climbing. With it, RSS returns to roughly the same place every time: 1.11, 1.23, 1.25 GB. Flat.</p>
<p>The one-liner belongs inside whatever <code>free_memory()</code> helper you already have, next to <code>gc.collect()</code> and <code>empty_cache()</code>. Wrap it in a <code>try</code> so non-glibc platforms (musl, macOS) skip it quietly rather than crashing.</p>
<hr>
</section>
<section id="the-framing-that-makes-it-stick" class="level2">
<h2 class="anchored" data-anchor-id="the-framing-that-makes-it-stick">The framing that makes it stick</h2>
<blockquote class="blockquote">
<p><code>torch.cuda.empty_cache()</code> is to VRAM what <code>malloc_trim(0)</code> is to system RAM. On a small box you need both, and almost everyone only knows about the first.</p>
</blockquote>
<p>The asymmetry is purely cultural. Everyone doing GPU work learns <code>empty_cache()</code> early, because VRAM is the budget people talk about. System RAM feels like something the OS handles for you, right up until you are in a container with a hard limit and a process whose RSS only goes one direction.</p>
<div class="quarto-figure quarto-figure-center">
<figure class="figure">
<p><img src="https://bthek1.github.io/bthek1_blog/posts/17_ram_release_paths.svg" class="img-fluid figure-img"></p>
<figcaption>After del pipe and gc.collect the Python objects are gone, but while empty_cache returns VRAM, freed system RAM stays in the glibc arena and counts as RSS until malloc_trim(0) returns it.</figcaption>
</figure>
</div>
<hr>
</section>
<section id="a-note-on-measuring-it-honestly" class="level2">
<h2 class="anchored" data-anchor-id="a-note-on-measuring-it-honestly">A note on measuring it honestly</h2>
<p><code>psutil</code> reads RSS, which means it only shows the RAM as reclaimed <em>after</em> the <code>malloc_trim</code>. That is sometimes read as the tool lying before the trim.</p>
<p>It is the opposite. RSS is what the kernel and the OOM killer see. If a monitoring helper reported the memory as free before the arenas were returned, it would be telling you a comfortable number while the thing that actually kills your container disagreed.</p>
<div class="code-copy-outer-scaffold"><div class="sourceCode" id="cb2" style="background: #f1f3f5;"><pre class="sourceCode python code-with-copy"><code class="sourceCode python"><span id="cb2-1"><span class="kw" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">def</span> memory_report():</span>
<span id="cb2-2">    vm <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">=</span> psutil.virtual_memory()</span>
<span id="cb2-3">    <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"RAM  </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>(vm.total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">-</span> vm.available) <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e9</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:5.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> / </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>vm<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>total <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e9</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:5.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> GB"</span>)</span>
<span id="cb2-4">    <span class="cf" style="color: #003B4F;
background-color: null;
font-weight: bold;
font-style: inherit;">if</span> torch.cuda.is_available():</span>
<span id="cb2-5">        <span class="bu" style="color: null;
background-color: null;
font-style: inherit;">print</span>(<span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"VRAM </span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>torch<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>cuda<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>memory_allocated() <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e9</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:5.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> / "</span></span>
<span id="cb2-6">              <span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;">f"</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">{</span>torch<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>cuda<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>get_device_properties(<span class="dv" style="color: #AD0000;
background-color: null;
font-style: inherit;">0</span>)<span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">.</span>total_memory <span class="op" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">/</span> <span class="fl" style="color: #AD0000;
background-color: null;
font-style: inherit;">1e9</span><span class="sc" style="color: #5E5E5E;
background-color: null;
font-style: inherit;">:5.2f}</span><span class="ss" style="color: #20794D;
background-color: null;
font-style: inherit;"> GB"</span>)</span></code></pre></div></div>
<p>Call it after each heavy stage. A well-behaved notebook returns close to baseline. If it does not, something is still referenced, and it is worth finding rather than leaving the notebook to die on the next run. Jupyter’s own <code>_</code>, <code>__</code> and <code>Out[...]</code> are a common culprit: a cell whose last expression is a big tensor pins it in RAM for the life of the kernel.</p>
<hr>
</section>
<section id="takeaway" class="level2">
<h2 class="anchored" data-anchor-id="takeaway">Takeaway</h2>
<p>If a long notebook OOMs the <em>container</em> rather than the kernel, and every <code>del</code> looks right, stop hunting for the Python reference. Check whether the RAM was ever handed back to the OS at all.</p>
<p>One line, inside <code>free_memory()</code>, next to the two calls you already make. The rest of the memory rules for this box, along with the download-size trap that catches you before you even get to RAM, are in <a href="../posts/what_fits_12gb_gpu.html">what actually fits on a 12 GB GPU</a>.</p>
<hr>


</section>

<a onclick="window.scrollTo(0, 0); return false;" id="quarto-back-to-top"><i class="bi bi-arrow-up"></i> Back to top</a> ]]></description>
  <category>Small Hardware</category>
  <guid>https://bthek1.github.io/bthek1_blog/posts/malloc_trim_rss.html</guid>
  <pubDate>Thu, 09 Jul 2026 00:00:00 GMT</pubDate>
</item>
</channel>
</rss>
