<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Francesco Oliva - Notes on ML &amp; CV</title>
    <link>https://olibartfast.ninja/blog/index.html</link>
    <description>Thoughts and explorations in Computer Vision, Machine Learning, C++, and more.</description>
    <language>en-us</language>
    <lastBuildDate>Tue, 17 Nov 2026 12:00:00 +0000</lastBuildDate>
    <item>
      <title>Free Models in OpenCode: Free Does Not Mean Risk-Free</title>
      <link>https://olibartfast.ninja/blog/select-opencode-free-models.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/select-opencode-free-models.html</guid>
      <pubDate>Tue, 17 Nov 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>Free removes cost, not risk: Console, OpenRouter and NVIDIA free models compared on privacy, geoblocking, rate limits, and safe fallbacks.</description>
      <content:encoded><![CDATA[<p>Free models accessible through OpenCode — Console, OpenRouter, NVIDIA, and other configured providers — are convenient: you experiment without a credit card, parallelize without watching the meter, and switch model families with one line of configuration. The problem is that "free" is a temporary entitlement, not a property of the model.</p>

                <p>Two free models with similar names can differ in <strong>privacy, regional availability, request limits, quality, and how long they will exist</strong>. One declares zero retention, another retains prompts for safety, a third uses them for model improvement. One is reachable from your account, another answers <code>not available in your country</code>. One disappears next month.</p>

                <p>This post walks through a practical workflow: classify the work, read the catalog, probe reachability, classify privacy, assign roles with fallbacks, and record the choice so it can be re-verified.</p>

                <div class="note-box">
                    <h3>The starting rule</h3>
                    <p>Treat "free" as a temporary entitlement to verify per role and re-verify before every long or sensitive run. The catalog is a dated snapshot, not a contract.</p>
                </div>

                <nav class="table-of-contents" aria-label="Table of contents">
                    <h3>Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#boundary">Scope: what this workflow covers</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#classify">1. Classify the work before the model</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#catalog">2. Read the current catalog</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#probe">3. Probe reachability</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#privacy">4. Classify privacy and retention</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#roles">5. Assign roles and fallbacks</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#record">6. Record and re-verify</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#rate-limits">Rate limits by provider</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#failures">Failure handling</a></li>
                        <li><a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#antipatterns">Anti-patterns to avoid</a></li>
                    </ul>
                </nav>

                <section id="boundary" class="blog-section">
                    <h2>Scope: what this workflow covers</h2>
                    <p>We are talking about free models accessible through OpenCode, referenced as <code>&lt;provider&gt;/&lt;model-id&gt;</code>:</p>
                    <ul>
                        <li><strong>OpenCode Console:</strong> <code>opencode/&lt;model-id&gt;</code>, with an optional variant (e.g. <code>opencode/deepseek-v4.1-flash-free#max</code>).</li>
                        <li><strong>OpenRouter:</strong> <code>openrouter/&lt;model-id&gt;</code> (e.g. <code>openrouter/qwen/qwen-2.5-coder-32b-instruct:free</code> — prefer current coding-capable <code>:free</code> endpoints with tool support; old 7B/8B instruct models often fail multi-step tool schemas).</li>
                        <li><strong>NVIDIA:</strong> <code>nvidia/&lt;model-id&gt;</code> (e.g. <code>nvidia/nemotron-3-ultra</code>).</li>
                        <li><strong>Other providers:</strong> any provider configured in OpenCode that offers free models.</li>
                    </ul>
                    <p>Paid Console models are out of scope. The catalog changes without notice. Documentation and runtime can both be stale. That is why every choice must be probed, not just read.</p>
                </section>

                <section id="classify" class="blog-section">
                    <h2>1. Classify the work before the model</h2>
                    <p>Before opening the model picker, capture six facts. They narrow down the candidates, not the other way around.</p>
                    <ul>
                        <li><strong>Confidentiality:</strong> can sources, prompts, or outputs leave the trust boundary? This decides whether logged or training models are allowed.</li>
                        <li><strong>Region:</strong> some models are geo-blocked. A catalog row does not prove your account can reach them.</li>
                        <li><strong>Volume:</strong> free tiers cap aggressively — often 20–40 RPM or tens of requests per day. See <a href="https://olibartfast.ninja/blog/select-opencode-free-models.html#rate-limits">Rate limits by provider</a> before planning fan-out.</li>
                        <li><strong>Role:</strong> architecture and review need reasoning; implementation needs code quality and throughput; exploration needs latency.</li>
                        <li><strong>Independence:</strong> when a genuine second opinion matters, the reviewer should not share the implementer's model family.</li>
                        <li><strong>Lifetime:</strong> free models are time-limited. Plan a fallback in the same privacy class.</li>
                    </ul>
                    <p>Example: reviewing a concurrent interface on proprietary code calls for zero retention + strong reasoning + an independent reviewer. High-volume exploration over synthetic code can settle for a fast model in the trial class.</p>
                </section>

                <section id="catalog" class="blog-section">
                    <h2>2. Read the current catalog</h2>
                    <p>One runtime, several documentations — each with a different job:</p>
                    <ul>
                        <li><strong>OpenCode Console:</strong> <a href="https://opencode.ai/docs/console/models/">opencode.ai/docs/console/models/</a> lists the free set, variants, pricing, privacy notes, and deprecations. Use it for contractual terms.</li>
                        <li><strong>OpenRouter:</strong> <a href="https://openrouter.ai/models?max_price=0">openrouter.ai/models?max_price=0</a> filters free models. Check each model's Context and Architecture tabs plus the upstream provider's policy for privacy and retention.</li>
                        <li><strong>NVIDIA:</strong> <a href="https://build.nvidia.com/explore/discover">build.nvidia.com/explore/discover</a> lists Nemotron and other models; free tiers are marked. Review NVIDIA's data usage policy per model.</li>
                        <li><strong>Runtime:</strong> <code>opencode models</code>, or <code>/models</code> in the TUI, lists what this account can actually select across all configured providers. Use it for entitlement.</li>
                    </ul>
                    <p>Reference a model as <code>&lt;provider&gt;/&lt;model-id&gt;</code>, such as <code>opencode/deepseek-v4.1-flash-free#max</code> or <code>openrouter/qwen/qwen-2.5-coder-32b-instruct:free</code>. The <code>#variant</code> suffix is OpenCode 2 syntax — on 1.x use <code>--variant</code> instead.</p>
                    <p>When docs and runtime disagree, trust the docs for terms and the runtime for entitlement. In both cases, probe before trusting either.</p>
                    <p>For quality, use an independent tie-breaker: <a href="https://lmarena.ai/">LMArena</a> (formerly LMSYS Chatbot Arena) provides Elo ratings — prefer the Coding leaderboard for agentic work, and complement it with tool-assisted benchmarks like SWE-bench or LiveCodeBench where available. It only makes sense at equal privacy class and reachability — a higher Elo never compensates for unacceptable retention.</p>
                </section>

                <section id="probe" class="blog-section">
                    <h2>3. Probe reachability</h2>
                    <p>Catalog status is not reachability. Probe the exact provider, model, and variant. Examples target <strong>OpenCode 2</strong> — on 1.x replace <code>#max</code> with <code>--variant max</code>. <code>--archived</code> is recent; upgrade if your CLI reports an unknown-flag error.</p>
                    <pre class="code-snippet"><code># OpenCode Console, with variant
opencode run --archived --model opencode/deepseek-v4.1-flash-free#max "Reply with exactly: OK"

# OpenRouter (:free has no variant — tool support varies by upstream model)
opencode run --archived --model openrouter/qwen/qwen-2.5-coder-32b-instruct:free "Reply with exactly: OK"

# NVIDIA
opencode run --archived --model nvidia/nemotron-3-ultra "Reply with exactly: OK"

# Tool-use probe for Implementer/Explorer candidates (chat OK ≠ agent OK)
opencode run --archived --model opencode/glm-5.3-flash-free#max "Read package.json and list its dependencies without editing anything"</code></pre>
                    <p>A plain <code>OK</code> ping only proves chat completion. Free endpoints — especially via OpenRouter — can pass it and still fail the first real agent turn with a 400 or malformed output when the upstream model lacks tool/function-calling support. Probe at least one read-only tool call for any role that will use tools.</p>
                    <p><code>--archived</code> keeps probes out of normal history. To probe a set of models, automate the same command in a script that iterates over the candidates for your provider list.</p>

                    <div class="table-scroll" role="region" aria-label="Probe results" tabindex="0">
                        <table class="workflow-table">
                            <thead>
                                <tr>
                                    <th scope="col">Result</th>
                                    <th scope="col">Meaning</th>
                                    <th scope="col">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>prints <code>OK</code></td>
                                    <td>reachable</td>
                                    <td>keep it</td>
                                </tr>
                                <tr>
                                    <td><code>Model unavailable</code></td>
                                    <td>not in the runtime catalog or not entitled</td>
                                    <td>replace it</td>
                                </tr>
                                <tr>
                                    <td><code>not available in your country</code></td>
                                    <td>geo-block</td>
                                    <td>replace it; do not retry</td>
                                </tr>
                                <tr>
                                    <td>timeout</td>
                                    <td>endpoint or network stall</td>
                                    <td>retry once, then replace</td>
                                </tr>
                                <tr>
                                    <td>429 or quota text</td>
                                    <td>rate or daily cap</td>
                                    <td>move the role or reduce fan-out; do not retry in burst — honor reset / Retry-After</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <p>A model can show as <code>active</code> in the catalog and still fail. Always record the probe date.</p>
                </section>

                <section id="privacy" class="blog-section">
                    <h2>4. Classify privacy and retention</h2>
                    <p>Before using a free model on non-public code, read the current privacy and retention policy for <strong>each provider and model</strong>. Sort candidates into four classes:</p>

                    <div class="table-scroll" role="region" aria-label="Privacy classes" tabindex="0">
                        <table class="workflow-table">
                            <thead>
                                <tr>
                                    <th scope="col">Class</th>
                                    <th scope="col">Meaning</th>
                                    <th scope="col">Typical use</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Zero-retention, no training</td>
                                    <td>provider states no retention and no training</td>
                                    <td>confidential code, subject to policy</td>
                                </tr>
                                <tr>
                                    <td>Retained, no training</td>
                                    <td>short safety retention only</td>
                                    <td>internal but not secret</td>
                                </tr>
                                <tr>
                                    <td>May improve the model</td>
                                    <td>inputs may be used for improvement</td>
                                    <td>public or disposable code</td>
                                </tr>
                                <tr>
                                    <td>Trial or training</td>
                                    <td>logged trial data or training use</td>
                                    <td>public or synthetic code only</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <div class="note-box">
                        <h3>Never infer privacy from the name</h3>
                        <p>Providers change terms, and free endpoints often differ from the paid model of the same family. Read the class from the current terms, not the name. "Zero retention" on a free promotional endpoint is a contractual promise, not an enterprise BAA/DPA — regulated teams often treat any non-contracted free tier as off-limits for crown-jewel IP regardless of retention claims.</p>
                    </div>

                    <p>Provider-specific notes:</p>
                    <ul>
                        <li><strong>OpenCode Console:</strong> privacy class documented per model in the Console docs.</li>
                        <li><strong>OpenRouter:</strong> varies by upstream provider. Check the OpenRouter model card and the original provider's policy. Many free models log prompts for moderation.</li>
                        <li><strong>NVIDIA:</strong> Nemotron free endpoints are trials; data may be logged. Do not submit confidential code.</li>
                        <li><strong>Other providers:</strong> check each provider's terms; free tiers often have weaker privacy than paid tiers.</li>
                    </ul>
                </section>

                <section id="roles" class="blog-section">
                    <h2>5. Assign roles and fallbacks</h2>
                    <p>Think of the team as a pyramid: one architect at the apex making few high-reasoning calls, implementer and reviewer in the middle, and high-fan-out explorers at the base. "Pyramid suitability" in the next sections means which level — and which request volume — a provider can sustain without hitting its cap.</p>
                    <p>Different roles ask for different capabilities. A reasonable starting split:</p>

                    <div class="table-scroll" role="region" aria-label="Role assignment" tabindex="0">
                        <table class="workflow-table">
                            <thead>
                                <tr>
                                    <th scope="col">Role</th>
                                    <th scope="col">Prefer</th>
                                    <th scope="col">Why</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Architect, planner</td>
                                    <td>strongest reasoning, high variant</td>
                                    <td>design quality drives everything downstream</td>
                                </tr>
                                <tr>
                                    <td>Orchestrator</td>
                                    <td>reliable instruction-follower, mid or high variant</td>
                                    <td>coordinates, does not edit</td>
                                </tr>
                                <tr>
                                    <td>Implementer</td>
                                    <td>strong coding model, high variant</td>
                                    <td>correctness and iteration speed</td>
                                </tr>
                                <tr>
                                    <td>Reviewer</td>
                                    <td>different family from the implementer, high variant</td>
                                    <td>independent failure modes</td>
                                </tr>
                                <tr>
                                    <td>Explorer</td>
                                    <td>fast, low variant</td>
                                    <td>high volume, low stakes</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <p>At equal privacy class and reachability, use LMArena Elo for the role's primary capability: reasoning and instruction-following for architect/planner, coding Elo for the implementer (Coding leaderboard, plus SWE-bench / LiveCodeBench where available), a different family with the highest Elo for the reviewer, throughput for orchestrator/explorer.</p>
                    <p>Build a <strong>fallback chain inside the same privacy class</strong>. Prefer same-provider fallbacks for simpler config, cross-provider for independence. Never downgrade from a zero-retention model to a trial-logged one just to keep working.</p>

                    <div class="table-scroll" role="region" aria-label="Cross-provider fallback chains" tabindex="0">
                        <table class="workflow-table">
                            <thead>
                                <tr>
                                    <th scope="col">Privacy class</th>
                                    <th scope="col">Example chain</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>Zero-retention</td>
                                    <td><code>opencode/deepseek-v4.1-flash-free</code> → <code>opencode/glm-5.3-flash-free</code> → <code>opencode/minimax-m3.1-flash-free</code></td>
                                </tr>
                                <tr>
                                    <td>May improve</td>
                                    <td><code>openrouter/qwen/qwen-2.5-coder-32b-instruct:free</code> → <code>openrouter/meta-llama/llama-3.3-70b-instruct:free</code> (filter for current coding-capable <code>:free</code> endpoints with tool support)</td>
                                </tr>
                                <tr>
                                    <td>Trial / logged</td>
                                    <td><code>nvidia/nemotron-3-ultra</code> → <code>opencode/nemotron-3.5-super-vl-free</code></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <p>Watch out for variants: support differs per model. Use only variants advertised in the picker or provider metadata. A wrong variant fails at request time, not at config load. When a subagent pins <code>model:</code>, it overrides parent variant inheritance and silently falls back to the provider default — always pin the variant alongside the model.</p>
                </section>

                <section id="record" class="blog-section">
                    <h2>6. Record and re-verify</h2>
                    <p>Record provider, model ID, variant, role, privacy class, region result, probe date, rate-limit snapshot, and fallback in the project or agent config. <code>opencode.json/jsonc</code> and agent frontmatter do not validate custom fields — store probe metadata as comments or in a companion manifest next to the config.</p>
                    <ul>
                        <li>before a long or expensive run;</li>
                        <li>after any <code>Model unavailable</code>, geo-block, or quota error;</li>
                        <li>when provider documentation changes;</li>
                        <li>when a free model is withdrawn or deprecated.</li>
                    </ul>
                    <p>Minimal record per role: provider + model + variant, privacy class, reachability + date, RPM/RPD snapshot + quota check method, 429 strategy, pyramid suitability (e.g. OpenRouter <code>:free</code> for explorer only, NVIDIA for fallback/reviewer, Console zero-retention for architect/implementer), and the same-class fallback.</p>
                    <pre class="code-snippet"><code>// opencode.jsonc — roles with probe/privacy recorded in comments
{
  // architect: opencode/deepseek-v4.1-flash-free#max
  //   privacy: zero-retention | probe: 2026-11-17 OK + tool-read OK
  //   fallback (manual): opencode/glm-5.3-flash-free#max
  "architect": "opencode/deepseek-v4.1-flash-free#max",
  // reviewer: different family from implementer
  //   privacy: zero-retention | probe: 2026-11-17 OK
  //   fallback (manual): opencode/minimax-m3.1-flash-free
  "reviewer": "opencode/glm-5.3-flash-free#max",
  // explorer: low-volume only — OpenRouter :free, 20 RPM / small daily bucket
  //   privacy: may-improve (logged for moderation) | probe: 2026-11-17 OK
  "explorer": "openrouter/qwen/qwen-2.5-coder-32b-instruct:free"
}
// Fallback is manual (or wrapper-scripted), not automatic:
// on 429/unavailable, switch the role string above to its
// same-privacy-class fallback. Exception: OpenRouter's own
// models array can route within OpenRouter.</code></pre>
                </section>

                <section id="rate-limits" class="blog-section">
                    <h2>Rate limits by provider</h2>
                    <p>Free tiers fail on throughput before they fail on quality. The three providers cap differently, and the cap decides which roles each provider can hold.</p>

                    <div class="table-scroll" role="region" aria-label="Rate limits by provider" tabindex="0">
                        <table class="workflow-table">
                            <thead>
                                <tr>
                                    <th scope="col">Provider</th>
                                    <th scope="col">Free tier limits</th>
                                    <th scope="col">Pyramid guidance</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><strong>OpenCode Console</strong></td>
                                    <td>No published general RPM/RPD; only explicit cap is <code>LongCat 2.5 Free: 100 req/day</code>. Others are "free for a limited time" without declared caps. Shared per account/network/IP bucket, reset 00:00 UTC, dynamic with capacity vs demand.</td>
                                    <td>Good for architect/implementer on zero-retention models. On <code>Free usage limit reached</code>, move the role or reduce parallelism; do not retry in burst.</td>
                                </tr>
                                <tr>
                                    <td><strong>OpenRouter</strong></td>
                                    <td><code>:free</code> models: <strong>20 RPM</strong> always; <strong>50 RPD</strong> (&lt;10 lifetime credits) / <strong>1,000 RPD</strong> (≥10 credits). Shared across all <code>:free</code> models, UTC day. Negative balance → 402. Upstream 429s apply independently.</td>
                                    <td>Explorer / low-volume only. Do not use for fan-out or architect with many subagents.</td>
                                </tr>
                                <tr>
                                    <td><strong>NVIDIA</strong></td>
                                    <td><strong>~40 RPM global</strong>, shared across all models at key level, not per model. No official daily. Requires Developer Program + phone verification, geo-blocked in ~10 countries. Trial only: no production, no confidential data.</td>
                                    <td>Fallback / reviewer / secondary vision worker only. On 429 with <code>Retry-After</code>, back off and move sustained work to <code>opencode/*</code> zero-retention.</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <p>Check quota before a large run:</p>
                    <pre class="code-snippet"><code># OpenRouter: free daily counter
curl -s https://openrouter.ai/api/v1/key \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  | jq '.data.free_model_daily_requests'
# OpenCode Console: no API — reset time is in the error message, reset 00:00 UTC
# NVIDIA: account page on build.nvidia.com — ~40 RPM shared, no official daily</code></pre>

                    <div class="note-box">
                        <h3>429 handling differs per provider</h3>
                        <p>OpenCode: wait for the reset time in the error, reduce parallelism. OpenRouter: honor <code>X-RateLimit-Reset</code>; if the source is <code>upstream_provider_shared_pool</code>, switch model or add a paid fallback. The <code>free_model_daily_requests</code> counter can lag ~1 minute in bursts, and a missing <code>:free</code> suffix can silently route to a paid endpoint — double-check the suffix before a large run. NVIDIA: honor <code>Retry-After</code> and move sustained parallelism to Console zero-retention.</p>
                    </div>
                </section>

                <section id="failures" class="blog-section">
                    <h2>Failure handling</h2>
                    <ul>
                        <li><strong>Model unavailable:</strong> switch the role to its recorded same-class fallback. Do not silently downgrade privacy.</li>
                        <li><strong>Geo-blocked:</strong> replace it. Retrying cannot change the region.</li>
                        <li><strong>Rate limited:</strong> treat as a routing signal, not a retry signal — move the role or narrow fan-out per the provider table above.</li>
                        <li><strong>Deprecated:</strong> migrate before the removal date; check the deprecation table for both the family and the exact version.</li>
                        <li><strong>Unexpected quality drop:</strong> re-check the selected variant and whether the free alias now points to a different backend.</li>
                    </ul>
                </section>

                <section id="antipatterns" class="blog-section">
                    <h2>Anti-patterns to avoid</h2>
                    <ul>
                        <li>Treating a catalog row as proof of entitlement.</li>
                        <li>Sending confidential code to trial-logged or training models — including NVIDIA trials.</li>
                        <li>Assigning every role to a single provider family.</li>
                        <li>Using a daily-capped model for fan-out work — notably OpenRouter <code>:free</code> for architect with many subagents.</li>
                        <li>Using NVIDIA trial endpoints for sustained parallelism or production.</li>
                        <li>Hardcoding a free model with no fallback.</li>
                        <li>Confusing a deprecated base model with its current free variant.</li>
                    </ul>
                    <div class="note-box further-reading">
                        <h3>Further reading</h3>
                        <ul>
                            <li><strong>Console catalog:</strong> <a href="https://opencode.ai/docs/console/models/">opencode.ai/docs/console/models/</a> <span>— free set, variants, privacy, deprecations.</span></li>
                            <li><strong>OpenRouter free models:</strong> <a href="https://openrouter.ai/models?max_price=0">openrouter.ai/models?max_price=0</a> <span>— filter <code>:free</code>, check Context/Architecture tabs.</span></li>
                            <li><strong>NVIDIA models:</strong> <a href="https://build.nvidia.com/explore/discover">build.nvidia.com/explore/discover</a> <span>— free tiers marked, trial terms apply.</span></li>
                            <li><strong>Independent ranking:</strong> <a href="https://lmarena.ai/">LMArena</a> <span>— Coding leaderboard for Elo tie-breaker.</span></li>
                        </ul>
                    </div>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>Choosing an Agent Workflow: Match Coordination to the Task</title>
      <link>https://olibartfast.ninja/blog/choose-agent-workflow.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/choose-agent-workflow.html</guid>
      <pubDate>Sun, 15 Nov 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>Choose between one agent, pipelines, parallel workers, and bounded delegation using task dependencies, acceptance criteria, and coordination costs.</description>
      <content:encoded><![CDATA[<p>A failing integration test, a dataset audit, and a review spanning several services can all involve AI agents. Their coordination needs are quite different. The bug may depend on one person holding the whole execution path in mind. The audit may repeat the same operation thousands of times. The system review may contain independent investigations whose conclusions must eventually agree.</p>

                <p>Choosing a workflow starts with the shape of the work, its constraints, and the evidence needed to accept the result. This post walks through the coordination patterns and their costs, with illustrative engineering examples. The examples are design choices to evaluate against your own workload; they make no benchmark claims about which arrangement is fastest or cheapest.</p>

                <div class="note-box">
                    <h3>The starting rule</h3>
                    <p>Use the simplest arrangement that can meet the acceptance criteria. Add parallel work for independent tasks, verification for a quality problem, and another management layer when a subtask needs coordination of its own.</p>
                </div>

                <nav class="table-of-contents" aria-label="Table of contents">
                    <h3>Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#hierarchy">Multi-tier pyramid</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#single-agent">One agent with tools and selective context</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#code-driven">Code-driven workflow or DAG</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#flat-fan-out">Flat fan-out with one integration owner</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#sequential-pipeline">Sequential pipeline</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#verification">Generator and verifier loop</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#shared-workspace">Shared workspace or blackboard</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#routing">Routing and peer handoffs</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#patterns">Workflow comparison</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#decision">Define the decision before choosing roles</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#handoffs">Make handoffs and ownership explicit</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#examples">Three tasks, three starting points</a></li>
                        <li><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#recommendation">Write a recommendation you can evaluate</a></li>
                    </ul>
                </nav>

                <section id="hierarchy" class="blog-section">
                    <h2>Multi-tier pyramid</h2>

                    <p>The <strong>multi-tier pyramid</strong> is a hierarchical delegation workflow: a root coordinator assigns broad areas to manager agents, and each manager delegates narrower tasks to workers. Managers plan their area's work, reconcile findings, and return an integrated result. The root remains responsible for the final deliverable.</p>

                    <figure class="workflow-figure" id="hierarchy-diagram">
                        <svg class="diagram-desktop" viewBox="0 0 840 350" role="img" aria-labelledby="hierarchy-title hierarchy-desc">
                            <title id="hierarchy-title">Multi-tier pyramid for a system review</title>
                            <desc id="hierarchy-desc">A root coordinator delegates to backend and frontend managers. The backend manager assigns API and persistence reviews; the frontend manager assigns user-flow and accessibility reviews. Findings return up the same branches.</desc>
                            <defs><marker id="hierarchy-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 Z"/></marker></defs>
                            <g class="edge" marker-end="url(#hierarchy-arrow)">
                                <path d="M420 76 V104 H220 V135"/><path d="M420 76 V104 H620 V135"/>
                                <path d="M220 195 V230 H115 V265"/><path d="M220 195 V230 H305 V265"/>
                                <path d="M620 195 V230 H535 V265"/><path d="M620 195 V230 H725 V265"/>
                            </g>
                            <rect class="node control" x="330" y="16" width="180" height="60"/>
                            <rect class="node control" x="130" y="135" width="180" height="60"/>
                            <rect class="node control" x="530" y="135" width="180" height="60"/>
                            <rect class="node" x="30" y="265" width="170" height="54"/>
                            <rect class="node" x="220" y="265" width="170" height="54"/>
                            <rect class="node" x="450" y="265" width="170" height="54"/>
                            <rect class="node" x="640" y="265" width="170" height="54"/>
                            <text x="420" y="52">Root coordinator</text>
                            <text x="220" y="160">Backend<tspan x="220" dy="22">manager</tspan></text>
                            <text x="620" y="160">Frontend<tspan x="620" dy="22">manager</tspan></text>
                            <text x="115" y="298">API contracts</text><text x="305" y="298">Persistence</text>
                            <text x="535" y="298">User flows</text><text x="725" y="298">Accessibility</text>
                        </svg>
                        <svg class="diagram-mobile" viewBox="0 0 340 450" role="img" aria-labelledby="hierarchy-mobile-title hierarchy-mobile-desc">
                            <title id="hierarchy-mobile-title">Multi-tier pyramid for a system review</title>
                            <desc id="hierarchy-mobile-desc">A root coordinator delegates to two managers. Each manager coordinates two worker reviews; evidence returns through the managers to the root.</desc>
                            <defs><marker id="hierarchy-mobile-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 Z"/></marker></defs>
                            <g class="edge" marker-end="url(#hierarchy-mobile-arrow)">
                                <path d="M170 78 V108 H87 V140"/><path d="M170 78 V108 H253 V140"/>
                                <path d="M87 200 V240 H12 V305 H26"/><path d="M87 200 V240 H12 V405 H26"/>
                                <path d="M253 200 V240 H178 V305 H192"/><path d="M253 200 V240 H178 V405 H192"/>
                            </g>
                            <rect class="node control" x="75" y="18" width="190" height="60"/>
                            <rect class="node control" x="16" y="140" width="142" height="60"/>
                            <rect class="node control" x="182" y="140" width="142" height="60"/>
                            <rect class="node" x="26" y="280" width="132" height="50"/>
                            <rect class="node" x="26" y="380" width="132" height="50"/>
                            <rect class="node" x="192" y="280" width="132" height="50"/>
                            <rect class="node" x="192" y="380" width="132" height="50"/>
                            <text x="170" y="54">Root coordinator</text>
                            <text x="87" y="165">Backend<tspan x="87" dy="22">manager</tspan></text>
                            <text x="253" y="165">Frontend<tspan x="253" dy="22">manager</tspan></text>
                            <text x="92" y="311">API contracts</text><text x="92" y="411">Persistence</text>
                            <text x="258" y="311">User flows</text><text x="258" y="411">Accessibility</text>
                        </svg>
                        <figcaption><strong>Multi-tier pyramid.</strong> Arrows show delegation; evidence and integrated findings return up the same branches. Each manager must resolve a real coordination problem within its area.</figcaption>
                    </figure>

                    <p>Consider a system review. A backend manager might need to reconcile API behavior, persistence rules, and migration compatibility before the root compares those findings with frontend assumptions. That intermediate integration is useful work. A manager who only forwards a question and repeats an answer adds a handoff without resolving anything.</p>

                    <p>Every layer can omit constraints, duplicate analysis, or wait on a slow branch. Put limits on depth, concurrent work, and total effort. Preserve original requirements and exact evidence references, and require unresolved disagreements to travel upward. Different branches can have different depths; the structure should follow their coordination needs.</p>

                    <div class="note-box">
                        <h3>Context separation and permissions</h3>
                        <p>An agent's role description does not enforce access restrictions. Separate sessions may share a filesystem, and their initial context depends on the runtime. Check actual tool permissions, model controls, and workspace isolation before relying on them.</p>
                    </div>

                    <p>Workload size alone is a weak reason to add managers. A thousand independent records may suit a batch job. A small change across a tightly coupled interface may need careful coordination. The useful question is whether a branch contains decisions and dependencies that someone must actively reconcile.</p>
                </section>

                <section id="single-agent" class="blog-section">
                    <h2>One agent with tools and selective context</h2>
                    <p>For an unfamiliar bug, keeping the reproduction, suspected cause, and proposed fix in one session can be valuable. Load relevant code as needed and save important discoveries. If context becomes the problem, first consider better retrieval, durable notes, and compaction. Each can omit details, so keep original evidence accessible. Additional agents introduce their own context-transfer problem.</p>
                </section>

                <section id="code-driven" class="blog-section">
                    <h2>Code-driven workflow or DAG</h2>
                    <p>When the steps are known, ordinary code can enumerate inputs, schedule dependencies, and validate results. A directed acyclic graph, or DAG, represents steps that become eligible to run when their prerequisites finish. Independent branches can run together; dependent ones wait.</p>
                    <p>Checkpoints, caching, and retries must be implemented deliberately. A repeatable scheduler does not make model output deterministic, and retries need stable item identifiers and protection against duplicated side effects. Keep operations that require no model judgment in ordinary code.</p>
                </section>

                <section id="flat-fan-out" class="blog-section">
                    <h2>Flat fan-out with one integration owner</h2>
                    <p>Flat fan-out works when each worker can answer a bounded question and one owner can combine the answers. Independent branches run in parallel and return evidence to the integrator. Predetermined branches are a <strong>parallelization</strong> workflow; when an agent decides how to break down each incoming task and assigns the resulting work, the arrangement follows the <strong>orchestrator-workers</strong> pattern. Similar diagrams can therefore hide different choices about who controls the work.</p>

                    <figure class="workflow-figure" id="parallel-diagram">
                        <svg class="diagram-desktop" viewBox="0 0 840 300" role="img" aria-labelledby="parallel-title parallel-desc">
                            <title id="parallel-title">Flat fan-out with one integration owner</title>
                            <desc id="parallel-desc">A coordinator assigns independent tasks to three workers. Their findings return to the same coordinator for integration into one result.</desc>
                            <defs><marker id="parallel-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 Z"/></marker></defs>
                            <g class="edge" marker-end="url(#parallel-arrow)">
                                <path d="M182 150 C240 150 242 55 300 55"/><path d="M182 150 H300"/><path d="M182 150 C240 150 242 245 300 245"/>
                                <path d="M470 55 C548 55 542 150 620 150"/><path d="M470 150 H620"/><path d="M470 245 C548 245 542 150 620 150"/>
                            </g>
                            <rect class="node control" x="20" y="120" width="162" height="60"/>
                            <rect class="node" x="300" y="25" width="170" height="60"/>
                            <rect class="node" x="300" y="120" width="170" height="60"/>
                            <rect class="node" x="300" y="215" width="170" height="60"/>
                            <rect class="node control" x="620" y="120" width="196" height="60"/>
                            <text x="101" y="156">Coordinator</text>
                            <text x="385" y="61">Worker A</text><text x="385" y="156">Worker B</text><text x="385" y="251">Worker C</text>
                            <text x="718" y="156">Integrate results</text>
                        </svg>
                        <svg class="diagram-mobile" viewBox="0 0 340 420" role="img" aria-labelledby="parallel-mobile-title parallel-mobile-desc">
                            <title id="parallel-mobile-title">Flat fan-out with one integration owner</title>
                            <desc id="parallel-mobile-desc">The coordinator fans out to three independent workers, then gathers their results into one integrated answer.</desc>
                            <defs><marker id="parallel-mobile-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 Z"/></marker></defs>
                            <g class="edge" marker-end="url(#parallel-mobile-arrow)">
                                <path d="M170 78 V118 H57 V170"/><path d="M170 78 V170"/><path d="M170 78 V118 H283 V170"/>
                                <path d="M57 240 V280 H170 V340"/><path d="M170 240 V340"/><path d="M283 240 V280 H170 V340"/>
                            </g>
                            <rect class="node control" x="85" y="18" width="170" height="60"/>
                            <rect class="node" x="12" y="170" width="90" height="70"/>
                            <rect class="node" x="125" y="170" width="90" height="70"/>
                            <rect class="node" x="238" y="170" width="90" height="70"/>
                            <rect class="node control" x="70" y="340" width="200" height="60"/>
                            <text x="170" y="54">Coordinator</text>
                            <text x="57" y="200">Worker<tspan x="57" dy="22">A</tspan></text>
                            <text x="170" y="200">Worker<tspan x="170" dy="22">B</tspan></text>
                            <text x="283" y="200">Worker<tspan x="283" dy="22">C</tspan></text>
                            <text x="170" y="376">Integrate results</text>
                        </svg>
                        <figcaption><strong>Flat fan-out with one integration owner.</strong> Independent branches run concurrently. The coordinator appears at both ends: it scopes the assignments and owns the final integration.</figcaption>
                    </figure>
                </section>

                <section id="sequential-pipeline" class="blog-section">
                    <h2>Sequential pipeline</h2>
                    <p>A sequential pipeline fits ordered transformations such as extracting facts, normalizing records, and drafting a report. Each stage needs an input and output contract; it does not automatically need its own autonomous agent. Dependent stages remain serial for one item, even if several items move through the pipeline at once. When successive model calls consume the previous call's output, this is <strong>prompt chaining</strong>.</p>

                    <figure class="workflow-figure" id="pipeline-diagram">
                        <svg class="diagram-desktop" viewBox="0 0 840 200" role="img" aria-labelledby="pipeline-title pipeline-desc">
                            <title id="pipeline-title">Sequential pipeline with a validation gate</title>
                            <desc id="pipeline-desc">Inputs pass through extraction and a check. Passing records become a report; failed records stop for inspection.</desc>
                            <defs><marker id="pipeline-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 Z"/></marker></defs>
                            <g class="edge" marker-end="url(#pipeline-arrow)">
                                <path d="M136 68 H218"/><path d="M362 68 H438"/><path d="M582 68 H668"/>
                                <path d="M510 100 V136"/>
                            </g>
                            <rect class="node terminal" x="24" y="36" width="112" height="64"/>
                            <rect class="node" x="218" y="36" width="144" height="64"/>
                            <rect class="node check" x="438" y="36" width="144" height="64"/>
                            <rect class="node terminal" x="668" y="36" width="144" height="64"/>
                            <rect class="node control" x="420" y="136" width="180" height="48"/>
                            <text x="80" y="74">Inputs</text><text x="290" y="74">Extract</text>
                            <text x="510" y="74">Check</text><text x="740" y="74">Report</text>
                            <text x="510" y="166">Stop + inspect</text>
                            <text class="edge-label" x="625" y="55">pass</text><text class="edge-label" x="541" y="123">fail</text>
                        </svg>
                        <svg class="diagram-mobile" viewBox="0 0 340 420" role="img" aria-labelledby="pipeline-mobile-title pipeline-mobile-desc">
                            <title id="pipeline-mobile-title">Sequential pipeline with a validation gate</title>
                            <desc id="pipeline-mobile-desc">Inputs flow down through extraction and a check to a report. A failed check branches right to stop and inspect.</desc>
                            <defs><marker id="pipeline-mobile-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 Z"/></marker></defs>
                            <g class="edge" marker-end="url(#pipeline-mobile-arrow)">
                                <path d="M115 80 V120"/><path d="M115 180 V220"/><path d="M115 280 V350"/>
                                <path d="M200 250 H238"/>
                            </g>
                            <rect class="node terminal" x="30" y="20" width="170" height="60"/>
                            <rect class="node" x="30" y="120" width="170" height="60"/>
                            <rect class="node check" x="30" y="220" width="170" height="60"/>
                            <rect class="node terminal" x="30" y="350" width="170" height="60"/>
                            <rect class="node control" x="238" y="220" width="92" height="60"/>
                            <text x="115" y="56">Inputs</text><text x="115" y="156">Extract</text>
                            <text x="115" y="256">Check</text><text x="115" y="386">Report</text>
                            <text x="284" y="245">Stop +<tspan x="284" dy="21">inspect</tspan></text>
                            <text class="edge-label" x="146" y="319">pass</text><text class="edge-label" x="219" y="236">fail</text>
                        </svg>
                        <figcaption><strong>Sequential pipeline.</strong> Each step consumes a defined artifact. A failed check stops the flow before an invalid record reaches the report. Stages can be ordinary code or model calls.</figcaption>
                    </figure>
                </section>

                <section id="verification" class="blog-section">
                    <h2>Generator and verifier loop</h2>

                    <p>A <strong>generator and verifier loop</strong> can improve any of these arrangements: produce an artifact, evaluate it against agreed criteria, then accept it, return specific defects, or escalate. When one model call evaluates another's output and feeds back improvements, this is the <strong>evaluator-optimizer</strong> pattern. Verification can also use objective tests and independent evidence. Two agents can make the same mistake; agreement alone does not establish correctness.</p>

                    <figure class="workflow-figure" id="verification-diagram">
                        <svg class="diagram-desktop" viewBox="0 0 840 250" role="img" aria-labelledby="verification-title verification-desc">
                            <title id="verification-title">A bounded generator and verifier loop</title>
                            <desc id="verification-desc">An artifact is produced and verified. A passing artifact is accepted. Defects return for revision while budget remains; unresolved failures escalate when the limit is reached.</desc>
                            <defs><marker id="verification-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 Z"/></marker></defs>
                            <g class="edge" marker-end="url(#verification-arrow)">
                                <path d="M194 62 H330"/><path d="M500 62 H640"/>
                                <path d="M415 94 V160 H109 V94"/><path d="M415 160 V210 H640"/>
                            </g>
                            <rect class="node" x="24" y="30" width="170" height="64"/>
                            <rect class="node check" x="330" y="30" width="170" height="64"/>
                            <rect class="node terminal" x="640" y="30" width="170" height="64"/>
                            <rect class="node control" x="640" y="184" width="170" height="52"/>
                            <text x="109" y="68">Produce</text><text x="415" y="68">Verify</text><text x="725" y="68">Accept</text>
                            <text x="725" y="216">Escalate</text>
                            <text class="edge-label" x="262" y="49">artifact</text><text class="edge-label" x="570" y="49">pass</text>
                            <text class="edge-label" x="262" y="146">defects: revise within budget</text>
                            <text class="edge-label" x="530" y="197">limit reached</text>
                        </svg>
                        <svg class="diagram-mobile" viewBox="0 0 340 475" role="img" aria-labelledby="verification-mobile-title verification-mobile-desc">
                            <title id="verification-mobile-title">A bounded generator and verifier loop</title>
                            <desc id="verification-mobile-desc">Produce and verify an artifact, then accept it if it passes. Revision loops back to production on the left. Reaching the revision limit leads to escalation on the right.</desc>
                            <defs><marker id="verification-mobile-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0 0 L10 5 L0 10 Z"/></marker></defs>
                            <g class="edge" marker-end="url(#verification-mobile-arrow)">
                                <path d="M170 84 V158"/><path d="M170 222 V298"/>
                                <path d="M75 190 H20 V52 H75"/><path d="M265 190 H320 V430 H265"/>
                            </g>
                            <rect class="node" x="75" y="20" width="190" height="64"/>
                            <rect class="node check" x="75" y="158" width="190" height="64"/>
                            <rect class="node terminal" x="75" y="298" width="190" height="56"/>
                            <rect class="node control" x="75" y="402" width="190" height="56"/>
                            <text x="170" y="58">Produce</text><text x="170" y="196">Verify</text>
                            <text x="170" y="332">Accept</text><text x="170" y="436">Escalate</text>
                            <text class="edge-label" x="209" y="124">artifact</text><text class="edge-label" x="201" y="263">pass</text>
                            <text class="edge-label" transform="translate(42 121) rotate(-90)">revise</text>
                            <text class="edge-label" transform="translate(301 310) rotate(90)">limit reached</text>
                        </svg>
                        <figcaption><strong>Generator and verifier loop.</strong> Tests or source evidence drive the check. Failed artifacts return with specific defects; the revision budget determines when unresolved failures escalate.</figcaption>
                    </figure>

                    <p>Define a review rubric before the loop begins. For a compatibility patch, that might cover the reproduced failure, behavior of existing clients, required tests, and adherence to the allowed scope. The verifier should identify actionable failures and the evidence behind them.</p>

                    <p>Also define an exit. An illustrative policy might allow two revision attempts, then return remaining failures to the integration owner for a decision. That number is a budget choice for the task, not a universal rule. Without a limit, a review loop can keep spending effort while repeating the same disagreement.</p>

                    <p>If speed or cost drives the architecture choice, compare it with a simpler baseline on representative tasks using the same acceptance criteria. Record total spend, elapsed time, output quality, and human intervention. Include coordination, retries, review, and integration. Finishing individual branches quickly is only useful if the final accepted result also improves.</p>
                </section>

                <section id="shared-workspace" class="blog-section">
                    <h2>Shared workspace or blackboard</h2>
                    <p>A shared workspace, also called a <strong>blackboard</strong>, becomes useful when specialists repeatedly need each other's changing findings. Record ownership, status, dependencies, versions, and decisions. Choose a conflict-control mechanism that fits the environment: one writer per file, isolated branches, transactions, or explicit merge rules. A directory full of outputs does not establish which output is authoritative. This state-sharing pattern can support either a flat team or a hierarchy.</p>
                </section>

                <section id="routing" class="blog-section">
                    <h2>Routing and peer handoffs</h2>
                    <p><strong>Routing</strong> selects a specialist for an incoming request. <strong>Peer handoffs</strong> let specialists transfer responsibility as the diagnosis changes. For example, intake might send a support request to billing, which transfers it to technical support after identifying a service failure. Record the current owner, preserve relevant findings, and bound transfers to prevent loops. Routing chooses where work goes; it does not require every specialist to run concurrently.</p>
                </section>

                <section id="patterns" class="blog-section">
                    <h2>Workflow comparison</h2>

                    <p>The table compares where each workflow fits and the costs to watch. Some patterns describe the structure of the work; others add shared state or verification to that structure.</p>

                    <div class="table-scroll" role="region" aria-label="Agent workflow comparison" tabindex="0">
                        <table class="workflow-table">
                            <thead>
                                <tr>
                                    <th scope="col">Workflow name</th>
                                    <th scope="col">When it fits</th>
                                    <th scope="col">Cost to watch</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#hierarchy">Multi-tier pyramid</a></td>
                                    <td>A delegated area needs its own planning and integration</td>
                                    <td>Extra latency and lost requirements at handoffs</td>
                                </tr>
                                <tr>
                                    <td><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#single-agent">One agent with tools and selective context</a></td>
                                    <td>Discovery with tightly connected decisions</td>
                                    <td>Serial work and growing context</td>
                                </tr>
                                <tr>
                                    <td><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#code-driven">Code-driven workflow or DAG</a></td>
                                    <td>A repeated procedure with known steps</td>
                                    <td>Implementation, maintenance, and safe retries</td>
                                </tr>
                                <tr>
                                    <td><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#flat-fan-out">Flat fan-out with one integration owner</a></td>
                                    <td>Investigations that can proceed independently</td>
                                    <td>Duplicate effort and too much output to reconcile</td>
                                </tr>
                                <tr>
                                    <td><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#sequential-pipeline">Sequential pipeline</a></td>
                                    <td>Ordered transformations of an artifact</td>
                                    <td>Early errors reaching later stages</td>
                                </tr>
                                <tr>
                                    <td><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#verification">Generator and verifier loop</a></td>
                                    <td>Quality is limiting acceptance</td>
                                    <td>Review expense and shared blind spots</td>
                                </tr>
                                <tr>
                                    <td><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#shared-workspace">Shared workspace or blackboard</a></td>
                                    <td>Specialists repeatedly need evolving information</td>
                                    <td>Stale versions and competing writes</td>
                                </tr>
                                <tr>
                                    <td><a href="https://olibartfast.ninja/blog/choose-agent-workflow.html#routing">Routing and peer handoffs</a></td>
                                    <td>Different request categories need different expertise</td>
                                    <td>Misrouting and handoff loops</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </section>

                <section id="decision" class="blog-section">
                    <h2>Define the decision before choosing roles</h2>

                    <p>Start with the deliverable. A patch that fixes a reproduced defect, a report whose findings link to source evidence, and a validated set of dataset labels require different checks. Write down what would make the result acceptable before deciding who should produce it.</p>

                    <p>Then identify the constraint that matters most: elapsed time, quality, cost, context size, or the effort needed to combine results. Map which steps depend on others and which files or data they share. Include practical limits such as available tools, concurrency, permissions, and where sensitive data may be processed. These facts determine whether a proposed workflow can actually run.</p>

                    <p>It helps to separate four choices that are easy to collapse into a single label like “multi-agent”:</p>

                    <ul>
                        <li><strong>Control:</strong> does code determine the next step, does an agent decide, or do they share that responsibility?</li>
                        <li><strong>Structure:</strong> does the work run in one session, in sequence, in parallel branches, or through managers and workers?</li>
                        <li><strong>State:</strong> how do participants retain and exchange information: messages, saved artifacts, or structured shared records?</li>
                        <li><strong>Verification:</strong> what establishes that the output is acceptable: tests, source checks, human review, or a bounded revision loop?</li>
                    </ul>

                    <p>These choices combine. A script can schedule parallel model calls, collect their artifacts, and send questionable results to a reviewer. A single agent can use tests and durable notes. A hierarchy can use the same shared records as a flat team.</p>
                </section>

                <section id="handoffs" class="blog-section">
                    <h2>Make handoffs and ownership explicit</h2>

                    <p>A delegated task needs enough context to succeed without reconstructing the entire conversation. Include the original goal, relevant constraints, bounded scope, dependencies, permitted actions, acceptance criteria, and the expected return format. Keep authoritative references intact as the task passes between people or agents.</p>

                    <p>Here is an illustrative handoff for one branch of an API review:</p>

                    <pre class="code-snippet handoff-example"><code>Goal: assess whether the proposed API change preserves existing clients.
Scope: inspect the API schema and the client contract tests at the supplied revision.
Dependencies: use the interface proposal attached to the task; flag missing decisions.
Allowed actions: read files and run existing checks; do not modify implementation or tests.
Acceptance: each finding identifies an affected contract, supporting evidence, and a verification step.
Return: a concise finding list, exact source references, checks run, and unresolved questions.
Integration owner: the coordinator resolves conflicts with the service implementation review.</code></pre>

                    <p>For a large result, save detailed evidence in an artifact and return its location and version with a short account of findings, assumptions, and validation status. This keeps the coordinator's immediate context manageable while retaining detail. Someone still has to read the evidence that matters before accepting the conclusion.</p>

                    <p>Parallel reading with one integration owner is a useful engineering starting point. Parallel editing also works when ownership is distinct, interfaces are agreed, changes are isolated, and the combined result is checked. Assign the integration responsibility before starting the workers.</p>
                </section>

                <section id="examples" class="blog-section">
                    <h2>Three tasks, three starting points</h2>

                    <p>These examples illustrate the decision process. They are proposed arrangements, not reports of measured outcomes.</p>

                    <h3>A failing integration test</h3>
                    <p>Start with one agent that can reproduce the failure, follow the execution path, implement a focused correction, and run the relevant checks. The diagnosis and implementation are tightly coupled. Add a separate review if the change affects a sensitive contract or the initial validation leaves a material uncertainty. The trigger is an observed need for another check.</p>

                    <h3>A recurring image dataset audit</h3>
                    <p>Use code to enumerate batches and maintain stable item identifiers. Call a model where visual judgment is needed, validate the returned records, and aggregate flagged items. Independent batches can run concurrently within resource limits. Add targeted verification for uncertain cases. This combines explicit scheduling, parallel work, and quality checks without requiring a management hierarchy.</p>

                    <h3>A review of twenty modules, four sharing an API</h3>
                    <p>Start with flat reviewers for independent areas and one integration owner. Treat the four coupled modules as a connected review area with a common interface reference. If reconciling that area requires substantial internal planning and coordination, assign it a manager. Keep simpler branches flat.</p>
                    <p>The return should identify defects with evidence, resolve duplicate reports, and flag disagreements about the shared API. If combining the findings becomes the bottleneck, first narrow worker scopes and improve their return format. Add another coordination layer only if it has a concrete integration job to do.</p>
                </section>

                <section id="recommendation" class="blog-section">
                    <h2>Write a recommendation you can evaluate</h2>

                    <p>Before implementing a workflow, capture the choice in a short recommendation. State the deliverable, dependencies, constraints, and priority, then explain how the proposed responsibilities and checks address them.</p>

                    <p>For example, a review of a service and two clients before an API migration might start with this recommendation:</p>

                    <pre class="code-snippet handoff-example"><code>Setup: one coordinator and two reviewers, with at most three agents running concurrently.

Why: the service and clients share a schema, so they need one agreed contract and a combined compatibility check. Review quality is the priority.

Responsibilities: the coordinator records the contract and resolves disagreements. One reviewer examines the service; the other traces both clients against that contract.

Checks: findings cite exact source locations. Acceptance requires the agreed compatibility checks and an explicit disposition for each finding.

Trade-off: the client review stays serial within one branch, reducing handoffs but potentially increasing elapsed time.

Change condition: if the clients prove independent and their review dominates elapsed time, give each its own reviewer while retaining the shared concurrency limit.</code></pre>

                    <p>A useful recommendation makes one clear choice, explains the task facts or assumptions behind it, assigns responsibilities and checks, identifies the main trade-off, and gives an observable condition for changing course. Resolve missing information when it could materially alter the choice; otherwise make the assumption visible.</p>

                    <p>Keep that recommendation beside the acceptance criteria. After a representative run, compare the expected bottleneck with what actually consumed time and effort. That evidence gives the next workflow decision a firmer basis.</p>

                    <div class="note-box">
                        <h3>Further reading</h3>
                        <p>Anthropic's <a href="https://www.anthropic.com/research/building-effective-agents">Building effective agents</a> discusses composable patterns including prompt chaining, parallelization, orchestrator-workers, and evaluator-optimizer loops. Its box-and-arrow explanations inspired the presentation of the original diagrams in this article.</p>
                    </div>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>From Colab to Brev: A Practical GPU Development Cheatsheet</title>
      <link>https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html</guid>
      <pubDate>Sun, 11 Oct 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>Prototype CUDA projects on Colab, then move to persistent cloud GPUs for larger workloads and reproducible development.</description>
      <content:encoded><![CDATA[<p>Most GPU projects follow the same path: prototype quickly, validate correctness, then move to a more persistent environment when compute, VRAM, or iteration speed becomes a bottleneck.</p>

                <p>Google Colab is convenient for notebook-based experiments and quick CUDA builds. Brev — the cloud option used in my own workflow, not the only option — provides access to configurable cloud GPU instances that you can manage from a terminal or IDE.</p>

                <p>This guide combines two practical cheatsheets: one for identifying GPUs, building CUDA/C++ projects, and managing Colab's ephemeral runtimes; the other for searching, provisioning, and operating Brev GPU instances. The commands are designed to be copied, adapted, and tested without assuming a particular project repository.</p>

                <div class="note-box">
                    <h3>Mental model in one paragraph</h3>
                    <p>Colab is an ephemeral notebook VM: free tier is usually a T4, Pro can give you L4/A100, there is no Docker daemon, and the filesystem resets on recycle. Brev is the opposite: you pick an exact GPU type, VRAM, provider and boot time, create a persistent box, SSH into it, and pay per hour. Prototype on Colab, scale on Brev.</p>
                </div>

                <div class="note-box">
                    <h3>Tested with</h3>
                    <p>Colab GPU runtime (verify with <code>!nvidia-smi</code> and <code>!nvcc --version</code> — assignment varies), CMake 3.24+ for <code>CMAKE_CUDA_ARCHITECTURES=native</code>, Brev CLI <code>v0.6.335</code> verified October 11, 2026. Brev flags and inventory change over time — run <code>brev search --help</code> and <code>brev create --dry-run</code> to confirm behavior on your version.</p>
                </div>

                <div class="table-of-contents">
                    <h3>Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#choosing">1. Choosing: Colab vs Brev</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#colab-start">2. Colab: Enable and Identify the GPU</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#cuda-arch">3. CUDA Architectures (Applies to Both)</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#colab-shell">4. Colab Shell Basics and Python GPU Packages</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#colab-build">5. Colab: Build Any CUDA C++ Project</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#colab-monitor">6. Colab: Monitor, Persist, and Survive Resets</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#brev-search">7. Brev: Search for GPUs</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#brev-filter">8. Brev: Filter by Model, VRAM, and Provider</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#brev-recipes">9. Brev: Preset Recipes and JSON + jq</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#brev-create">10. Brev: Create Instances Safely</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#brev-use">11. Brev: Daily Use — Shell, Copy, Ports, List</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#troubleshoot">12. Troubleshooting Both</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#checklist">13. Cross-Environment Reproducibility Checklist</a></li>
                        <li><a href="https://olibartfast.ninja/blog/colab-to-brev-gpu-cheatsheet.html#conclusion">Conclusion</a></li>
                    </ul>
                </div>

                <section id="choosing" class="blog-section">
                    <h2>1. Choosing: Colab vs Brev</h2>
                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th></th>
                                <th>Colab</th>
                                <th>Brev</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong>Best for</strong></td>
                                <td>Free prototyping, notebooks, quick CUDA builds</td>
                                <td>Training, large VRAM, persistent boxes, multi-GPU</td>
                            </tr>
                            <tr>
                                <td><strong>GPU choice</strong></td>
                                <td>Assigned (T4 common, A100/L4 not guaranteed)</td>
                                <td>You choose, e.g.: T4, L4, A10G, A100, H100, L40S, RTX — examples only, inventory varies</td>
                            </tr>
                            <tr>
                                <td><strong>Lifetime</strong></td>
                                <td>Ephemeral; runtime limits and idle timeouts vary</td>
                                <td>Persistent until you stop/delete; stopping may end compute charges while attached storage and other resources can continue to incur costs — check pricing and storage-retention policy</td>
                            </tr>
                            <tr>
                                <td><strong>Access</strong></td>
                                <td>Browser notebook, <code>!cmd</code> shell</td>
                                <td>SSH, VS Code / Cursor, port-forward, managed ports</td>
                            </tr>
                            <tr>
                                <td><strong>Cost control</strong></td>
                                <td>Quotas and disconnects</td>
                                <td><code>--dry-run</code> for preview plus check of actual hourly price and disk config, per-hour pricing, stop when idle</td>
                            </tr>
                        </tbody>
                    </table>
                    <p>My default flow: validate the idea and the CUDA build on Colab, then reproduce it on a Brev box with the VRAM the model actually needs.</p>
                </section>

                <section id="colab-start" class="blog-section">
                    <h2>2. Colab: Enable and Identify the GPU</h2>
                    <p>In the Colab UI:</p>
                    <pre class="code-snippet"><code>Runtime → Change runtime type → Hardware accelerator: GPU → Save</code></pre>
                    <p>Then confirm what you actually got — never assume T4. GPU assignment and installed CUDA tooling are separate checks: a GPU runtime does not guarantee <code>nvcc</code> is installed.</p>
                    <pre class="code-snippet"><code class="language-bash">!nvidia-smi
!nvidia-smi --query-gpu=name,driver_version,memory.total,compute_cap --format=csv
!nvcc --version || echo "nvcc not installed on this runtime"
!python3 --version</code></pre>
                    <pre class="code-snippet"><code class="language-python">import torch
print(torch.__version__)
print(torch.cuda.is_available())
print(torch.cuda.get_device_name(0) if torch.cuda.is_available() else "no cuda")</code></pre>
                    <p>TensorFlow / JAX alternates:</p>
                    <pre class="code-snippet"><code class="language-python">import tensorflow as tf; print(tf.config.list_physical_devices('GPU'))
import jax; print(jax.devices())</code></pre>
                </section>

                <section id="cuda-arch" class="blog-section">
                    <h2>3. CUDA Architectures (Applies to Both)</h2>
                    <p>A GPU architecture mismatch can cause <code>no kernel image available</code> at runtime; rebuild with the correct flag. Compute capability identifies hardware features, while CUDA toolkit and driver compatibility are separate constraints — matching the arch flag alone does not guarantee the toolkit/driver combination is supported. An <code>illegal instruction</code> error can have other causes, so check the surrounding error output before changing the architecture. Reference table:</p>
                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>GPU</th>
                                <th>Compute Cap.</th>
                                <th>CMake flag</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td>T4 (Colab free tier)</td><td>7.5</td><td><code>-DCMAKE_CUDA_ARCHITECTURES=75</code></td></tr>
                            <tr><td>V100</td><td>7.0</td><td><code>-DCMAKE_CUDA_ARCHITECTURES=70</code></td></tr>
                            <tr><td>A100</td><td>8.0</td><td><code>-DCMAKE_CUDA_ARCHITECTURES=80</code></td></tr>
                            <tr><td>RTX 30xx / A10G / A40</td><td>8.6</td><td><code>-DCMAKE_CUDA_ARCHITECTURES=86</code></td></tr>
                            <tr><td>L4 / L40S / RTX 4090</td><td>8.9</td><td><code>-DCMAKE_CUDA_ARCHITECTURES=89</code></td></tr>
                            <tr><td>H100</td><td>9.0</td><td><code>-DCMAKE_CUDA_ARCHITECTURES=90</code></td></tr>
                            <tr><td>B100 / B200 (Blackwell DC)</td><td>10.0</td><td><code>-DCMAKE_CUDA_ARCHITECTURES=100</code></td></tr>
                            <tr><td>RTX 5090 (Blackwell GeForce)</td><td>12.0</td><td><code>-DCMAKE_CUDA_ARCHITECTURES=120</code></td></tr>
                        </tbody>
                    </table>
                    <p>Auto-detect instead of guessing (works on Colab and on any Brev box):</p>
                    <pre class="code-snippet"><code class="language-bash"># Fast bash one-liner (uses primary GPU):
ARCH=$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader | head -n1 | tr -d '.')
echo "-DCMAKE_CUDA_ARCHITECTURES=${ARCH}"</code></pre>
                    <p>Or via Python (multi-GPU safe, deduplicates capabilities):</p>
                    <pre class="code-snippet"><code class="language-bash">%%bash
python3 - &lt;&lt;'PY'
import subprocess

result = subprocess.run(
    ['nvidia-smi', '--query-gpu=compute_cap', '--format=csv,noheader'],
    check=True, capture_output=True, text=True,
)
archs = sorted(set(result.stdout.strip().replace('.', '').splitlines()))
print('-DCMAKE_CUDA_ARCHITECTURES=' + ';'.join(archs))
PY</code></pre>
                    <p>On CMake ≥ 3.24 you can also delegate detection entirely — but <code>native</code> detects the GPU visible at configure time, so it is for local development, not portable binaries:</p>
                    <pre class="code-snippet"><code class="language-bash">!cmake -S . -B build -DCMAKE_CUDA_ARCHITECTURES=native</code></pre>
                    <ul>
                        <li><strong>Local development:</strong> <code>native</code> — fastest iteration on the current GPU.</li>
                        <li><strong>Known deployment target:</strong> explicit arch, e.g. <code>-DCMAKE_CUDA_ARCHITECTURES=80</code> for A100.</li>
                        <li><strong>Multiple deployment targets:</strong> deliberate list, potentially including PTX for forward compatibility, e.g. <code>-DCMAKE_CUDA_ARCHITECTURES="75;80;90a"</code>.</li>
                    </ul>
                    <p>For the full story on <code>native</code> vs <code>all-major</code> vs explicit lists, see my <a href="https://olibartfast.ninja/blog/cmake-cuda-architectures-guide.html">CMake CUDA Architecture Configuration guide</a>.</p>
                    <div class="note-box">
                        <h3>Brev capability shortcut</h3>
                        <p>Brev search exposes the same architecture as a filter: <code>--min-capability 7.5</code> (Turing+), <code>8.0</code> (Ampere+), <code>8.9</code> (Ada+), <code>9.0</code> (Hopper and newer). Use it when you care about features (e.g. FP8, Transformer Engine) rather than a specific card name.</p>
                    </div>
                </section>

                <section id="colab-shell" class="blog-section">
                    <h2>4. Colab Shell Basics and Python GPU Packages</h2>
                    <p>Two rules: <code>!cmd</code> runs shell, <code>%cd dir</code> persists directory (<code>!cd</code> does not). Colab idle timeouts and maximum runtime vary with availability and usage.</p>
                    <pre class="code-snippet"><code class="language-bash">!pwd &amp;&amp; ls
%cd /content
!apt-get update -qq &amp;&amp; apt-get install -y -qq cmake ninja-build
!cmake --version</code></pre>
                    <p>First inspect what is already installed — Colab runtimes often ship with PyTorch:</p>
                    <pre class="code-snippet"><code class="language-bash">!nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv
!python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.is_available())"</code></pre>
                    <p>Optional pinned environment (example only — match the wheel channel to your runtime and project; this can replace pre-installed packages):</p>
                    <pre class="code-snippet"><code class="language-bash">!pip install -q "torch==2.3.1" "torchvision==0.18.1" --index-url https://download.pytorch.org/whl/cu121
!pip freeze | grep -Ei "torch|transformers|accelerate|datasets|cuda"
!python -c "import torch; print(torch.__version__, torch.version.cuda, torch.cuda.get_device_name(0))"</code></pre>
                    <p>For a reproducible project, record <code>pip freeze</code> output plus <code>nvidia-smi</code> driver, <code>nvcc --version</code>, and <code>cmake --version</code> alongside the code.</p>
                    <p>Free VRAM before big jobs (<code>empty_cache()</code> releases unused cached allocations only — it does not free memory held by live tensors):</p>
                    <pre class="code-snippet"><code class="language-python">import torch
torch.cuda.empty_cache()</code></pre>
                    <pre class="code-snippet"><code class="language-bash">!nvidia-smi --query-gpu=memory.used,memory.total --format=csv</code></pre>
                </section>

                <section id="colab-build" class="blog-section">
                    <h2>5. Colab: Build Any CUDA C++ Project</h2>
                    <p>Generic recipe — replace the arch flag with the value from Section 3:</p>
                    <pre class="code-snippet"><code class="language-bash">!git clone &lt;repo-url&gt;
%cd /content/&lt;repo&gt;
!cmake -S . -B build -DCMAKE_CUDA_ARCHITECTURES=75 -DCMAKE_BUILD_TYPE=Release
!cmake --build build -j$(nproc)
!./build/&lt;binary&gt;</code></pre>
                    <p>Iterate on a single target instead of rebuilding everything:</p>
                    <pre class="code-snippet"><code class="language-bash">!cmake --build build --target &lt;target&gt; -j$(nproc)</code></pre>
                    <p>If the build gets killed mid-way, <code>-j$(nproc)</code> is usually too parallel for the available RAM — retry with <code>-j2</code>.</p>
                    <p>Validate against hidden env dependencies with a clean build or fresh clone before calling it done:</p>
                    <pre class="code-snippet"><code class="language-bash">!rm -rf build &amp;&amp; cmake -S . -B build -DCMAKE_CUDA_ARCHITECTURES=75 -DCMAKE_BUILD_TYPE=Release &amp;&amp; cmake --build build -j2
# or: fresh clone in /tmp and build there to catch files only present in /content</code></pre>
                </section>

                <section id="colab-monitor" class="blog-section">
                    <h2>6. Colab: Monitor, Persist, and Survive Resets</h2>
                    <p>Live monitoring:</p>
                    <pre class="code-snippet"><code class="language-bash">!nvidia-smi -l 1        # live (Ctrl-C to stop)
!nvidia-smi dmon -s u   # util stream
!which ncu nsys nvprof || echo "no profilers on this runtime"</code></pre>
                    <p>In-code timing (CUDA events / chrono around kernels) beats missing <code>ncu</code> on most Colab runtimes.</p>
                    <p>The filesystem resets. Build in <code>/content</code> (fast), store on Drive (durable):</p>
                    <pre class="code-snippet"><code class="language-python">from google.colab import drive
drive.mount('/content/drive')</code></pre>
                    <pre class="code-snippet"><code class="language-bash">!cp -r /content/drive/MyDrive/&lt;src&gt; /content/work
!df -h /content
!free -h</code></pre>
                    <p>Drive is durable but slow — copy datasets and checkpoints to <code>/content</code> once per session and work there; avoid repeatedly copying multi-GB files in a loop if I/O becomes the bottleneck.</p>
                    <p>Quotas and resets:</p>
                    <pre class="code-snippet"><code class="language-bash">!df -h
!free -h
# Runtime → Disconnect and delete runtime → factory reset when stuck</code></pre>
                    <div class="warning-box">
                        <h3>Expect on Colab</h3>
                        <p>Idle disconnects, runtime limits, and GPU assignment vary. Free-tier notebooks can run for up to 12 hours depending on availability and usage; A100/L4 access is not guaranteed. If files vanished, the runtime recycled — re-clone and restore from Drive.</p>
                    </div>
                </section>

                <section id="brev-search" class="blog-section">
                    <h2>7. Brev: Search for GPUs</h2>
                    <p>Commands below tested with Brev CLI <code>v0.6.335</code> (October 11, 2026). Flags evolve — run <code>brev search --help</code> if a filter or sort key is rejected on your version.</p>
                    <p>GPU instances only. For CPU-only, replace <code>brev search</code> with <code>brev search cpu</code>.</p>
                    <pre class="code-snippet"><code class="language-bash">brev search                    # all GPUs, cheapest first
brev search gpu                # same (explicit)
brev search gpu --wide         # +RAM, ARCH columns
brev search --json | head -n 40</code></pre>
                    <p>Output columns include <code>TYPE | GPU | COUNT | VRAM | TOTAL | $/HR | BOOT | FEATURES</code> (use <code>brev search gpu --wide</code> for extra <code>RAM, ARCH</code> columns; exact columns vary by version — check <code>brev search --help</code>). Features: <code>S</code> = stoppable, <code>R</code> = rebootable, <code>P</code> = flex-ports.</p>
                    <h3>Sort</h3>
                    <pre class="code-snippet"><code class="language-bash">brev search --sort price       # default, cheapest first
brev search --sort vram
brev search --sort total-vram
brev search --sort boot-time   # fastest boot first
brev search --sort gpu-count
brev search --sort vcpu
brev search --sort type
brev search --sort disk
brev search --sort price --desc  # most expensive first</code></pre>
                </section>

                <section id="brev-filter" class="blog-section">
                    <h2>8. Brev: Filter by Model, VRAM, and Provider</h2>
                    <p>Partial, case-insensitive match on GPU name. Models below are examples of what may be available — not guaranteed inventory:</p>
                    <pre class="code-snippet"><code class="language-bash">brev search --gpu-name T4       # budget 16GB
brev search --gpu-name L4       # efficient 24GB
brev search --gpu-name A10G     # balanced 24GB (e.g. g5.xlarge)
brev search --gpu-name A100     # 40/80GB training
brev search --gpu-name H100     # Hopper 80GB
brev search --gpu-name L40S     # 48GB Ada
brev search --gpu-name RTX      # RTX4090 / RTX6000Ada / RTX5090
brev search --gpu-name A4000    # cheap 16GB (e.g. hyperstack_A4000 — price varies, checked Oct 2026)
brev search --gpu-name A6000    # 48GB Ampere</code></pre>
                    <p>Filter by VRAM, provider, disk, boot time, and features. <code>--min-vram</code> is the minimum per GPU; <code>--min-total-vram</code> is the sum across devices (COUNT x VRAM) — not a single unified pool. An 80 GB aggregate does not allow a single 80 GB allocation on one GPU:</p>
                    <pre class="code-snippet"><code class="language-bash">brev search --min-vram 16 --sort price        # per-GPU minimum
brev search --min-vram 24 --sort price
brev search --min-vram 40 --sort price
brev search --min-vram 80 --sort price        # A100-80GB / H100
brev search --min-total-vram 48 --sort price  # COUNT x VRAM (multi-GPU), e.g. 2x24GB
brev search --min-total-vram 160 --sort price # e.g. 2x80GB — per-GPU limits still apply

brev search --provider aws --sort price
brev search --provider gcp --sort price
brev search --gpu-name A100 --provider aws --sort price

brev search --min-disk 500                     # GB
brev search --max-boot-time 3 --sort price     # fast boot
brev search --max-boot-time 5 --sort price
brev search --stoppable --sort price
brev search --rebootable --sort price
brev search --flex-ports --sort price</code></pre>
                    <p>Compute capability reference (same arch table as Section 3, Brev view):</p>
                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Cap</th>
                                <th>Arch</th>
                                <th>GPUs</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td>6.1</td><td>Pascal</td><td>P4 (avoid for new work)</td></tr>
                            <tr><td>7.5</td><td>Turing</td><td>T4</td></tr>
                            <tr><td>8.0</td><td>Ampere</td><td>A100, A10</td></tr>
                            <tr><td>8.6</td><td>Ampere</td><td>A10G, A40, A4000, A6000, RTX30xx</td></tr>
                            <tr><td>8.9</td><td>Ada</td><td>L4, L40/L40S, RTX4090, RTX6000Ada</td></tr>
                            <tr><td>9.0</td><td>Hopper</td><td>H100</td></tr>
                            <tr><td>10.0</td><td>Blackwell DC</td><td>B100/B200</td></tr>
                            <tr><td>12.0</td><td>Blackwell</td><td>RTX 5090</td></tr>
                        </tbody>
                    </table>
                    <pre class="code-snippet"><code class="language-bash">brev search --min-capability 7.5 --sort price  # Turing+
brev search --min-capability 8.0 --sort price  # Ampere+
brev search --min-capability 8.9 --sort price  # Ada+
brev search --min-capability 9.0 --sort price  # Hopper and newer</code></pre>
                </section>

                <section id="brev-recipes" class="blog-section">
                    <h2>9. Brev: Preset Recipes and JSON + jq</h2>
                    <p>Recipes I reuse:</p>
                    <pre class="code-snippet"><code class="language-bash"># dev: fast + cheap
brev search --max-boot-time 3 --sort price | head -10

# ML training: high VRAM
brev search --min-vram 40 --sort price | head -10

# large model: total VRAM
brev search --min-total-vram 80 --sort price | head -10

# production: specific GPU + fast boot
brev search --gpu-name A100 --max-boot-time 5 --sort price

# budget: cheapest usable
brev search --min-vram 16 --sort price | head -5

# Hopper and newer
brev search --min-capability 9.0 --sort price

# stoppable + VRAM (cost-saving training)
brev search --stoppable --min-total-vram 40 --sort price</code></pre>
                    <p>Scriptable search with JSON (field names vary by CLI version — inspect <code>brev search --json | jq '.[0]'</code> first):</p>
                    <pre class="code-snippet"><code class="language-bash">brev search --json | jq '.[0]'
brev search --json | jq -r '.[0] | keys'
# example only — verify keys on v0.6.335 before scripting:
brev search --gpu-name A100 --json | jq -r '.[] | "\(.type) \(.price_per_hour)/hr"'</code></pre>
                </section>

                <section id="brev-create" class="blog-section">
                    <h2>10. Brev: Create Instances Safely</h2>
                    <pre class="code-snippet"><code class="language-bash">brev create my-box                                   # smart defaults (~20GB VRAM, 500GB disk, cap 8.0+, &lt;7m boot)
brev create my-box --type g5.xlarge                  # exact type
brev create my-box --type g5.xlarge,g5.2xlarge       # fallback chain
brev create my-box --gpu-name A100 --min-vram 40     # filters directly on create
brev create my-cluster --count 3 --type g5.xlarge    # multi (confirm first: cost x3)
brev create my-box --startup-script @setup.sh        # local file, @ prefix
brev create my-box --startup-script 'pip install torch'
brev create my-box --dry-run                         # preview match, no cost — always run first, then still check hourly price + disk
brev search --gpu-name A100 | brev create my-box     # pipe search -&gt; create
brev search cpu --min-ram 64 | brev create my-cpu-box</code></pre>
                    <div class="warning-box">
                        <h3>Safety before create</h3>
                        <p>Confirm first: <code>delete</code>, <code>stop</code>, <code>--count &gt;1</code>, H100 / multi-GPU create (expensive). Always: <code>--dry-run</code> before create, then verify the actual hourly price and disk configuration in the search output — dry-run does not replace that check. Preview <code>brev ls | awk ...</code> before piping to stop/delete, show cost/type before create. Stopped instances may still accrue storage charges.</p>
                    </div>
                </section>

                <section id="brev-use" class="blog-section">
                    <h2>11. Brev: Daily Use — Shell, Copy, Ports, List</h2>
                    <h3>Shell and exec</h3>
                    <pre class="code-snippet"><code class="language-bash">brev shell my-box                      # interactive SSH
brev exec my-box "nvidia-smi"          # one-shot command
brev exec my-box @setup.sh             # run local script remotely
brev exec box1 box2 box3 "nvidia-smi"  # multi-instance</code></pre>
                    <h3>Open in editor</h3>
                    <pre class="code-snippet"><code class="language-bash">brev open my-box          # default editor
brev open my-box code     # VS Code
brev open my-box cursor
brev open my-box windsurf
brev open my-box tmux
brev open --set-default cursor</code></pre>
                    <h3>Copy files</h3>
                    <pre class="code-snippet"><code class="language-bash">brev copy ./train.py my-box:/home/ubuntu/
brev copy my-box:/home/ubuntu/ckpt/ ./ckpt/</code></pre>
                    <h3>Port-forward (simple)</h3>
                    <pre class="code-snippet"><code class="language-bash">brev port-forward my-box -p 8888:8888  # jupyter (-p / --port, same flag on v0.6.335)
brev port-forward my-box -p 8000:8000</code></pre>
                    <h3>Managed ports (needs <code>P</code> / flex-ports)</h3>
                    <pre class="code-snippet"><code class="language-bash">brev ports ls my-box
brev ports ls my-box --json
brev ports get nport-abc123
brev ports open my-box 8080
brev ports open my-box 8000-8031
brev ports open my-box 3000 --protocol http --public
brev ports open my-box 8888 --protocol http --authorize me@example.com
brev ports open my-box 53 --protocol udp --allow 203.0.113.10/32
brev ports update nport-abc123 --destination-port 8081
brev ports update nport-abc123 --public
brev ports remove my-box 8080
brev ports rm nport-abc123</code></pre>
                    <div class="warning-box">
                        <h3>Public ports are public</h3>
                        <p>Managed ports with <code>--public</code> can expose services to the internet. Avoid publishing unauthenticated Jupyter servers or dev endpoints — prefer <code>--authorize me@example.com</code> or IP allow-lists, and close ports when done.</p>
                    </div>
                    <h3>List / manage</h3>
                    <p><code>brev ls</code> = cloud instances only. <code>brev ls nodes</code> = Brev Connect machines only (never in <code>brev ls</code>).</p>
                    <pre class="code-snippet"><code class="language-bash">brev ls
brev ls instances
brev ls nodes
brev ls orgs
brev ls --json | jq -r '.workspaces[].name'
brev ls nodes --json | jq -r '.[].name'
brev ls nodes --json | jq -r '.[] | select(.status=="Connected") | .name'

brev stop my-box
brev start my-box
brev delete my-box
brev reset my-box        # recover from errors
brev stop --all          # all running (confirm first)</code></pre>
                    <p>Bulk (preview before destructive):</p>
                    <pre class="code-snippet"><code class="language-bash">brev ls | awk '/RUNNING/ {print $1}'              # preview
brev ls | awk '/RUNNING/ {print $1}' | brev stop
brev ls | awk '/STOPPED/ {print $1}' | brev delete
brev ls | awk '/STOPPED/ {print $1}' | brev start
brev ls | grep "test-" | awk '{print $1}' | brev stop
brev ls | awk '/RUNNING/ {print $1}' | brev exec "nvidia-smi"
brev search --gpu-name A100 | brev create my-box | brev open cursor
brev create my-box | brev exec @setup.sh</code></pre>
                    <p>Orgs:</p>
                    <pre class="code-snippet"><code class="language-bash">brev org ls
brev org set my-org   # alias: brev set my-org
brev invite</code></pre>
                    <p>Once the box is up, the Colab checks from Section 2 apply verbatim — <code>nvidia-smi</code>, compute-cap query, and the CMake arch flag for whatever GPU Brev gave you.</p>
                </section>

                <section id="troubleshoot" class="blog-section">
                    <h2>12. Troubleshooting Both</h2>
                    <h3>Colab</h3>
                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Symptom</th>
                                <th>Fix</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td><code>CUDA unknown / no GPU</code></td><td>Runtime → GPU type set? <code>!nvidia-smi</code> must list a GPU first</td></tr>
                            <tr><td><code>no kernel image available</code></td><td>CUDA-arch mismatch — rebuild with Section 3 flag for this GPU</td></tr>
                            <tr><td><code>CUDA error / toolkit-driver mismatch</code></td><td><code>nvcc --version</code> vs driver in <code>nvidia-smi</code> — align toolkit/channel, reinstall wheel if needed</td></tr>
                            <tr><td><code>illegal memory access / illegal instruction</code></td><td>Separate bug class — check indices/bounds, UVM, arch flag; do not assume arch fix alone</td></tr>
                            <tr><td><code>CUDA out of memory</code></td><td>Smaller batch, release tensors, <code>empty_cache()</code> (cached-only), restart runtime</td></tr>
                            <tr><td><code>nvcc</code> missing</td><td>Normal on CPU runtime — switch to GPU runtime</td></tr>
                            <tr><td><code>cmake</code> old/missing</td><td><code>apt-get install -y cmake</code>, need 3.24+ for <code>native</code> (3.20+ minimum for most CUDA projects otherwise)</td></tr>
                            <tr><td>Build killed mid-way</td><td><code>-j$(nproc)</code> too parallel for RAM — try <code>-j2</code>; keep tab active</td></tr>
                            <tr><td>Profilers absent</td><td><code>which ncu</code> check; fall back to in-app timing</td></tr>
                            <tr><td>Files vanished</td><td>Runtime recycled — re-clone, use Drive for durable storage</td></tr>
                        </tbody>
                    </table>
                    <h3>Brev</h3>
                    <pre class="code-snippet"><code class="language-bash">brev ls                # does it exist? RUNNING?
brev ls nodes          # Connect machines live here, not in brev ls
brev org ls            # wrong org?
brev refresh           # fix SSH config
brev healthcheck
which code cursor      # editor in PATH?
brev feedback "what failed, what you expected"  # no secrets</code></pre>
                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Symptom</th>
                                <th>Fix</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td>Instance not found</td><td><code>brev ls</code> + <code>brev ls nodes</code> + <code>brev org ls</code></td></tr>
                            <tr><td>Create fails</td><td>Try another type: <code>brev search --sort price</code>; check quota</td></tr>
                            <tr><td>SSH fails</td><td><code>brev refresh</code>, instance must be RUNNING</td></tr>
                            <tr><td>Editor won't open</td><td><code>which code</code>, <code>brev open --set-default code</code></td></tr>
                        </tbody>
                    </table>
                </section>

                <section id="checklist" class="blog-section">
                    <h2>13. Cross-Environment Reproducibility Checklist</h2>
                    <p>The move from Colab to Brev only pays off if the same project builds and behaves consistently in both. Run this before scaling:</p>
                    <ul>
                        <li>Record GPU model, compute capability (<code>nvidia-smi --query-gpu=compute_cap</code>), driver (<code>nvidia-smi</code>), and CUDA toolkit (<code>nvcc --version</code>).</li>
                        <li>Pin compiler, CMake (3.24+ for <code>native</code>), and Python deps (<code>pip freeze</code>).</li>
                        <li>Keep build configuration and architecture selection in a script or CMake preset — not a pasted shell line.</li>
                        <li>Run the same correctness tests on both environments.</li>
                        <li>Benchmark with warm-up iterations and CUDA events or another appropriate GPU timing method.</li>
                        <li>Save test outputs, benchmark results, and checkpoints outside ephemeral storage (Drive on Colab, persistent disk/snapshot on Brev).</li>
                    </ul>
                </section>

                <section id="conclusion" class="blog-section">
                    <h2>Conclusion</h2>
                    <p>Colab minimizes setup friction; Brev provides a more persistent environment with configurable GPU resources. The useful skill is knowing when to move between them — and how to keep builds, tests, and benchmarks reproducible across both.</p>
                    <p>Identify the GPU, select an appropriate CUDA architecture, pin the environment, validate correctness, and measure performance before scaling up. Treat cloud costs and persistent storage as part of the engineering workflow, not an afterthought.</p>
                    <p>For production-oriented CUDA development, pair this cheatsheet with the <a href="https://olibartfast.ninja/blog/cmake-cuda-architectures-guide.html">CMake CUDA architecture guide</a> to understand native builds, explicit architecture targets, and portable deployment.</p>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>The AI Engineering Skills Map, Read from the Systems Side</title>
      <link>https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html</guid>
      <pubDate>Mon, 14 Sep 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A condensed pass through Andrew Ng's four-skill map, then the part that interests me more — what each skill looks like when the product is a GPU pipeline on a fixed power budget rather than an LLM web app.</description>
      <content:encoded><![CDATA[<p>Consider a detector that passes its accuracy checks but starts missing frame deadlines after the device heats up. The model may be good enough; the product still needs work. That is the perspective I bring to Andrew Ng’s <a href="https://www.deeplearning.ai/the-batch/the-ai-engineering-skills-map">AI Engineering Skills Map</a>: what do its four skills require when you ship a perception pipeline on a fixed compute and power budget?</p>

                <p>Ng published the five-part series in <em>The Batch</em> between August 14 and September 11, 2026. DeepLearning.AI reports drawing on more than 10,000 job postings, structured interviews, surveys and other online data. That gives the map a useful basis. The first letter describes an informal clustering process and gives no breakdown by specialism, so I read it as a broad synthesis rather than a measure of demand for embedded or systems roles. Its scope is skills that developers can use across roles, rather than a definition of one job title.</p>

                <p>Below is a compact reference to the four skills and their twenty sub-skills, followed by my systems interpretation. The practical question is what evidence each skill should produce: an evaluation dataset, a resource budget, a verifiable change, or a product decision with explicit tradeoffs.</p>

                <div class="note-box">
                    <h3>Summary in one line</h3>
                    <p>My reading: the useful skills connect what we choose to build with evidence that it works under the conditions where it will run.</p>
                </div>

                <div class="table-of-contents">
                    <h3>Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html#the-map">1. The Map at a Glance</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html#applications">2. Building and Deploying AI Applications</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html#fundamentals">3. Software Engineering Fundamentals</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html#agents">4. Using Coding Agents</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html#shaping">5. Shaping the Build</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html#systems-side">6. The Same Map, Read from the Systems Side</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html#audit">7. Use It as an Audit, Not a Reading List</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-engineering-skills-map-systems-view.html#conclusion">Conclusion</a></li>
                    </ul>
                </div>

                <section id="the-map" class="blog-section">
                    <h2>1. The Map at a Glance</h2>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Skill</th>
                                <th>The claim</th>
                                <th>Sub-skills</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Building and deploying AI applications</td>
                                <td>Getting reliable systems out of unreliable components</td>
                                <td>6</td>
                            </tr>
                            <tr>
                                <td>Software engineering fundamentals</td>
                                <td>Knowing which tradeoffs exist so you can steer them</td>
                                <td>5</td>
                            </tr>
                            <tr>
                                <td>Using coding agents</td>
                                <td>Directing, bounding and verifying agent work</td>
                                <td>5</td>
                            </tr>
                            <tr>
                                <td>Shaping the build</td>
                                <td>Deciding what goes in the spec, not just implementing it</td>
                                <td>4</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>I use the table’s middle column as my own shorthand. The map connects implementation with specification, verification and product judgment; continuous learning runs through all four areas.</p>
                </section>

                <section id="applications" class="blog-section">
                    <h2>2. Building and Deploying AI Applications</h2>
                    <!-- Publisher canonical URL verified 2026-09-14: the slug starts with he-ai. -->
                    <p>Sub-skills from <a href="https://www.deeplearning.ai/the-batch/he-ai-engineering-skills-map-in-detail-building-and-deploying-ai-applications">Ng’s letter</a>, briefly paraphrased:</p>
                    <ul>
                        <li><strong>LLM foundations</strong> — Understand tokenisation, context limits, caching and tool calling well enough to choose models and diagnose failures.</li>
                        <li><strong>Grounding models with data</strong> — Choose retrieval and representations — vector indexes, knowledge graphs or structured-data layers — and keep inputs fresh.</li>
                        <li><strong>Building agentic systems</strong> — Choose workflow structure, tools and memory; account for adversarial inputs and data-exfiltration risks.</li>
                        <li><strong>Evaluation-driven development</strong> — Use error analysis to decide the next useful experiment.</li>
                        <li><strong>Operating in production</strong> — Track drift and failures on real traffic, maintain regression checks, and manage cost and latency.</li>
                        <li><strong>Machine learning foundations</strong> — Understand learning methods, data requirements and model tradeoffs.</li>
                    </ul>
                    <p>Ng explicitly includes code-based evaluations, model judges and human review. The emphasis is choosing and checking the evaluation method that fits the task, rather than adopting one universal toolkit.</p>
                </section>

                <section id="fundamentals" class="blog-section">
                    <h2>3. Software Engineering Fundamentals</h2>
                    <p>Sub-skills from <a href="https://www.deeplearning.ai/the-batch/the-ai-engineering-skills-map-in-detail-software-engineering-fundamentals">Ng’s letter</a>, briefly paraphrased:</p>
                    <ul>
                        <li><strong>Building full-stack applications</strong> — Understand UI rendering, APIs, authentication, asynchronous processing and persistence around the AI capability.</li>
                        <li><strong>Managing data</strong> — Choose storage around access patterns; understand transactions, concurrency and data integrity.</li>
                        <li><strong>Designing system architectures</strong> — Choose service boundaries, state placement and dependencies to fit the project’s stage.</li>
                        <li><strong>Making systems secure and reliable</strong> — Design tests, failure handling and security into development.</li>
                        <li><strong>Scaling and operating in production</strong> — Use release automation, observability and incident response; adapt infrastructure to measured load.</li>
                    </ul>
                    <p>The useful lesson for me is that delegating implementation still requires enough understanding to recognise the decisions being delegated. A working result can conceal an unsuitable tradeoff. Knowing the syntax is less useful than knowing why the system is slow, fragile or expensive.</p>
                </section>

                <section id="agents" class="blog-section">
                    <h2>4. Using Coding Agents</h2>
                    <p>Sub-skills from <a href="https://www.deeplearning.ai/the-batch/the-ai-engineering-skills-map-in-detail-using-coding-agents">Ng’s letter</a>, briefly paraphrased:</p>
                    <ul>
                        <li><strong>Directing the workflow</strong> — Balance planning, implementation and review effort; divide work into verifiable steps.</li>
                        <li><strong>Enabling agent autonomy</strong> — Choose delegation boundaries and permissions; carry changed assumptions forward in context.</li>
                        <li><strong>Reviewing the work</strong> — Check outputs and whether the tests establish the intended result.</li>
                        <li><strong>Customising the agent and its environment</strong> — Maintain project instructions, tools, hooks and shared conventions; prune obsolete context.</li>
                        <li><strong>Coding agent foundations</strong> — Understand retrieval, context limits and the harness; recognise overengineering and missing verification.</li>
                    </ul>
                    <p>The letter groups the workflow into planning; execution, including testing and verification; and deployment and monitoring, with feedback between them. It also cautions against equating long autonomous runs with useful output: intervention and cost still matter.</p>
                </section>

                <section id="shaping" class="blog-section">
                    <h2>5. Shaping the Build</h2>
                    <p>Sub-skills from <a href="https://www.deeplearning.ai/the-batch/the-ai-engineering-skills-map-in-detail-shaping-the-build">Ng’s letter</a>, briefly paraphrased:</p>
                    <ul>
                        <li><strong>Driving the build loop</strong> — Decide whether the next step needs an experiment, user feedback or implementation.</li>
                        <li><strong>Making product decisions</strong> — Connect requirements with user needs and economic constraints.</li>
                        <li><strong>Communicating and leading</strong> — Coordinate stakeholders and explain technical possibilities and limits.</li>
                        <li><strong>High-agency ownership</strong> — Identify worthwhile problems and take responsibility for outcomes.</li>
                    </ul>
                    <p>Ng describes developers taking on parts of specification and product work, while PMs and designers increasingly participate in building. I read this as an invitation to make engineering judgment visible earlier. A developer can help define the problem and the acceptance criteria while working within the team’s priorities.</p>
                </section>

                <section id="systems-side" class="blog-section">
                    <h2>6. The Same Map, Read from the Systems Side</h2>

                    <p>On a single-device perception pipeline, these skills meet a fixed resource budget and physical operating conditions. Here is where I would put the engineering effort: timing guarantees, representative datasets, hardware-aware verification and early feasibility decisions.</p>

                    <h3>Unpredictability has a second axis</h3>

                    <p>In a real-time pipeline, timing can also be part of correctness: a prediction arriving after its consumer’s deadline may no longer be useful. Measure end-to-end latency and deadline misses under representative load, including sustained operation after warm-up. Percentiles such as p99 help describe observed behaviour, but do not establish a hard worst-case bound. The specification must say whether occasional misses are acceptable and what the system does when they occur.</p>

                    <h3>Evals without a judge model</h3>

                    <p>For detection or pose estimation, my starting point would be labelled data, task-specific metrics, slice-based error analysis, and a curated regression set: low-light frames, occlusions, and unusual camera angles. A model judge cannot replace geometric or numerical correctness checks. The discipline transfers directly; much of the work is choosing representative cases and maintaining trustworthy labels.</p>

                    <h3>Operating within a fixed compute budget</h3>

                    <p>For a single edge device with a fixed power and compute budget, adding servers does not solve the local frame deadline. The relevant choices include model size, precision, operator fusion, buffer reuse and scheduling less important work less often. Batching may improve throughput while increasing waiting time, so it needs an end-to-end check. A fleet still needs deployment, observability and capacity planning; local optimisation is one part of operating it.</p>

                    <h3>Data management includes the dataset</h3>

                    <p>For a perception system, data management includes dataset versions, class balance, labelling protocols, capture provenance and sensor calibration. Calibration changes must be recorded so comparisons between captures remain meaningful. Gaps here can produce a model that fails silently in a condition nobody captured. Runtime data still matters too: frame timestamps, buffer ownership and telemetry determine whether the pipeline processes the right inputs and leaves enough evidence to diagnose a failure.</p>

                    <h3>Make systems changes verifiable</h3>

                    <p>For a generated CUDA kernel, the evidence should include numerical comparison against an independent reference, checks for memory and synchronisation errors, and performance measurements on the target hardware. Compared with a straightforward UI change, this can require more specialised infrastructure. The scope of the claim matters: passing on one GPU does not establish correctness or performance on every supported architecture.</p>

                    <div class="note-box">
                        <h3>Example: accepting a preprocessing kernel change</h3>
                        <p>Suppose an agent fuses image resizing and normalisation into one kernel. Before implementation, specify channel order, resize coordinates, input layouts and numerical tolerances. Compare against an independent reference using odd image dimensions, padded rows and boundary pixel values. Run memory and synchronisation checks, then measure the full pipeline on the target device under sustained load.</p>
                        <p>Accept the patch only if it meets those checks and the agreed latency and memory budgets. Faster kernel timing alone is insufficient if transfers or queueing make the complete pipeline slower. These are illustrative acceptance criteria, not results from a benchmark.</p>
                    </div>

                    <h3>Hardware choices belong in the specification</h3>

                    <p>In embedded and robotics work, product decisions include the compute module, sensor, thermal design and power budget. These choices constrain the software and become more expensive to revise as board design and manufacturing progress. Engineers should make the consequences visible early: which accuracy and timing targets fit the proposed hardware, what remains uncertain, and which prototype would reduce that uncertainty before committing.</p>

                    <p>The two areas I would prioritise for this kind of work are evaluation-driven development and managing data. Together, they make it possible to distinguish a promising demonstration from a system that meets its intended operating conditions.</p>
                </section>

                <section id="audit" class="blog-section">
                    <h2>7. Use It as an Audit, Not a Reading List</h2>

                    <p>Use the four categories to review a recent project. Assess your judgment through evidence, rather than inferring strengths from your job title:</p>

                    <ul>
                        <li><strong>AI applications:</strong> Can you show a versioned evaluation set and an error analysis that changed your next experiment?</li>
                        <li><strong>Fundamentals:</strong> Can you show a resource budget or architecture decision with alternatives and measured consequences?</li>
                        <li><strong>Coding agents:</strong> Can you show an accepted patch, its independent checks, and a defect those checks caught?</li>
                        <li><strong>Shaping the build:</strong> Can you show a requirement changed by user feedback or a hardware feasibility experiment?</li>
                    </ul>
                    <p>Pick one weak area and one real project. Define the missing evidence before starting, then review whether it improved a decision or exposed a failure. That gives the next learning step a concrete purpose.</p>
                </section>

                <section id="conclusion" class="blog-section">
                    <h2>Conclusion</h2>

                    <p>For a systems engineer, this map is useful when each skill leads to something inspectable: requirements that name the operating conditions, data that covers them, and verification that tests the complete pipeline. Coding agents can help produce and use those artifacts, but someone still has to decide whether they answer the right question.</p>

                    <p>The detector from the opening needs more than an accuracy pass. It needs evidence that predictions arrive in time after the device heats up, and a defined response when they do not. Connecting that evidence to the product requirement is the engineering work I would use this map to strengthen.</p>

                    <div class="note-box">
                        <h3>Sources</h3>
                        <p>All five letters by Andrew Ng, published in <em>The Batch</em> by DeepLearning.AI. The summary above is a paraphrase and a personal reading, not a substitute for the originals.</p>
                        <ul>
                            <li>Part 1 — <a href="https://www.deeplearning.ai/the-batch/the-ai-engineering-skills-map">The AI Engineering Skills Map</a> (August 14, 2026)</li>
                            <li>Part 2 — <a href="https://www.deeplearning.ai/the-batch/he-ai-engineering-skills-map-in-detail-building-and-deploying-ai-applications">Building and Deploying AI Applications</a> (August 21, 2026)</li>
                            <li>Part 3 — <a href="https://www.deeplearning.ai/the-batch/the-ai-engineering-skills-map-in-detail-software-engineering-fundamentals">Software Engineering Fundamentals</a> (August 28, 2026)</li>
                            <li>Part 4 — <a href="https://www.deeplearning.ai/the-batch/the-ai-engineering-skills-map-in-detail-using-coding-agents">Using Coding Agents</a> (September 4, 2026)</li>
                            <li>Part 5 — <a href="https://www.deeplearning.ai/the-batch/the-ai-engineering-skills-map-in-detail-shaping-the-build">Shaping the Build</a> (September 11, 2026)</li>
                        </ul>
                        <p>DeepLearning.AI is collecting community input to keep the map current through a survey linked from the first letter.</p>
                    </div>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>Cutting a Release by Hand: Gitflow with Plain Git</title>
      <link>https://olibartfast.ninja/blog/manual-gitflow-release-process.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/manual-gitflow-release-process.html</guid>
      <pubDate>Sun, 30 Aug 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>The manual git commands behind a Gitflow release — branch model, tagging, the merge back into develop everyone forgets, a checklist, and how to recover when a step is missed.</description>
      <content:encoded><![CDATA[<p>The <a href="https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow">Gitflow workflow</a> is usually presented through the <code>git-flow</code> CLI extension, which is fine until the day it is not installed, or the release has to happen from a CI runner, or something goes wrong halfway through and you need to know which of the six things <code>release finish</code> does had already happened.</p>

                <p>Every step below is raw <code>git</code>. No extension required. The <code>git flow</code> equivalents are in <a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#appendix-a">Appendix A</a> for anyone who does have it installed and just wants to know what it wraps.</p>

                <p>Two details account for most of the release bugs I have seen, so they are worth stating before the mechanics:</p>

                <ul>
                    <li>A release branch merges into <strong>both</strong> <code>main</code> and <code>develop</code>. Skipping the second merge silently loses the version bump and every stabilisation fix.</li>
                    <li>The tag <em>is</em> the release. Everything else — the branch, the merge commit, the changelog — is bookkeeping around a single annotated tag on <code>main</code>.</li>
                </ul>

                <div class="table-of-contents">
                    <h3>Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#branch-model">1. The Branch Model</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#setup">2. One-Time Repository Setup</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#release">3. Cutting a Release</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#hotfix">4. Hotfix Releases</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#features">5. Feature Branches, for Context</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#versioning">6. Versioning</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#checklist">7. The Release Checklist</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#recovery">8. Recovering from Mistakes</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#appendix-a">Appendix A — <code>git flow</code> CLI Equivalents</a></li>
                        <li><a href="https://olibartfast.ninja/blog/manual-gitflow-release-process.html#appendix-b">Appendix B — Quick Reference</a></li>
                    </ul>
                </div>

                <section id="branch-model" class="blog-section">
                    <h2>1. The Branch Model</h2>

                    <p>Five kinds of branch, two of which live forever:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Branch</th>
                                <th>Lives</th>
                                <th>Branches from</th>
                                <th>Merges into</th>
                                <th>Purpose</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><code>main</code></td>
                                <td>forever</td>
                                <td>—</td>
                                <td>—</td>
                                <td>Official release history. Every commit is a tagged release.</td>
                            </tr>
                            <tr>
                                <td><code>develop</code></td>
                                <td>forever</td>
                                <td><code>main</code> (once)</td>
                                <td>—</td>
                                <td>Integration branch. Holds the complete history of features.</td>
                            </tr>
                            <tr>
                                <td><code>feature/*</code></td>
                                <td>temporary</td>
                                <td><code>develop</code></td>
                                <td><code>develop</code></td>
                                <td>One new capability. Never touches <code>main</code>.</td>
                            </tr>
                            <tr>
                                <td><code>release/*</code></td>
                                <td>temporary</td>
                                <td><code>develop</code></td>
                                <td><code>main</code> <strong>and</strong> <code>develop</code></td>
                                <td>Stabilise and bump the version. No new features.</td>
                            </tr>
                            <tr>
                                <td><code>hotfix/*</code></td>
                                <td>temporary</td>
                                <td><code>main</code></td>
                                <td><code>main</code> <strong>and</strong> <code>develop</code></td>
                                <td>Urgent fix against production.</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>The rules that actually matter:</p>

                    <ul>
                        <li><strong><code>main</code> only ever receives merges from <code>release/*</code> and <code>hotfix/*</code>.</strong> Never merge <code>develop</code> or a feature branch directly into <code>main</code>.</li>
                        <li><strong>Every commit on <code>main</code> gets a version tag.</strong></li>
                        <li><strong>A release branch merges into both long-lived branches</strong>, so the version bump and any stabilisation fixes survive.</li>
                        <li>Once a release branch exists, <code>develop</code> is free again — the next cycle's features can land there while the release is being polished.</li>
                    </ul>

                    <div class="branch-diagram">main     ──●────────────────────●───────────●──   (tags: v1.0.0, v1.1.0, v1.1.1)
            \                  /           /
release      \        ●──●──●─/           /       release/1.1.0
              \      /        \          /
develop  ──●───●────●──────────●────●───●─────    (release fixes merged back)
            \     /                 \
feature      ●──●                    ●──●         feature/…</div>

                    <p>That fork-and-rejoin shape on the release branch is the whole workflow in one picture. The branch leaves <code>develop</code>, collects the version bump and whatever the QA pass turns up, lands on <code>main</code> as a single revertable node, and then comes back down into <code>develop</code>.</p>
                </section>

                <section id="setup" class="blog-section">
                    <h2>2. One-Time Repository Setup</h2>

                    <p>Only needed if <code>develop</code> does not exist yet.</p>

                    <pre class="code-snippet"><code>git clone &lt;repo-url&gt;
cd &lt;repo&gt;

# Create develop off main and publish it
git checkout main
git pull origin main
git checkout -b develop
git push -u origin develop</code></pre>

                    <p>Optionally make <code>develop</code> the default branch on the host (GitHub, GitLab, Bitbucket) so pull requests target it automatically, and protect both long-lived branches.</p>
                </section>

                <section id="release" class="blog-section">
                    <h2>3. Cutting a Release</h2>

                    <p>Assume the next version is <code>1.1.0</code>. Substitute your own version everywhere.</p>

                    <h3>3.1 Make sure <code>develop</code> is what you want to ship</h3>

                    <pre class="code-snippet"><code>git checkout develop
git pull origin develop
git log --oneline main..develop      # review exactly what is going out</code></pre>

                    <p>Everything intended for this release must already be merged into <code>develop</code>. Anything not merged yet <strong>waits for the next release</strong> — do not add features once the release branch is cut. That single rule is what makes the release branch stabilise instead of drifting.</p>

                    <h3>3.2 Create the release branch</h3>

                    <pre class="code-snippet"><code>git checkout -b release/1.1.0 develop
git push -u origin release/1.1.0</code></pre>

                    <p>From this moment <code>develop</code> is open for the <em>next</em> cycle's work.</p>

                    <h3>3.3 Prepare the release on the branch</h3>

                    <p>Only release-preparation commits belong here: version bumps, changelog, docs, and bug fixes found during testing. <strong>No new features.</strong></p>

                    <pre class="code-snippet"><code># 1. Bump the version in whatever file holds it, e.g.:
#      package.json / pyproject.toml / Cargo.toml / VERSION / CMakeLists.txt
$EDITOR VERSION

# 2. Update the changelog
$EDITOR CHANGELOG.md

git add -A
git commit -m "Bump version to 1.1.0"
git push</code></pre>

                    <p>Then run the full test suite, build and QA against this branch. Fix problems by committing <strong>on the release branch</strong>:</p>

                    <pre class="code-snippet"><code>git checkout release/1.1.0
$EDITOR src/thing.c
git commit -am "Fix off-by-one in thing parser"
git push</code></pre>

                    <h3>3.4 Merge the release into <code>main</code> and tag it</h3>

                    <pre class="code-snippet"><code>git checkout main
git pull origin main
git merge --no-ff release/1.1.0 -m "Release 1.1.0"</code></pre>

                    <p><code>--no-ff</code> is deliberate: it keeps an explicit merge commit, so the release is a single, revertable node in <code>main</code>'s history rather than a run of commits you would have to unpick individually.</p>

                    <p>Tag the merge commit — this is the release artefact:</p>

                    <pre class="code-snippet"><code>git tag -a v1.1.0 -m "Release 1.1.0"
git push origin main
git push origin v1.1.0</code></pre>

                    <div class="note-box">
                        <h3>Use annotated tags</h3>
                        <p>Use an annotated (<code>-a</code>) or signed (<code>-s</code>) tag, not a lightweight one. Annotated tags carry the tagger, date and message, and are what <code>git describe</code> picks up — which is usually what ends up embedded in a build as its version string.</p>
                    </div>

                    <h3>3.5 Merge the release back into <code>develop</code></h3>

                    <p>This is the step people forget. Without it, the version bump and any fixes made during stabilisation exist only on <code>main</code>, and will be clobbered by the next release.</p>

                    <pre class="code-snippet"><code>git checkout develop
git pull origin develop
git merge --no-ff release/1.1.0 -m "Merge release 1.1.0 back into develop"
git push origin develop</code></pre>

                    <p>If this conflicts — usually only on the version file — resolve in favour of the release branch's content, then continue:</p>

                    <pre class="code-snippet"><code>git status                 # see conflicted files
$EDITOR &lt;conflicted-file&gt;
git add &lt;conflicted-file&gt;
git commit                 # accept the default merge message
git push origin develop</code></pre>

                    <h3>3.6 Delete the release branch</h3>

                    <pre class="code-snippet"><code>git branch -d release/1.1.0
git push origin --delete release/1.1.0</code></pre>

                    <h3>3.7 Verify</h3>

                    <pre class="code-snippet"><code>git checkout main
git log --oneline -3
git describe --tags        # should print v1.1.0
git log --oneline main..develop   # release commits should NOT appear here</code></pre>

                    <p>That last command is the cheap check on step 3.5. If the release commits still show up as "on develop but not on main", the merge back did not happen.</p>
                </section>

                <section id="hotfix" class="blog-section">
                    <h2>4. Hotfix Releases</h2>

                    <p>A hotfix branches off <code>main</code>, not <code>develop</code>, so an urgent fix ships without dragging in unreleased work. Assume production is <code>v1.1.0</code> and the fix is <code>1.1.1</code>.</p>

                    <pre class="code-snippet"><code># 1. Branch from main
git checkout main
git pull origin main
git checkout -b hotfix/1.1.1
git push -u origin hotfix/1.1.1

# 2. Fix the bug and bump the patch version
$EDITOR src/broken.c
$EDITOR VERSION CHANGELOG.md
git commit -am "Fix crash on empty config; bump version to 1.1.1"
git push

# 3. Merge into main and tag
git checkout main
git merge --no-ff hotfix/1.1.1 -m "Hotfix 1.1.1"
git tag -a v1.1.1 -m "Hotfix 1.1.1"
git push origin main
git push origin v1.1.1

# 4. Merge into develop as well, so the fix is not lost
git checkout develop
git pull origin develop
git merge --no-ff hotfix/1.1.1 -m "Merge hotfix 1.1.1 into develop"
git push origin develop

# 5. Clean up
git branch -d hotfix/1.1.1
git push origin --delete hotfix/1.1.1</code></pre>

                    <div class="warning-box">
                        <h3>Exception: an open release branch</h3>
                        <p>If a release branch is currently open, merge the hotfix into the <strong>release branch</strong> instead of <code>develop</code>. The release branch will carry the fix into <code>develop</code> when it is merged back in step 3.5. Merging into both produces a duplicated fix and a conflict later.</p>
                    </div>
                </section>

                <section id="features" class="blog-section">
                    <h2>5. Feature Branches, for Context</h2>

                    <p>Features never interact with a release directly; they land in <code>develop</code> first.</p>

                    <pre class="code-snippet"><code>git checkout develop
git pull origin develop
git checkout -b feature/user-avatars
# ...commit work...
git push -u origin feature/user-avatars

# When approved (via PR, or locally):
git checkout develop
git pull origin develop
git merge --no-ff feature/user-avatars
git push origin develop
git branch -d feature/user-avatars
git push origin --delete feature/user-avatars</code></pre>
                </section>

                <section id="versioning" class="blog-section">
                    <h2>6. Versioning</h2>

                    <p>Use <a href="https://semver.org/">Semantic Versioning</a> — <code>MAJOR.MINOR.PATCH</code>:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Component</th>
                                <th>Means</th>
                                <th>Usually ships via</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong>MAJOR</strong></td>
                                <td>Incompatible API changes</td>
                                <td><code>release/*</code></td>
                            </tr>
                            <tr>
                                <td><strong>MINOR</strong></td>
                                <td>Backwards-compatible functionality</td>
                                <td><code>release/*</code></td>
                            </tr>
                            <tr>
                                <td><strong>PATCH</strong></td>
                                <td>Backwards-compatible bug fixes</td>
                                <td><code>hotfix/*</code></td>
                            </tr>
                        </tbody>
                    </table>

                    <p>Tags are prefixed with <code>v</code> (<code>v1.1.0</code>); branches are not (<code>release/1.1.0</code>). Worth being consistent about, because <code>git describe</code> output and release-note tooling both key off the tag name.</p>
                </section>

                <section id="checklist" class="blog-section">
                    <h2>7. The Release Checklist</h2>

                    <p>Copy this into the release ticket or PR description.</p>

                    <ul class="checklist">
                        <li>Everything intended for the release is merged into <code>develop</code></li>
                        <li><code>git log --oneline main..develop</code> reviewed</li>
                        <li><code>release/X.Y.Z</code> created from <code>develop</code> and pushed</li>
                        <li>Version bumped in all version-bearing files</li>
                        <li><code>CHANGELOG.md</code> updated</li>
                        <li>Full test suite green on the release branch</li>
                        <li>Build and packaging verified from the release branch</li>
                        <li>Merged into <code>main</code> with <code>--no-ff</code></li>
                        <li>Annotated tag <code>vX.Y.Z</code> created <strong>and pushed</strong> (<code>git push origin vX.Y.Z</code>)</li>
                        <li>Merged back into <code>develop</code> with <code>--no-ff</code></li>
                        <li>Release branch deleted locally and on the remote</li>
                        <li>Release notes published on the host, from the tag</li>
                        <li>Artifacts published — registry, images, binaries — if applicable</li>
                    </ul>
                </section>

                <section id="recovery" class="blog-section">
                    <h2>8. Recovering from Mistakes</h2>

                    <h3>Forgot to merge back into <code>develop</code></h3>

                    <p>Just do it now. The release branch may already be deleted, so merge the tag instead:</p>

                    <pre class="code-snippet"><code>git checkout develop
git merge --no-ff v1.1.0
git push origin develop</code></pre>

                    <h3>Tagged the wrong commit, tag not yet pushed</h3>

                    <pre class="code-snippet"><code>git tag -d v1.1.0
git tag -a v1.1.0 -m "Release 1.1.0" &lt;correct-sha&gt;</code></pre>

                    <h3>Tagged the wrong commit, tag already pushed</h3>

                    <p>Prefer cutting <code>v1.1.1</code> over moving a published tag; anyone who already fetched the old tag keeps it, and no amount of remote surgery changes that. If you must:</p>

                    <pre class="code-snippet"><code>git push origin :refs/tags/v1.1.0     # delete remote tag
git tag -d v1.1.0
git tag -a v1.1.0 -m "Release 1.1.0" &lt;correct-sha&gt;
git push origin v1.1.0
# then tell everyone to run: git fetch --tags --force</code></pre>

                    <h3>Bad release merged into <code>main</code></h3>

                    <p>Revert the merge commit, which keeps history honest, then fix forward on a new hotfix branch:</p>

                    <pre class="code-snippet"><code>git checkout main
git revert -m 1 &lt;merge-commit-sha&gt;
git push origin main</code></pre>

                    <p><code>-m 1</code> selects the first parent — the state of <code>main</code> before the release — as the mainline to revert back to.</p>

                    <h3>Feature accidentally committed on the release branch</h3>

                    <p>Move it to <code>develop</code> and take it back off the release:</p>

                    <pre class="code-snippet"><code>git checkout develop
git cherry-pick &lt;sha&gt;
git push origin develop

git checkout release/1.1.0
git revert &lt;sha&gt;
git push</code></pre>
                </section>

                <section id="appendix-a" class="blog-section">
                    <h2>Appendix A — <code>git flow</code> CLI Equivalents</h2>

                    <p>If the <a href="https://github.com/nvie/gitflow">git-flow extension</a> is installed, these wrap the manual steps above:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Manual steps</th>
                                <th><code>git flow</code></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>§2 setup</td>
                                <td><code>git flow init</code></td>
                            </tr>
                            <tr>
                                <td>§3.2 create release</td>
                                <td><code>git flow release start 1.1.0</code></td>
                            </tr>
                            <tr>
                                <td>§3.4–3.6 merge, tag, merge back, delete</td>
                                <td><code>git flow release finish 1.1.0</code></td>
                            </tr>
                            <tr>
                                <td>§4 step 1</td>
                                <td><code>git flow hotfix start 1.1.1</code></td>
                            </tr>
                            <tr>
                                <td>§4 steps 3–5</td>
                                <td><code>git flow hotfix finish 1.1.1</code></td>
                            </tr>
                            <tr>
                                <td>§5 create feature</td>
                                <td><code>git flow feature start user-avatars</code></td>
                            </tr>
                            <tr>
                                <td>§5 merge feature</td>
                                <td><code>git flow feature finish user-avatars</code></td>
                            </tr>
                        </tbody>
                    </table>

                    <p>Note that <code>finish</code> does <strong>not</strong> push — follow it with:</p>

                    <pre class="code-snippet"><code>git push origin main develop --tags</code></pre>
                </section>

                <section id="appendix-b" class="blog-section">
                    <h2>Appendix B — Quick Reference</h2>

                    <pre class="code-snippet"><code># Release
git checkout -b release/X.Y.Z develop
# ...bump version, changelog, fixes, test...
git checkout main   &amp;&amp; git merge --no-ff release/X.Y.Z
git tag -a vX.Y.Z -m "Release X.Y.Z"
git checkout develop &amp;&amp; git merge --no-ff release/X.Y.Z
git push origin main develop vX.Y.Z
git branch -d release/X.Y.Z &amp;&amp; git push origin --delete release/X.Y.Z

# Hotfix
git checkout -b hotfix/X.Y.Z main
# ...fix, bump patch version...
git checkout main   &amp;&amp; git merge --no-ff hotfix/X.Y.Z
git tag -a vX.Y.Z -m "Hotfix X.Y.Z"
git checkout develop &amp;&amp; git merge --no-ff hotfix/X.Y.Z
git push origin main develop vX.Y.Z
git branch -d hotfix/X.Y.Z &amp;&amp; git push origin --delete hotfix/X.Y.Z</code></pre>

                    <div class="note-box">
                        <h3>Source</h3>
                        <p>This post is the expanded version of a gist I keep as a working reference: <a href="https://gist.github.com/olibartfast/1b917c2aaabbe187a7901507a5e04abf">Manual Release Process (Gitflow)</a>. Background reading: Atlassian's <a href="https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow">Gitflow workflow</a> tutorial and Vincent Driessen's original <a href="https://nvie.com/posts/a-successful-git-branching-model/">A successful Git branching model</a>, which the model comes from.</p>
                    </div>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>AI Coding Workflows: From Cloud to Local</title>
      <link>https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html</guid>
      <pubDate>Sun, 16 Aug 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>The useful skill is not picking the best coding model — it is writing an engineering contract that lets the model, provider, and execution location change without rewriting anything.</description>
      <content:encoded><![CDATA[<p>Most arguments about AI-assisted development are arguments about which model is best. That question has a short shelf life and, more importantly, it is the wrong unit of analysis. A coding agent is an arrangement of parts: a harness that calls tools, an inference provider, a model doing the planning, possibly another doing the typing, and a physical location where the computation happens. Fix the arrangement badly and the best model in the world will still burn tokens re-reading files it already understood.</p>

                <p><strong>The useful skill is not choosing the best coding model. It is designing a workflow in which the model, provider, execution location, and worker roles can change without changing the engineering contract.</strong></p>

                <p>I first encountered this framing in DeepLearning.AI's <a href="https://www.deeplearning.ai/short-courses/ai-coding-workflows-from-cloud-to-local/">AI Coding Workflows: From Cloud to Local</a>, built with JetBrains. Its experiment rebuilds one small Python web app across eight configurations and records what each change does to context, tool calls, time and cost. That data is genuinely useful and I have summarised it in the case study at the end — but the argument below is about what it implies for any repository with explicit constraints and executable validation, which for me usually means a C++ codebase with a build system, a test suite, and interfaces whose misuse is expensive.</p>

                <p>Two results are worth stating up front, because both contradict what I expected:</p>

                <ul>
                    <li>Splitting work across subagents made the first runs <strong>more</strong> expensive, not less. Delegation is an investment that only pays once the worker role changes model.</li>
                    <li>Moving work off the expensive model did not remove context pressure. It relocated it onto the orchestrator, which then became the largest consumer in the run.</li>
                </ul>

                <div class="table-of-contents">
                    <h3>Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#more-than-model">1. A Coding Workflow Is More Than a Model</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#harness">2. Build a Repeatable Evaluation Harness</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#economics">3. The Real Economics of Delegation</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#roles">4. Strong Planner, Cheaper Implementer</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#packet">5. Design the Handoff Packet</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#boundaries">6. Enforce Boundaries with Tools and Permissions</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#local">7. What Changes When Inference Becomes Local</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#measure">8. What to Measure</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#choosing">9. Choosing a Configuration per Task</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#case-study">10. A Compact Case Study</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-coding-workflows-cloud-to-local.html#conclusion">Conclusion</a></li>
                    </ul>
                </div>

                <section id="more-than-model" class="blog-section">
                    <h2>1. A Coding Workflow Is More Than a Model</h2>

                    <p>Separating the harness from the model is the move that makes everything else visible. The harness reads instructions, calls tools, runs commands and manages the loop; the model only decides what to do next. Once those are distinct, three more parts separate out, and each is a decision rather than a given.</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Part</th>
                                <th>What it decides</th>
                                <th>What you inherit by default</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Harness</td>
                                <td>Which tools exist, what is permitted, how work is delegated</td>
                                <td>Whatever you installed, plus its model ecosystem</td>
                            </tr>
                            <tr>
                                <td>Inference provider</td>
                                <td>Whose hardware runs the model, and the price per token</td>
                                <td>The vendor bundled with the harness</td>
                            </tr>
                            <tr>
                                <td>Planner model</td>
                                <td>Decomposition, delegation, review, accept/reject</td>
                                <td>The largest available, for everything</td>
                            </tr>
                            <tr>
                                <td>Worker model</td>
                                <td>The mechanical production of code</td>
                                <td>Also the largest available</td>
                            </tr>
                            <tr>
                                <td>Execution location</td>
                                <td>What leaves the machine, and what a run costs at the margin</td>
                                <td>Someone else's data centre</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>These are dials, not a ladder with a best setting at the top. A concurrency-sensitive refactor and the mechanical addition of a serialization function are not the same job, and there is no reason they should run on the same model in the same place.</p>

                    <p>What makes the dials turnable is the engineering contract: the written constraints, the executable validation, and the delegation boundary between planning and implementation. If those three live in the repository, swapping a model is a configuration change. If they live in a chat transcript, they leave with the session, and every swap is a rewrite.</p>
                </section>

                <section id="harness" class="blog-section">
                    <h2>2. Build a Repeatable Evaluation Harness</h2>

                    <p>You cannot compare configurations unless each one receives the same task, the same constraints, the same starting revision, and the same judgement. Four artifacts, under version control:</p>

                    <ul>
                        <li><strong>Intent</strong> — what the software does and who it serves.</li>
                        <li><strong>Constraints</strong> — the decisions already made, which are not the agent's to revisit.</li>
                        <li><strong>Roadmap</strong> — the work split into phases that can be implemented and judged one at a time.</li>
                        <li><strong>Acceptance tests</strong> — owned by whoever specified the phase, and off-limits to the worker.</li>
                    </ul>

                    <p>The constraints document does the heaviest lifting, because it closes the decisions an agent would otherwise make silently and differently on every run. For a C++ repository that means being explicit about the things a plausible-looking diff can quietly violate:</p>

                    <ul>
                        <li>Language standard and the compilers that must keep working.</li>
                        <li>Warning policy, and whether warnings are errors.</li>
                        <li>Sanitizer configuration the tests run under.</li>
                        <li>Dependency manifest and whether adding to it requires approval.</li>
                        <li>API and ABI stability boundaries — which headers are contracts and which are internal.</li>
                        <li>Performance budgets, where a correct-but-slower implementation is a defect.</li>
                    </ul>

                    <p>Without that, one run adds a dependency, another redesigns an interface, a third picks a different concurrency model, and you are comparing engineering decisions rather than configurations.</p>

                    <p>Beyond the contents, three properties do the real work.</p>

                    <p><strong>One command decides the outcome.</strong> Every run must end in the same invocation returning the same kind of exit status — <code>cmake --workflow --preset ci</code>, which configures, builds and tests in one invocation, or whatever equivalent wrapper your project uses. That command is the scoreboard: it converts an impression into a result you can record beside a token count. Make sure it actually rebuilds — a bare <code>ctest</code> will happily test stale binaries after a source or build-system change, which is exactly the failure a worker will not notice and you will not see in a green result.</p>

                    <p><strong>The scoreboard is not writable by what it scores.</strong> Acceptance tests belong to whoever specified the phase. If a worker can edit them, a run can pass by weakening the check instead of meeting it. Workers may add unit tests next to their code; those are output, not scoreboard.</p>

                    <p><strong>Every run starts clean and ends reverted.</strong> A fresh context per run, and a return to the same commit afterwards, so the next configuration is not inheriting its predecessor's half-finished state or conversational memory. This discipline is worth keeping outside the experiment too — carrying a long context into a new task is the cheapest way to degrade quality without noticing.</p>
                </section>

                <section id="economics" class="blog-section">
                    <h2>3. The Real Economics of Delegation</h2>

                    <p>The standard advice is to split work across subagents so that each gets a small, focused context. The stated reason is sound: as a context window fills, output quality degrades even when everything still technically fits, because attention spreads across more material and details in the middle lose weight. A large model on a small task barely notices. A small model does not have the window to begin with.</p>

                    <p>The implied conclusion — that splitting the work therefore saves tokens — is wrong, and the measurements say so clearly. Delegating each phase to a fresh subagent <em>on the same model</em> made the orchestrator leaner and the total bill larger: roughly 50% more context and turns, 20% more tool calls, and a higher cost than the single-context baseline.</p>

                    <p>The mechanism is obvious in retrospect. A single long session reads a file once and keeps it. Every handoff re-establishes context the previous session already had: the worker reads the same headers, rediscovers the same conventions, and returns a summary the orchestrator must then absorb. With one model in both roles you are paying premium rates for that duplication and receiving nothing in exchange.</p>

                    <div class="note-box">
                        <h3>Delegation is a precondition, not a result</h3>
                        <p>You cannot put a cheaper or local model on implementation until implementation is a separable, well-scoped job with an explicit interface. The cost increase from splitting the work is the price of building that interface. Judge it as an investment and check the return at the next step — not at this one.</p>
                    </div>

                    <p>The second correction is subtler and outlasts any particular pricing. When the work moved to eight small workers instead of two large ones, the average worker session dropped by roughly a factor of six — and the orchestrator's context grew almost eightfold, from 90K to 712K. Total context barely moved. Someone has to compose eight briefs and review eight results, and that someone is the expensive model.</p>

                    <p>So context pressure relocates rather than disappearing. Two practical consequences: measure the planner and the worker separately or you will congratulate yourself on a saving that moved next door; and treat orchestration itself as a workload to be designed, because past a certain granularity you are paying more to describe the work than to do it.</p>
                </section>

                <section id="roles" class="blog-section">
                    <h2>4. Strong Planner, Cheaper Implementer</h2>

                    <p>Once implementation sits behind an interface, the model behind that interface becomes a variable — and this is where the cost curve actually bends. Keeping planning and review on a capable model while routing implementation to a small fast one produced a clear cost drop in the measured runs, even though turns and tool calls both rose.</p>

                    <p>The split that matters is between judgement and transcription. In a C++ codebase the line is usually easy to draw:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Keep on the strong model</th>
                                <th>Delegate to a cheap or local worker</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>A concurrency-sensitive refactor: what the locking discipline is, which invariants hold across threads</td>
                                <td>Applying an agreed signature change across call sites</td>
                            </tr>
                            <tr>
                                <td>Ownership and lifetime decisions at an interface boundary</td>
                                <td>Implementing serialization against a fixed schema</td>
                            </tr>
                            <tr>
                                <td>Whether a change breaks ABI or leaks an internal header into a public one</td>
                                <td>Adding a bounded CMake target with stated sources, includes and link dependencies</td>
                            </tr>
                            <tr>
                                <td>Template and overload design that downstream code will depend on</td>
                                <td>Writing table-driven tests for behaviour that is already specified</td>
                            </tr>
                            <tr>
                                <td>Reviewing the diff for the above, and rejecting it</td>
                                <td>Mechanical adaptation of build files, fixtures and boilerplate</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>The economics only work if the brief is tight. Cheap models are cheap for a reason: given a vague or oversized task they produce mistakes, mistakes produce more turns, and enough extra turns cost more in time and money than using the capable model would have. The mitigation is a smaller, more explicit unit of work — not a better worker.</p>

                    <h3>The same split, in three harnesses</h3>

                    <p>This division is not a workaround; the tooling now assumes it. Both vendor-tied harnesses ship a tiered family designed for exactly this, and the open one lets you assemble your own. The names differ, the shape does not:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Role</th>
                                <th>Claude Code</th>
                                <th>Codex</th>
                                <th>OpenCode</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><strong>Architect / reviewer</strong><br>Ambiguous, difficult, or expensive to get wrong: the concurrency design, the ABI question, the review that can reject a diff</td>
                                <td>Opus</td>
                                <td>Sol</td>
                                <td>whichever frontier model you point it at</td>
                            </tr>
                            <tr>
                                <td><strong>Planner / orchestrator</strong><br>Normal feature work, debugging, refactors — decomposing a phase and writing the handoff packet</td>
                                <td>Sonnet</td>
                                <td>Terra</td>
                                <td>a mid-tier hosted model via a router</td>
                            </tr>
                            <tr>
                                <td><strong>Implementer</strong><br>Clear, repeatable work with objective checks — which is exactly what a good packet plus an immutable test suite produces</td>
                                <td>Haiku</td>
                                <td>Luna</td>
                                <td>a cheap hosted model, or a local one</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>That last row is worth dwelling on, because "clear, repeatable, with objective checks" is not a property of the task you are handed — it is a property you manufacture. A bounded CMake target with named sources and a pass/fail preset qualifies. "Make this module thread-safe" does not. The specification work in sections 2 and 5 is what moves a job from the top row to the bottom one, and the price spread between tiers is the return on doing it.</p>

                    <p>Mechanically, the assignment belongs in configuration rather than in a prompt. All three harnesses put a delegated agent in its own file under the project, so the worker's tier becomes a committed, reviewable artifact instead of a sentence someone has to remember to type. Claude Code uses Markdown with YAML front matter, where the body is the agent's system prompt:</p>

                    <pre class="code-snippet"><code>&lt;!-- .claude/agents/implementer.md --&gt;
---
name: implementer
description: Implements one delegated packet against named paths.
model: haiku
maxTurns: 12
disallowedTools: WebFetch, WebSearch
permissionMode: acceptEdits
---

Implement only the delegated packet, touching only the paths it names.
Write each file's complete final content; never patch by anchor.
Build and run targeted tests as often as you need while working.
Finish by running the scoreboard command exactly once, then stop and
report its result whether it passes or fails. Do not repair after it.</code></pre>

                    <p>Codex splits the same information between the planner's <code>config.toml</code> and one TOML file per delegated agent, with the system prompt as a <code>developer_instructions</code> string:</p>

                    <pre class="code-snippet"><code># ~/.codex/config.toml — the planner
model = "gpt-5.6-terra"
model_reasoning_effort = "medium"</code></pre>

                    <pre class="code-snippet"><code># .codex/agents/implementer.toml — the worker
name = "implementer"
description = "Implements one delegated packet against named paths."
model = "gpt-5.6-luna"
model_reasoning_effort = "low"
sandbox_mode = "workspace-write"
developer_instructions = """
Implement only the delegated packet, touching only the paths it names.
Write each file's complete final content; never patch by anchor.
Build and run targeted tests as often as you need while working.
Finish by running the scoreboard command exactly once, then stop and
report its result whether it passes or fails. Do not repair after it.
"""</code></pre>

                    <p>OpenCode uses Markdown with front matter like Claude Code, but qualifies the model with its provider — which is where the open harness earns its keep:</p>

                    <pre class="code-snippet"><code>&lt;!-- .opencode/agents/implementer.md --&gt;
---
description: Implements one delegated packet against named paths.
mode: subagent
model: openrouter/deepseek/deepseek-v4-flash
steps: 12
---

Implement only the delegated packet, touching only the paths it names.
Write each file's complete final content; never patch by anchor.
Build and run targeted tests as often as you need while working.
Finish by running the scoreboard command exactly once, then stop and
report its result whether it passes or fails. Do not repair after it.</code></pre>

                    <p>Change that one string to <code>lmstudio/&lt;model-id&gt;</code> and the same worker, with the same brief and the same guardrails, runs on your own hardware instead of someone else's. Nothing else in the file moves. That is the thesis of this article reduced to a single line of configuration — and the reason the open harness is worth the setup cost even if you never leave the cloud.</p>

                    <p>One thing these three files do <em>not</em> do is confine the worker to the paths its packet names. <code>permissionMode: acceptEdits</code> and <code>sandbox_mode = "workspace-write"</code> are coarse boundaries: they decide whether the agent may write in the working directory at all, not which files it may touch. The named-path restriction lives in the body, which makes it advisory — a distinction section 6 takes seriously, because path-level enforcement is available in some harnesses and has to be replaced by review in the others.</p>

                    <p>The vocabularies differ; the levers are largely the same. Every one of these files carries a model choice and some way to restrict what the worker can reach — though, as the table shows, they do not all give you the same control:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Lever</th>
                                <th>Claude Code</th>
                                <th>Codex</th>
                                <th>OpenCode</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Worker tier</td>
                                <td><code>model:</code></td>
                                <td><code>model</code></td>
                                <td><code>model:</code>, provider-qualified</td>
                            </tr>
                            <tr>
                                <td>Loop ceiling</td>
                                <td><code>maxTurns:</code></td>
                                <td>none per agent — see below</td>
                                <td><code>steps:</code></td>
                            </tr>
                            <tr>
                                <td>Reachable tools</td>
                                <td><code>tools:</code> / <code>disallowedTools:</code></td>
                                <td><code>sandbox_mode</code>, <code>mcp_servers</code></td>
                                <td><code>permission:</code> keys</td>
                            </tr>
                            <tr>
                                <td>Write scope</td>
                                <td>coarse (working directory)</td>
                                <td>coarse (workspace)</td>
                                <td>fine (per-path allow/deny)</td>
                            </tr>
                            <tr>
                                <td>Behaviour brief</td>
                                <td>Markdown body</td>
                                <td><code>developer_instructions</code></td>
                                <td>Markdown body</td>
                            </tr>
                            <tr>
                                <td>Scope of model choice</td>
                                <td>one vendor's family</td>
                                <td>one vendor's family</td>
                                <td>any provider, cloud or local</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>The distinction that matters is between the behaviour brief and everything above it. The brief is persuasion; every other row is enforced by the harness. That is the argument of section 6 — and it is why a reviewer agent should be defined with <code>disallowedTools: Write, Edit</code>, <code>sandbox_mode = "read-only"</code>, or a deny-by-default <code>permission</code> block, rather than merely told not to change anything.</p>

                    <p>Two gaps are worth naming rather than papering over. Codex has no documented per-agent turn or step cap — the session-wide token controls are not the same thing — so termination has to come from the parent workflow: delegate one phase, require a single scoreboard run, and check that the child returned instead of trusting it to stop itself. And only OpenCode offers path-level write rules; in the other two, "these files and no others" is a review obligation, not a setting.</p>

                    <p>The last row is the one that decides how many of these dials you actually have. A vendor-tied harness gives you a tier ladder inside one family, which covers the cost argument but not the location one. An open harness treats the provider as part of the model identifier, so the cheap-worker move and the go-local move become the same edit.</p>

                    <p>One caution on comparisons: reasoning effort is part of the configuration, not a detail. The tiers span the same documented effort range, so a high-effort run measured against a default-effort one tells you about the setting rather than the model. Pin it explicitly on both sides or the comparison is meaningless.</p>

                    <p>The deeper reason this example belongs here: separating a generation number from a durable capability tier is the vendor conceding the argument of this article. The tier is a role you assign; the model behind it is expected to be replaced. A workflow built around roles survives that replacement, while one built around a specific model name does not.</p>

                    <h3>Watch who actually does the work</h3>

                    <p>A failure mode to watch for specifically: the planner, seeing weak output, quietly rewrites the code itself. Cost returns to the single-model baseline while the workflow still looks delegated. Instruct the planner to send defects back to a fresh worker rather than fixing them, and verify it by checking which role consumed the tokens.</p>

                    <p>The allocation I would default to, in decreasing order of capability: a top-tier model for architecture, roadmap shaping and periodic whole-project review; a mid-tier model for orchestration inside a phase; a cheap or local model for each implementer.</p>
                </section>

                <section id="packet" class="blog-section">
                    <h2>5. Design the Handoff Packet</h2>

                    <p>The handoff packet — the instructions, context and constraints the planner prepares before delegating — is the interface between the two roles, and the main lever that makes the split succeed or fail. It has to be sized for the worker's actual capacity: its context window, its tool-calling reliability, its tendency to improvise.</p>

                    <p>What belongs in one:</p>

                    <ul>
                        <li>The repo-relative paths the worker may write, and nothing beyond them.</li>
                        <li>The paths it must read but never modify — the interface it implements against, the acceptance suite that scores it.</li>
                        <li>The complete required final state in prose: declarations, behaviour, error handling, and which existing behaviour must survive unchanged.</li>
                        <li>Exact identifiers where they are contract requirements: a type name, a signature, a build target, an error string a test asserts on.</li>
                        <li>The scoreboard command, named explicitly, to be run once as the final action.</li>
                        <li>An explicit stop condition — report the scoreboard result whether it passes or fails, and do not continue past it.</li>
                    </ul>

                    <p>What to leave out matters just as much. Do not point the worker at the specification directory; following references costs context it does not have. Do not paste whole files. And do not hand it finished code — if the planner writes the implementation into the packet, you have paid the expensive model to produce it and the cheap one to copy it.</p>

                    <p>A packet for a typical C++ phase — one new concrete type behind an interface that already exists — comes out roughly like this. The module and type names are placeholders; the structure is what to copy.</p>

                    <pre class="code-snippet"><code>Writable paths:
  include/core/component.hpp   (new)
  src/core/component.cpp       (new)
  src/core/CMakeLists.txt      (modify: add the two sources to
                                the existing core target)

Read-only — read these, never modify them:
  include/core/component_base.hpp   (the interface to implement)
  tests/acceptance/                 (the suite that scores you)

Required final state:
  - Component publicly implements ComponentBase and overrides
    every pure virtual member.
  - Fallible operations return the project's error type rather
    than throwing; the failure cases named in the acceptance
    tests map to the documented error codes.
  - Every owned resource is held in an RAII member, so a
    partially constructed object releases what it acquired.
  - Construction either succeeds or fails through the project's
    result type; there is no half-initialised, reachable state.
  - The core target keeps its current public include directory
    and link dependencies; add no new third-party library.

For every writable file, use `write` with its complete final
content; never use `edit`.

While implementing, build and run targeted tests as often as
useful — the compiler is your fastest feedback.

Scoreboard, run once as your final action:
  cmake --workflow --preset ci
Stop after it, pass or fail, and report the result.</code></pre>

                    <p>Every clause in the required-final-state block is a contract the acceptance suite can check and a reviewer can reject on. None of them describe how to write the code, which is the line worth holding: the packet fixes the obligations, the worker chooses the implementation.</p>

                    <p>Two properties make this worth the effort. The packet is model-independent — the same brief works on a frontier worker, a hosted open-weight one, and a local model, which is precisely what makes the roles swappable. And it is inspectable while the run is still going: reading the packet tells you whether the delegation matches your intent long before the diff does.</p>
                </section>

                <section id="boundaries" class="blog-section">
                    <h2>6. Enforce Boundaries with Tools and Permissions</h2>

                    <p>Prompt instructions are advisory. Configuration is enforced. This distinction is not theoretical: in the recorded runs, a worker told not to write complete code obeyed the instruction in one phase and partially ignored it in the next, with no other change. What you write in a prompt or an agent definition body is persuasion; small models in particular have a mind of their own.</p>

                    <p>So anything that actually matters belongs in the part of the agent definition the harness applies — and it should be written as an allowlist. A rule that permits everything except the specs still leaves the worker free to edit the dependency manifest, the build presets, the acceptance suite and its own definition: every input the comparison depends on.</p>

                    <pre class="code-snippet"><code>&lt;!-- .opencode/agents/implementer.md --&gt;
---
description: Minimal implementer for one well-specified phase.
mode: subagent
model: &lt;small-or-local-model-id&gt;
steps: 12
permission:
  edit:
    "*": deny
    "include/core/component.hpp": allow
    "src/core/component.cpp": allow
    "src/core/CMakeLists.txt": allow
  bash:
    "*": deny
    "cmake --preset ci": allow
    "cmake --build --preset ci *": allow
    "ctest --preset ci *": allow
    "cmake --workflow --preset ci": allow
  glob: deny
  webfetch: deny
  websearch: deny
---</code></pre>

                    <p>This is OpenCode's syntax, chosen because it is the one that expresses path-level write rules directly. Claude Code and Codex give you the coarser boundaries from section 4 — whether the agent may write at all — so the "these files and nothing else" clause stays in the packet and becomes something review has to check rather than something the harness refuses.</p>

                    <p>Every line maps to an observed failure:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Constraint</th>
                                <th>Failure it prevents</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Step ceiling</td>
                                <td>Retry loops that run until the context is exhausted</td>
                            </tr>
                            <tr>
                                <td>Write allowlist</td>
                                <td>Editing the specs, tests, manifest or presets to match what was built</td>
                            </tr>
                            <tr>
                                <td>Command allowlist</td>
                                <td>Package installs, network fetches, anything bypassing the project's presets</td>
                            </tr>
                            <tr>
                                <td>Search and web tools disabled</td>
                                <td>Wandering the repository and exploding its own context</td>
                            </tr>
                            <tr>
                                <td>Whole-file writes, never anchored edits</td>
                                <td>A mismatched anchor retried forever — the most common small-model failure</td>
                            </tr>
                            <tr>
                                <td>Read the real file before changing it</td>
                                <td>Rewriting a half-remembered version held in context</td>
                            </tr>
                            <tr>
                                <td>No recursive listing of generated trees</td>
                                <td>One command flooding the window from <code>build/</code>, <code>_deps/</code> or a vendored tree</td>
                            </tr>
                            <tr>
                                <td>Run the scoreboard once, report, do not repair</td>
                                <td>The rerun-and-fix death spiral after the result is in</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>That last one needs a distinction that is easy to get wrong, and I had it wrong at first. The worker's inner development loop is not the enemy: compiling and running targeted tests while writing code is the fastest feedback a C++ worker has, and forbidding it makes the compiler useless as a tool. The allowlist above therefore permits the ordinary configure, build and test commands.</p>

                    <p>What must happen exactly once is the <em>scoreboard</em> — the full run whose exit status you record. After it reports, the worker stops. Without that boundary a worker reacting to a red result will edit and rebuild indefinitely, and in a C++ project each iteration is expensive enough that a great deal of wall clock disappears before anyone notices. One scoreboard run, reported upward, keeps the failure cheap and legible; whether to repair is the planner's decision, not the worker's.</p>

                    <p>Note the asymmetry with the planner: broad read access, no write access during review. Read-only review is what lets you trust a report about work produced by a model you would not trust to implement unsupervised.</p>

                    <p>The cost of a path allowlist is that the packet and the agent definition must agree, which means regenerating the permission block per phase. That is a fair trade — it forces the decision about what a phase may touch to happen before the worker starts, rather than in the diff.</p>
                </section>

                <section id="local" class="blog-section">
                    <h2>7. What Changes When Inference Becomes Local</h2>

                    <p>Serving the model from your own hardware — LM Studio, Ollama, llama.cpp, vLLM — takes the metered inference cost of a run to zero, works offline, and means the model itself never transmits your source anywhere. For code under a confidentiality obligation, that last point can be the entire justification.</p>

                    <div class="warning-box">
                        <h3>Local closes one egress path, not all of them</h3>
                        <p>Web-fetch tools, package installs, MCP servers and telemetry in the surrounding tooling can still send data outward. If confidentiality is why you went local, audit the tool list, not just the model endpoint.</p>
                    </div>

                    <p>What gets harder is specific and predictable:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Constraint</th>
                                <th>Symptom</th>
                                <th>Mitigation</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Small context window</td>
                                <td>The worker loses the earlier half of the task</td>
                                <td>Smaller phases; self-contained packets; never reference spec files</td>
                            </tr>
                            <tr>
                                <td>Weaker tool calling</td>
                                <td>Malformed or repeated edit calls</td>
                                <td>Whole-file writes; step ceiling; one permitted command</td>
                            </tr>
                            <tr>
                                <td>Slower generation</td>
                                <td>Minutes per file on consumer hardware</td>
                                <td>Quantisation sized to available memory; keep worker output short</td>
                            </tr>
                            <tr>
                                <td>Loose instruction following</td>
                                <td>Unrequested changes, invented dependencies</td>
                                <td>Deny-by-default permissions rather than prose</td>
                            </tr>
                            <tr>
                                <td>Platform-specific model builds</td>
                                <td>Identifiers differ between hardware-specific formats</td>
                                <td>Read the served model ID from the runtime rather than copying it</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>The design consequence is that <strong>the unit of work is sized for the weakest participant</strong>. In the measured runs, one roadmap phase had to be split in two before a local worker could complete it. Splitting costs a capable model nothing, so the granularity should be set by whatever you intend to run at the bottom end. For a C++ project that argues for phases scoped to a single target or a single translation unit's worth of behaviour, with the interface fixed beforehand by the planner.</p>

                    <p>One piece of local-inference advice runs against instinct and is worth repeating: do not maximise the served context window. A larger window on a small model invites exactly the oversized, unfocused sessions that make small models fail. Keep the worker's context modest on purpose and control size through the packet instead.</p>

                    <p>The honest summary of the state of the art is that the weights are ahead of the harnesses. Most of the work in making a local worker succeed is hand-written guardrails of the kind in the previous section, because few frameworks ship that scaffolding yet. That is the layer worth watching — more than the model leaderboards.</p>
                </section>

                <section id="measure" class="blog-section">
                    <h2>8. What to Measure</h2>

                    <p>Run each configuration against the same phases and record the same columns, split between planner and worker. The split is more informative than the totals, because delegation is precisely a claim about moving work between those two columns.</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Metric</th>
                                <th>How to read it</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Total context processed</td>
                                <td>Tokens billed and re-read across the session. A cost and repetition measure — track per role, or you will miss relocation</td>
                            </tr>
                            <tr>
                                <td>Peak and average active context</td>
                                <td>How full the window actually got on a given turn. This, not the total, is what predicts degraded output</td>
                            </tr>
                            <tr>
                                <td>Tool calls</td>
                                <td>An activity proxy, not a work measure — a full build and a one-line read each count once</td>
                            </tr>
                            <tr>
                                <td>Turns</td>
                                <td>Interaction style, not work done — see the caveat below</td>
                            </tr>
                            <tr>
                                <td>Wall-clock time</td>
                                <td>Useful but noisy; hardware load and network affect it</td>
                            </tr>
                            <tr>
                                <td>Metered cost</td>
                                <td>Zero for local inference, which is the entire point of going there</td>
                            </tr>
                            <tr>
                                <td>First-pass validation result</td>
                                <td>The correctness signal, taken before any repair by planner or human</td>
                            </tr>
                            <tr>
                                <td>Interventions</td>
                                <td>How often you had to step in — the cost that does not appear on any dashboard</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>Separating the two context measures matters because they answer different questions. A session that reads the same header twenty times has a large total and a small active context: it is expensive but not confused. A single turn carrying an entire subsystem has the opposite profile, and that is the one that produces subtly wrong code. Delegation improves the second while often worsening the first, which is precisely why reporting only the total makes the trade invisible.</p>

                    <p>The turns caveat is not pedantry. In the fully local run, total turns rose from 6 to 45 while tool calls went from 51 to 57. Seven times the turns for essentially identical tool activity: the models were simply taking more, smaller steps between actions. Ranking configurations by turn count would have produced a completely wrong conclusion.</p>

                    <p>Intervention count is the one most often omitted and the one most likely to reverse a decision. A configuration that is an order of magnitude cheaper but needs three corrective rounds and half an hour of your attention is not cheaper in any sense that matters for paid work. It may still be the right choice for a personal project where your time is not billed.</p>

                    <p>Finally, run each configuration more than once. These systems are stochastic; a single green result proves less than it appears to.</p>
                </section>

                <section id="choosing" class="blog-section">
                    <h2>9. Choosing a Configuration per Task</h2>

                    <p>The measurements produce a preference, but the choice is usually settled by the nature of the work rather than the benchmark table.</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>Situation</th>
                                <th>Reasonable configuration</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Novel architecture, unclear requirements, a subtle bug in threading or lifetime</td>
                                <td>Single capable model, one context. Judgement is the bottleneck; delegation only adds overhead</td>
                            </tr>
                            <tr>
                                <td>Well-specified phases in an established codebase</td>
                                <td>Capable planner, cheap implementers. The best default for routine work</td>
                            </tr>
                            <tr>
                                <td>Cost pressure, or unwillingness to depend on one vendor</td>
                                <td>Open-weight workers behind a router, planner unchanged</td>
                            </tr>
                            <tr>
                                <td>Confidential code, offline work, unmetered experimentation</td>
                                <td>Local worker, capable planner. Phases sized accordingly</td>
                            </tr>
                            <tr>
                                <td>Mechanical work with strong test coverage</td>
                                <td>Fully local, with review as the only cloud step — or no cloud step at all</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>Mixing is the mature answer. The constraints, the roadmap and the acceptance suite are the durable assets; the model configuration is a per-task dial. A project with that contract in place can run a local worker on boilerplate in the morning and a frontier model on a data race in the afternoon without changing anything about how the work is described.</p>
                </section>

                <section id="case-study" class="blog-section">
                    <h2>10. A Compact Case Study</h2>

                    <p>The figures quoted throughout come from the course's experiment: one small FastAPI application — a home page, a list view, and a submission form — specified in three Markdown files and rebuilt from scratch in each configuration, with a fresh context each time and a revert in between.</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Configuration</th>
                                <th>Key figures</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>1</td>
                                <td>Cloud harness, capable model, single context</td>
                                <td>19 turns, 28 tool calls, 474K context. A subagent spawned by the harness itself took 54% of context</td>
                            </tr>
                            <tr>
                                <td>2</td>
                                <td>Same model, one subagent per phase</td>
                                <td>Planner 217K → 192K; workers 257K → 511K; total context and turns <strong>+50%</strong>, cost up</td>
                            </tr>
                            <tr>
                                <td>3</td>
                                <td>Capable planner, cheap workers</td>
                                <td>Turns +50%, tool calls +48%, context +29% — and cost <strong>down notably</strong>. Context per worker turn 21K → 17K</td>
                            </tr>
                            <tr>
                                <td>4</td>
                                <td>Open-source harness, router, open-weight model</td>
                                <td>25 turns, 38 tool calls, 530K, ~$0.02. Cheaper tokens, not better orchestration</td>
                            </tr>
                            <tr>
                                <td>5</td>
                                <td>Same, one subagent per phase</td>
                                <td>Planner down to 90K; workers 94% of context; total context +179%, cost ~3×</td>
                            </tr>
                            <tr>
                                <td>6</td>
                                <td>Capable planner, small workers via agent definition</td>
                                <td>8 workers instead of 2; per-worker context 694K → 110K; <strong>planner 90K → 712K</strong>; total context +8%, cost −28%</td>
                            </tr>
                            <tr>
                                <td>7</td>
                                <td>Cloud planner, local worker (12B, quantised)</td>
                                <td>Workers 117K across three phases; planner 69% of context; ~$0.02 total; 8m52s</td>
                            </tr>
                            <tr>
                                <td>8</td>
                                <td>Fully local (27B planner, 12B worker)</td>
                                <td>Planner 178K, workers 158K, total context −11%; turns 45 vs 6 for 57 vs 51 tool calls; <strong>$0.00</strong></td>
                            </tr>
                        </tbody>
                    </table>

                    <p>Rows 1–6 are a controlled comparison: same task, same phases, same prompt shape, one variable moving at a time. <strong>Rows 7 and 8 are not.</strong> Reaching a local worker required changing the workflow as well as the model — the roadmap was split from two phases into three, the worker gained the guardrails described in section 6, and the single-shot prompt became one run per phase. Those rows measure a different way of working, not just different weights, and their totals cover three phases rather than two. Read them as evidence that local inference is reachable, not as a like-for-like delta against row 6.</p>

                    <p>With that caveat, three findings generalise beyond the toy project. <strong>Rows 1→2:</strong> delegation on a single model costs more and buys only the interface. <strong>Row 6:</strong> shrinking worker sessions inflates the planner — the work relocates. <strong>Row 8:</strong> a 27B model on a laptop produced task briefs that held up against a much larger hosted model, and completed two of three phases with no reported defects; the third failed on an HTTP redirect detail caught by a test and repaired by delegating back to the worker.</p>

                    <div class="note-box">
                        <h3>How much weight to put on these numbers</h3>
                        <p>Each row is a single recorded run of a deliberately small application, on one machine, with the models available at the time. They are evidence about direction and magnitude — that delegation initially costs more, that context relocates, that turns mislead — not benchmarks to reproduce. The methodology transfers; the figures do not.</p>
                    </div>
                </section>

                <section id="conclusion" class="blog-section">
                    <h2>Conclusion</h2>

                    <p>The configuration that wins today will be obsolete within a year, and the models named in any article about this will age faster than the article does. What survives is the contract: constraints written where any agent can read them, one command that settles whether the work is done, acceptance tests that the worker cannot touch, and a delegation boundary explicit enough that the thing on the other side of it is replaceable.</p>

                    <p>Build that and the dials become real. You can put a local model on mechanical work and keep judgement in the cloud, or move the whole pipeline in-house when the code is confidential, or go back to a single capable model for a problem that is genuinely hard — and in each case you are choosing, with evidence, rather than inheriting a default.</p>

                    <p>Start with the smallest version: pin the constraints, wrap validation behind one command, make the acceptance tests immutable, and write one handoff packet by hand. Everything else in this article is a configuration change on top of that.</p>

                    <div class="note-box">
                        <h3>Source</h3>
                        <p>The measurements cited here are from <a href="https://www.deeplearning.ai/short-courses/ai-coding-workflows-from-cloud-to-local/">AI Coding Workflows: From Cloud to Local</a>, a short course from DeepLearning.AI and JetBrains taught by Paul Everitt; its <a href="https://github.com/https-deeplearning-ai/sc-ai-coding-workflows-files">companion repository</a> holds the specifications, subagent definitions and prompts. For the specification practices this workflow depends on, see also <a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html">AI Spec-Driven Development</a>.</p>
                    </div>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>AI Spec-Driven Development: A Practical Workflow for Coding Agents</title>
      <link>https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html</guid>
      <pubDate>Sat, 15 Aug 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A practical, agent-agnostic workflow for turning product intent into versioned specifications, implementation plans, executable validation, and repeatable AI-assisted delivery.</description>
      <content:encoded><![CDATA[<p>AI coding agents can produce code faster than most teams can review it. That is useful, but it also exposes a less glamorous bottleneck: the agent often does not know which product to build, which constraints are permanent, which decisions are still open, or what evidence will make the work mergeable.</p>

                <p>A long prompt is not enough. It disappears into chat history, mixes durable rules with temporary requests, and leaves the next developer—or the next agent—to reconstruct intent from a diff.</p>

                <p><strong>Spec-driven development (SDD)</strong> gives that intent a durable home. The project keeps a small set of versioned documents for its mission and technical boundaries, then creates a focused specification for each feature before implementation begins. The agent still writes code, but it works inside a visible contract that humans can review and amend.</p>

                <p>This article presents an agent-agnostic workflow inspired by DeepLearning.AI's <a href="https://www.deeplearning.ai/courses/spec-driven-development-with-coding-agents">Spec-Driven Development with Coding Agents</a> short course and its <a href="https://github.com/https-deeplearning-ai/sc-spec-driven-development-files">open companion repository</a>. The examples and recommendations below are a practical synthesis rather than a reproduction of the course project.</p>

                <div class="note-box">
                    <h3>The core idea</h3>
                    <p>Move the important conversation out of an ephemeral prompt and into version-controlled artifacts: why the project exists, what the feature must do, how it will be built, and how everyone will know it is done.</p>
                </div>

                <div class="table-of-contents">
                    <h3>Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#what-sdd-is">1. What Spec-Driven Development Is</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#spec-architecture">2. A Small, Durable Spec Architecture</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#workflow">3. The End-to-End Workflow</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#living-specs">4. Keep Specifications and Code in Sync</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#brownfield">5. Bringing SDD to an Existing Codebase</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#automation">6. Turn Repetition into Reusable Agent Skills</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#failure-modes">7. Common Failure Modes</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#starter-kit">8. A Minimal Starter Kit</a></li>
                        <li><a href="https://olibartfast.ninja/blog/ai-spec-driven-development-workflow.html#conclusion">Conclusion</a></li>
                    </ul>
                </div>

                <section id="what-sdd-is" class="blog-section">
                    <h2>1. What Spec-Driven Development Is</h2>

                    <p>Spec-driven development is a feedback loop in which human intent is captured as repository artifacts before an agent changes the product. Those artifacts guide implementation, validation feeds discoveries back into them, and the final merge leaves both code and intent in a coherent state.</p>

                    <div class="workflow-flow" aria-label="Spec-driven development workflow">
                        <span>Constitution</span><b>→</b>
                        <span>Feature spec</span><b>→</b>
                        <span>Implement</span><b>→</b>
                        <span>Validate</span><b>→</b>
                        <span>Integrate</span><b>→</b>
                        <span>Replan</span>
                    </div>

                    <p>This is not an attempt to predict the entire system upfront. Good SDD deliberately uses small phases. A feature spec should be detailed enough to remove consequential ambiguity and small enough to revise without ceremony.</p>

                    <p>It also does not mean that the specification writes the software automatically. The spec improves the agent's context and makes its choices inspectable; engineering judgment is still required for architecture, security, performance, usability, and review.</p>

                    <h3>Why it fits coding agents</h3>

                    <p>An experienced teammate accumulates unwritten context over months. An agent session may start with none of it. Repository-level specifications act as shared, persistent memory:</p>

                    <ul>
                        <li>Humans can review product intent before paying the cost of implementation.</li>
                        <li>Agents can discover constraints without relying on one giant prompt.</li>
                        <li>Validation is agreed in advance instead of improvised after the code looks finished.</li>
                        <li>A fresh agent can continue the work from files and Git history.</li>
                        <li>Changes to scope become visible changes to the spec, not silent prompt drift.</li>
                    </ul>

                    <p>The result is not perfect autonomy. It is better alignment, cheaper correction, and a much clearer audit trail.</p>
                </section>

                <section id="spec-architecture" class="blog-section">
                    <h2>2. A Small, Durable Spec Architecture</h2>

                    <p>The workflow starts with two levels of documentation: a stable project constitution and a temporary-but-versioned packet for each feature.</p>

                    <pre class="code-snippet"><code>specs/
├── mission.md
├── tech-stack.md
├── roadmap.md
└── 2026-08-15-feature-name/
    ├── requirements.md
    ├── plan.md
    └── validation.md</code></pre>

                    <h3>The project constitution</h3>

                    <p>The constitution records decisions that should influence many features. It should be short enough that an agent can read it at the start of every planning task.</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>File</th>
                                <th>Question it answers</th>
                                <th>Typical contents</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><code>mission.md</code></td>
                                <td>Why does this product exist, and for whom?</td>
                                <td>Problem, audience, product promise, success criteria, tone</td>
                            </tr>
                            <tr>
                                <td><code>tech-stack.md</code></td>
                                <td>What technical boundaries should every feature respect?</td>
                                <td>Languages, frameworks, data store, tests, tooling, explicit non-choices</td>
                            </tr>
                            <tr>
                                <td><code>roadmap.md</code></td>
                                <td>What is the smallest sensible delivery order?</td>
                                <td>Short, independently reviewable phases with visible status</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>Explicit non-choices matter. “No ORM in the first release” or “do not add a client-side framework” prevents an agent from expanding the architecture simply because a familiar dependency would make one task convenient.</p>

                    <h3>The feature packet</h3>

                    <p>Each roadmap phase gets its own directory. Separating the three documents keeps three different conversations from collapsing into one:</p>

                    <table class="workflow-table">
                        <thead>
                            <tr>
                                <th>File</th>
                                <th>Purpose</th>
                                <th>What belongs there</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><code>requirements.md</code></td>
                                <td>Define the contract</td>
                                <td>In scope, out of scope, user-visible behavior, decisions, constraints, context</td>
                            </tr>
                            <tr>
                                <td><code>plan.md</code></td>
                                <td>Sequence the work</td>
                                <td>Numbered task groups that are independently implementable and verifiable</td>
                            </tr>
                            <tr>
                                <td><code>validation.md</code></td>
                                <td>Define the evidence</td>
                                <td>Automated checks, manual walkthroughs, edge cases, and merge criteria</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>A useful shorthand is: <strong>requirements describe what, the plan describes how, and validation describes proof.</strong></p>
                </section>

                <section id="workflow" class="blog-section">
                    <h2>3. The End-to-End Workflow</h2>

                    <h3>Stage 1: Interview before writing the constitution</h3>

                    <p>Begin with the available stakeholder material: a README, product brief, issue list, meeting notes, or an existing application. Ask targeted questions before writing files. The most valuable questions cluster around three areas:</p>

                    <ol>
                        <li><strong>Mission:</strong> Who is the product for, which problem matters most, and what does success look like?</li>
                        <li><strong>Technical boundaries:</strong> Which choices are fixed, which are preferences, and which remain open?</li>
                        <li><strong>Delivery order:</strong> What is the first end-to-end slice that proves the stack and provides value?</li>
                    </ol>

                    <p>The interview step is a guardrail against confident invention. If an unanswered question could materially change the feature, the agent should surface it before committing the assumption to code.</p>

                    <p>The roadmap should then decompose the product into thin, shippable phases. “Build the dashboard” is usually too broad. “Render the shared shell,” “show a read-only list,” and “add the first editable workflow” create clearer review and validation points.</p>

                    <h3>Stage 2: Select one roadmap phase and isolate it</h3>

                    <p>Choose the next incomplete phase, create a branch, and give the specification a dated directory. The date makes parallel or repeated efforts distinguishable; the feature name makes the history searchable.</p>

                    <pre class="code-snippet"><code>git switch -c phase-2-agent-list
mkdir -p specs/2026-08-15-agent-list</code></pre>

                    <p>The branch boundary is important. It lets the feature's spec and code evolve together, and it gives reviewers one coherent unit to compare against the roadmap.</p>

                    <h3>Stage 3: Resolve scope, decisions, and context</h3>

                    <p>Before drafting the feature packet, conduct a smaller feature interview:</p>

                    <ul>
                        <li><strong>Scope:</strong> What data enters and leaves the feature? Which behaviors and states are included? What is explicitly deferred?</li>
                        <li><strong>Decisions:</strong> Which storage, API, validation, navigation, and UX choices need to be fixed now?</li>
                        <li><strong>Context:</strong> Which existing patterns, tone rules, compatibility needs, or operational constraints shape the work?</li>
                    </ul>

                    <p>Grouped questions are efficient because the human can resolve product and engineering ambiguity in one pass. The agent should then cross-check the answers against <code>mission.md</code> and <code>tech-stack.md</code>.</p>

                    <h3>Stage 4: Write the three-part feature contract</h3>

                    <p>Write the requirements first. Separate in-scope behavior from out-of-scope work so “helpful” expansion is easy to detect. Record important decisions with their rationale, especially when the obvious implementation would violate the constitution.</p>

                    <p>Next, turn the requirements into numbered task groups. Good groups follow dependency order and end in something observable:</p>

                    <pre class="code-snippet"><code>## Group 1 — Data
1. Add the migration.
2. Add typed queries.
3. Seed representative records.

## Group 2 — Presentation
4. Add the list component.
5. Cover empty and populated states.

## Group 3 — Route and navigation
6. Add the route.
7. Link it from the shared navigation.

## Group 4 — Verification
8. Add focused tests.
9. Run the repository's full validation commands.</code></pre>

                    <p>Finally, write validation as observable evidence. Include exact commands where possible, expected user-visible behavior, failure cases, accessibility or tone checks, and the conditions required for merge.</p>

                    <div class="note-box">
                        <h3>Write validation before implementation</h3>
                        <p>If success is defined only after the agent has produced a solution, the criteria tend to fit whatever was built. Defining proof first keeps the implementation accountable to the requirement.</p>
                    </div>

                    <h3>Stage 5: Implement in task groups</h3>

                    <p>The agent can now execute a bounded plan rather than infer the entire feature from scratch. Work through one task group at a time, run the closest relevant checks, and inspect the diff before moving forward.</p>

                    <p>This makes failures easier to localize. It also creates natural pause points for human review. For higher-risk work, commit by task group; for smaller features, keep the branch uncommitted until the full validation pass.</p>

                    <p>The plan is a guide, not a substitute for repository discovery. The agent must still inspect existing conventions, reuse established components, protect unrelated user changes, and avoid dependencies that the constitution does not authorize.</p>

                    <h3>Stage 6: Validate against the declared evidence</h3>

                    <p>Validation should be executed from <code>validation.md</code>, not summarized from memory. A practical validation ladder is:</p>

                    <ol>
                        <li>Static checks: formatting, linting, types, schema validation.</li>
                        <li>Focused tests for the changed behavior.</li>
                        <li>The full regression suite.</li>
                        <li>Build or packaging checks.</li>
                        <li>Manual walkthroughs for user-visible behavior and edge cases.</li>
                        <li>Diff review against every requirement and out-of-scope boundary.</li>
                    </ol>

                    <p>Record deviations honestly. “Tests pass” is not equivalent to “validation is complete” if the specification also requires a keyboard-only walkthrough or a real database migration.</p>

                    <h3>Stage 7: Integrate, update, and replan</h3>

                    <p>Once validation passes, update the roadmap, changelog, and any durable technical guidance discovered during the feature. Merge the branch only when the code and specifications tell the same story.</p>

                    <p>Then reconsider the roadmap. Delivered work often changes what should come next. Several tiny phases may now belong together; a newly discovered dependency may need an earlier spike; an MVP may be closer than the original sequence suggested.</p>

                    <p>Replanning is part of the workflow, not an admission that the first plan failed. The project constitution provides continuity while the roadmap adapts to evidence.</p>
                </section>

                <section id="living-specs" class="blog-section">
                    <h2>4. Keep Specifications and Code in Sync</h2>

                    <p>The most important operational rule is simple: <strong>when the requirement changes, update the spec in the same branch as the code.</strong></p>

                    <p>Suppose implementation reveals that a shared layout must be split into separate header, main, and footer components. There are three possible reactions:</p>

                    <ul>
                        <li>Change only the code. The spec immediately becomes misleading.</li>
                        <li>Refuse the discovery because the plan did not predict it. The spec becomes bureaucracy.</li>
                        <li>Review the change, update requirements and plan, adjust validation, then implement it. The spec remains useful.</li>
                    </ul>

                    <p>The third option is living specification. The documents are authoritative enough to guide work but editable enough to incorporate what the team learns.</p>

                    <h3>Global decisions must propagate</h3>

                    <p>Some discoveries belong in one feature; others change the whole project. Adding responsive design or adopting a test framework, for example, should update <code>tech-stack.md</code>, relevant feature specs, current code, and validation—not just the latest prompt.</p>

                    <p>This propagation prevents a common form of drift where the newest feature follows one rule while older specs continue teaching agents another.</p>

                    <h3>Specs are an interface between humans and agents</h3>

                    <p>A good spec does not depend on one model's conversational memory. Another agent should be able to read the repository, understand the current contract, run the checks, and continue the work. That replaceability is a useful test of documentation quality: if changing agents destroys the workflow, critical context probably lives outside the repository.</p>
                </section>

                <section id="brownfield" class="blog-section">
                    <h2>5. Bringing SDD to an Existing Codebase</h2>

                    <p>SDD does not require a greenfield project. For a brownfield system, the first task is reconstruction rather than invention.</p>

                    <ol>
                        <li>Read the README, issue tracker, TODO files, package manifests, build configuration, tests, and recent history.</li>
                        <li>Infer the current mission and stack, but label assumptions and interview maintainers about the gaps.</li>
                        <li>Write a roadmap from unfinished work rather than pretending the existing product starts at phase one.</li>
                        <li>Create feature packets only for new or actively changing work.</li>
                        <li>Use tests and current behavior as evidence when documentation and implementation disagree.</li>
                    </ol>

                    <p>Do not attempt to specify the entire legacy system in one pass. Capture stable boundaries, then improve the constitution as features expose missing context. This keeps adoption proportional to the work being done.</p>

                    <div class="warning-box">
                        <h3>Brownfield caution</h3>
                        <p>An agent can summarize a codebase convincingly while misunderstanding an important operational constraint. Treat reconstructed documentation as a draft until maintainers and executable checks confirm it.</p>
                    </div>
                </section>

                <section id="automation" class="blog-section">
                    <h2>6. Turn Repetition into Reusable Agent Skills</h2>

                    <p>Once a team repeats the workflow, the repeated procedure should become automation. The source course materials demonstrate this with reusable agent skills for feature specification and changelog generation.</p>

                    <p>A feature-spec skill can encode the mechanical parts:</p>

                    <ul>
                        <li>Find the next incomplete roadmap phase.</li>
                        <li>Create a correctly named branch.</li>
                        <li>Ask the scope, decisions, and context questions before writing.</li>
                        <li>Read the constitution.</li>
                        <li>Create the dated directory and three required documents.</li>
                        <li>Enforce rules such as “no new dependency without approval.”</li>
                    </ul>

                    <p>A changelog skill can inspect work since the previous merge and update a consistent project history. Similar skills can encode release checks, dependency reviews, database migration procedures, or documentation updates.</p>

                    <p>The right automation target is the <em>procedure</em>, not the product decision. A skill should remember how to interview and structure a spec; it should not silently decide what a user wants.</p>

                    <h3>Keep the workflow portable</h3>

                    <p>Prefer ordinary Markdown, repository scripts, and standard Git operations as the durable layer. Tool-specific commands can be convenient adapters, but the core artifacts should remain usable by a different coding agent—or by a human with no agent at all.</p>
                </section>

                <section id="failure-modes" class="blog-section">
                    <h2>7. Common Failure Modes</h2>

                    <h3>The giant prompt</h3>
                    <p>A single prompt mixes mission, architecture, feature scope, and validation. It is difficult to review, easy to truncate, and almost impossible to maintain. Split durable context by responsibility.</p>

                    <h3>Specification theater</h3>
                    <p>The repository contains polished documents, but implementation never reads them and review never checks them. Make the spec operational: point the agent to it, derive tasks from it, and validate against it.</p>

                    <h3>Over-specifying implementation</h3>
                    <p>A plan that dictates every function name before discovery can lock in weak assumptions. Specify behavior and consequential architecture; let routine implementation details follow repository conventions.</p>

                    <h3>Validation written after the fact</h3>
                    <p>Post-hoc success criteria tend to bless the existing solution. Write the observable contract first, then adjust it explicitly if a legitimate discovery changes the requirement.</p>

                    <h3>Silent assumptions</h3>
                    <p>An agent fills product gaps with plausible defaults. Some defaults are harmless; others change data retention, security, compatibility, or user experience. Use the feature interview to expose high-impact assumptions.</p>

                    <h3>Specs that never change</h3>
                    <p>Frozen specs drift away from reality. Update requirements, plan, and validation with the implementation whenever the team's understanding changes.</p>

                    <h3>Specs for microscopic changes</h3>
                    <p>Not every typo needs three files. Use the full workflow when ambiguity, risk, handoff cost, or multi-step implementation justifies it. A short issue plus a test can be enough for a trivial fix.</p>
                </section>

                <section id="starter-kit" class="blog-section">
                    <h2>8. A Minimal Starter Kit</h2>

                    <p>You can adopt the workflow without installing a framework. Add the three constitution files, choose one modest roadmap phase, and use the following compact feature templates.</p>

                    <h3><code>requirements.md</code></h3>

                    <pre class="code-snippet"><code># Feature Requirements

## Goal
What user or system outcome does this feature create?

## In Scope
- Observable behavior included in this branch

## Out of Scope
- Related work deliberately deferred

## Decisions
- Important choice and its rationale

## Constraints and Context
- Constitution rules and existing patterns that apply</code></pre>

                    <h3><code>plan.md</code></h3>

                    <pre class="code-snippet"><code># Feature Plan

## Group 1 — Foundation
1. First independently verifiable task
2. Second task

## Group 2 — Behavior
3. Implement the user-visible slice

## Group 3 — Verification
4. Add or update tests
5. Run the declared validation commands</code></pre>

                    <h3><code>validation.md</code></h3>

                    <pre class="code-snippet"><code># Feature Validation

## Automated
- [ ] Typecheck/lint command exits successfully
- [ ] Focused tests cover success and failure paths
- [ ] Full regression suite passes
- [ ] Production build succeeds

## Manual
- [ ] Primary workflow behaves as specified
- [ ] Empty, invalid, and failure states are usable
- [ ] Accessibility and responsive behavior are checked

## Definition of Done
- [ ] Every requirement is implemented or explicitly deferred
- [ ] Spec, code, roadmap, and changelog agree</code></pre>

                    <h3>Practical operating checklist</h3>

                    <ul>
                        <li>Keep the constitution concise and read it before feature planning.</li>
                        <li>Make roadmap phases independently reviewable and testable.</li>
                        <li>Interview for scope, decisions, and context before writing the feature spec.</li>
                        <li>State what is out of scope.</li>
                        <li>Define validation before implementation.</li>
                        <li>Update specifications when discoveries change the design.</li>
                        <li>Run the checks; do not merely describe them.</li>
                        <li>Merge spec and code as one coherent change.</li>
                        <li>Automate repeated workflow steps without automating product judgment.</li>
                    </ul>
                </section>

                <section id="conclusion" class="blog-section">
                    <h2>Conclusion</h2>

                    <p>AI-assisted development becomes more reliable when the agent is not asked to infer the product from a transient conversation. A small project constitution supplies durable direction. A three-part feature packet turns one roadmap phase into an explicit contract. Predeclared validation makes completion measurable. Living updates keep the contract useful as implementation teaches the team something new.</p>

                    <p>The deeper benefit is continuity. The codebase becomes less dependent on one prompt, one developer's memory, or one agent. Intent, decisions, work, and evidence travel together through Git.</p>

                    <p>Start small: write the mission, technical boundaries, and next shippable phase. Specify one feature, validate it honestly, and refine the workflow from what you learn. That is enough to turn an AI coding session into an engineering process.</p>

                    <div class="note-box">
                        <h3>Source and further exploration</h3>
                        <p>The workflow in this article was inspired by <a href="https://www.deeplearning.ai/courses/spec-driven-development-with-coding-agents">Spec-Driven Development with Coding Agents</a>, a short course from DeepLearning.AI and JetBrains taught by Paul Everitt, and by the course's <a href="https://github.com/https-deeplearning-ai/sc-spec-driven-development-files">open companion materials</a>. Together, they walk through the project constitution, the plan–implement–validate cycle, legacy adoption, and packaging the workflow into reusable agent skills.</p>
                    </div>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>Modern C++ Design Patterns Beyond GoF</title>
      <link>https://olibartfast.ninja/blog/modern-cpp-design-patterns-beyond-gof.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/modern-cpp-design-patterns-beyond-gof.html</guid>
      <pubDate>Wed, 03 Jun 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A practical taxonomy of modern C++ idioms, dependency patterns, real-time pipelines, boundary patterns, and production architecture beyond the original GoF catalog.</description>
      <content:encoded><![CDATA[<p>In 1994, the "Gang of Four" published <em>Design Patterns: Elements of Reusable Object-Oriented Software</em>. It quickly became one of the most influential books in software architecture. However, the GoF patterns were created in an era dominated by class hierarchies, inheritance-heavy designs, runtime polymorphism, raw pointers, and mostly single-threaded desktop applications.</p>

                <p>C++ has changed dramatically since then.</p>

                <p>With C++11, C++17, C++20, C++23, and the upcoming C++26, the language has moved toward value semantics, RAII-based lifetime management, compile-time validation, safer abstractions, and explicit ownership. Modern C++ often favors composition over inheritance, static polymorphism over virtual dispatch when possible, and clear resource ownership over raw pointer manipulation.</p>

                <p>Modern C++ is also used in very different domains from those that shaped the original GoF catalog: high-frequency trading, game engines, embedded systems, real-time computer vision, AI inference pipelines, robotics, microservices, and distributed infrastructure. These domains require patterns that deal with concurrency, data locality, hardware resources, runtime plugins, resilience, and clean architectural boundaries.</p>

                <p>This article revisits classic design patterns from a Modern C++ perspective, explains where the Service Locator fits, and presents a practical taxonomy of contemporary non-GoF patterns used in production systems.</p>

                <div class="note-box">
                    <h3>Important clarification</h3>
                    <p>Not everything discussed here is a "design pattern" in the strict GoF sense. Some are language idioms, some are architectural patterns, some are deployment patterns, and others are domain-specific production practices. The goal is not to force everything into the GoF taxonomy, but to understand which recurring solutions are useful in modern C++ systems.</p>
                </div>

                <div class="table-of-contents">
                    <h3>Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-design-patterns-beyond-gof.html#modern-idioms">1. Modern C++ Idioms That Replace Some GoF Patterns</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-design-patterns-beyond-gof.html#dependency-management">2. Dependency Management: Service Locator vs Dependency Injection</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-design-patterns-beyond-gof.html#taxonomy">3. Taxonomy of Contemporary Non-GoF Patterns</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-design-patterns-beyond-gof.html#rule-of-thumb">4. Practical Rule of Thumb</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-design-patterns-beyond-gof.html#shortlist">5. The Modern C++ Developer's Shortlist</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-design-patterns-beyond-gof.html#conclusion">Conclusion</a></li>
                    </ul>
                </div>

                <section id="modern-idioms" class="blog-section">
                    <h2>1. Modern C++ Idioms That Replace Some GoF Patterns</h2>
                    <p>Before looking at larger architectural structures, it is useful to see how Modern C++ language features can replace or simplify several classic object-oriented patterns.</p>

                    <p>Many GoF patterns were designed to solve limitations of older C++ and Java-like object models. In modern C++, some of those problems are better solved with value types, templates, lambdas, concepts, <code>std::variant</code>, RAII, and type erasure.</p>

                    <h3>A. Modern Visitor: <code>std::variant</code> and <code>std::visit</code></h3>
                    <p>The classic Visitor pattern is often associated with invasive boilerplate: base classes, virtual functions, <code>accept()</code> methods, and a visitor interface with one overload per concrete type.</p>

                    <p>In modern C++, if the set of possible types is known at compile time, <code>std::variant</code> and <code>std::visit</code> often provide a cleaner alternative. This approach models a closed set of alternatives without requiring inheritance.</p>

                    <pre class="code-snippet"><code>#include &lt;iostream&gt;
#include &lt;variant&gt;
#include &lt;vector&gt;

struct Circle {
    double radius;
};

struct Square {
    double side;
};

// Sum type: no base class, no virtual functions.
using Shape = std::variant&lt;Circle, Square&gt;;

// Helper for combining lambdas.
template&lt;class... Ts&gt;
struct overloaded : Ts... {
    using Ts::operator()...;
};

template&lt;class... Ts&gt;
overloaded(Ts...) -&gt; overloaded&lt;Ts...&gt;;

int main() {
    std::vector&lt;Shape&gt; shapes{
        Circle{2.0},
        Square{3.0}
    };

    for (const auto&amp; shape : shapes) {
        std::visit(overloaded{
            [](const Circle&amp; c) {
                std::cout &lt;&lt; "Circle area: "
                          &lt;&lt; 3.14159 * c.radius * c.radius &lt;&lt; "\n";
            },
            [](const Square&amp; s) {
                std::cout &lt;&lt; "Square area: "
                          &lt;&lt; s.side * s.side &lt;&lt; "\n";
            }
        }, shape);
    }
}</code></pre>

                    <p>This approach avoids virtual dispatch, avoids pointer-based object graphs, keeps data types simple, and makes missing cases visible at compile time. However, it is best suited for closed type sets. If you need third-party plugins to add new types at runtime, classical polymorphism or type erasure may still be a better fit.</p>

                    <h3>B. Modern Strategy: Type Erasure and Callables</h3>
                    <p>The GoF Strategy pattern encapsulates interchangeable algorithms behind a common interface. Traditionally, this means defining an abstract base class and several concrete implementations.</p>

                    <p>In modern C++, many strategies can be represented directly as callables: lambdas, function objects, or type-erased wrappers such as <code>std::function</code> or C++23's <code>std::move_only_function</code>.</p>

                    <pre class="code-snippet"><code>#include &lt;algorithm&gt;
#include &lt;functional&gt;
#include &lt;iostream&gt;
#include &lt;vector&gt;

// C++23.
// If unavailable, use std::function or a custom type-erased wrapper.
using SortingStrategy =
    std::move_only_function&lt;void(std::vector&lt;int&gt;&amp;) const&gt;;

class Sequence {
public:
    Sequence(std::vector&lt;int&gt; data, SortingStrategy sorter)
        : data_(std::move(data)),
          sorter_(std::move(sorter)) {}

    void sort_data() {
        sorter_(data_);
    }

    void print() const {
        for (int value : data_) {
            std::cout &lt;&lt; value &lt;&lt; " ";
        }
        std::cout &lt;&lt; "\n";
    }

private:
    std::vector&lt;int&gt; data_;
    SortingStrategy sorter_;
};

int main() {
    Sequence sequence(
        {4, 2, 5, 1, 3},
        [](std::vector&lt;int&gt;&amp; values) {
            std::ranges::sort(values);
        }
    );

    sequence.sort_data();
    sequence.print();
}</code></pre>

                    <p><code>std::move_only_function</code> is a C++23 feature and may not be fully available on all toolchains. In C++17 or C++20 codebases, common alternatives include <code>std::function</code>, custom type erasure, template-based policies, or plain function objects.</p>

                    <h3>C. Static Polymorphism: Concepts Instead of Runtime Interfaces</h3>
                    <p>Classic object-oriented design often uses pure virtual interfaces to define behavior. This is still useful when runtime polymorphism is required. But when types are known at compile time, C++20 concepts provide a cleaner alternative. Concepts let you express requirements on template parameters directly.</p>

                    <pre class="code-snippet"><code>#include &lt;concepts&gt;
#include &lt;iostream&gt;
#include &lt;string_view&gt;

template&lt;typename T&gt;
concept Logger = requires(T logger, std::string_view message) {
    { logger.log(message) } -&gt; std::same_as&lt;void&gt;;
};

struct ConsoleLogger {
    void log(std::string_view message) {
        std::cout &lt;&lt; message &lt;&lt; "\n";
    }
};

void process(Logger auto&amp; logger) {
    logger.log("Processing with compile-time checked logging.");
}

int main() {
    ConsoleLogger logger;
    process(logger);
}</code></pre>

                    <p>Concepts make constraints explicit, improve compiler diagnostics, allow inlining, and avoid virtual dispatch when runtime polymorphism is unnecessary. This is especially valuable in performance-sensitive code such as inference engines, math libraries, embedded systems, and generic infrastructure.</p>
                </section>

                <section id="dependency-management" class="blog-section">
                    <h2>2. Dependency Management: Service Locator vs Dependency Injection</h2>
                    <p>How components obtain their dependencies is one of the most important architectural decisions in a codebase. This brings us to the Service Locator pattern.</p>

                    <h3>Where Does Service Locator Belong?</h3>
                    <p>Service Locator is not one of the original GoF 23 patterns. It is best classified as a dependency-access or object-lookup pattern. Some taxonomies place it near creational patterns because it helps obtain objects, but its real role is dependency management.</p>

                    <p>A Service Locator provides a central registry from which components can request services.</p>

                    <pre class="code-snippet"><code>#include &lt;iostream&gt;
#include &lt;string&gt;

class Logger {
public:
    void log(const std::string&amp; message) {
        std::cout &lt;&lt; message &lt;&lt; "\n";
    }
};

class ServiceLocator {
public:
    static void provide(Logger* logger) {
        logger_ = logger;
    }

    static Logger&amp; get_logger() {
        return *logger_;
    }

private:
    static inline Logger* logger_ = nullptr;
};</code></pre>

                    <p>A class can then retrieve the dependency directly:</p>

                    <pre class="code-snippet"><code>class Tracker {
public:
    void run() {
        auto&amp; logger = ServiceLocator::get_logger();
        logger.log("tracking");
    }
};</code></pre>

                    <p>This is convenient, but it comes with serious trade-offs.</p>

                    <h3>Why Service Locator Is Often Considered an Anti-Pattern</h3>
                    <p>The main problem with Service Locator is that it hides dependencies. Looking at the public API of <code>Tracker</code>, nothing tells you that it requires a <code>Logger</code>. The dependency is invisible. This makes the class harder to understand, harder to test, and harder to reuse.</p>

                    <pre class="code-snippet"><code>Tracker tracker;
tracker.run(); // Fails if ServiceLocator has not been initialized.</code></pre>

                    <p>The class appears simple, but it secretly depends on global setup. This creates several problems:</p>

                    <ul>
                        <li>hidden coupling;</li>
                        <li>order-of-initialization issues;</li>
                        <li>harder unit testing;</li>
                        <li>implicit global state;</li>
                        <li>unclear ownership;</li>
                        <li>harder reasoning in multithreaded systems.</li>
                    </ul>

                    <p>Service Locator is not "bad" because it never works. It is problematic because it makes dependencies less visible and moves failures from compile time or construction time to runtime.</p>

                    <h3>Modern Alternative: Explicit Dependency Injection</h3>
                    <p>A more explicit alternative is Constructor Injection. Instead of allowing a class to pull dependencies from a global registry, dependencies are pushed into the object from the outside.</p>

                    <pre class="code-snippet"><code>class Tracker {
public:
    explicit Tracker(Logger&amp; logger)
        : logger_(logger) {}

    void run() {
        logger_.log("tracking");
    }

private:
    Logger&amp; logger_;
};</code></pre>

                    <p>Now the dependency is visible in the constructor. This makes the design easier to test:</p>

                    <pre class="code-snippet"><code>Logger logger;
Tracker tracker{logger};
tracker.run();</code></pre>

                    <p>In production systems, dependencies are usually wired together in one place at application startup. This place is called the Composition Root.</p>

                    <pre class="code-snippet"><code>int main() {
    Logger logger;
    Tracker tracker{logger};

    tracker.run();
}</code></pre>

                    <p>The Composition Root keeps object graph construction centralized and prevents dependency-resolution logic from spreading throughout the codebase.</p>

                    <h3>When Is Service Locator Still Acceptable?</h3>
                    <table class="pattern-table">
                        <thead>
                            <tr>
                                <th>Context</th>
                                <th>Why it may be acceptable</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Legacy migration</td>
                                <td>Allows gradual replacement of hardcoded globals.</td>
                            </tr>
                            <tr>
                                <td>Plugin systems</td>
                                <td>Helps discover runtime-registered services.</td>
                            </tr>
                            <tr>
                                <td>Game engines</td>
                                <td>Avoids passing large context objects through thousands of entities.</td>
                            </tr>
                            <tr>
                                <td>Embedded systems</td>
                                <td>Sometimes used for constrained global infrastructure.</td>
                            </tr>
                            <tr>
                                <td>Cross-cutting diagnostics</td>
                                <td>Logging, metrics, tracing, or profiling hooks.</td>
                            </tr>
                            <tr>
                                <td>Test harnesses</td>
                                <td>Can simplify controlled replacement of infrastructure.</td>
                            </tr>
                        </tbody>
                    </table>

                    <p>The rule of thumb is simple: use explicit dependency injection for core business dependencies. Use Service Locator only when the dependency is truly infrastructural, cross-cutting, or difficult to pass explicitly without damaging the design.</p>
                </section>

                <section id="taxonomy" class="blog-section">
                    <h2>3. Taxonomy of Contemporary Non-GoF Patterns</h2>
                    <p>Modern C++ systems use many recurring design solutions that do not belong to the original GoF catalog. A useful way to organize them is by scope.</p>

                    <h3>A. Dependency and Composition Patterns</h3>
                    <p>These patterns control how components are wired together.</p>

                    <table class="pattern-table">
                        <thead>
                            <tr>
                                <th>Pattern</th>
                                <th>What it solves</th>
                                <th>C++ relevance</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Dependency Injection</td>
                                <td>Pass dependencies from outside instead of constructing them internally.</td>
                                <td>Standard for testable C++ services.</td>
                            </tr>
                            <tr>
                                <td>Composition Root</td>
                                <td>Centralize application wiring in one place.</td>
                                <td>Keeps construction out of business logic.</td>
                            </tr>
                            <tr>
                                <td>Factory Registry</td>
                                <td>Select implementations dynamically by name or type.</td>
                                <td>Useful for inference backends, codecs, and plugins.</td>
                            </tr>
                            <tr>
                                <td>Plugin Architecture</td>
                                <td>Load or register implementations at runtime.</td>
                                <td>Common in engines, SDKs, and ML runtimes.</td>
                            </tr>
                            <tr>
                                <td>Service Locator</td>
                                <td>Centralized service lookup.</td>
                                <td>Useful selectively, but dangerous if overused.</td>
                            </tr>
                        </tbody>
                    </table>

                    <h3>Factory Registry Example</h3>
                    <p>A Factory Registry is especially useful in C++ systems that support multiple backends, such as TensorRT, ONNX Runtime, LibTorch, OpenVINO, Vulkan, CUDA, or CPU fallback implementations.</p>

                    <pre class="code-snippet"><code>#include &lt;functional&gt;
#include &lt;memory&gt;
#include &lt;stdexcept&gt;
#include &lt;string&gt;
#include &lt;string_view&gt;
#include &lt;unordered_map&gt;

class IBackend {
public:
    virtual ~IBackend() = default;
    virtual void infer() = 0;
};

class BackendRegistry {
public:
    using Factory = std::function&lt;std::unique_ptr&lt;IBackend&gt;()&gt;;

    void register_backend(std::string name, Factory factory) {
        factories_.emplace(std::move(name), std::move(factory));
    }

    std::unique_ptr&lt;IBackend&gt; create(std::string_view name) const {
        auto it = factories_.find(std::string{name});

        if (it == factories_.end()) {
            throw std::runtime_error("Unknown backend");
        }

        return it-&gt;second();
    }

private:
    std::unordered_map&lt;std::string, Factory&gt; factories_;
};</code></pre>

                    <p>This avoids scattering large <code>if</code>, <code>else</code>, or <code>switch</code> blocks across the codebase. Instead of hardcoding every backend decision at every call site, you centralize backend creation in a registry.</p>

                    <h3>B. Data, ML, and Real-Time Inference Patterns</h3>
                    <p>High-performance systems often care more about memory layout, latency, cache behavior, and ownership than about class hierarchies. In AI inference, robotics, video processing, and real-time audio, the most important patterns are often data-centric.</p>

                    <h4>Pipeline and Producer-Consumer</h4>
                    <p>Instead of running one large sequential loop, a system can be split into stages connected by queues.</p>

                    <pre class="code-snippet"><code>[Camera Capture]
       |
       v
[Frame Queue]
       |
       v
[Inference Engine]
       |
       v
[Postprocessing]
       |
       v
[Output / Tracking / Alerts]</code></pre>

                    <p>A camera thread produces frames. An inference thread consumes frames and produces detections. A postprocessing stage consumes detections and produces application-level results. This is a natural fit for real-time systems because it improves CPU utilization, separates responsibilities, supports backpressure management, simplifies profiling, and isolates slow stages from fast ones.</p>

                    <h4>Zero-Copy Pipeline</h4>
                    <p>In high-throughput systems, copying large buffers is expensive. A zero-copy pipeline avoids copying raw frame data between stages. Instead, it passes ownership or references.</p>

                    <pre class="code-snippet"><code>using FramePtr = std::unique_ptr&lt;Frame&gt;;

ThreadSafeQueue&lt;FramePtr&gt; frame_queue;</code></pre>

                    <p>A producer can move the frame into the queue, and a consumer receives ownership without copying the underlying frame buffer.</p>

                    <pre class="code-snippet"><code>frame_queue.push(std::move(frame));

auto frame = frame_queue.pop();</code></pre>

                    <p>This is especially important for camera frames, GPU buffers, audio blocks, network packets, and tensor batches.</p>

                    <h4>Object Pool</h4>
                    <p>Repeated heap allocation in a hot path can cause latency spikes, memory fragmentation, and unpredictable performance. An Object Pool preallocates reusable resources and recycles them.</p>

                    <pre class="code-snippet"><code>#include &lt;functional&gt;
#include &lt;memory&gt;
#include &lt;mutex&gt;
#include &lt;vector&gt;

class Buffer {
public:
    Buffer() {
        // Heavy allocation, for example GPU memory or pinned host memory.
    }

    void reset() {
        // Clear metadata before reuse.
    }
};

class BufferPool {
public:
    using PoolPtr = std::unique_ptr&lt;Buffer, std::function&lt;void(Buffer*)&gt;&gt;;

    PoolPtr acquire() {
        std::lock_guard&lt;std::mutex&gt; lock(mutex_);

        if (pool_.empty()) {
            return PoolPtr(
                new Buffer(),
                [this](Buffer* buffer) {
                    recycle(buffer);
                }
            );
        }

        auto buffer = std::move(pool_.back());
        pool_.pop_back();

        return PoolPtr(
            buffer.release(),
            [this](Buffer* buffer) {
                recycle(buffer);
            }
        );
    }

private:
    void recycle(Buffer* buffer) {
        buffer-&gt;reset();

        std::lock_guard&lt;std::mutex&gt; lock(mutex_);
        pool_.push_back(std::unique_ptr&lt;Buffer&gt;(buffer));
    }

    std::vector&lt;std::unique_ptr&lt;Buffer&gt;&gt; pool_;
    std::mutex mutex_;
};</code></pre>

                    <p>This example is useful pedagogically, but the deleter captures <code>this</code>. That means the <code>BufferPool</code> must outlive every <code>PoolPtr</code> returned by <code>acquire()</code>. If a buffer handle survives longer than the pool, the deleter will call a destroyed object. In production code, enforce pool lifetime carefully or store the pool state in a <code>std::shared_ptr</code>-managed control block.</p>

                    <h4>Double Buffering</h4>
                    <p>Double buffering allows one part of the system to write into one buffer while another part reads from another buffer.</p>

                    <pre class="code-snippet"><code>Writer -&gt; Buffer A
Reader -&gt; Buffer B

Swap

Writer -&gt; Buffer B
Reader -&gt; Buffer A</code></pre>

                    <p>This reduces blocking and is commonly used in rendering, camera acquisition, real-time audio, and shared sensor state.</p>

                    <h3>C. Boundary and Migration Patterns</h3>
                    <p>Modern C++ systems often integrate with old C APIs, vendor SDKs, drivers, external services, and legacy codebases. Good architecture keeps those messy details at the boundary.</p>

                    <h4>Anti-Corruption Layer</h4>
                    <p>An Anti-Corruption Layer, often abbreviated as ACL, protects your clean domain model from external APIs. This is especially useful when dealing with vendor camera SDKs, legacy C libraries, hardware drivers, third-party inference runtimes, external network protocols, and old internal codebases.</p>

                    <pre class="code-snippet"><code>#include &lt;cstdint&gt;
#include &lt;expected&gt;
#include &lt;stdexcept&gt;
#include &lt;string&gt;
#include &lt;string_view&gt;
#include &lt;vector&gt;

// Legacy unsafe Vendor C API.
extern "C" {
    struct LegacyCamera {
        int handle;
    };

    int init_cam_sdk(LegacyCamera* camera, const char* config);
    int read_raw_frame(LegacyCamera* camera, void* buffer, int* size);
}

class ICamera {
public:
    virtual ~ICamera() = default;

    virtual std::expected&lt;std::vector&lt;std::uint8_t&gt;, std::string&gt;
    capture_frame() = 0;
};

class VendorCameraACL final : public ICamera {
public:
    explicit VendorCameraACL(std::string_view config) {
        if (init_cam_sdk(&amp;camera_, config.data()) != 0) {
            throw std::runtime_error("Failed to initialize camera SDK");
        }
    }

    std::expected&lt;std::vector&lt;std::uint8_t&gt;, std::string&gt;
    capture_frame() override {
        std::vector&lt;std::uint8_t&gt; buffer(1920 * 1080 * 3);

        int bytes_read = 0;

        if (read_raw_frame(&amp;camera_, buffer.data(), &amp;bytes_read) != 0) {
            return std::unexpected("Hardware read failure");
        }

        buffer.resize(static_cast&lt;std::size_t&gt;(bytes_read));
        return buffer;
    }

private:
    LegacyCamera camera_{};
};</code></pre>

                    <p><code>std::expected</code> is a C++23 feature. Before C++23, similar behavior can be achieved with <code>tl::expected</code>, <code>boost::outcome</code>, <code>std::variant</code>, or project-specific <code>Result&lt;T, E&gt;</code> types. The key idea is not the specific type. The key idea is to keep unsafe external APIs outside the clean core of your system.</p>

                    <h4>Strangler Fig</h4>
                    <p>The Strangler Fig pattern is used to gradually migrate legacy systems. Instead of rewriting everything at once, you place a new interface around the old system and replace functionality piece by piece.</p>

                    <pre class="code-snippet"><code>Old System
    |
    v
Compatibility Interface
    |
    v
New Modern C++ Implementation</code></pre>

                    <p>Over time, the new implementation grows until the old system is no longer needed. This is safer than big-bang rewrites, especially in production systems where correctness and uptime matter.</p>

                    <h4>Adapter at the Architecture Boundary</h4>
                    <p>The Adapter pattern still matters in modern C++, but it is often most valuable at architectural boundaries. Instead of adapting every object internally, you adapt external APIs before they enter your domain model.</p>

                    <pre class="code-snippet"><code>Vendor SDK Model  ---&gt;  Adapter  ---&gt;  Internal Domain Model</code></pre>

                    <p>This keeps the rest of the codebase independent from vendor-specific data structures.</p>

                    <h3>D. Resilience and Cloud-Native Patterns</h3>
                    <p>C++ is increasingly used in distributed systems, backend services, robotics fleets, edge devices, and cloud-native infrastructure. In those environments, failures are normal. Networks fail. Services time out. GPUs run out of memory. Queues grow. Downstream systems become overloaded.</p>

                    <h4>Circuit Breaker</h4>
                    <p>A Circuit Breaker wraps fragile operations, such as remote calls, database queries, or external service requests. If too many failures occur, the circuit opens and future calls fail fast for a period of time.</p>

                    <pre class="code-snippet"><code>Closed    -&gt; calls allowed
Open      -&gt; calls fail fast
Half-open -&gt; limited trial calls allowed</code></pre>

                    <p>This prevents the system from wasting threads and resources waiting on operations that are likely to fail.</p>

                    <h4>Bulkhead</h4>
                    <p>The Bulkhead pattern isolates resources so that one overloaded subsystem does not take down the whole application.</p>

                    <pre class="code-snippet"><code>Thread Pool A -&gt; video processing
Thread Pool B -&gt; REST API
Thread Pool C -&gt; telemetry</code></pre>

                    <p>If the REST API is overloaded, the video processing pipeline can continue running. This is especially useful in systems that combine real-time processing with management APIs, dashboards, telemetry, or background tasks.</p>

                    <h4>Retry with Exponential Backoff</h4>
                    <p>Retries are useful for transient failures, but retrying too aggressively can make the situation worse. Exponential backoff increases the delay between attempts:</p>

                    <pre class="code-snippet"><code>100 ms -&gt; 200 ms -&gt; 400 ms -&gt; 800 ms -&gt; ...</code></pre>

                    <p>In distributed systems, this is often combined with jitter to prevent many clients from retrying at exactly the same time.</p>

                    <h3>E. Enterprise, Domain, and Event-Driven Patterns</h3>
                    <p>Some non-GoF patterns are especially common in enterprise systems, event-driven systems, and domain-driven design. They are not specific to C++, but they can be useful when C++ is used in backend or infrastructure services.</p>

                    <h4>CQRS</h4>
                    <p>CQRS stands for Command Query Responsibility Segregation. The idea is to separate write operations from read operations.</p>

                    <pre class="code-snippet"><code>Commands -&gt; modify state
Queries  -&gt; read state</code></pre>

                    <p>This can simplify scaling and performance tuning. For example, a write path may enforce domain invariants and transactions, while a read path may use optimized projections or cache-friendly views.</p>

                    <h4>Repository</h4>
                    <p>The Repository pattern hides persistence details behind a collection-like interface. Instead of scattering SQL, file access, or remote database calls throughout the business logic, the domain code talks to a repository.</p>

                    <pre class="code-snippet"><code>class UserRepository {
public:
    virtual ~UserRepository() = default;

    virtual std::optional&lt;User&gt; find_by_id(UserId id) = 0;
    virtual void save(const User&amp; user) = 0;
};</code></pre>

                    <p>This is useful when the business logic should not depend directly on the database implementation.</p>

                    <h4>Unit of Work</h4>
                    <p>Unit of Work groups multiple changes into a single transactional operation.</p>

                    <pre class="code-snippet"><code>begin transaction
    modify object A
    modify object B
    modify object C
commit</code></pre>

                    <p>This is common in systems that need consistency across multiple repository operations.</p>

                    <h4>Sidecar and Backend-for-Frontend</h4>
                    <p>Sidecar and BFF are not C++ design patterns in the traditional sense. They are architectural and deployment patterns. A Sidecar is a helper process or container deployed alongside the main application. It may handle telemetry, logging, TLS, service discovery, or proxying.</p>

                    <pre class="code-snippet"><code>[C++ Service] &lt;-&gt; [Sidecar Proxy]</code></pre>

                    <p>A Backend-for-Frontend, or BFF, is a dedicated backend tailored to a specific frontend or client type. These patterns are common in cloud-native systems where infrastructure concerns are separated from core application logic.</p>
                </section>

                <section id="rule-of-thumb" class="blog-section">
                    <h2>4. Practical Rule of Thumb</h2>
                    <p>Here is a practical decision matrix for modern C++ systems.</p>

                    <table class="pattern-table">
                        <thead>
                            <tr>
                                <th>Situation</th>
                                <th>Prefer</th>
                                <th>Avoid</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>Core dependency required by a class</td>
                                <td>Constructor Injection</td>
                                <td>Service Locator or hidden globals</td>
                            </tr>
                            <tr>
                                <td>Wiring many objects at startup</td>
                                <td>Composition Root</td>
                                <td>Scattered initialization</td>
                            </tr>
                            <tr>
                                <td>Selecting implementation at runtime</td>
                                <td>Factory Registry / Plugin Pattern</td>
                                <td>Hardcoded conditional branches everywhere</td>
                            </tr>
                            <tr>
                                <td>Integrating with C APIs or vendor SDKs</td>
                                <td>Anti-Corruption Layer</td>
                                <td>Spreading raw SDK calls across business logic</td>
                            </tr>
                            <tr>
                                <td>Optional cross-cutting infrastructure</td>
                                <td>Carefully controlled Service Locator</td>
                                <td>Raw global variables</td>
                            </tr>
                            <tr>
                                <td>High-throughput frame processing</td>
                                <td>Pipeline + Producer-Consumer</td>
                                <td>One massive sequential loop</td>
                            </tr>
                            <tr>
                                <td>Passing large buffers</td>
                                <td>Move ownership or references</td>
                                <td>Repeated deep copies</td>
                            </tr>
                            <tr>
                                <td>High-frequency allocations</td>
                                <td>RAII + Object Pool</td>
                                <td>Repeated hot-path heap allocation</td>
                            </tr>
                            <tr>
                                <td>Runtime failure on hot path</td>
                                <td><code>expected</code> / result types</td>
                                <td>Error codes spread everywhere</td>
                            </tr>
                            <tr>
                                <td>Remote service instability</td>
                                <td>Circuit Breaker + Backoff</td>
                                <td>Infinite retries</td>
                            </tr>
                            <tr>
                                <td>Resource overload</td>
                                <td>Bulkhead isolation</td>
                                <td>Shared thread pool for everything</td>
                            </tr>
                        </tbody>
                    </table>
                </section>

                <section id="shortlist" class="blog-section">
                    <h2>5. The Modern C++ Developer's Shortlist</h2>
                    <p>If you work on modern C++ systems, especially in backend, AI inference, robotics, computer vision, or high-performance computing, the most useful patterns and idioms to master are the following.</p>

                    <h3>RAII and Rule of Zero</h3>
                    <p>RAII is the foundation of reliable C++. Resources should be acquired in constructors and released in destructors. Whenever possible, ownership should be expressed using standard library types such as <code>std::vector</code>, <code>std::unique_ptr</code>, <code>std::shared_ptr</code>, <code>std::lock_guard</code>, and <code>std::jthread</code>.</p>

                    <p>The Rule of Zero says that most classes should not manually define destructors, copy constructors, move constructors, or assignment operators. Let the members manage themselves.</p>

                    <h3>Dependency Injection and Composition Root</h3>
                    <p>Make dependencies explicit. A class should clearly state what it needs to function. Constructor injection makes code easier to test, easier to understand, and easier to maintain. The Composition Root keeps dependency wiring in one place.</p>

                    <h3>Type Erasure and Policy-Based Design</h3>
                    <p>Use type erasure when you need runtime flexibility without exposing inheritance-heavy APIs. Use policy-based design when behavior can be selected at compile time. Both are powerful alternatives to traditional object-oriented hierarchies.</p>

                    <h3>Concepts and Static Polymorphism</h3>
                    <p>Use concepts to express compile-time requirements clearly. They are especially useful in generic libraries, performance-sensitive code, and template-heavy systems.</p>

                    <h3>Pipeline and Producer-Consumer</h3>
                    <p>Use pipelines to split real-time processing into independent stages. This is one of the most important patterns for video processing, AI inference, robotics, streaming systems, and data acquisition.</p>

                    <h3>Object Pool and Zero-Copy Ownership</h3>
                    <p>Avoid repeated allocation and copying in hot paths. Use object pools, move semantics, preallocated buffers, and ownership-passing queues to reduce latency and improve predictability.</p>

                    <h3>Anti-Corruption Layer</h3>
                    <p>Keep unsafe, ugly, or unstable external APIs at the boundary. Do not let vendor SDK types, C APIs, or legacy models spread throughout your internal codebase.</p>

                    <h3>Circuit Breaker and Bulkhead</h3>
                    <p>In distributed or service-oriented systems, design for failure. Use circuit breakers to fail fast when dependencies are unhealthy. Use bulkheads to isolate critical resources.</p>
                </section>

                <section id="conclusion" class="blog-section">
                    <h2>Conclusion</h2>
                    <p>The original GoF patterns are still historically important, but modern C++ requires a broader vocabulary.</p>

                    <p>Today, good C++ architecture is not only about class diagrams. It is about ownership, lifetimes, data movement, concurrency, compile-time constraints, hardware resources, dependency boundaries, and operational resilience.</p>

                    <p>Some classic patterns remain useful. Others are replaced by language features. Many new recurring solutions come from domains the GoF book did not address: real-time systems, cloud infrastructure, AI inference, GPU programming, and distributed services.</p>

                    <p>The modern C++ mindset is this:</p>

                    <ul>
                        <li>Prefer explicit ownership.</li>
                        <li>Prefer explicit dependencies.</li>
                        <li>Prefer value semantics when possible.</li>
                        <li>Prefer compile-time validation when practical.</li>
                        <li>Protect your domain from messy boundaries.</li>
                        <li>Design hot paths around data movement, not object hierarchies.</li>
                        <li>Design distributed systems assuming failure will happen.</li>
                    </ul>

                    <p>By moving from inheritance-heavy designs toward RAII, composition, concepts, pipelines, type erasure, and clean architectural boundaries, modern C++ systems become faster, safer, easier to test, and better prepared for production workloads.</p>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>CMake CUDA Architecture Configuration: A Practical Guide</title>
      <link>https://olibartfast.ninja/blog/cmake-cuda-architectures-guide.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/cmake-cuda-architectures-guide.html</guid>
      <pubDate>Fri, 06 Feb 2026 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A practical guide to handling GPU architectures correctly in CMake 3.23+, covering native detection, special values, and production best practices.</description>
      <content:encoded><![CDATA[<p>When building CUDA applications with CMake, one of the most common pain points is handling GPU architectures correctly. Let's explore the right way to do this in 2025.</p>

                <h2>The Problem</h2>
                <p>You've probably seen (or written) code like this:</p>

                <pre class="cuda-snippet"><code class="language-cmake">set_target_properties(my_cuda_app PROPERTIES 
    CUDA_ARCHITECTURES 70)  # Hardcoded for Tesla T4</code></pre>

                <p>This works... until you try to run on a different GPU, or distribute your code to others. Not ideal.</p>

                <h2>The Solution: Let CMake Do The Work</h2>

                <h3>Modern Approach (CMake 3.23+)</h3>
                <p>The simplest solution? <strong>Don't set it at all.</strong></p>

                <pre class="cuda-snippet"><code class="language-cmake">cmake_minimum_required(VERSION 3.23)
project(MyCudaApp LANGUAGES CXX CUDA)

add_executable(my_app main.cu)

set_target_properties(my_app PROPERTIES 
    CUDA_SEPARABLE_COMPILATION ON
    CXX_STANDARD 17)

# That's it! CMake will auto-detect your GPU</code></pre>

                <p>CMake 3.23+ automatically detects the GPU on your build machine and compiles for it.</p>

                <h3>Using Special Architecture Values</h3>
                <p>CMake provides three special values for <code>CMAKE_CUDA_ARCHITECTURES</code>:</p>

                <pre class="cuda-snippet"><code class="language-cmake"># Auto-detect GPU on build machine (CMake 3.24+)
set(CMAKE_CUDA_ARCHITECTURES native)

# Compile for ALL supported architectures (slow, large binaries)
set(CMAKE_CUDA_ARCHITECTURES all)

# Compile for major architecture versions only (balanced)
set(CMAKE_CUDA_ARCHITECTURES all-major)</code></pre>

                <h3>Flexible Configuration</h3>
                <p>For maximum flexibility, allow users to override while providing sensible defaults:</p>

                <pre class="cuda-snippet"><code class="language-cmake">cmake_minimum_required(VERSION 3.23)
project(MyCudaApp LANGUAGES CXX CUDA)

# Default to native detection, but allow override
if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
    set(CMAKE_CUDA_ARCHITECTURES native)
endif()

add_executable(my_app main.cu)
set_target_properties(my_app PROPERTIES CUDA_SEPARABLE_COMPILATION ON)</code></pre>

                <p>Users can now override at build time:</p>
                <pre class="cuda-snippet"><code class="language-bash">cmake -DCMAKE_CUDA_ARCHITECTURES="80;86" ..</code></pre>

                <h2>Understanding CUDA Compute Capabilities</h2>
                <p>Here's a quick reference for common GPU architectures:</p>

                <table>
                    <thead>
                        <tr>
                            <th>Architecture</th>
                            <th>Compute Capability</th>
                            <th>Examples</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>Pascal</td>
                            <td>60, 61</td>
                            <td>P100, GTX 1080</td>
                        </tr>
                        <tr>
                            <td>Volta</td>
                            <td>70</td>
                            <td>V100, Titan V</td>
                        </tr>
                        <tr>
                            <td>Turing</td>
                            <td>75</td>
                            <td>RTX 2080, T4</td>
                        </tr>
                        <tr>
                            <td>Ampere</td>
                            <td>80, 86</td>
                            <td>A100, RTX 3090, Orin</td>
                        </tr>
                        <tr>
                            <td>Ada Lovelace</td>
                            <td>89</td>
                            <td>RTX 4090, L40</td>
                        </tr>
                        <tr>
                            <td>Hopper</td>
                            <td>90</td>
                            <td>H100, H200</td>
                        </tr>
                    </tbody>
                </table>

                <h2>Real vs Virtual Architectures</h2>
                <p>When you specify architectures, you can use suffixes:</p>

                <pre class="cuda-snippet"><code class="language-cmake"># Generate native code only (SASS) - faster runtime, GPU-specific
set(CMAKE_CUDA_ARCHITECTURES 80-real)

# Generate PTX intermediate code - slower runtime, forward compatible
set(CMAKE_CUDA_ARCHITECTURES 80-virtual)

# Generate both (default if no suffix)
set(CMAKE_CUDA_ARCHITECTURES 80)</code></pre>

                <p><strong>Rule of thumb:</strong></p>
                <ul>
                    <li>Use <code>-real</code> for production builds targeting specific hardware</li>
                    <li>Omit suffix for distribution (includes PTX for forward compatibility)</li>
                    <li>Never use <code>-virtual</code> alone unless you have a specific reason</li>
                </ul>

                <h2>Practical Examples</h2>

                <h3>Development Build (Fast Iteration)</h3>
                <pre class="cuda-snippet"><code class="language-cmake"># Just compile for your local GPU
set(CMAKE_CUDA_ARCHITECTURES native)</code></pre>

                <h3>Distribution Build (Maximum Compatibility)</h3>
                <pre class="cuda-snippet"><code class="language-cmake"># Cover common datacenter and consumer GPUs (2017-2024)
set(CMAKE_CUDA_ARCHITECTURES 70-real 75-real 80-real 86-real 89 90)</code></pre>
                <p>Note: Including one architecture without <code>-real</code> (like <code>89</code>) adds PTX for forward compatibility.</p>

                <h3>Edge Deployment (Specific Hardware)</h3>
                <pre class="cuda-snippet"><code class="language-cmake"># You know your target hardware
set(CMAKE_CUDA_ARCHITECTURES 87)  # NVIDIA Orin</code></pre>

                <h3>CI/CD Pipeline</h3>
                <pre class="cuda-snippet"><code class="language-cmake">if(DEFINED ENV{CI})
    # In CI, compile for multiple targets
    set(CMAKE_CUDA_ARCHITECTURES 70 75 80 86 89 90)
else()
    # Local development: use native
    set(CMAKE_CUDA_ARCHITECTURES native)
endif()</code></pre>

                <h2>Complete Example</h2>
                <p>Here's a production-ready CMakeLists.txt:</p>

                <pre class="cuda-snippet"><code class="language-cmake">cmake_minimum_required(VERSION 3.23)
project(CudaVisionApp VERSION 1.0.0 LANGUAGES CXX CUDA)

# Architecture configuration
if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
    if(DEFINED ENV{CI})
        # CI: compile for multiple common architectures
        set(CMAKE_CUDA_ARCHITECTURES 70 75 80 86 89 90)
        message(STATUS "CI detected: compiling for multiple architectures")
    else()
        # Local: auto-detect current GPU
        set(CMAKE_CUDA_ARCHITECTURES native)
        message(STATUS "Using native GPU architecture detection")
    endif()
endif()

message(STATUS "CUDA architectures: ${CMAKE_CUDA_ARCHITECTURES}")

# Your CUDA executable
add_executable(vision_app 
    src/main.cu
    src/kernel.cu
)

target_include_directories(vision_app PRIVATE include)

set_target_properties(vision_app PROPERTIES
    CUDA_SEPARABLE_COMPILATION ON
    CXX_STANDARD 17
    CUDA_STANDARD 17
)

# Optional: link against cuDNN, TensorRT, etc.
# find_package(CUDAToolkit REQUIRED)
# target_link_libraries(vision_app PRIVATE CUDA::cudart)</code></pre>

                <h2>Build Commands</h2>

                <pre class="cuda-snippet"><code class="language-bash"># Use defaults (native detection)
cmake -B build
cmake --build build

# Override for specific architecture
cmake -B build -DCMAKE_CUDA_ARCHITECTURES="80;86"
cmake --build build

# Override for all major architectures
cmake -B build -DCMAKE_CUDA_ARCHITECTURES=all-major
cmake --build build

# Check what architectures were used
cmake -B build -DCMAKE_CUDA_ARCHITECTURES=native --trace-expand | grep CUDA_ARCHITECTURES</code></pre>

                <h2>Common Pitfalls</h2>

                <h3>❌ Don't hardcode architectures in CMakeLists.txt</h3>
                <pre class="cuda-snippet"><code class="language-cmake">set(CMAKE_CUDA_ARCHITECTURES 70)  # Bad!</code></pre>

                <h3>✅ Do provide flexible defaults</h3>
                <pre class="cuda-snippet"><code class="language-cmake">if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
    set(CMAKE_CUDA_ARCHITECTURES native)
endif()</code></pre>

                <h3>❌ Don't use <code>all</code> for production</h3>
                <pre class="cuda-snippet"><code class="language-cmake">set(CMAKE_CUDA_ARCHITECTURES all)  # Extremely slow builds, huge binaries</code></pre>

                <h3>✅ Do target your actual deployment hardware</h3>
                <pre class="cuda-snippet"><code class="language-cmake">set(CMAKE_CUDA_ARCHITECTURES 80-real 86-real 89)  # A100, RTX30xx, RTX40xx + PTX</code></pre>

                <h2>Version Compatibility</h2>

                <table>
                    <thead>
                        <tr>
                            <th>CMake Version</th>
                            <th>Feature</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>3.18+</td>
                            <td><code>CMAKE_CUDA_ARCHITECTURES</code> property</td>
                        </tr>
                        <tr>
                            <td>3.23+</td>
                            <td>Automatic architecture detection</td>
                        </tr>
                        <tr>
                            <td>3.24+</td>
                            <td><code>native</code> value support</td>
                        </tr>
                    </tbody>
                </table>

                <p>If you're stuck on CMake < 3.23, you'll need to detect manually or require users to specify architectures.</p>

                <h2>Conclusion</h2>
                <p>For most projects in 2025:</p>
                <ol>
                    <li>Use CMake 3.23 or newer</li>
                    <li>Set <code>CMAKE_CUDA_ARCHITECTURES</code> to <code>native</code> as default</li>
                    <li>Allow override via command line: <code>-DCMAKE_CUDA_ARCHITECTURES="..."</code></li>
                    <li>For distribution, explicitly list your target architectures</li>
                </ol>

                <p>This gives you fast local development while maintaining flexibility for CI/CD and distribution.</p>

                <h2>Further Reading</h2>
                <ul>
                    <li><a href="https://cmake.org/cmake/help/latest/prop_tgt/CUDA_ARCHITECTURES.html">CMake CUDA_ARCHITECTURES Documentation</a></li>
                    <li><a href="https://developer.nvidia.com/cuda-gpus">NVIDIA CUDA Compute Capabilities</a></li>
                    <li><a href="https://cmake.org/cmake/help/latest/manual/cmake-compile-features.7.html#cuda-standards">CMake CUDA Support Guide</a></li>
                </ul>]]></content:encoded>
    </item>
    <item>
      <title>The Ultimate Guide to Modern C++ Projects</title>
      <link>https://olibartfast.ninja/blog/modern-cpp-projects-guide.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/modern-cpp-projects-guide.html</guid>
      <pubDate>Sat, 20 Dec 2025 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A comprehensive guide to setting up, structuring, and managing modern C++ projects with best practices, tools, and workflows.</description>
      <content:encoded><![CDATA[<p>In the era of Modern C++ (C++17/20/23), the language has evolved into a powerful tool for safe and expressive high-performance computing. However, the ecosystem around it—build systems, testing, and continuous integration—is just as critical as the code itself.</p>
                
                <p>This guide walks you through setting up a production-ready C++ project using modern CMake, proper dependency injection, compiler hardening, and a robust CI/CD pipeline.</p>

                <div class="table-of-contents">
                    <h3>📑 Table of Contents</h3>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-projects-guide.html#project-structure">1. Project Structure and Modularity</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-projects-guide.html#testability">2. Testability and Dependency Injection</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-projects-guide.html#e2e-testing">3. End-to-End Testing with CTest</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-projects-guide.html#compiler-hardening">4. Compiler Hardening and Sanitizers</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-projects-guide.html#dependency-management">5. Reproducibility and Dependency Management</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-projects-guide.html#ci-cd">6. CI/CD Pipeline (GitHub Actions)</a></li>
                        <li><a href="https://olibartfast.ninja/blog/modern-cpp-projects-guide.html#summary">Summary</a></li>
                    </ul>
                </div>

                <section id="project-structure" class="blog-section">
                    <h2>1. Project Structure and Modularity</h2>
                    <p>The days of a single <code>main.cpp</code> or a flat folder structure are over. A modern project should be modular, separating public interfaces from private implementations.</p>

                    <h3>The Recommended Layout</h3>
                    <p>Adopt a standard layout that tools and other developers expect:</p>

                    <pre class="code-snippet"><code>my-project/
├── CMakeLists.txt            # Root build definition
├── CMakePresets.json         # Build configurations
├── vcpkg.json                # Dependency manifest
├── src/
│   ├── app/                  # Executable code
│   └── core/                 # Business logic (library)
├── include/
│   └── myproject/            # Public headers
├── tests/
│   ├── unit/
│   └── e2e/
└── external/                 # For vendored dependencies</code></pre>

                    <h3>Modern CMake: Targets over Variables</h3>
                    <p>Forget <code>include_directories</code> and <code>link_libraries</code>. Modern CMake is all about <strong>Targets</strong> and <strong>Properties</strong>.</p>
                    
                    <ul>
                        <li><strong>Rule:</strong> Always use <code>target_include_directories</code>, <code>target_compile_features</code>, and <code>target_link_libraries</code>.</li>
                        <li><strong>Visibility:</strong> Use <code>PUBLIC</code>, <code>PRIVATE</code>, and <code>INTERFACE</code> to control dependency propagation.</li>
                    </ul>

                    <p><strong>src/core/CMakeLists.txt:</strong></p>
                    <pre class="code-snippet"><code>add_library(core_lib STATIC implementation.cpp)

# Consumers automatically get the include path
target_include_directories(core_lib PUBLIC
    $&lt;BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/../../include&gt;
    $&lt;INSTALL_INTERFACE:include&gt;
)

# Enforce C++20 for this library and its consumers
target_compile_features(core_lib PUBLIC cxx_std_20)</code></pre>

                    <h3>CMake Presets for Reproducible Builds</h3>
                    <p>CMakePresets.json (introduced in CMake 3.19) standardizes build configurations across your team and CI. Instead of remembering complex command-line flags, developers simply run <code>cmake --preset=release</code>.</p>

                    <p><strong>CMakePresets.json:</strong></p>
                    <pre class="code-snippet"><code>{
  "version": 6,
  "cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
  "configurePresets": [
    {
      "name": "base",
      "hidden": true,
      "generator": "Ninja",
      "binaryDir": "${sourceDir}/build/${presetName}",
      "cacheVariables": {
        "CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
      }
    },
    {
      "name": "debug",
      "inherits": "base",
      "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" }
    },
    {
      "name": "release",
      "inherits": "base",
      "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" }
    }
  ],
  "buildPresets": [
    { "name": "debug", "configurePreset": "debug" },
    { "name": "release", "configurePreset": "release" }
  ]
}</code></pre>
                </section>

                <section id="testability" class="blog-section">
                    <h2>2. Testability and Dependency Injection</h2>
                    <p>Writing testable C++ means writing code that is <strong>loosely coupled</strong>. The biggest enemies of unit testing are singletons and direct instantiation of heavy dependencies (databases, network sockets, file systems) inside your business logic.</p>

                    <h3>The Approach: Constructor Injection</h3>
                    <p>Instead of instantiating a dependency inside your class, accept an interface (abstract base class) in the constructor.</p>

                    <p><strong>The Interface (The Contract):</strong></p>
                    <pre class="code-snippet"><code>// IDataStore.hpp
class IDataStore {
public:
    virtual ~IDataStore() = default;
    virtual std::string GetData(int id) = 0;
};</code></pre>

                    <p><strong>The Consumer (Your Business Logic):</strong></p>
                    <pre class="code-snippet"><code>// UserManager.hpp
class UserManager {
    IDataStore& db_;  // Reference to interface

public:
    // Dependency Injection via Constructor
    explicit UserManager(IDataStore& db) : db_(db) {}

    std::string GetUserName(int id) {
        return "User: " + db_.GetData(id);
    }
};</code></pre>

                    <h3>Unit Testing with Google Mock</h3>
                    <p>Now you can inject a mock object during testing without needing a real database:</p>

                    <pre class="code-snippet"><code>// tests/unit/TestUserManager.cpp
#include &lt;gtest/gtest.h&gt;
#include &lt;gmock/gmock.h&gt;
#include "UserManager.hpp"

class MockDB : public IDataStore {
public:
    MOCK_METHOD(std::string, GetData, (int id), (override));
};

TEST(UserManagerTest, FormatsNameCorrectly) {
    MockDB mock_db;

    // Expectation: When GetData(42) is called, return "Alice"
    EXPECT_CALL(mock_db, GetData(42)).WillOnce(testing::Return("Alice"));

    UserManager mgr(mock_db);
    EXPECT_EQ(mgr.GetUserName(42), "User: Alice");
}</code></pre>
                </section>

                <section id="e2e-testing" class="blog-section">
                    <h2>3. End-to-End Testing with CTest</h2>
                    <p>Unit tests verify logic in isolation, but E2E tests verify the application works as a whole. CMake's CTest tool is excellent for orchestrating both.</p>

                    <p>For a C++ CLI application, an E2E test typically looks like: run the binary with arguments X, expect output Y.</p>

                    <p><strong>tests/e2e/CMakeLists.txt:</strong></p>
                    <pre class="code-snippet"><code>add_test(
    NAME E2E_Login_Flow
    COMMAND python3 ${CMAKE_CURRENT_SOURCE_DIR}/test_login.py
            $&lt;TARGET_FILE:my_app_executable&gt;
)</code></pre>

                    <p><strong>tests/e2e/test_login.py:</strong></p>
                    <pre class="code-snippet"><code>import subprocess
import sys

executable_path = sys.argv[1]
result = subprocess.run(
    [executable_path, "--login", "user"],
    capture_output=True,
    text=True
)

if "Welcome, user" in result.stdout:
    sys.exit(0)  # Success
else:
    print(f"Failed! Output was: {result.stdout}")
    sys.exit(1)  # Failure</code></pre>

                    <div class="tips-box">
                        <p><strong>💡 Tip:</strong> For more complex E2E scenarios, consider using <code>pytest</code> with fixtures for setup/teardown and better assertion messages.</p>
                    </div>

                    <p>Running <code>ctest</code> in your build folder will execute both your GTest unit tests and your Python E2E scripts.</p>
                </section>

                <section id="compiler-hardening" class="blog-section">
                    <h2>4. Compiler Hardening and Sanitizers</h2>
                    <p>A production-ready project should catch bugs at compile time whenever possible and use runtime sanitizers in Debug builds.</p>

                    <h3>Warning Flags</h3>
                    <p>Create a reusable interface target for compiler warnings:</p>

                    <p><strong>cmake/CompilerWarnings.cmake:</strong></p>
                    <pre class="code-snippet"><code>add_library(project_warnings INTERFACE)

if(MSVC)
    target_compile_options(project_warnings INTERFACE /W4 /WX /permissive-)
else()
    target_compile_options(project_warnings INTERFACE
        -Wall -Wextra -Wpedantic -Werror
        -Wshadow -Wnon-virtual-dtor -Wold-style-cast
        -Wcast-align -Wunused -Woverloaded-virtual
        -Wconversion -Wsign-conversion -Wnull-dereference
    )
endif()

# Usage: target_link_libraries(my_target PRIVATE project_warnings)</code></pre>

                    <h3>Address and Undefined Behavior Sanitizers</h3>
                    <p>Enable sanitizers in Debug builds to catch memory errors and undefined behavior:</p>

                    <p><strong>cmake/Sanitizers.cmake:</strong></p>
                    <pre class="code-snippet"><code>option(ENABLE_SANITIZERS "Enable ASan and UBSan" OFF)

if(ENABLE_SANITIZERS AND NOT MSVC)
    add_compile_options(-fsanitize=address,undefined -fno-omit-frame-pointer)
    add_link_options(-fsanitize=address,undefined)
endif()</code></pre>
                </section>

                <section id="dependency-management" class="blog-section">
                    <h2>5. Reproducibility and Dependency Management</h2>
                    <p>"It works on my machine" is not an acceptable excuse. To achieve reproducibility, you must manage third-party libraries strictly. <strong>Do not ask users to install dependencies manually</strong>—use a package manager.</p>

                    <h3>Using vcpkg</h3>
                    <p>vcpkg integrates seamlessly with CMake via a toolchain file. Create a manifest file to declare your dependencies:</p>

                    <p><strong>vcpkg.json:</strong></p>
                    <pre class="code-snippet"><code>{
  "name": "my-project",
  "version-string": "1.0.0",
  "dependencies": [
    "fmt",
    "gtest",
    "nlohmann-json",
    "spdlog"
  ]
}</code></pre>

                    <p>When you run CMake with the vcpkg toolchain, it automatically downloads and builds specific versions of these libraries, ensuring every developer and CI runner has the exact same binary dependencies.</p>

                    <h3>Alternative: Conan</h3>
                    <p>Conan is another popular option, especially for projects that need fine-grained control over package versions or binary compatibility. A <code>conanfile.txt</code> serves the same purpose:</p>

                    <pre class="code-snippet"><code>[requires]
fmt/10.1.1
gtest/1.14.0
nlohmann_json/3.11.2

[generators]
CMakeDeps
CMakeToolchain</code></pre>
                </section>

                <section id="ci-cd" class="blog-section">
                    <h2>6. CI/CD Pipeline (GitHub Actions)</h2>
                    <p>A modern C++ project must build and test on multiple platforms automatically. This proves your code compiles with GCC, Clang, and MSVC.</p>

                    <p><strong>.github/workflows/ci.yml:</strong></p>
                    <pre class="code-snippet"><code>name: CI

on: [push, pull_request]

jobs:
  build:
    name: ${{ matrix.os }} - ${{ matrix.config }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        config: [Debug, Release]

    steps:
    - uses: actions/checkout@v4
      with:
        submodules: true

    - name: Setup vcpkg
      shell: bash
      run: |
        if [[ "$RUNNER_OS" == "Windows" ]]; then
          ./vcpkg/bootstrap-vcpkg.bat
        else
          ./vcpkg/bootstrap-vcpkg.sh
        fi

    - name: Configure CMake
      run: |
        cmake -B build -S . \
          -DCMAKE_TOOLCHAIN_FILE=vcpkg/scripts/buildsystems/vcpkg.cmake \
          -DCMAKE_BUILD_TYPE=${{ matrix.config }} \
          -DENABLE_SANITIZERS=${{ matrix.config == 'Debug' }}

    - name: Build
      run: cmake --build build --config ${{ matrix.config }}

    - name: Run Tests
      working-directory: build
      run: ctest -C ${{ matrix.config }} --output-on-failure</code></pre>

                    <h3>Key Features of This Pipeline</h3>
                    <ol>
                        <li><strong>Cross-Platform:</strong> Proves your code compiles with GCC (Linux), Clang (macOS), and MSVC (Windows).</li>
                        <li><strong>Configuration Matrix:</strong> Tests both Debug (catches assertions, enables sanitizers) and Release (catches optimization bugs).</li>
                        <li><strong>Platform-Aware Setup:</strong> Uses bash conditionals to run the correct bootstrap script per OS.</li>
                        <li><strong>Automated Testing:</strong> If ctest fails, the Pull Request cannot be merged.</li>
                    </ol>
                </section>

                <section id="summary" class="blog-section">
                    <h2>Summary</h2>
                    <p>By combining these modern practices, you elevate your C++ project from "just code" to a professional engineering product:</p>

                    <ol>
                        <li><strong>Structure:</strong> Use <code>src/</code>, <code>include/</code>, and <code>tests/</code> with clear separation of concerns.</li>
                        <li><strong>Modularity:</strong> Use <code>add_subdirectory</code> and <code>target_link_libraries</code> with proper visibility.</li>
                        <li><strong>Testability:</strong> Inject dependencies via interfaces; mock them with Google Mock.</li>
                        <li><strong>Hardening:</strong> Enable strict warnings (<code>-Wall -Wextra -Werror</code>) and sanitizers in Debug.</li>
                        <li><strong>Reproducibility:</strong> Use vcpkg or Conan manifests to lock dependency versions.</li>
                        <li><strong>CI/CD:</strong> Automate cross-platform builds and tests on every push.</li>
                    </ol>

                    <div class="tips-box">
                        <p><em>Modern C++ is not just about language features like concepts or coroutines—it's about the discipline of building software that is portable, verifiable, and maintainable.</em></p>
                    </div>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>Understanding RabbitMQ and MQTT: A Complete Comparison Guide</title>
      <link>https://olibartfast.ninja/blog/rabbitmq-mqtt-comparison-guide.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/rabbitmq-mqtt-comparison-guide.html</guid>
      <pubDate>Mon, 01 Dec 2025 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A deep dive into message brokers vs protocols. When to use RabbitMQ, when to choose MQTT, and how to leverage both in hybrid architectures.</description>
      <content:encoded><![CDATA[<p><em>A deep dive into two popular messaging technologies and when to use each</em></p>

            

            <h2>Introduction</h2>
            <p>
                In the world of distributed systems and real-time communication, choosing the right messaging technology 
                can make or break your application. Two names that frequently come up in these discussions are 
                <strong>RabbitMQ</strong> and <strong>MQTT</strong>. But here's the thing — comparing them directly is 
                like comparing apples to oranges.
            </p>
            <p>
                Why? Because RabbitMQ is a <strong>message broker</strong> (software), while MQTT is a <strong>protocol</strong> 
                (specification). Yet, they often serve similar purposes, which is why understanding their differences matters.
            </p>
            <p>
                In this post, we'll explore both technologies, compare their features, and help you decide which one fits your use case. 
                Whether you're building an IoT platform, designing microservices, or just curious about messaging systems, 
                this guide will give you the clarity you need.
            </p>

            <hr>

            <h2>What is RabbitMQ?</h2>
            <p>
                RabbitMQ is a robust, feature-rich <strong>message broker</strong> that acts as an intermediary for messaging. 
                Think of it as a sophisticated post office that can route, store, and deliver messages based on complex rules. 
                It's battle-tested in production environments worldwide and has become a staple in enterprise architectures.
            </p>
            <p>
                Originally built on the AMQP (Advanced Message Queuing Protocol), RabbitMQ has evolved to support multiple 
                protocols, making it incredibly versatile. Whether you're connecting microservices, handling background jobs, 
                or streaming events, RabbitMQ provides the reliability and features you need.
            </p>

            <div class="comparison-box">
                <h3>Key Characteristics:</h3>
                <ul>
                    <li>Enterprise-grade messaging platform with proven reliability</li>
                    <li>Supports multiple protocols (AMQP, MQTT, STOMP, HTTP)</li>
                    <li>Complex routing capabilities with exchanges and bindings</li>
                    <li>Rich feature set including dead-letter queues, priority queues, delayed messages, and more</li>
                    <li>Built-in clustering and high availability</li>
                </ul>
            </div>

            <hr>

            <h2>What is MQTT?</h2>
            <p>
                MQTT (Message Queuing Telemetry Transport) is a lightweight <strong>publish-subscribe protocol</strong> 
                designed for constrained devices and low-bandwidth, high-latency networks. Created in 1999 for monitoring 
                oil pipelines via satellite, MQTT has since become the de facto standard for IoT applications.
            </p>
            <p>
                What makes MQTT special is its extreme simplicity and efficiency. It was designed from the ground up to 
                work in challenging environments where every byte counts and network connections might drop at any moment. 
                This makes it perfect for battery-powered sensors, mobile devices, and remote monitoring systems.
            </p>

            <div class="comparison-box">
                <h3>Key Characteristics:</h3>
                <ul>
                    <li>Extremely lightweight and efficient protocol</li>
                    <li>Designed for unreliable networks with automatic reconnection</li>
                    <li>Minimal code footprint (implementations exist for tiny microcontrollers)</li>
                    <li>Perfect for battery-powered devices due to low power consumption</li>
                    <li>Three Quality of Service (QoS) levels for different reliability needs</li>
                </ul>
            </div>

            <hr>

            <h2>Architecture: How They Work</h2>
            <p>
                Understanding the architectural differences is crucial for making the right choice. Let's break down 
                how each system handles messages.
            </p>

            <h3>MQTT Architecture</h3>
            <p>
                MQTT follows a simple, elegant publish-subscribe pattern. There's a central broker, and clients either 
                publish messages to topics or subscribe to receive messages from topics they're interested in:
            </p>

            <div class="architecture-diagram">
                <pre><code>Publisher → Broker → Subscriber
           (topic-based)</code></pre>
            </div>

            <p>
                Messages are published to <strong>topics</strong> (e.g., <code>sensors/temperature/room1</code>), 
                and subscribers receive messages from topics they've subscribed to. The broker handles the routing. 
                Simple, effective, and easy to understand.
            </p>

            <h3>RabbitMQ Architecture</h3>
            <p>
                RabbitMQ introduces additional components for more sophisticated routing. Instead of just a simple broker, 
                you have producers, exchanges, queues, and consumers:
            </p>

            <div class="architecture-diagram">
                <pre><code>Producer → Exchange → Queue → Consumer
          (routing logic)</code></pre>
            </div>

            <p>
                The <strong>exchange</strong> receives messages from producers and routes them to one or more <strong>queues</strong> 
                based on rules called <strong>bindings</strong>. Different exchange types (direct, topic, fanout, headers) 
                provide different routing strategies. Consumers then read from these queues. This extra layer of abstraction 
                enables complex messaging patterns that MQTT simply can't handle.
            </p>

            <hr>

            <h2>Feature Comparison</h2>
            <p>
                Let's break down the key differences in a side-by-side comparison. This will help you quickly understand 
                where each technology excels:
            </p>

            <table>
                <thead>
                    <tr>
                        <th>Feature</th>
                        <th>RabbitMQ</th>
                        <th>MQTT</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>Type</strong></td>
                        <td>Message Broker (software)</td>
                        <td>Protocol (specification)</td>
                    </tr>
                    <tr>
                        <td><strong>Overhead</strong></td>
                        <td>Higher (more features = more overhead)</td>
                        <td>Very low (minimal header size)</td>
                    </tr>
                    <tr>
                        <td><strong>Message Size</strong></td>
                        <td>No practical limit</td>
                        <td>Optimized for small payloads</td>
                    </tr>
                    <tr>
                        <td><strong>QoS Levels</strong></td>
                        <td>Confirms, transactions, publisher confirms</td>
                        <td>0 (at most once), 1 (at least once), 2 (exactly once)</td>
                    </tr>
                    <tr>
                        <td><strong>Routing</strong></td>
                        <td>Complex (exchanges, bindings, multiple types)</td>
                        <td>Simple (topic-based only)</td>
                    </tr>
                    <tr>
                        <td><strong>Persistence</strong></td>
                        <td>Full support with durable queues</td>
                        <td>Retained messages (last message only)</td>
                    </tr>
                    <tr>
                        <td><strong>Protocol Support</strong></td>
                        <td>AMQP, MQTT, STOMP, HTTP, WebSockets</td>
                        <td>MQTT only</td>
                    </tr>
                    <tr>
                        <td><strong>Best For</strong></td>
                        <td>Enterprise applications, microservices</td>
                        <td>IoT devices, sensors, mobile apps</td>
                    </tr>
                </tbody>
            </table>

            <hr>

            <h2>Concept Mapping: MQTT to RabbitMQ</h2>
            <p>
                If you're coming from an MQTT background and moving to RabbitMQ (or vice versa), understanding how concepts 
                translate between the two can save you a lot of confusion. Here's a handy mapping:
            </p>

            <table>
                <thead>
                    <tr>
                        <th>MQTT Concept</th>
                        <th>RabbitMQ Equivalent</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Topic</td>
                        <td>Routing Key + Exchange</td>
                    </tr>
                    <tr>
                        <td>Publisher</td>
                        <td>Producer</td>
                    </tr>
                    <tr>
                        <td>Subscriber/Listener</td>
                        <td>Consumer</td>
                    </tr>
                    <tr>
                        <td>Broker</td>
                        <td>Exchange + Queues</td>
                    </tr>
                    <tr>
                        <td>Subscribe action</td>
                        <td>Queue Bind</td>
                    </tr>
                </tbody>
            </table>

            <h3>Topic Wildcards</h3>
            <p>
                Both systems support wildcards for flexible topic matching, but they use different syntax. 
                This is important to know when migrating or integrating:
            </p>

            <table>
                <thead>
                    <tr>
                        <th>Pattern Type</th>
                        <th>MQTT</th>
                        <th>RabbitMQ</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Single-level wildcard</td>
                        <td><code>+</code></td>
                        <td><code>*</code></td>
                    </tr>
                    <tr>
                        <td>Multi-level wildcard</td>
                        <td><code>#</code></td>
                        <td><code>#</code></td>
                    </tr>
                    <tr>
                        <td>Separator</td>
                        <td><code>/</code></td>
                        <td><code>.</code></td>
                    </tr>
                </tbody>
            </table>

            <p><strong>Examples:</strong></p>
            <pre><code>MQTT:           sensors/+/room1
RabbitMQ:       sensors.*.room1

MQTT:           sensors/#
RabbitMQ:       sensors.#</code></pre>

            <hr>

            <h2>Code Examples</h2>
            <p>
                Theory is great, but nothing beats seeing actual code. Let's look at practical examples in Python 
                for both technologies. You'll notice the difference in complexity immediately.
            </p>

            <h3>MQTT Example</h3>
            <p>
                Here's a simple MQTT client that publishes and subscribes to messages. Notice how concise and 
                straightforward it is:
            </p>

            <pre><code class="language-python">import paho.mqtt.client as mqtt

# Create client and connect to a public broker
client = mqtt.Client()
client.connect("broker.hivemq.com", 1883)

# Publish a temperature reading
client.publish("sensors/temperature", "23.5")

# Define callback for received messages
def on_message(client, userdata, message):
    print(f"Received: {message.payload.decode()} on topic {message.topic}")

# Subscribe to temperature sensor
client.subscribe("sensors/temperature")
client.on_message = on_message

# Start the network loop to process callbacks
client.loop_forever()</code></pre>

            <p>
                That's it! In just a few lines, you have a working pub/sub system. This simplicity is exactly 
                why MQTT is so popular for IoT applications.
            </p>

            <h3>RabbitMQ Example</h3>
            <p>
                Now let's see the RabbitMQ equivalent. It requires more setup, but gives you much more control 
                over message routing:
            </p>

            <pre><code class="language-python">import pika

# Connect to RabbitMQ server
connection = pika.BlockingConnection(
    pika.ConnectionParameters('localhost')
)
channel = connection.channel()

# Declare a topic exchange
channel.exchange_declare(exchange='sensors', exchange_type='topic')

# Declare a queue and bind it to the exchange
channel.queue_declare(queue='temperature_queue')
channel.queue_bind(
    queue='temperature_queue',
    exchange='sensors',
    routing_key='temperature'
)

# Publish a message to the exchange
channel.basic_publish(
    exchange='sensors',
    routing_key='temperature',
    body='23.5'
)

# Define callback for consuming messages
def callback(ch, method, properties, body):
    print(f"Received: {body.decode()}")

# Start consuming messages
channel.basic_consume(
    queue='temperature_queue',
    on_message_callback=callback,
    auto_ack=True
)

print('Waiting for messages...')
channel.start_consuming()</code></pre>

            <p>
                Notice how RabbitMQ requires explicit declaration of exchanges, queues, and bindings. 
                While this adds complexity, it also provides powerful routing capabilities that MQTT lacks.
            </p>

            <hr>

            <h2>When to Choose What</h2>
            <p>
                The million-dollar question: which one should you use? The answer depends on your specific requirements. 
                Let's break it down:
            </p>

            <h3>Choose RabbitMQ When:</h3>
            <ul class="checklist">
                <li>You need complex routing logic (different messages go to different queues based on content)</li>
                <li>Your application requires enterprise-grade features like transactions and dead-letter queues</li>
                <li>You need support for multiple protocols in the same infrastructure</li>
                <li>Advanced features like message priority, delayed messages, or message TTL are required</li>
                <li>Strong delivery guarantees and persistence are critical</li>
                <li>You're building backend microservices that need sophisticated messaging patterns</li>
                <li>You need detailed monitoring, management tools, and clustering</li>
            </ul>

            <h3>Choose MQTT When:</h3>
            <ul class="checklist">
                <li>You're working with IoT devices, embedded systems, or sensors</li>
                <li>Bandwidth is limited or expensive (satellite, cellular networks)</li>
                <li>Devices have battery constraints and need power-efficient protocols</li>
                <li>Network connections are unreliable or have high latency</li>
                <li>Simple publish-subscribe messaging is sufficient for your use case</li>
                <li>You need to support thousands of lightweight clients simultaneously</li>
                <li>Fast development and ease of implementation are priorities</li>
            </ul>

            <hr>

            <h2>The Best of Both Worlds</h2>
            <p>
                Here's the good news: you don't always have to choose! RabbitMQ includes an MQTT plugin that allows 
                MQTT clients to connect directly to RabbitMQ. This is a game-changer for hybrid architectures.
            </p>
            <p>
                This means you can have IoT devices communicating via MQTT (lightweight, simple) while your backend 
                services use AMQP (powerful, feature-rich) — all through the same broker. Messages published via MQTT 
                can be consumed by AMQP clients and vice versa.
            </p>

            <p>To enable the MQTT plugin in RabbitMQ:</p>
            <pre><code class="language-bash">rabbitmq-plugins enable rabbitmq_mqtt</code></pre>

            <p>
                After enabling the plugin, MQTT clients can connect to RabbitMQ on port 1883 (default MQTT port), 
                while AMQP clients use port 5672. This hybrid approach gives you:
            </p>

            <ul>
                <li>The lightweight nature of MQTT on the edge (sensors, mobile devices)</li>
                <li>The powerful features of RabbitMQ in your core infrastructure (routing, persistence, monitoring)</li>
                <li>A single broker to manage instead of separate MQTT and message broker infrastructure</li>
                <li>The ability to bridge IoT data directly into your enterprise messaging backbone</li>
            </ul>

            <hr>

            <h2>Conclusion</h2>
            <p>
                Both RabbitMQ and MQTT are excellent technologies, but they serve different purposes and excel in 
                different scenarios. Understanding their strengths helps you make informed architectural decisions.
            </p>

            <table>
                <thead>
                    <tr>
                        <th></th>
                        <th>RabbitMQ</th>
                        <th>MQTT</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>Think of it as</strong></td>
                        <td>Full-featured post office with complex routing</td>
                        <td>Simple, efficient mailbox system</td>
                    </tr>
                    <tr>
                        <td><strong>Ideal for</strong></td>
                        <td>Backend services, microservices, enterprise apps</td>
                        <td>Edge devices, sensors, mobile apps, IoT</td>
                    </tr>
                    <tr>
                        <td><strong>Learning curve</strong></td>
                        <td>Steeper (more concepts to learn)</td>
                        <td>Easy (minimal concepts)</td>
                    </tr>
                    <tr>
                        <td><strong>Resource usage</strong></td>
                        <td>Higher (more features require more resources)</td>
                        <td>Minimal (designed for constrained environments)</td>
                    </tr>
                </tbody>
            </table>

            <p>The choice ultimately depends on your specific requirements:</p>

            <ul>
                <li><strong>Building an IoT platform</strong> with thousands of sensors? Start with MQTT for simplicity and efficiency.</li>
                <li><strong>Designing a complex enterprise system</strong> with sophisticated routing needs? Go with RabbitMQ for its rich feature set.</li>
                <li><strong>Need both?</strong> Use RabbitMQ with the MQTT plugin to get the best of both worlds.</li>
            </ul>

            <p>
                Understanding these technologies and their trade-offs will help you architect better systems and 
                make informed decisions for your projects. Don't just pick the technology everyone else is using — 
                pick the one that fits your actual requirements.
            </p>

            <p>
                Remember: the best architecture is the one that solves your problem efficiently and maintainably. 
                Sometimes that's the simple elegance of MQTT, sometimes it's the powerful flexibility of RabbitMQ, 
                and sometimes it's a thoughtful combination of both.
            </p>

            <p><strong>Happy messaging! 🚀</strong></p>]]></content:encoded>
    </item>
    <item>
      <title>Generic Useful kubectl Commands</title>
      <link>https://olibartfast.ninja/blog/generic-useful-kubectl-commands.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/generic-useful-kubectl-commands.html</guid>
      <pubDate>Wed, 19 Nov 2025 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A compact cheatsheet of kubectl commands for everyday cluster inspection, debugging, and troubleshooting.</description>
      <content:encoded><![CDATA[<h2>Introduction</h2>
            <p>
                If you work with Kubernetes daily, you know that <code>kubectl</code> is your best friend—and sometimes your worst enemy. 
                Whether you're debugging a failing pod at 2 AM or just trying to check if your deployment rolled out successfully, 
                having a solid arsenal of <code>kubectl</code> commands at your fingertips can save you hours of frustration.
            </p>
            <p>
                This guide is a collection of the commands I find myself using constantly. It's not meant to be exhaustive 
                (the official kubectl docs are great for that), but rather a practical reference for the everyday tasks: 
                inspecting deployments, tailing logs, debugging pods, managing ConfigMaps and Secrets, and—one of my favorites—port-forwarding 
                to access services locally without exposing them to the internet.
            </p>
            <p>
                One thing you'll notice: all commands include the <code>--kubeconfig</code> flag. In production environments, 
                you often work with multiple clusters, and explicitly specifying the kubeconfig file prevents those "oops, wrong cluster" 
                moments we've all experienced. Of course, you can export <code>KUBECONFIG</code> as an environment variable to avoid 
                repetition—I'll show you how later.
            </p>

            

            <h2>Working with Deployments</h2>
            <p>
                Deployments are the bread and butter of Kubernetes workloads. When something goes wrong, these commands help you 
                quickly understand what's happening and take action.
            </p>

            <h3>Get basic info</h3>
            <p>Start simple—get a quick overview of your deployment's status, replicas, and age:</p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get deployment &lt;name&gt; -n &lt;namespace&gt;</code></pre>

            <h3>Describe a deployment (full debug info)</h3>
            <p>
                When things aren't working as expected, <code>describe</code> is your go-to command. 
                It shows everything: events, conditions, replica sets, and any recent errors.
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml describe deployment &lt;name&gt; -n &lt;namespace&gt;</code></pre>

            <h3>Get deployment YAML</h3>
            <p>Need to see the full configuration? This dumps the deployment spec in YAML format, useful for debugging or creating templates:</p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get deployment &lt;name&gt; -n &lt;namespace&gt; -o yaml</code></pre>

            <h3>Show rollout status</h3>
            <p>After applying changes, track the rollout in real-time to see if your new version is deploying successfully:</p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml rollout status deployment/&lt;name&gt; -n &lt;namespace&gt;</code></pre>

            <h3>Undo last rollout</h3>
            <p>
                Deployed a breaking change? No problem. This command rolls back to the previous revision—a lifesaver when things go south:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml rollout undo deployment/&lt;name&gt; -n &lt;namespace&gt;</code></pre>

            <hr>

            <h2>Inspecting Pods</h2>
            <p>
                Pods are where your containers actually run. Most debugging sessions start here, especially when containers are crashing 
                or stuck in <code>Pending</code> or <code>CrashLoopBackOff</code> states.
            </p>

            <h3>List pods in a namespace</h3>
            <p>The simplest command to see all pods in a namespace, including their status and restart counts:</p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get pods -n &lt;namespace&gt;</code></pre>

            <h3>List pods created by a deployment (label selector)</h3>
            <p>
                Deployments create pods with specific labels. Use label selectors to filter and see only the pods managed by a particular app:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get pods -n &lt;namespace&gt; -l app=&lt;appname&gt;</code></pre>

            <h3>Describe a pod</h3>
            <p>
                This is where the magic happens. <code>describe pod</code> shows you container states, recent events, volume mounts, 
                and most importantly—why a pod is failing. Look at the "Events" section at the bottom for clues.
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml describe pod &lt;pod-name&gt; -n &lt;namespace&gt;</code></pre>

            <h3>Get full pod YAML (spec + volumes)</h3>
            <p>Need to see the complete pod specification including environment variables, volumes, and resource limits?</p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get pod &lt;pod-name&gt; -n &lt;namespace&gt; -o yaml</code></pre>

            <hr>

            <h2>Tailing and Analyzing Logs</h2>
            <p>
                Logs are your window into what's actually happening inside containers. Whether you're debugging application errors 
                or tracking down performance issues, these commands are essential.
            </p>

            <h3>Simple logs from a pod</h3>
            <p>Basic log retrieval—shows you what the container has been outputting recently:</p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml logs &lt;pod&gt; -n &lt;namespace&gt;</code></pre>

            <h3>Logs of pods selected by label (aggregates logs from all matching pods)</h3>
            <p>
                When you have multiple replicas, this aggregates logs from all pods matching the label. 
                Super handy for seeing patterns across your deployment:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml logs -n &lt;namespace&gt; -l app=&lt;appname&gt;</code></pre>

            <h3>Follow logs</h3>
            <p>The <code>-f</code> flag works just like <code>tail -f</code>—it streams logs in real-time. Essential for watching live activity:</p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml logs -f &lt;pod&gt; -n &lt;namespace&gt;</code></pre>

            <h3>Logs for a specific container in a pod</h3>
            <p>
                Pods can have multiple containers (sidecars, init containers, etc.). Use <code>-c</code> to specify which container's logs you want:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml logs &lt;pod&gt; -c &lt;container&gt; -n &lt;namespace&gt;</code></pre>

            <hr>

            <h2>ConfigMaps &amp; Secrets</h2>
            <p>
                ConfigMaps and Secrets are how you inject configuration and sensitive data into your pods. 
                Managing them properly is crucial—especially Secrets, which require extra care.
            </p>

            <h3>List ConfigMaps</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get configmap -n &lt;namespace&gt;</code></pre>

            <h3>View ConfigMap YAML</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get configmap &lt;name&gt; -n &lt;namespace&gt; -o yaml</code></pre>

            <h3>Describe ConfigMap</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml describe configmap &lt;name&gt; -n &lt;namespace&gt;</code></pre>

            <h3>Describe Secret (metadata)</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml describe secret &lt;name&gt; -n &lt;namespace&gt;</code></pre>

            <h3>View Secret (base64 decode) — caution: secrets are sensitive</h3>
            <p>
                Secrets are base64-encoded (not encrypted!) in Kubernetes. This command decodes them for viewing. 
                <strong>Be careful</strong>—never run this in production logs or share the output publicly. 
                The <code>jq</code> command formats the output nicely:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get secret &lt;name&gt; -n &lt;namespace&gt; -o jsonpath="{.data}" \
  | jq -r 'to_entries[] | "\(.key)=\(.value | @base64d)"'</code></pre>

            <hr>

            <h2>Services &amp; Networking</h2>
            <p>
                Services expose your pods to the network. When connectivity issues arise, these commands help you understand 
                how traffic is being routed.
            </p>

            <h3>List services</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get svc -n &lt;namespace&gt;</code></pre>

            <h3>Describe a service</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml describe svc &lt;name&gt; -n &lt;namespace&gt;</code></pre>

            <hr>

            <h2>Cluster Events</h2>
            <p>
                Events are Kubernetes' way of telling you what's happening under the hood. They're time-limited (usually kept for about an hour), 
                so checking them early in your debugging process is important.
            </p>

            <h3>List all events</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get events -n &lt;namespace&gt;</code></pre>

            <h3>Filter events for a specific object</h3>
            <p>
                When you're debugging a specific pod or deployment, filter events to see only what's relevant. 
                This cuts through the noise in busy clusters:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get events -n &lt;namespace&gt; \
  --field-selector involvedObject.name=&lt;name&gt;</code></pre>

            <hr>

            <h2>Interactive Debugging &amp; Access</h2>
            <p>
                Sometimes you need to get "inside" a container to poke around, or access a service that isn't exposed externally. 
                These commands are your friends for hands-on debugging.
            </p>

            <h3>Exec into a pod (shell)</h3>
            <p>
                Open an interactive shell inside a running container. Perfect for checking files, testing network connectivity, 
                or running diagnostic commands. Note that some minimal containers might only have <code>/bin/sh</code> instead of bash:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml exec -it &lt;pod&gt; -n &lt;namespace&gt; -- /bin/bash
# or use /bin/sh if bash is not present</code></pre>

            <h3>Port-forward to a pod (localPort:remotePort)</h3>
            <p>
                This is one of my most-used commands. It creates a secure tunnel from your local machine to a pod, 
                letting you access services as if they were running on localhost. No need to expose ports publicly!
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml port-forward pod/&lt;pod-name&gt; 8080:80 -n &lt;namespace&gt;</code></pre>

            <hr>

            <h2>Namespace Management</h2>
            <p>
                Namespaces are how Kubernetes organizes resources. In multi-tenant clusters or environments with many teams, 
                they're essential for isolation.
            </p>

            <h3>List namespaces</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get ns</code></pre>

            <hr>

            <h2>Applying &amp; Managing Resources</h2>
            <p>
                Beyond inspecting, you need to create, update, and delete resources. These commands handle the lifecycle of your Kubernetes objects.
            </p>

            <h3>Apply manifests in a folder</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml apply -f ./deploy/</code></pre>

            <h3>Delete a resource file</h3>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml delete -f &lt;file.yaml&gt;</code></pre>

            <h3>Dry-run apply (client-side diff)</h3>
            <p>
                Before making changes to a live cluster, always dry-run! This shows you what <em>would</em> happen without actually applying it. 
                It's saved me from many mistakes:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml apply -f &lt;file.yaml&gt; --dry-run=client -o yaml</code></pre>

            <hr>

            <h2>Pro Tips: Simplifying Your Workflow</h2>
            <p>
                Typing <code>--kubeconfig=/path/to/kubeconfig.yaml</code> on every command gets old fast. 
                Here are some tricks to streamline your workflow.
            </p>

            <h3>Export <code>KUBECONFIG</code> to avoid repeating the flag</h3>
            <p>
                Set <code>KUBECONFIG</code> as an environment variable in your shell session. Now all kubectl commands will use this config automatically:
            </p>
            <pre><code>export KUBECONFIG=/path/to/kubeconfig.yaml
# then omit --kubeconfig in following commands:
kubectl get pods -n &lt;namespace&gt;</code></pre>

            <h3>Use a different kubeconfig for a single command</h3>
            <p>
                Need to quickly switch contexts for one command? Prefix it with the environment variable—no permanent changes needed:
            </p>
            <pre><code>KUBECONFIG=/path/to/kubeconfig.yaml kubectl get pods -n &lt;namespace&gt;</code></pre>

            <hr>

            <h2>Port-Forwarding Deep Dive</h2>
            <p>
                Port-forwarding deserves special attention because it's such a versatile tool. Whether you're testing a database connection, 
                debugging a web service, or accessing an admin panel, port-forwarding lets you work as if everything were local. 
                Here's a comprehensive look at different scenarios.
            </p>

            <h3>1) Pod → local port (single port)</h3>
            <p>
                The most basic form: forward a single port from a pod to your local machine. 
                After running this, you can access the service at <code>http://localhost:8080</code>:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml port-forward pod/&lt;pod-name&gt; 8080:80 -n &lt;namespace&gt;
# access locally at http://localhost:8080</code></pre>

            <h3>2) Service → local port</h3>
            <p>
                Instead of targeting a specific pod, forward to a service. Kubernetes will automatically route to one of the backing pods—great 
                when you don't care which pod handles the request:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml port-forward svc/&lt;service-name&gt; 8080:80 -n &lt;namespace&gt;</code></pre>

            <h3>3) Multiple ports at once</h3>
            <p>
                Need to forward HTTP and HTTPS? Or a web server and a metrics endpoint? Just list them all:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml port-forward pod/&lt;pod-name&gt; 8080:80 8443:443 -n &lt;namespace&gt;</code></pre>

            <h3>4) Port-forward from a Deployment</h3>
            <p>
                Deployments don't have a direct port-forward option, but you can grab the first pod from the deployment and forward to it. 
                This one-liner does the trick:
            </p>
            <pre><code>POD=$(kubectl --kubeconfig=/path/to/kubeconfig.yaml get pod -n &lt;namespace&gt; -l app=&lt;appname&gt; -o jsonpath="{.items[0].metadata.name}")
kubectl --kubeconfig=/path/to/kubeconfig.yaml port-forward pod/$POD 8080:80 -n &lt;namespace&gt;</code></pre>

            <h3>5) Background port-forwarding</h3>
            <p>
                Sometimes you want port-forwarding to run in the background while you do other work. 
                This approach redirects output to a log file and saves the process ID so you can kill it later. 
                <strong>Note:</strong> For production use, consider a more robust solution like a systemd service or supervisor process:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml port-forward pod/&lt;pod-name&gt; 8080:80 -n &lt;namespace&gt; &gt; /tmp/portforward.log 2&gt;&1 &
echo $! &gt; /tmp/portforward.pid
# to stop:
kill $(cat /tmp/portforward.pid)</code></pre>

            <h3>6) Dealing with port conflicts</h3>
            <p>
                Already have something running on port 8080? No problem—just pick a different local port. 
                The remote port (the one in the container) stays the same:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml port-forward pod/&lt;pod-name&gt; 18080:80 -n &lt;namespace&gt;</code></pre>

            <h3>7) Debugging service-to-pod mapping</h3>
            <p>
                Ever wonder which pods are actually backing a service? Check the endpoints—they show you the exact pod IPs and ports 
                that the service routes to:
            </p>
            <pre><code>kubectl --kubeconfig=/path/to/kubeconfig.yaml get endpoints &lt;service-name&gt; -n &lt;namespace&gt; -o yaml</code></pre>

            <hr>

            <h2>Wrapping Up</h2>
            <p>
                These commands form the backbone of my daily Kubernetes workflow. I've probably run <code>kubectl logs -f</code> 
                and <code>kubectl port-forward</code> thousands of times at this point—they're that useful.
            </p>
            <p>
                The key to mastering kubectl is muscle memory. Keep this reference handy, but more importantly, use these commands regularly. 
                Over time, you'll develop intuition for which command to reach for in different situations.
            </p>
            <p>
                Remember: Kubernetes can be complex, but having the right tools at your fingertips makes all the difference. 
                Whether you're troubleshooting production issues or exploring a new cluster, these commands will serve you well.
            </p>
            <p>
                Happy debugging! 🚀
            </p>]]></content:encoded>
    </item>
    <item>
      <title>Object Detection Architectures Guide</title>
      <link>https://olibartfast.ninja/blog/object-detection-architectures-guide.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/object-detection-architectures-guide.html</guid>
      <pubDate>Sun, 14 Sep 2025 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A comprehensive guide to major detector families including YOLO, RT-DETR, and YOLO-NAS — architectures, trade-offs, and deployment considerations.</description>
      <content:encoded><![CDATA[<p>Object detection is one of the most fundamental tasks in computer vision, with applications ranging from autonomous driving to medical imaging. This comprehensive guide explores the major detector families, their architectures, trade-offs, and deployment considerations to help you choose the right approach for your project.</p>

                <div class="toc">
                    <h2>Table of Contents</h2>
                    <ul>
                        <li><a href="https://olibartfast.ninja/blog/object-detection-architectures-guide.html#at-a-glance-selection">At-a-Glance Selection</a></li>
                        <li><a href="https://olibartfast.ninja/blog/object-detection-architectures-guide.html#yolo-family">YOLO Family</a></li>
                        <li><a href="https://olibartfast.ninja/blog/object-detection-architectures-guide.html#rt-detr-family">RT-DETR Family</a></li>
                        <li><a href="https://olibartfast.ninja/blog/object-detection-architectures-guide.html#yolo-nas">YOLO-NAS</a></li>
                        <li><a href="https://olibartfast.ninja/blog/object-detection-architectures-guide.html#specialized-architectures">Specialized Architectures</a></li>
                        <li><a href="https://olibartfast.ninja/blog/object-detection-architectures-guide.html#architecture-comparison">Architecture Comparison Summary</a></li>
                        <li><a href="https://olibartfast.ninja/blog/object-detection-architectures-guide.html#deployment-notes">Deployment Notes</a></li>
                        <li><a href="https://olibartfast.ninja/blog/object-detection-architectures-guide.html#references">References</a></li>
                    </ul>
                </div>

                <section id="at-a-glance-selection" class="blog-section">
                    <h2>At-a-Glance Selection</h2>
                    <div class="quick-selection">
                        <ul>
                            <li><strong>Edge real-time (balanced speed/accuracy):</strong> YOLOv8/YOLO11 (S/M) or YOLO-NAS (with QAT) 🚀</li>
                            <li><strong>Highest accuracy on server GPUs:</strong> RT-DETR variants or transformer-based refinements 🧠</li>
                            <li><strong>NMS-free pipeline:</strong> YOLOv10 or RT-DETR ✅</li>
                            <li><strong>Tight memory/latency budget:</strong> YOLO-NAS with quantization, or small YOLO models 📦</li>
                        </ul>
                    </div>
                </section>

                <section id="yolo-family" class="blog-section">
                    <h2>YOLO Family</h2>
                    <div class="family-section">
                        <p>YOLO ("You Only Look Once") is a family of single-stage detectors optimized for speed. Predictions are made densely over feature maps, producing bounding boxes and classes in one forward pass.</p>

                        <h3>Architecture and Core Idea</h3>
                        <ul>
                            <li><strong>Early YOLO (v1–v2):</strong> Grid-based predictions (S×S cells); each cell predicts a fixed number of boxes, objectness, and class probabilities. v2 introduces anchors (dimension clustering), BN, and a stronger backbone.</li>
                            <li><strong>Modern YOLO (v3+):</strong> Dense predictions on multi-scale feature maps (FPN/PAN-like necks). Anchor-based heads (v2–v7) → anchor-free heads (v8+). Decoupled heads for classification vs box regression are common (v6+). Inference typically uses NMS; YOLOv10 is NMS-free by design.</li>
                        </ul>

                        <h3>Evolution Timeline</h3>
                        <div class="evolution-timeline">
                            <h4>YOLOv1 (2016)</h4>
                            <ul>
                                <li><strong>Innovation:</strong> Single-shot detection paradigm</li>
                                <li><strong>Architecture:</strong> CNN with fully connected detection head</li>
                                <li><strong>Limitation:</strong> Struggles with small objects and precise localization</li>
                            </ul>

                            <h4>YOLOv2 / YOLO9000 (2017)</h4>
                            <ul>
                                <li><strong>Improvements:</strong> Anchor boxes, BN, higher-resolution pretraining</li>
                                <li><strong>Backbone:</strong> Darknet-19</li>
                            </ul>

                            <h4>YOLOv3 (2018)</h4>
                            <ul>
                                <li><strong>Key Changes:</strong> Multi-scale predictions (FPN-style), 3 detection layers</li>
                                <li><strong>Backbone:</strong> Darknet-53 with residuals</li>
                                <li><strong>Loss:</strong> BCE/logistic for multi-label classification</li>
                            </ul>

                            <h4>YOLOv4 (2020)</h4>
                            <ul>
                                <li><strong>Backbone:</strong> CSPDarknet53 (better gradient flow)</li>
                                <li><strong>Neck:</strong> SPP + PANet</li>
                                <li><strong>Training:</strong> Mosaic, CutMix, DropBlock; Mish activations</li>
                            </ul>

                            <h4>YOLOv5 (2020)</h4>
                            <ul>
                                <li><strong>Notes:</strong> Popular PyTorch implementation (no official paper)</li>
                                <li><strong>Architecture:</strong> CSP bottlenecks; AutoAnchor; evolved training pipeline</li>
                            </ul>

                            <h4>YOLOv6 (2022)</h4>
                            <ul>
                                <li><strong>Focus:</strong> Industrial deployment</li>
                                <li><strong>Blocks:</strong> RepVGG-style reparameterizable convs</li>
                                <li><strong>Head:</strong> Decoupled classification/localization heads</li>
                                <li><strong>Label Assignment:</strong> SimOTA</li>
                            </ul>

                            <h4>YOLOv7 (2022)</h4>
                            <ul>
                                <li><strong>E-ELAN:</strong> Extended Efficient Layer Aggregation Networks</li>
                                <li><strong>Training:</strong> Trainable bag-of-freebies; optional auxiliary heads</li>
                            </ul>

                            <h4>YOLOv8 (2023)</h4>
                            <ul>
                                <li><strong>Features:</strong> Anchor-free heads; C2f modules; decoupled head</li>
                                <li><strong>Unified tasks:</strong> detection, segmentation, classification, pose</li>
                            </ul>

                            <h4>YOLOv9 (2024)</h4>
                            <ul>
                                <li><strong>PGI:</strong> Programmable Gradient Information</li>
                                <li><strong>GELAN:</strong> Generalized Efficient Layer Aggregation Network</li>
                            </ul>

                            <h4>YOLOv10 (2024)</h4>
                            <ul>
                                <li><strong>NMS-free:</strong> One-to-many + one-to-one dual assignments</li>
                                <li><strong>Efficiency:</strong> Reduced post-processing latency</li>
                            </ul>

                            <h4>YOLO11 (2024)</h4>
                            <ul>
                                <li><strong>Latest:</strong> Ultralytics release (successor to YOLOv8)</li>
                                <li><strong>Features:</strong> Anchor-free heads, C2f-style components</li>
                            </ul>
                        </div>

                        <div class="strengths-weaknesses">
                            <div class="strengths">
                                <h3>Strengths</h3>
                                <ul>
                                    <li>Real-time performance on commodity GPUs and edge devices</li>
                                    <li>End-to-end trainable single-stage designs</li>
                                    <li>Strong, active ecosystem (repos, pretrained weights, tutorials)</li>
                                    <li>Flexible: detection, segmentation, classification, and pose support</li>
                                </ul>
                            </div>
                            <div class="weaknesses">
                                <h3>Weaknesses</h3>
                                <ul>
                                    <li>Small/occluded/crowded objects remain challenging</li>
                                    <li>Pre–YOLOv10 variants rely on NMS; threshold tuning impacts recall/latency</li>
                                    <li>Class imbalance and long-tail distributions require careful loss/assigner tuning</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </section>

                <section id="rt-detr-family" class="blog-section">
                    <h2>RT-DETR Family</h2>
                    <div class="family-section">
                        <p>RT-DETR combines efficient CNN backbones with transformer encoders/decoders to achieve real-time, end-to-end detection without NMS.</p>

                        <h3>Core Concept</h3>
                        <ul>
                            <li>CNN backbone for efficient feature extraction</li>
                            <li>Transformer encoder/decoder with learnable object queries for global reasoning</li>
                            <li>Set-based prediction with bipartite (Hungarian) matching and no NMS at inference</li>
                        </ul>

                        <h3>Architecture Components</h3>
                        <ol>
                            <li><strong>Backbone:</strong> ResNet-like or other efficient CNN for multi-scale features</li>
                            <li><strong>Encoder:</strong> Multi-scale transformer encoder to aggregate global context</li>
                            <li><strong>Decoder:</strong> Transformer decoder with learnable queries producing object slots</li>
                            <li><strong>Prediction Heads:</strong> Boxes (e.g., L1/GIoU) and classes (CE/Focal), trained end-to-end</li>
                        </ol>

                        <h3>Training and Inference Notes</h3>
                        <ul>
                            <li><strong>Matching:</strong> Hungarian matching aligns predictions with ground truth (set prediction)</li>
                            <li><strong>Auxiliary losses:</strong> On intermediate decoder layers help convergence</li>
                            <li><strong>NMS-free:</strong> By design; some repos expose optional NMS for convenience/compatibility</li>
                        </ul>

                        <h3>Variants</h3>
                        <div class="evolution-timeline">
                            <h4>RT-DETR (Original, 2023)</h4>
                            <ul>
                                <li><strong>Innovation:</strong> Real-time DETR with hybrid CNN–Transformer design</li>
                                <li><strong>Paper:</strong> DETRs Beat YOLOs on Real-time Object Detection</li>
                            </ul>

                            <h4>RT-DETR v2</h4>
                            <ul>
                                <li><strong>Description:</strong> Enhanced training strategies and architectural tweaks</li>
                                <li><strong>Focus:</strong> Better accuracy/throughput balance</li>
                            </ul>

                            <h4>RT-DETR (Ultralytics)</h4>
                            <ul>
                                <li><strong>Implementation:</strong> Integrated into the Ultralytics framework</li>
                                <li><strong>Benefits:</strong> Simplified API and ecosystem integration</li>
                            </ul>
                        </div>

                        <div class="strengths-weaknesses">
                            <div class="strengths">
                                <h3>Strengths</h3>
                                <ul>
                                    <li>Captures long-range dependencies with global attention</li>
                                    <li>End-to-end training and inference (NMS-free)</li>
                                    <li>Scales well across model sizes for different speed/accuracy targets</li>
                                </ul>
                            </div>
                            <div class="weaknesses">
                                <h3>Weaknesses</h3>
                                <ul>
                                    <li>Typically higher memory/compute than YOLO on the same hardware budget</li>
                                    <li>Training dynamics (matching, auxiliary losses) can be more complex to tune</li>
                                    <li>Ecosystem and tooling are newer than classic YOLO pipelines</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </section>

                <section id="yolo-nas" class="blog-section">
                    <h2>YOLO-NAS</h2>
                    <div class="family-section">
                        <p>YOLO-NAS leverages Neural Architecture Search (NAS) to discover architectures optimized for accuracy–latency trade-offs and deployment constraints.</p>

                        <h3>Core Innovation</h3>
                        <ul>
                            <li>Automated architecture search to balance accuracy, latency, and memory</li>
                            <li>Quantization-aware design for efficient edge deployment</li>
                            <li>Training strategies often include knowledge distillation</li>
                        </ul>

                        <h3>Key Features</h3>
                        <ol>
                            <li>NAS-optimized backbones/necks/heads for target hardware</li>
                            <li>QAT-ready (Quantization-Aware Training) and export-friendly</li>
                            <li>Built on Deci's SuperGradients training library and deployment stack</li>
                            <li>Production-focused recipes and tools</li>
                        </ol>

                        <div class="strengths-weaknesses">
                            <div class="strengths">
                                <h3>Strengths</h3>
                                <ul>
                                    <li>Strong real-world deployment focus with competitive accuracy–latency trade-offs</li>
                                    <li>Built-in quantization/compression support</li>
                                    <li>Modern training techniques (distillation, QAT) out of the box</li>
                                </ul>
                            </div>
                            <div class="weaknesses">
                                <h3>Weaknesses</h3>
                                <ul>
                                    <li>NAS/search itself is resource-intensive (done by provider; not replicated by users)</li>
                                    <li>Architectures can feel "black box" compared to hand-designed networks</li>
                                    <li>Some features are tightly integrated with a specific tooling ecosystem</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </section>

                <section id="specialized-architectures" class="blog-section">
                    <h2>Specialized Architectures (Project-Specific)</h2>
                    
                    <div class="family-section">
                        <h3>D-FINE</h3>
                        <p>Fine-grained object detection focused on precise localization and subtle detail differences.</p>
                        
                        <h4>Key Features</h4>
                        <ul>
                            <li>Fine-grained detection of small details</li>
                            <li>High-precision localization</li>
                            <li>Advanced multi-scale feature fusion</li>
                        </ul>

                        <h4>Typical Use Cases</h4>
                        <ul>
                            <li>Medical imaging analysis</li>
                            <li>Manufacturing quality control</li>
                            <li>Scientific image analysis</li>
                            <li>Detail-focused surveillance</li>
                        </ul>
                    </div>

                    <div class="family-section">
                        <h3>DEIM</h3>
                        <p>Detection with Enhanced Instance Modeling for improved instance-level reasoning.</p>
                        
                        <h4>Key Features</h4>
                        <ul>
                            <li>Enhanced instance representations</li>
                            <li>Context-aware modeling of object relations</li>
                            <li>Robust detection under cluttered or complex scenes</li>
                        </ul>

                        <h4>Typical Applications</h4>
                        <ul>
                            <li>Crowded scenes</li>
                            <li>Instance segmentation workflows</li>
                            <li>Complex scene understanding</li>
                            <li>Multi-object tracking</li>
                        </ul>
                    </div>

                    <div class="family-section">
                        <h3>RF-DETR</h3>
                        <p>Refined Detection Transformer emphasizing better convergence and feature quality.</p>
                        
                        <h4>Key Improvements</h4>
                        <ul>
                            <li>Optimized transformer components and training schedule</li>
                            <li>Improved feature representations and decoding strategy</li>
                            <li>Accuracy-focused while maintaining reasonable efficiency</li>
                        </ul>

                        <h4>Strengths</h4>
                        <ul>
                            <li>High accuracy and more stable training</li>
                            <li>Strong feature quality and interpretability</li>
                        </ul>
                    </div>
                </section>

                <section id="architecture-comparison" class="blog-section">
                    <h2>Architecture Comparison Summary</h2>
                    <div style="overflow-x: auto;">
                        <table class="architecture-table">
                            <thead>
                                <tr>
                                    <th>Family</th>
                                    <th>Paradigm</th>
                                    <th>Anchors</th>
                                    <th>NMS at Inference</th>
                                    <th>Scales</th>
                                    <th>Typical Deployment</th>
                                    <th>Relative Compute</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>YOLO (v4–v7)</td>
                                    <td>Single-stage CNN</td>
                                    <td>Yes</td>
                                    <td>Yes</td>
                                    <td>T/S/M/L/XL</td>
                                    <td>T: mobile/edge<br>S: edge GPU<br>M: desktop GPU<br>L: server GPU</td>
                                    <td>T: very low<br>S: low<br>M: medium<br>L: high</td>
                                </tr>
                                <tr>
                                    <td>YOLO (v8–YOLO11)</td>
                                    <td>Single-stage CNN</td>
                                    <td>No (anchor-free)</td>
                                    <td>Yes (except YOLOv10)</td>
                                    <td>T/S/M/L/XL</td>
                                    <td>T: mobile/edge<br>S: edge GPU<br>M: desktop GPU<br>L: server GPU</td>
                                    <td>T: very low<br>S: low<br>M: medium<br>L: high</td>
                                </tr>
                                <tr>
                                    <td>YOLOv10</td>
                                    <td>Single-stage CNN</td>
                                    <td>No</td>
                                    <td>No (end-to-end)</td>
                                    <td>T/S/M/L/XL</td>
                                    <td>T: mobile/edge<br>S: edge GPU<br>M: desktop GPU<br>L: server GPU</td>
                                    <td>T: very low<br>S: low<br>M: medium<br>L: high</td>
                                </tr>
                                <tr>
                                    <td>RT-DETR</td>
                                    <td>CNN + Transformer</td>
                                    <td>N/A</td>
                                    <td>No (by design)</td>
                                    <td>S/M/L/XL</td>
                                    <td>S: edge GPU<br>M: desktop/server GPU<br>L: server GPU</td>
                                    <td>S: medium<br>M: medium–high<br>L: high</td>
                                </tr>
                                <tr>
                                    <td>YOLO-NAS</td>
                                    <td>NAS-optimized CNN</td>
                                    <td>Varies</td>
                                    <td>Typically Yes</td>
                                    <td>S/M/L</td>
                                    <td>S: edge devices<br>M: desktop GPU<br>L: server GPU</td>
                                    <td>S: low<br>M: medium<br>L: high</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <p><em>Scale key: T = Tiny, S = Small, M = Medium, L = Large, XL = Extra Large</em></p>
                </section>

                <section id="deployment-notes" class="blog-section">
                    <h2>Deployment Notes</h2>
                    <div class="deployment-notes">
                        <h3>Export/Inference</h3>
                        <ul>
                            <li><strong>YOLO families and YOLO-NAS:</strong> Strong support for ONNX, TensorRT, and various runtimes (OpenVINO, CoreML) depending on repo/tools</li>
                            <li><strong>RT-DETR:</strong> Exportability improving; NMS-free simplifies deployment graphs, but attention blocks may need optimized kernels</li>
                        </ul>

                        <h3>Quantization</h3>
                        <ul>
                            <li><strong>YOLO-NAS:</strong> QAT-ready by design; good fit for INT8 on edge</li>
                            <li><strong>YOLO (v8/YOLO11):</strong> Widely used with post-training quantization or QAT via vendor toolchains</li>
                        </ul>

                        <h3>NMS-free Benefits</h3>
                        <ul>
                            <li>Eliminates post-processing latency and threshold sensitivity (YOLOv10, RT-DETR)</li>
                            <li>Can simplify end-to-end pipelines and make latency more predictable</li>
                        </ul>
                    </div>
                </section>

                <section class="blog-section">
                    <h2>Conclusion</h2>
                    <p>The landscape of object detection architectures continues to evolve rapidly, with each family offering distinct advantages for different use cases. YOLO remains the go-to choice for real-time applications with its proven track record and extensive ecosystem. RT-DETR represents the cutting edge of transformer-based detection, offering NMS-free inference and global reasoning capabilities. YOLO-NAS brings automated architecture optimization to the table, while specialized architectures like D-FINE, DEIM, and RF-DETR address specific domain requirements.</p>
                    
                    <p>When choosing an architecture, consider your deployment constraints, accuracy requirements, and development timeline. The "at-a-glance selection" guide at the beginning of this post provides a quick reference, but thorough evaluation on your specific dataset and hardware remains essential for optimal results.</p>
                </section>

                <section id="references" class="blog-section">
                    <h2>References</h2>
                    <div class="references-list">
                        <ul>
                            <li>YOLOv1 (2016): <a href="https://arxiv.org/abs/1506.02640" target="_blank">https://arxiv.org/abs/1506.02640</a></li>
                            <li>YOLOv2/YOLO9000 (2017): <a href="https://arxiv.org/abs/1612.08242" target="_blank">https://arxiv.org/abs/1612.08242</a></li>
                            <li>YOLOv3 (2018): <a href="https://arxiv.org/abs/1804.02767" target="_blank">https://arxiv.org/abs/1804.02767</a></li>
                            <li>YOLOv4 (2020): <a href="https://arxiv.org/abs/2004.10934" target="_blank">https://arxiv.org/abs/2004.10934</a></li>
                            <li>YOLOv5 (2020, repo): <a href="https://github.com/ultralytics/yolov5" target="_blank">https://github.com/ultralytics/yolov5</a></li>
                            <li>YOLOX (SimOTA, 2021): <a href="https://arxiv.org/abs/2107.08430" target="_blank">https://arxiv.org/abs/2107.08430</a></li>
                            <li>YOLOv6 (2022): <a href="https://arxiv.org/abs/2209.02976" target="_blank">https://arxiv.org/abs/2209.02976</a></li>
                            <li>YOLOv7 (2022): <a href="https://arxiv.org/abs/2207.02696" target="_blank">https://arxiv.org/abs/2207.02696</a></li>
                            <li>YOLOv8 (2023, repo): <a href="https://github.com/ultralytics/ultralytics" target="_blank">https://github.com/ultralytics/ultralytics</a></li>
                            <li>YOLOv9 (2024): <a href="https://arxiv.org/abs/2402.13616" target="_blank">https://arxiv.org/abs/2402.13616</a></li>
                            <li>YOLOv10 (2024): <a href="https://arxiv.org/abs/2405.14458" target="_blank">https://arxiv.org/abs/2405.14458</a></li>
                            <li>Ultralytics YOLO11 (2024, docs): <a href="https://docs.ultralytics.com/models/yolo11/" target="_blank">https://docs.ultralytics.com/models/yolo11/</a></li>
                            <li>RT-DETR (2023): <a href="https://arxiv.org/abs/2304.08069" target="_blank">https://arxiv.org/abs/2304.08069</a></li>
                            <li>RT-DETR (Ultralytics, docs): <a href="https://docs.ultralytics.com/models/rtdetr/" target="_blank">https://docs.ultralytics.com/models/rtdetr/</a></li>
                            <li>YOLO-NAS (repo): <a href="https://github.com/Deci-AI/super-gradients" target="_blank">https://github.com/Deci-AI/super-gradients</a></li>
                        </ul>
                    </div>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>Ninja Build System Tutorial for C++ Projects</title>
      <link>https://olibartfast.ninja/blog/ninja-build-system-tutorial.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/ninja-build-system-tutorial.html</guid>
      <pubDate>Thu, 28 Aug 2025 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>A comprehensive guide to using Ninja, the fast build system designed for speed. Setup, commands, and best practices for C++ projects.</description>
      <content:encoded><![CDATA[<p>If you're working on large C++ projects and finding that build times are becoming a bottleneck in your development workflow, it might be time to consider Ninja. This small but powerful build system is designed with speed in mind and has become increasingly popular among C++ developers who value efficient incremental builds.</p>
                
                <p>In this tutorial, we'll explore what Ninja is, how to set it up with CMake, and discover the essential commands that will make your C++ build process faster and more efficient.</p>

                <section class="blog-section">
                    <h2>What is Ninja?</h2>
                    <p>Ninja is a small, fast build system designed to have its input files generated by a higher-level build system like CMake. Unlike traditional build systems that focus on ease of use and flexibility, Ninja is laser-focused on one thing: speed.</p>
                    
                    <p>Key characteristics of Ninja:</p>
                    <ul>
                        <li><strong>Speed</strong>: Optimized for fast incremental builds</li>
                        <li><strong>Minimalism</strong>: Simple syntax and fast parsing</li>
                        <li><strong>Generated files</strong>: Ninja build files are meant to be generated, not written by hand</li>
                        <li><strong>Cross-platform</strong>: Works seamlessly on Linux, macOS, and Windows</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>Basic Setup</h2>
                    <p>Getting started with Ninja is straightforward, especially if you're already using CMake for your C++ projects.</p>

                    <h3>1. Generate Ninja files with CMake</h3>
                    <p>First, create a build directory and generate the Ninja build files:</p>
                    <pre class="command-example"># Create build directory
mkdir build && cd build

# Generate Ninja build files
cmake -G Ninja ..

# Or specify build type
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release ..</pre>

                    <h3>2. Build the project</h3>
                    <p>Once you have the Ninja files generated, building is simple:</p>
                    <pre class="command-example"># Build everything
ninja

# Build specific target
ninja target_name

# Build with verbose output
ninja -v

# Build using multiple cores (default: all available)
ninja -j 8</pre>
                </section>

                <section class="blog-section">
                    <h2>Common Commands</h2>
                    <p>Ninja provides several useful commands for managing your build process:</p>

                    <pre class="ninja-snippet"><code># Clean build artifacts
ninja clean

# List all available targets
ninja -t targets

# Show dependency graph
ninja -t graph | dot -Tpng -o deps.png

# Show build rules
ninja -t rules

# Dry run (show what would be built)
ninja -n</code></pre>

                    <p>These commands are particularly useful for debugging build issues and understanding your project's structure. The dependency graph visualization can be especially helpful for complex projects with intricate dependencies.</p>
                </section>

                <section class="blog-section">
                    <h2>Example Workflow</h2>
                    <p>Here's a complete workflow showing how to use Ninja with a typical C++ project:</p>

                    <pre class="ninja-snippet"><code># Initial setup
git clone your-cpp-project
cd your-cpp-project
mkdir build && cd build

# Configure with CMake
cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug ..

# Build
ninja

# Run tests (if available)
ninja test

# Install (if configured)
ninja install</code></pre>

                    <p>This workflow demonstrates the typical development cycle: configure, build, test, and optionally install. The beauty of Ninja is that subsequent builds will be much faster thanks to its efficient dependency tracking.</p>
                </section>

                <section class="blog-section">
                    <h2>Advantages over Make</h2>
                    <div class="advantages-list">
                        <ul>
                            <li><strong>Speed</strong>: Parallelizes builds efficiently and has minimal startup overhead</li>
                            <li><strong>Simplicity</strong>: Minimal syntax means faster parsing and fewer surprises</li>
                            <li><strong>Dependency tracking</strong>: More accurate incremental builds reduce unnecessary recompilation</li>
                            <li><strong>Cross-platform</strong>: Consistent behavior across Linux, macOS, and Windows</li>
                            <li><strong>Better parallelization</strong>: Smarter job scheduling compared to traditional Make</li>
                        </ul>
                    </div>

                    <p>These advantages become particularly noticeable in large codebases where build times can significantly impact developer productivity. Ninja's focus on speed means you'll spend less time waiting for builds and more time coding.</p>
                </section>

                <section class="blog-section">
                    <h2>Tips and Best Practices</h2>
                    <div class="tips-box">
                        <h3>💡 Pro Tips</h3>
                        <ul>
                            <li><strong>Always use a separate build directory</strong> - This keeps your source tree clean and allows for multiple build configurations</li>
                            <li><strong>Don't edit Ninja files manually</strong> - They're generated by CMake and will be overwritten</li>
                            <li><strong>Use <code>ninja -C build_dir</code></strong> - Build from any directory without changing into the build folder</li>
                            <li><strong>For debugging, use <code>ninja -v</code></strong> - Shows full command lines to help troubleshoot build issues</li>
                            <li><strong>Leverage <code>ninja -j</code></strong> - Control parallelism based on your system's capabilities</li>
                        </ul>
                    </div>
                </section>

                <section class="blog-section">
                    <h2>Conclusion</h2>
                    <p>Ninja represents a shift in thinking about build systems - prioritizing speed and efficiency over complex features. For C++ developers working on projects where build time matters, adopting Ninja can lead to significant productivity improvements.</p>
                    
                    <p>The combination of CMake for configuration and Ninja for execution provides a powerful, cross-platform build solution that scales well from small projects to large codebases. Give it a try on your next C++ project - your future self will thank you for the time saved!</p>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>Parallel Programming Pattern Fundamentals in CUDA</title>
      <link>https://olibartfast.ninja/blog/cuda-parallel-programming-patterns.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/cuda-parallel-programming-patterns.html</guid>
      <pubDate>Fri, 20 Jun 2025 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>Core parallel programming patterns in CUDA, from reductions and scans to cooperative groups and stream parallelism.</description>
      <content:encoded><![CDATA[<p>This article outlines the core parallel programming patterns (cornerstones) used in CUDA to leverage modern NVIDIA GPU architectures. These patterns are fundamental for exploiting CUDA's Single Instruction, Multiple Thread (SIMT) execution model, memory hierarchy, and advanced thread management features for efficient parallel computation.</p>

                <p>A key theme in modern CUDA development is the use of highly optimized libraries. For many common patterns, NVIDIA <strong>CUB</strong> provides state-of-the-art implementations. While the original standalone <a href="https://github.com/NVIDIA/cub">CUB repository</a> is now archived, <strong>CUB is actively maintained as part of the <a href="https://github.com/NVIDIA/cccl">CUDA C++ Core Libraries (CCCL)</a></strong>. CCCL unifies CUB, Thrust, and libcu++ into a cohesive standard library included in every CUDA Toolkit. Using libraries like CUB is the recommended best practice for achieving maximum performance and reliability.</p>

                <h2>1. Reduction</h2>
                <p><strong>Description:</strong> Aggregates a dataset into a single value (e.g., sum, min, max) using a hierarchical, parallel approach.</p>
                <p><strong>CUDA Relevance:</strong> Utilizes shared memory and thread synchronization to perform partial reductions at the block level, minimizing costly global memory accesses. A second kernel or a grid-striding loop often combines these partial results.</p>
                <p><strong>Use Cases:</strong> Summing arrays, finding maxima, computing vector norms.</p>

                <h3>Key Considerations</h3>
                <ul>
                    <li>Minimize thread divergence within warps</li>
                    <li>Use tree-based reduction for efficiency</li>
                    <li>Leverage shared memory to reduce global memory latency</li>
                </ul>

                <h3>Modern Practice</h3>
                <ul>
                    <li>Use <code>cub::DeviceReduce</code> from the CCCL-integrated CUB library for production</li>
                    <li>Perform reduction in two stages: block-level, then global</li>
                </ul>

                <h3>Example: Block-Level Reduction</h3>
                <pre class="cuda-snippet"><code class="language-cpp">__global__ void sumReduction(float *input, float *output, int n) {
    extern __shared__ float sdata[];
    int tid = threadIdx.x;
    int i = blockIdx.x * blockDim.x + threadIdx.x;

    sdata[tid] = (i < n) ? input[i] : 0;
    __syncthreads();

    for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
        if (tid < s) {
            sdata[tid] += sdata[tid + s];
        }
        __syncthreads();
    }

    if (tid == 0) output[blockIdx.x] = sdata[0];
}</code></pre>

                <h2>2. Prefix Scan (Parallel Scan)</h2>
                <p><strong>Description:</strong> Computes cumulative results across an array (e.g., inclusive/exclusive prefix sum) where each element depends on all prior inputs.</p>
                <p><strong>CUDA Relevance:</strong> Essential in stream compaction, sorting, and memory allocation.</p>
                <p><strong>Use Cases:</strong> Running totals, partitioning, histogram equalization.</p>

                <h3>Key Considerations</h3>
                <ul>
                    <li>Use Hillis-Steele or Blelloch algorithms</li>
                    <li>Requires fine-grained synchronization</li>
                </ul>

                <h3>Modern Practice</h3>
                <ul>
                    <li>Use <code>cub::DeviceScan</code>, which includes inclusive and exclusive variants</li>
                    <li>Supports decoupled look-back for low-latency, memcpy-like performance</li>
                </ul>

                <h2>3. Map</h2>
                <p><strong>Description:</strong> Applies a function independently to each element in a dataset.</p>
                <p><strong>CUDA Relevance:</strong> Ideal for CUDA's thread-level parallelism.</p>
                <p><strong>Use Cases:</strong> Element-wise operations like scaling, filtering, or transformations.</p>

                <h3>Example</h3>
                <pre class="cuda-snippet"><code class="language-cpp">__global__ void mapScale(float *input, float *output, float scale, int n) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) {
        output[idx] = input[idx] * scale;
    }
}</code></pre>

                <h2>4. Tiled Partitioning</h2>
                <p><strong>Description:</strong> Splits data into tiles that fit in shared memory to reduce global memory traffic and improve data reuse.</p>
                <p><strong>CUDA Relevance:</strong> Crucial for memory-bound algorithms like GEMM and convolutions.</p>
                <p><strong>Use Cases:</strong> Tiled matrix multiplication, convolutions.</p>

                <h3>Modern Practice</h3>
                <ul>
                    <li><strong>Use Tensor Cores</strong> via cuBLAS or WMMA API</li>
                    <li>Tune tile sizes per GPU architecture (e.g., Hopper, Ampere)</li>
                </ul>

                <h2>5. Stencil</h2>
                <p><strong>Description:</strong> Each element is updated based on neighboring values.</p>
                <p><strong>CUDA Relevance:</strong> Common in PDE solvers, image processing.</p>
                <p><strong>Use Cases:</strong> Gaussian blur, edge detection, heat diffusion.</p>

                <h3>Key Considerations</h3>
                <ul>
                    <li>Cache halos/ghost zones in shared memory</li>
                    <li>Handle boundary conditions efficiently</li>
                </ul>

                <h2>6. Gather/Scatter</h2>
                <p><strong>Description:</strong></p>
                <ul>
                    <li><strong>Gather:</strong> Reads from arbitrary indices</li>
                    <li><strong>Scatter:</strong> Writes to arbitrary indices</li>
                </ul>
                <p><strong>CUDA Relevance:</strong> Enables irregular memory access patterns like sparse ops.</p>
                <p><strong>Use Cases:</strong> Histogramming, graph processing, sparse matrix ops.</p>

                <h3>Example: Histogram with Scatter</h3>
                <pre class="cuda-snippet"><code class="language-cpp">__global__ void histogram(unsigned int *input, int *bins, int n) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n) {
        atomicAdd(&bins[input[idx]], 1);
    }
}</code></pre>

                <h2>7. Cooperative Groups</h2>
                <p><strong>Description:</strong> Allows group-level synchronization and coordination beyond thread blocks.</p>
                <p><strong>CUDA Relevance:</strong> Enables grid-wide reductions, persistent kernels.</p>
                <p><strong>Use Cases:</strong> Grid-level synchronization, producer-consumer models.</p>

                <h2>8. Warp-Level Primitives</h2>
                <p><strong>Description:</strong> Enables communication within a warp without shared memory.</p>
                <p><strong>CUDA Relevance:</strong> Very low-latency; great for warp-local reductions or ballots.</p>

                <h3>Example: Warp Reduction</h3>
                <pre class="cuda-snippet"><code class="language-cpp">__device__ float warpReduceSum(float val) {
    for (int offset = 16; offset > 0; offset /= 2) {
        val += __shfl_down_sync(0xFFFFFFFF, val, offset);
    }
    return val;
}</code></pre>

                <h2>9. Stream Parallelism</h2>
                <p><strong>Description:</strong> Uses CUDA streams to overlap data transfers and computation.</p>
                <p><strong>CUDA Relevance:</strong> Maximizes throughput by exploiting concurrency.</p>
                <p><strong>Use Cases:</strong> Pipeline processing of datasets, latency hiding.</p>

                <h2>General Optimization Tips</h2>

                <h3>Libraries</h3>
                <ul>
                    <li>Prefer CUB, cuBLAS, cuFFT, or cuDNN over hand-written kernels</li>
                </ul>

                <h3>Memory</h3>
                <ul>
                    <li>Coalesce global memory accesses across warps</li>
                    <li>Use shared memory as a fast user-managed cache</li>
                </ul>

                <h3>Synchronization</h3>
                <ul>
                    <li>Use <code>__syncthreads()</code> and warp-sync intrinsics judiciously</li>
                    <li>Avoid unnecessary barriers to maintain pipeline efficiency</li>
                </ul>

                <h3>Profiling</h3>
                <ul>
                    <li>Use Nsight Compute or Visual Profiler to identify bottlenecks</li>
                    <li>Tune for occupancy, memory throughput, and instruction efficiency</li>
                </ul>

                <h2>References</h2>
                <ul>
                    <li><a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/">NVIDIA CUDA Programming Guide</a></li>
                    <li><a href="https://github.com/NVIDIA/cuda-samples">CUDA Samples</a></li>
                    <li><a href="https://github.com/NVIDIA/cccl/tree/main/cub">CUB in CCCL</a></li>
                    <li><a href="https://developer.nvidia.com/nsight-compute">Nsight Compute</a></li>
                </ul>]]></content:encoded>
    </item>
    <item>
      <title>Demystifying CMakeLists.txt</title>
      <link>https://olibartfast.ninja/blog/demystifying-cmakelists-txt.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/demystifying-cmakelists-txt.html</guid>
      <pubDate>Sun, 01 Jun 2025 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>Understanding the essential building blocks of CMakeLists.txt files, from basic commands to advanced concepts.</description>
      <content:encoded><![CDATA[<p>If you're diving into C++ development, especially for projects that need to work across different operating systems or with complex dependencies, you've likely encountered CMake. At the heart of every CMake-based project lies a crucial file: <code>CMakeLists.txt</code>. This unassuming text file is the brain of your build process, telling CMake exactly how to configure, build, and even install your software.</p>
                
                <p>Understanding the main components of a <code>CMakeLists.txt</code> file can feel daunting at first, but once you grasp the key commands, you'll unlock a powerful way to manage your C++ projects. Let's break down the essential building blocks!</p>

                <section class="blog-section">
                    <h2>1. Setting the Stage: <code>cmake_minimum_required</code></h2>
                    <p>Every good story needs a beginning, and for <code>CMakeLists.txt</code>, that's <code>cmake_minimum_required</code>.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">cmake_minimum_required(VERSION 3.10)</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: This command specifies the oldest version of CMake that can correctly process your <code>CMakeLists.txt</code> file. It ensures that you're using CMake features that are actually available.</li>
                        <li><strong>Why it's important</strong>: CMake evolves, adding new features and changing behaviors. This line prevents users with older CMake versions from encountering cryptic errors. It's almost always the very first line in your file.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>2. Naming Your Masterpiece: <code>project</code></h2>
                    <p>Next, you give your project an identity.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">project(MyAwesomeApp VERSION 1.2.0 LANGUAGES CXX C)</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: The <code>project()</code> command sets the name of your project. You can also optionally specify a version number and the programming languages used (e.g., <code>CXX</code> for C++, <code>C</code> for C).</li>
                        <li><strong>Why it's important</strong>: This name is used in various places by CMake, such as in generated project files for IDEs (like Visual Studio solutions or Xcode projects) and in install paths.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>3. Variables, Variables Everywhere: <code>set</code></h2>
                    <p>CMake is all about variables. The <code>set</code> command is your primary tool for creating and assigning values to them.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">set(CMAKE_CXX_STANDARD 17) # Request C++17 standard
set(MY_CUSTOM_OPTION ON CACHE BOOL "Enable my custom feature")
set(SOURCE_FILES main.cpp utils.cpp)</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: It assigns a value to a variable. CMake has many built-in variables (like <code>CMAKE_CXX_STANDARD</code>), and you'll define many of your own to hold source file lists, options, paths, etc. <code>CACHE</code> variables are special as they are stored in CMake's cache and can be configured by the user when running CMake.</li>
                        <li><strong>Why it's important</strong>: Variables make your build scripts flexible, readable, and maintainable.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>4. Building Executables: <code>add_executable</code></h2>
                    <p>This is where you tell CMake to create a program that users can run.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">add_executable(MyApp main.cpp app_logic.cpp ui_components.cpp)</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: It defines an executable target. You provide a name for your executable (e.g., <code>MyApp</code>) and then list all the source files (<code>.cpp</code>, <code>.c</code>) required to build it.</li>
                        <li><strong>Why it's important</strong>: This is fundamental for any application you want to produce.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>5. Creating Reusable Code: <code>add_library</code></h2>
                    <p>For code that you want to reuse across different executables or even other projects, you'll create libraries.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">add_library(MyUtils STATIC utils.cpp helpers.cpp) # A static library
add_library(CoreFeatures SHARED core_feature1.cpp core_feature2.cpp) # A shared library</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: It defines a library target. Libraries can be <code>STATIC</code> (code is copied into the target that links against it at compile time) or <code>SHARED</code> (loaded at runtime, also known as DLLs on Windows or .so files on Linux). There's also <code>MODULE</code> for plugins.</li>
                        <li><strong>Why it's important</strong>: Libraries promote modular design, code reuse, and can significantly speed up compilation times for large projects.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>6. Telling the Compiler Where to Look: <code>target_include_directories</code></h2>
                    <p>When your code uses <code>#include &lt;my_header.h&gt;</code>, the compiler needs to know where to find <code>my_header.h</code>.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">target_include_directories(MyApp PUBLIC
    "${CMAKE_CURRENT_SOURCE_DIR}/include"
    "vendor/some_library/include"
)</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: This command specifies directories where the compiler should search for header files for a given target (like <code>MyApp</code>).</li>
                        <li><strong>Keywords (<code>PUBLIC</code>, <code>PRIVATE</code>, <code>INTERFACE</code>)</strong>:
                            <ul>
                                <li><code>PRIVATE</code>: The include directories are only for compiling <code>MyApp</code> itself.</li>
                                <li><code>PUBLIC</code>: The include directories are for <code>MyApp</code> AND any other target that links against <code>MyApp</code>.</li>
                                <li><code>INTERFACE</code>: The include directories are ONLY for targets that link against <code>MyApp</code>, not for <code>MyApp</code> itself.</li>
                            </ul>
                        </li>
                        <li><strong>Why it's important</strong>: Essential for organizing your project and using third-party libraries.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>7. Linking it All Together: <code>target_link_libraries</code></h2>
                    <p>Your executable or library often depends on other libraries (either those you've built or external ones).</p>
                    <pre class="cmake-snippet"><code class="language-cmake"># Assuming MyUtils is a library defined with add_library()
target_link_libraries(MyApp PRIVATE MyUtils)

# Linking against a library found by find_package (see below)
# find_package(Boost REQUIRED COMPONENTS system)
# target_link_libraries(MyApp PRIVATE Boost::system)</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Specifies which libraries a target needs to link against. The <code>PUBLIC</code>, <code>PRIVATE</code>, and <code>INTERFACE</code> keywords work similarly to <code>target_include_directories</code>, controlling how link dependencies are propagated.</li>
                        <li><strong>Why it's important</strong>: This is how you connect different pieces of your project and incorporate external code.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>8. Defining Your Code's Behavior: <code>target_compile_definitions</code></h2>
                    <p>Sometimes you need to pass preprocessor definitions (like <code>#define DEBUG</code>) to your compiler.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">target_compile_definitions(MyApp PRIVATE "DEBUG" "VERSION_STRING=\"1.0\"" "USE_FEATURE_X")</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Adds compile definitions for a target. These are effectively <code>-D</code> flags passed to the compiler.</li>
                        <li><strong>Why it's important</strong>: Useful for conditional compilation (e.g., enabling debug-only code) or embedding version information.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>9. Fine-Tuning Compilation: <code>target_compile_options</code></h2>
                    <p>This command lets you pass specific flags directly to the compiler.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">target_compile_options(MyUtils PRIVATE -Wall -Wextra -pedantic) # Common GCC/Clang warning flags</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Adds compiler-specific options for a target.</li>
                        <li><strong>Why it's important</strong>: Allows you to enable warnings, optimizations, or other compiler-specific features. Be mindful that these can be compiler-dependent.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>10. Finding External Friends: <code>find_package</code></h2>
                    <p>Modern projects rarely live in isolation. <code>find_package</code> helps CMake locate and use external libraries and tools.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">find_package(Qt6 COMPONENTS Core Gui Widgets REQUIRED)
find_package(Boost 1.70 REQUIRED COMPONENTS system filesystem)
find_package(Threads REQUIRED)</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Searches for an installed package (like Qt, Boost, OpenSSL, etc.). If <code>REQUIRED</code> is specified and the package isn't found, CMake will stop with an error.</li>
                        <li><strong>Why it's important</strong>: This is the standard way to integrate third-party libraries into your build, providing their include directories, libraries to link against, and sometimes even compiler flags.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>11. Structuring Your Project: <code>add_subdirectory</code></h2>
                    <p>For larger projects, you'll often break down your <code>CMakeLists.txt</code> into smaller, more manageable pieces in subdirectories.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">add_subdirectory(src)       # Assumes a CMakeLists.txt exists in the 'src' folder
add_subdirectory(tests)     # And another one in the 'tests' folder
add_subdirectory(libs/my_custom_lib)</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Tells CMake to process another <code>CMakeLists.txt</code> file located in a subdirectory. This helps in organizing large projects into logical modules.</li>
                        <li><strong>Why it's important</strong>: Promotes modularity and keeps your main <code>CMakeLists.txt</code> cleaner.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>12. Including More CMake Code: <code>include</code></h2>
                    <p>Sometimes you have utility CMake scripts or want to use standard CMake modules.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">include(CTest) # Enables testing capabilities via CTest
include(GNUInstallDirs) # Provides standard installation directory variables like CMAKE_INSTALL_BINDIR</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Loads and runs CMake code from another file or a CMake-provided module.</li>
                        <li><strong>Why it's important</strong>: Allows for code reuse within your build scripts and access to powerful CMake modules for common tasks like testing or packaging.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>13. Controlling the Flow: <code>if</code>, <code>foreach</code>, <code>while</code></h2>
                    <p>CMake isn't just a list of commands; it's a scripting language with control flow.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    message(STATUS "Building in Debug mode with extra checks.")
    target_compile_definitions(MyApp PRIVATE DEBUG_MODE)
elseif(CMAKE_BUILD_TYPE STREQUAL "Release")
    message(STATUS "Building in Release mode with optimizations.")
endif()

set(MY_MODULES A B C)
foreach(MOD ${MY_MODULES})
    add_subdirectory(module_${MOD})
endforeach()</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Provides conditional logic (<code>if/else/endif</code>), loops (<code>foreach/endforeach</code>, <code>while/endwhile</code>), allowing your build to adapt to different situations, platforms, or options.</li>
                        <li><strong>Why it's important</strong>: Makes your build scripts dynamic and adaptable.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>14. Ready for Deployment: <code>install</code></h2>
                    <p>Once your project is built, you'll often want to install it to a system location or a packaging directory.</p>
                    <pre class="cmake-snippet"><code class="language-cmake">install(TARGETS MyApp MyLib
    RUNTIME DESTINATION bin          # Executables go to 'bin'
    LIBRARY DESTINATION lib          # Shared/Static libraries go to 'lib'
    ARCHIVE DESTINATION lib          # Static libraries on Windows
)
install(FILES "config/default.json" DESTINATION "etc/${PROJECT_NAME}")
install(DIRECTORY "include/" DESTINATION "include/${PROJECT_NAME}" FILES_MATCHING PATTERN "*.h")</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Defines rules for what gets installed and where when someone runs the <code>install</code> build step (e.g., <code>make install</code> or <code>cmake --install .</code>). You can install targets (executables, libraries), files, and entire directories.</li>
                        <li><strong>Why it's important</strong>: Crucial for distributing your software or for making it available system-wide.</li>
                    </ul>
                </section>

                <section class="blog-section">
                    <h2>15. Don't Forget the Comments: <code>#</code></h2>
                    <p>Last but not least, good code is documented code.</p>
                    <pre class="cmake-snippet"><code class="language-cmake"># This is a comment explaining the purpose of the next block
# set(OLD_FEATURE_FLAG OFF) # Temporarily disabling an old feature</code></pre>
                    <ul>
                        <li><strong>What it does</strong>: Lines starting with <code>#</code> are ignored by CMake.</li>
                        <li><strong>Why it's important</strong>: Use comments to explain complex parts of your script, document your intentions, or temporarily disable lines of code. Your future self (and your colleagues) will thank you!</li>
                    </ul>
                </section>]]></content:encoded>
    </item>
    <item>
      <title>Runtime Type Identification in C++</title>
      <link>https://olibartfast.ninja/blog/runtime-type-identification-cpp.html</link>
      <guid isPermaLink="true">https://olibartfast.ninja/blog/runtime-type-identification-cpp.html</guid>
      <pubDate>Wed, 02 Apr 2025 12:00:00 +0000</pubDate>
      <dc:creator>Francesco Oliva</dc:creator>
      <description>Exploring dynamic_cast, typeid, virtual functions, and enums for determining object types at runtime.</description>
      <content:encoded><![CDATA[<!-- === Blog Article Content Start === -->
            

            <p>This post explores various techniques for determining the dynamic type of an object at runtime in C++ when dealing with inheritance hierarchies, along with best practices for using polymorphism and smart pointers.</p>

            <h2>Scenario</h2>

            <p>We have a base class <code>A</code> and derived classes <code>B</code> and <code>C</code>:</p>

            <pre><code class="language-text">A (Base Class)
├── B (Derived Class)
└── C (Derived Class)</code></pre>

            <p>We want to be able to determine, at runtime, whether a pointer to <code>A</code> is actually pointing to an object of type <code>B</code> or <code>C</code>.</p>

            <h2>Techniques</h2>

            <h3>1. <code>dynamic_cast</code> (Recommended for Safe Downcasting)</h3>

            <p><code>dynamic_cast</code> is the safest and most standard way to perform downcasting in a polymorphic hierarchy.</p>

            <strong>How it works:</strong>
            <ul>
                <li>It checks at runtime if the cast is valid.</li>
                <li>If the cast is valid, it returns a pointer of the target type.</li>
                <li>If the cast is invalid, it returns <code>nullptr</code> (for pointer casts) or throws a <code>std::bad_cast</code> exception (for reference casts).</li>
            </ul>

            <strong>Requirements:</strong>
            <ul>
                <li>The base class must have at least one virtual function (usually the destructor). This enables Runtime Type Information (RTTI).</li>
                <li>RTTI must be enabled in your compiler settings (usually enabled by default).</li>
            </ul>

            <strong>Example with Smart Pointers:</strong>
            <pre class="cpp-snippet"><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;memory&gt;

class A {
public:
    virtual ~A() {} // Important: A must have at least one virtual function
};

class B : public A {
public:
    void bSpecific() { std::cout &lt;&lt; "B specific\n"; }
};

class C : public A {
public:
    void cSpecific() { std::cout &lt;&lt; "C specific\n"; }
};

int main() {
    std::unique_ptr&lt;A&gt; aPtr = std::make_unique&lt;B&gt;();

    if (B* bPtr = dynamic_cast&lt;B*&gt;(aPtr.get())) {
        std::cout &lt;&lt; "aPtr is pointing to an object of type B\n";
        bPtr-&gt;bSpecific();
    } else {
        std::cout &lt;&lt; "aPtr is not pointing to an object of type B\n";
    }

    if (C* cPtr = dynamic_cast&lt;C*&gt;(aPtr.get())) {
        std::cout &lt;&lt; "aPtr is pointing to an object of type C\n";
        cPtr-&gt;cSpecific();
    } else {
        std::cout &lt;&lt; "aPtr is not pointing to an object of type C\n";
    }

    return 0;
}</code></pre>

            <strong>Pros:</strong>
            <ul>
                <li><strong>Safe:</strong> Performs runtime type checking.</li>
                <li><strong>Standard:</strong> Part of the C++ standard.</li>
            </ul>

            <strong>Cons:</strong>
            <ul>
                <li><strong>Requires RTTI:</strong> Adds a small overhead.</li>
                <li><strong>Requires Polymorphism:</strong> Base class must have at least one virtual function.</li>
            </ul>

            <h3>2. <code>typeid</code> and <code>type_info</code> (Less Common for Downcasting)</h3>

            <p><code>typeid</code> returns a reference to a <code>std::type_info</code> object, which contains type information.</p>

            <strong>How it works:</strong>
            <ul>
                <li>It allows you to compare the types of objects.</li>
            </ul>

            <strong>Example with Smart Pointers:</strong>
            <pre class="cpp-snippet"><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;memory&gt;
#include &lt;typeinfo&gt;

// ... (A, B, C classes as before)

int main() {
    std::shared_ptr&lt;A&gt; aPtr = std::make_shared&lt;C&gt;();

    if (typeid(*aPtr) == typeid(B)) {
        std::cout &lt;&lt; "aPtr is pointing to an object of type B\n";
    } else if (typeid(*aPtr) == typeid(C)) {
        std::cout &lt;&lt; "aPtr is pointing to an object of type C\n";
    } else {
        std::cout &lt;&lt; "aPtr is pointing to an object of type A or another derived type\n";
    }

    return 0;
}</code></pre>

            <strong>Pros:</strong>
            <ul>
                <li>Can be used with non-polymorphic classes.</li>
            </ul>

            <strong>Cons:</strong>
            <ul>
                <li><strong>Less safe for downcasting:</strong> <code>typeid</code> only identifies the type; it doesn't perform a cast. You'd need a separate <code>static_cast</code> (unsafe) or <code>dynamic_cast</code> for downcasting.</li>
                <li><strong>Less readable for complex hierarchies:</strong> Multiple <code>typeid</code> comparisons can become cumbersome.</li>
            </ul>

            <h3>3. Polymorphism with Virtual Functions (Preferred Design)</h3>

            <p>Instead of explicit type checking, define virtual functions in the base class and override them in derived classes.</p>

            <strong>How it works:</strong>
            <ul>
                <li>The correct version of the function is called at runtime based on the object's actual type.</li>
            </ul>

            <strong>Example with Smart Pointers and Pure Virtual Function:</strong>
            <pre class="cpp-snippet"><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;memory&gt;
#include &lt;string&gt;

class A {
public:
    virtual std::string identify() = 0; // Pure virtual function
    virtual ~A() {}
};

class B : public A {
public:
    std::string identify() override { return "I am B"; }
};

class C : public A {
public:
    std::string identify() override { return "I am C"; }
};

int main() {
    std::unique_ptr&lt;A&gt; aPtr = std::make_unique&lt;B&gt;();
    std::cout &lt;&lt; aPtr-&gt;identify() &lt;&lt; std::endl;

    std::shared_ptr&lt;A&gt; aPtr2 = std::make_shared&lt;C&gt;();
    std::cout &lt;&lt; aPtr2-&gt;identify() &lt;&lt; std::endl;

    return 0;
}</code></pre>

            <strong>Pros:</strong>
            <ul>
                <li><strong>Elegant and object-oriented:</strong> Promotes good design.</li>
                <li><strong>Efficient:</strong> Virtual function calls are usually very efficient.</li>
                <li><strong>Extensible:</strong> Adding new derived classes doesn't require modifying existing code that uses base class pointers.</li>
            </ul>

            <strong>Cons:</strong>
            <ul>
                <li><strong>Requires design foresight:</strong> You need to anticipate type-specific behavior during design.</li>
                <li><strong>May not be suitable for all situations:</strong> If you need the exact type for reasons other than calling type-specific behavior, <code>dynamic_cast</code> might be necessary.</li>
            </ul>

            <h3>4. Using Enums and a Dictionary for Type Identification (Type-Safe and Readable)</h3>

            <p>This approach combines an <code>enum class</code> for type-safe identification with an <code>unordered_map</code> to store string representations of the types.</p>

            <strong>Example with Smart Pointers, Pure Virtual Function, and Enum:</strong>
            <pre class="cpp-snippet"><code class="language-cpp">#include &lt;iostream&gt;
#include &lt;memory&gt;
#include &lt;string&gt;
#include &lt;unordered_map&gt;

enum class ClassType {
    A,
    B,
    C
};

const std::unordered_map&lt;ClassType, std::string&gt; classTypeToString = {
    {ClassType::A, "Class A"},
    {ClassType::B, "Class B"},
    {ClassType::C, "Class C"}
};

class A {
public:
    virtual ClassType identify() = 0;
    virtual ~A() {}
};

class B : public A {
public:
    ClassType identify() override { return ClassType::B; }
};

class C : public A {
public:
    ClassType identify() override { return ClassType::C; }
};

int main() {
    std::unique_ptr&lt;A&gt; aPtr = std::make_unique&lt;B&gt;();
    ClassType typeB = aPtr-&gt;identify();
    std::cout &lt;&lt; "Type: " &lt;&lt; classTypeToString.at(typeB) &lt;&lt; std::endl;

    std::shared_ptr&lt;A&gt; aPtr2 = std::make_shared&lt;C&gt;();
    ClassType typeC = aPtr2-&gt;identify();
    std::cout &lt;&lt; "Type: " &lt;&lt; classTypeToString.at(typeC) &lt;&lt; std::endl;

    return 0;
}</code></pre>

            <strong>Pros:</strong>
            <ul>
                <li><strong>Type-safe:</strong> <code>enum class</code> provides type safety.</li>
                <li><strong>Readable:</strong> <code>ClassType</code> enum and <code>classTypeToString</code> map make the code self-documenting.</li>
                <li><strong>Maintainable:</strong> Easy to add new classes.</li>
                <li><strong>Efficient:</strong> <code>std::unordered_map</code> provides fast lookups.</li>
                <li><strong>Flexible:</strong> <code>ClassType</code> enum can be used for various purposes.</li>
            </ul>

            <strong>Cons:</strong>
            <ul>
                <li>Requires a bit more setup compared to just using <code>dynamic_cast</code>.</li>
            </ul>

            <h3>5. Adding a Type Identifier (Generally Discouraged)</h3>

            <p>Manually adding a type identifier (e.g., an enum or string member) to the base class is generally <strong>not recommended</strong>.</p>

            <strong>Cons:</strong>
            <ul>
                <li><strong>Error-prone:</strong> Manual management of type identifiers can lead to errors.</li>
                <li><strong>Not scalable:</strong> Cumbersome to maintain with many derived classes.</li>
                <li><strong>Violates the Open/Closed Principle:</strong> Adding new derived classes requires modifying the base class.</li>
            </ul>

            <h2>Recommendations</h2>

            <ol>
                <li><strong>Prefer polymorphism (virtual functions) whenever possible.</strong> It's the most object-oriented and efficient approach for handling type-specific behavior.</li>
                <li><strong>Use <code>dynamic_cast</code> when you need to know the exact type for reasons other than calling type-specific behavior.</strong> It's safe and standard.</li>
                <li><strong>Consider enums and a dictionary for type identification when type safety, readability, and maintainability are high priorities.</strong></li>
                <li><strong>Avoid <code>typeid</code> unless you have a specific reason to use it and understand its limitations for downcasting.</strong></li>
                <li><strong>Do not use manual type identifiers.</strong> They are error-prone and lead to less maintainable code.</li>
            </ol>

            <h2>Smart Pointers</h2>

            <p>Throughout these examples, we've used smart pointers (<code>std::unique_ptr</code> and <code>std::shared_ptr</code>) for automatic memory management.</p>

            <ul>
                <li><strong><code>std::unique_ptr</code>:</strong> Represents exclusive ownership. Use when you have a clear single owner.</li>
                <li><strong><code>std::shared_ptr</code>:</strong> Represents shared ownership using reference counting. Use when multiple parts of your code need to share ownership.</li>
            </ul>

            <p>Using smart pointers is crucial for writing safe and robust modern C++ code. They prevent memory leaks and dangling pointers, making your programs more reliable.</p>
            <!-- === Blog Article Content End === -->]]></content:encoded>
    </item>
  </channel>
</rss>
