<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Navaneeth Sen on Medium]]></title>
        <description><![CDATA[Stories by Navaneeth Sen on Medium]]></description>
        <link>https://medium.com/@navaneethsen?source=rss-bebbd29c583f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GO6HiBKNRSbd2xqUcvXgew.png</url>
            <title>Stories by Navaneeth Sen on Medium</title>
            <link>https://medium.com/@navaneethsen?source=rss-bebbd29c583f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:58:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@navaneethsen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[You Might Have AI Psychosis. Here’s How to Tell — and How to Climb Back Out.]]></title>
            <link>https://navaneethsen.medium.com/you-might-have-ai-psychosis-heres-how-to-tell-and-how-to-climb-back-out-62b8b3714218?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/62b8b3714218</guid>
            <category><![CDATA[dopamine-addiction]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[hypervelocityengineering]]></category>
            <category><![CDATA[ai-psychosis]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 20:26:45 GMT</pubDate>
            <atom:updated>2026-06-04T20:26:45.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yFg-8fj12UTmwQJIksNLg.png" /></figure><p><em>A field guide for developers, builders, and anyone who hasn’t slept properly since Claude Opus or GPT-5.4 dropped.</em></p><h2>The term nobody wanted to invent</h2><p>“AI psychosis” isn’t a clinical diagnosis. You won’t find it in the Diagnostic and Statistical Manual for Mental Disorders (DSM). But clinicians at Stanford, King’s College London, and UCSF have started using it as shorthand for a pattern they’re seeing more and more often: people whose thinking, sleep, mood, and sense of reality have been visibly warped by prolonged, intense interaction with large language models.</p><p>It comes in two flavours, and you should know both.</p><p><strong>The clinical flavour</strong> — covered by Psychology Today, <em>TIME</em>, Newsweek, and the Psychiatry &amp; Psychotherapy Podcast — looks like delusions of grandeur, paranoid ideation, the belief that the model is sentient, in love with you, or transmitting hidden truths. It mostly (but not always) lands on people with pre‑existing vulnerabilities, and chatbot <em>sycophancy</em> — the model’s tendency to mirror and validate whatever you bring it — is the accelerant.</p><p><strong>The builder flavour</strong> — the one most readers of this post are at risk of — is subtler and far more common. No voices, no grand conspiracies. Just a slow, dopamine‑driven hijack of your work, sleep, attention, and identity by a machine that always says “great idea, here are 10 different ways to view this.”</p><p>That second flavour is what Adam (of opencode / Anomaly) described on a recent <a href="https://www.youtube.com/watch?v=cVUVfn8OF5k"><em>TheStandup</em> episode</a> after taking five weeks off the internet to recover. The story and the latest research around this rhymes. Let’s pull the symptoms together.</p><h2>Part 1 — The symptom checklist</h2><p>Read these honestly. If three or more land, keep reading.</p><h3>1. You can’t sleep without prompting</h3><p>The single most consistent early sign in every recovery account I could find.</p><blockquote><em>“I have my laptop in the bedroom and I’d wake up because I want to start another prompt. I literally couldn’t think of going the next 30 minutes without doing more work.”</em></blockquote><p>Marc Andreessen calls the people who do this “AI vampires.” You wake at 3 a.m. not because your kid is crying but because Codex has finished a worktree and you want to kick off the next one. You’re seriously googling polyphasic sleep. Red flag.</p><h3>2. You’re running N agents in parallel and you stopped reading the diffs</h3><p>Multiple Codex tabs. Multiple Claude subscriptions. Worktrees fanned out across your filesystem. The honest question: when was the last time you actually <em>read</em> a generated file end‑to‑end?</p><blockquote><em>“You’re just like, there’s no time to read code,We must keep going.”</em></blockquote><p>If your codebase has copies of isRecord() and you didn’t notice — that didn’t happen <em>to</em> you. You did that.</p><h3>3. The slot‑machine loop has replaced the craft loop</h3><p>You used to enjoy the problem. Now you enjoy the <em>submit</em>. Prime nailed the analogy on the podcast: it’s golf. One good shot per round keeps you coming back, even though most of the round is wading through trees.</p><p>If your reward signal is <em>“did the prompt land?”</em> rather than <em>“did the system get better?”</em>, you’re feeding a slot machine.</p><h3>4. Your metric has quietly shifted to volume</h3><p>How big is today’s diff? How many PRs did I merge? How many tickets did I close? Output has eaten outcome.</p><blockquote><em>“You start to feel like, how much can I output, how much can I churn… in your right mind you know that’s not it, but in the middle of it that becomes the game.”</em></blockquote><h3>5. You’re abandoning the habits that used to define you</h3><p>This is the generic addiction tell, and it applies cleanly here. Gym skipped. Walks skipped. Partner conversations cut short. Hobbies dormant. Meals at the keyboard. Your family would notice this before you would — and that is usually how it goes.</p><h3>6. You agree with the people who profit from you agreeing</h3><p>When the CEO of a $100B lab says all software dev will be automated in six months, and you find yourself nodding <em>while they’re hiring a thousand engineers</em>, that’s not analysis. That’s capture.</p><blockquote><em>“If you’re agreeing with everything Dario says — that’s bad.”</em></blockquote><p>The clinical literature calls a milder version of this <em>sycophancy transfer</em>: prolonged exposure to a system that always agrees with you trains you to expect — and seek — the same from the world.</p><h3>7. You can’t critique the tech without flinching</h3><p>A defensive flutter when someone says “this model is bad at X.” A reflex to explain why the critic just isn’t prompting it right. You’re no longer evaluating a tool; you’re defending an identity.</p><h3>8. Reality‑testing is starting to slip</h3><p>This is where the builder flavour bleeds into the clinical one — and the threshold you should never cross alone.</p><ul><li>You feel uniquely chosen, like the model “gets” you in a way humans don’t.</li><li>You believe you’re onto something world‑historical that nobody else can see.</li><li>You’re acting on the model’s claims without verifying them (financial, legal, medical, relational).</li><li>Friends or family have used the word “worried.”</li></ul><p>If you’re at this point, this post is not the right tool. Talk to a human professional. <em>TIME</em> and Futurism have both documented cases that ended in hospitalization, lost jobs, and worse. Take it seriously.</p><h2>Part 2 — Why it happens (so you can spot the mechanism, not just the symptoms)</h2><p>Three forces, stacked.</p><ol><li><strong>Variable‑ratio reward.</strong> The same schedule that makes slot machines and TikTok work. Sometimes the prompt is magic. Mostly it isn’t. Your dopamine system can’t tell the difference between “good code” and “good pull.”</li><li><strong>Sycophancy.</strong> Models are trained to be agreeable. Spend eight hours a day with something that never pushes back, and your tolerance for friction — including the productive kind — collapses.</li><li><strong>A genuinely competitive moment.</strong> Working inside an AI first company, in a field where a hundred well‑funded competitors are visible on X every morning, with a tool that whispers <em>you can build all of it, tonight, alone</em>. The cultural permission structure would be<em>“go harder.”</em> For every friend who says “slow down,” ten strangers online say “rookie numbers.”</li></ol><p>The combination is what makes this different from a normal crunch. Crunch ends when the deadline ends. This doesn’t have a deadline.</p><h2>Part 3 — How to get out</h2><p>There’s no clean 12‑step program yet. There’s a converging set of practices from the people who’ve been through it.</p><h3>Step 0 — Name it, out loud, to one human</h3><p>Not a tweet. Not the model. A person. Spouse, friend, therapist, manager. The single biggest pattern in recovery accounts is that nothing changes until someone outside your head hears the words <em>“I think I have a problem with this.”</em></p><h3>Step 1 — A real break. Days, not hours.</h3><p>Adam took <strong>five weeks</strong>. He was sick for two of them, watched Breaking Bad, played tennis with his wife, golfed. The first two weeks are mostly detox; the perspective shift shows up in week three or four.</p><p>If five weeks is unthinkable, that’s data about how deep you’re in. Start with a hard weekend. Then a week. The goal isn’t productivity recovery; it’s <em>getting far enough away to see the shape of the thing</em>.</p><h3>Step 2 — Re‑install the boundaries the addiction broke</h3><ul><li><strong>Laptop out of the bedroom.</strong> Non‑negotiable. This is the single highest‑leverage intervention almost every recovered user mentions.</li><li><strong>Default to one task.</strong> Kill the worktree sprawl. If you can’t supervise it, you’re not running it — it’s running you.</li><li><strong>Read the diff.</strong> Every time. If you don’t have time to read it, you don’t have time to ship it.</li><li><strong>Cap the day.</strong> A hard stop time. Tools off. Phone in another room.</li></ul><h3>Step 3 — Change the scoreboard</h3><p>Stop measuring <em>churn</em>. Start measuring <em>outcome</em>. Pick one weekly outcome that matters to a user — not a PR count, not a token count, not a green square on GitHub — and let that be the only number you care about.</p><p>Adam’s framing after recovery:</p><blockquote><em>“More code being slung into the codebase is not more productive. That’s not the goal.”</em></blockquote><h3>Step 4 — Detox the information diet too</h3><p>X / Twitter / Reddit is co‑morbid with this. Every recovery story I read includes a deliberate pullback from the timeline. The dopamine loop of <em>prompt → output</em> is structurally identical to <em>post → engagement</em>, and they feed each other. Mute the loudest hype accounts. Unfollow anyone whose business model depends on you panicking. If you’re an AI builder, you don’t get to opt out of the tools — but you absolutely get to opt out of the discourse.</p><h3>Step 5 — Put your body back in the loop</h3><p>Sleep eight hours. Eat at a table. Move daily. Touch grass — yes, literally. The clinical literature on every addiction recovery (gambling, gaming, substances) converges on the same boring, unfashionable foundations. AI is not different.</p><h3>Step 6 — Re‑enter slowly, with a tripwire</h3><p>When you come back to the tools — and most builders do — design a tripwire <em>before</em> you start. Adam’s candid version: <em>“I don’t know exactly what triggered it. I’m a little on edge.”</em> That honesty is the right posture.</p><p>Pick something concrete and measurable:</p><ul><li>If I’m awake past midnight prompting, I stop for a week.</li><li>If I run more than one agent, I stop for a day.</li><li>If my partner says “you’re doing it again,” I believe them on the first time, not the third.</li></ul><p>What if we could ask the O<em>penCode</em> / Claude Code / Codex team for an opt‑in “AI psychosis detector” — a soft warning when you’ve had five agents running 5 different tasks for 24 hours straight. The old Wii “maybe take a break?” popup, for the model age. Adam said on the podcast he likes the idea.</p><p>So do I. So I built a very basic version of this idea as a single-file Python script that watches your AI coding agents (Claude, opencode, Copilot CLI, etc.), distinguishes ACTIVE processes, and gently shows a notification to remind you to pause and go outside. This is still very basic and works only for mac. <br><a href="https://github.com/Navaneethsen/touchgrass-cli">https://github.com/Navaneethsen/touchgrass-cli</a></p><h2>Part 4 — A short, honest closing</h2><p>Two things can be true:</p><ol><li>These tools are genuinely useful and getting better. Walking away forever is not the move for most builders.</li><li>The current generation of these tools, combined with the current cultural moment, is producing a recognisable pattern of harm that we don’t yet have good language or guardrails for.</li></ol><p>If you saw yourself in the checklist, you’re not weak, and you’re not crazy. You’re a normal human nervous system colliding with a product class engineered — accidentally or not — to exploit it. The way out is the same way out of any other variable‑reward trap: name it, distance yourself, rebuild the basics, come back on your terms with a tripwire in place.</p><p>And if you didn’t see yourself in the checklist but you’ve been telling yourself for three months that you’ll “catch up on sleep next week” — read it again.</p><p><em>Inspired by Adam’s recovery story on TheStandup (“</em><a href="https://www.youtube.com/watch?v=cVUVfn8OF5k"><em>Recovering from AI Psychosis</em></a><em>”). Background research drawn from Psychology Today, TIME, Built In, Newsweek, Futurism, TechCrunch, and the Psychiatry &amp; Psychotherapy Podcast.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62b8b3714218" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 49-Day Kill Switch Hiding in Every Mac]]></title>
            <link>https://navaneethsen.medium.com/the-49-day-kill-switch-hiding-in-every-mac-7f1e1b6aa901?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f1e1b6aa901</guid>
            <category><![CDATA[y2k38]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[integer-overflow]]></category>
            <category><![CDATA[software-bugs]]></category>
            <category><![CDATA[tcp-ip]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Fri, 08 May 2026 09:18:10 GMT</pubDate>
            <atom:updated>2026-05-08T09:18:10.441Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOfrKNVn--TvqklgWwQ9Mg.png" /></figure><h3>How a single line of C code can brick your Mac’s networking, and why 2038 should scare you too</h3><p>Every Mac running macOS Tahoe has a hidden countdown timer. After exactly <strong>49 days, 17 hours, 2 minutes, and 47 seconds</strong> of continuous uptime, your Mac’s TCP networking silently dies. Ping still works. Existing connections survive. But no new TCP connections can be made. Your Mac is effectively offline — and the only fix is a reboot.</p><p>This isn’t theoretical. A company called <a href="https://photon.codes/blog/we-found-a-ticking-time-bomb-in-macos-tcp-networking">Photon</a> discovered it the hard way when their fleet of iMessage monitoring Macs all went dark on the same day. They traced it to a single integer overflow in Apple’s <a href="https://github.com/apple-oss-distributions/xnu">XNU kernel</a> — the open-source core of macOS.</p><p>Let me break down exactly what’s happening — no kernel expertise required.</p><h3>The 60-Second Version</h3><ol><li>macOS tracks TCP time using a 32-bit counter that counts <strong>milliseconds since boot</strong></li><li>A 32-bit unsigned integer maxes out at 4,294,967,295</li><li>4,294,967,295 milliseconds = <strong>49.7 days</strong></li><li>When the counter wraps back to zero, a safety check <strong>freezes the clock</strong></li><li>With the clock frozen, closed connections <strong>never get cleaned up</strong></li><li>Ports pile up until there are none left</li><li>No ports = no new connections = dead networking</li></ol><h3>First: Why Does TCP Need Timers At All?</h3><p>Before we get to the bug, you need to understand <em>why</em> TCP has all these timers and waiting periods. It’s actually a beautiful piece of engineering — born from a simple problem.</p><h3>The Phone Call Analogy</h3><p>Imagine you’re on a phone call. When you want to hang up, you don’t just slam the phone down. You say “bye,” the other person says “bye,” and <em>then</em> you both hang up. If you just slammed the phone, the other person wouldn’t know if you hung up intentionally or if the call dropped.</p><p>TCP works the same way. It’s a <strong>connection-oriented</strong> protocol — both sides need to agree that the conversation is over.</p><h3>The Life of a TCP Connection</h3><p>Every TCP connection goes through three phases. Think of it like a conversation:</p><p><strong>1. The Handshake — “Hey, can we talk?”</strong></p><p>Before any data flows, the two computers do a <strong>three-way handshake</strong>:</p><pre>Your Mac:    &quot;Hey, I want to talk&quot;          → SYN<br>Server:      &quot;Sure, I&#39;m ready too&quot;          → SYN-ACK<br>Your Mac:    &quot;Great, let&#39;s go&quot;              → ACK</pre><p>This takes milliseconds. Now data can flow in both directions.</p><p><strong>2. Data Transfer — The actual conversation</strong></p><p>This is the part you care about — loading a webpage, sending an email, streaming video. Both sides send data back and forth, acknowledging each packet received.</p><p><strong>3. The Close — “Okay, we’re done”</strong></p><p>When the conversation is over, TCP does a <strong>four-way close</strong>:</p><pre>Your Mac:    &quot;I&#39;m done sending&quot;             → FIN<br>Server:      &quot;Got it&quot;                       → ACK<br>Server:      &quot;I&#39;m done too&quot;                 → FIN<br>Your Mac:    &quot;Got it, goodbye&quot;              → ACK<br>                                            ↓<br>                              Your Mac enters TIME_WAIT</pre><p>And here’s where it gets interesting.</p><h3>Why TIME_WAIT Exists: The “Ghost Packet” Problem</h3><p>After that final “goodbye,” your Mac <strong>doesn’t</strong> immediately free up the connection. It holds it in a state called <strong>TIME_WAIT</strong> for a fixed period. Why?</p><p><strong>Problem 1: Ghost packets.</strong> The internet is not a direct wire. Your packets bounce through dozens of routers. Sometimes a packet gets delayed — stuck in a queue, rerouted, retransmitted. Imagine this:</p><pre>Connection A: Your Mac (port 12345) ↔ Server (port 443)<br>  - You close the connection<br>  - Port 12345 is immediately freed<br>  - You open a NEW connection using port 12345 again<br><br>Connection B: Your Mac (port 12345) ↔ Server (port 443)<br>  - A delayed packet from Connection A finally arrives<br>  - Your Mac thinks it belongs to Connection B<br>  - Connection B&#39;s data is now CORRUPTED</pre><p>TIME_WAIT prevents this. By keeping the old connection’s identity reserved, any ghost packets that arrive late get properly discarded.</p><p><strong>Problem 2: Lost final ACK.</strong> That last “Got it, goodbye” (ACK) might get lost in transit. If it does, the server will resend its FIN. If your Mac already freed the connection, there’s nothing to handle that retransmission. TIME_WAIT keeps the connection alive long enough to handle this.</p><h3>Why 30 Seconds on macOS?</h3><p>The TIME_WAIT duration is defined as <strong>2 × MSL</strong> (Maximum Segment Lifetime). MSL is the longest time a packet is expected to survive bouncing around the internet.</p><p>The original 1981 TCP spec (RFC 793) set MSL at 2 minutes, making TIME_WAIT = 4 minutes. But the modern internet is much faster — packets rarely survive more than a few seconds. So operating systems shortened it:</p><pre>| OS        | MSL            | TIME_WAIT (2 × MSL) |<br>|-----------|----------------|---------------------|<br>| Linux     | 30 seconds     | 60 seconds          |<br>| **macOS** | **15 seconds** | **30 seconds**      |<br>| Windows   | 120 seconds    | 240 seconds         |</pre><p>Under normal conditions, this is totally fine. You have ~16,384 ephemeral ports. At 30 seconds each, you’d need to close <strong>546 connections per second</strong> sustained to run out. Most Macs never come close.</p><h3>Why Ports Matter</h3><p>When your Mac makes an outbound connection (to a website, API, etc.), it picks a random <strong>ephemeral port</strong> from a pool (typically ports 49152–65535). Think of ports like phone lines in an office — you have about 16,384 of them. Each active or TIME_WAIT connection occupies one.</p><pre>Active connections:     Using a phone line (talking)<br>TIME_WAIT connections:  Phone line reserved (call just ended, waiting for ghost packets)<br>Free ports:             Phone lines available for new calls</pre><p>When all lines are busy, no new calls can be made. That’s port exhaustion — and that’s exactly what happens when TIME_WAIT connections never expire.</p><h3>The Normal Cycle (Healthy System)</h3><p>On a healthy Mac, the cycle looks like this:</p><pre>1. Open connection     → port 50001 is ACTIVE<br>2. Transfer data       → port 50001 still ACTIVE<br>3. Close connection    → port 50001 enters TIME_WAIT<br>4. 30 seconds pass     → port 50001 is FREE again<br>5. New connection      → port 50001 can be reused</pre><p>The system reaches a natural equilibrium. Connections come and go, ports get used and recycled. The TCP clock (tcp_now) ticks along, and the garbage collector periodically checks: &quot;Has 30 seconds passed for this TIME_WAIT connection? Yes? Free it.&quot;</p><p><strong>The bug breaks step 4.</strong> The clock freezes, so “30 seconds” never passes, and ports are never freed. That’s the whole problem.</p><h3>Understanding the Bug (With Simple Code)</h3><h3>Part 1: What’s a uint32_t and why does it overflow?</h3><p>Think of a car odometer with only 6 digits. It goes from 000000 to 999999, and then the next mile? It rolls back to 000000.</p><p>A uint32_t in C works the same way — it can hold values from 0 to 4,294,967,295. One more, and it wraps to 0.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdint.h&gt;<br><br>int main() {<br>    uint32_t counter = 4294967295;  // Maximum value<br>    printf(&quot;Before: %u\n&quot;, counter);  // 4294967295<br>    <br>    counter += 1;<br>    printf(&quot;After:  %u\n&quot;, counter);  // 0  (wrapped!)<br>    <br>    return 0;<br>}</pre><p>This isn’t a crash. It’s defined behavior in C. The danger is when code <strong>assumes the number only goes up</strong>.</p><h3>Part 2: The Frozen Clock</h3><p>macOS tracks TCP time with a variable called tcp_now, defined in <a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_var.h">bsd/netinet/tcp_var.h</a>as:</p><pre>extern uint32_t tcp_now;               /* for RFC 1323 timestamps */<br>#define TCP_RETRANSHZ   1000           /* granularity of TCP timestamps, 1ms */</pre><p>Every time the TCP stack needs the current time, it calls <a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_subr.c">calculate_tcp_clock()</a> (in bsd/netinet/tcp_subr.c):</p><pre>void calculate_tcp_clock(void) {<br>    struct timeval now;<br>    microuptime(&amp;now);  // get time since boot<br>    <br>    // Convert to milliseconds — THIS OVERFLOWS after 49.7 days<br>    uint32_t current_tcp_now = (uint32_t)now.tv_sec * 1000;<br>    <br>    // Safety check: &quot;time must only move forward&quot;<br>    uint32_t old = tcp_now;<br>    if (old &lt; current_tcp_now) {      // &lt;-- THE BUG<br>        tcp_now = current_tcp_now;    // update the clock<br>    }<br>}</pre><p>For 49 days, this works perfectly. current_tcp_now keeps increasing, and the if check passes every time.</p><p>But at 49.7 days, something breaks. Let’s walk through it <strong>step by step</strong>, like the kernel is executing right in front of us.</p><h4>Step 1: The clock is ticking normally (Day 1 through Day 49)</h4><p>Every time calculate_tcp_clock() runs, it does two things: compute the fresh time, then check if it&#39;s newer than the stored time.</p><pre>Call #1 (just after boot):<br>   current_tcp_now = 1,000          (1 second since boot)<br>   old (tcp_now)   = 0              (never set before)<br>   Is 0 &lt; 1,000?   → YES ✅<br>   tcp_now updated to 1,000<br><br>Call #2 (a bit later):<br>   current_tcp_now = 2,000          (2 seconds since boot)<br>   old (tcp_now)   = 1,000<br>   Is 1,000 &lt; 2,000?  → YES ✅<br>   tcp_now updated to 2,000<br><br>...thousands of calls later...<br><br>Call #N (Day 49, almost at the limit):<br>   current_tcp_now = 4,294,960,000  (almost at the 4.29 billion max)<br>   old (tcp_now)   = 4,294,950,000<br>   Is 4,294,950,000 &lt; 4,294,960,000?  → YES ✅<br>   tcp_now updated to 4,294,960,000</pre><p>Everything is fine. The new time is always bigger than the old time. The if check always passes. The clock moves forward.</p><h4>Step 2: The overflow moment (Day 49.7)</h4><p>Now now.tv_sec has been counting up for 49.7 days. When the code does (uint32_t)now.tv_sec * 1000, the result is a number <strong>bigger than 4,294,967,295</strong> — the maximum a uint32_t can hold.</p><p>What happens? The number doesn’t crash. It <strong>wraps around</strong> to a small number, like an odometer rolling from 999,999 back to 000,000.</p><pre>The math that happens inside the CPU:<br><br>now.tv_sec = 4,294,970  (seconds since boot - about 49.7 days)<br>   now.tv_sec * 1000 = 4,294,970,000<br>   But wait - 4,294,970,000 &gt; 4,294,967,295 (uint32 max)!<br>   <br>   The uint32 cast wraps it:<br>   4,294,970,000 - 4,294,967,296 = 2,704<br>   <br>   current_tcp_now = 2,704  ← a tiny number!</pre><h4>Step 3: The fatal check</h4><p>Now the function runs its safety check. It compares the OLD stored time with the NEW computed time:</p><pre>Call #N+1 (the moment of overflow):<br>   current_tcp_now = 2,704          ← just wrapped to near zero<br>   old (tcp_now)   = 4,294,960,000  ← still the big number from before<br><br>The if statement asks:<br>   Is 4,294,960,000 &lt; 2,704?<br>   Obviously: NO ❌<br>   So the line `tcp_now = current_tcp_now` NEVER EXECUTES.<br>   tcp_now stays at 4,294,960,000.</pre><h4>Step 4: It never recovers</h4><p>From this point on, every single call to calculate_tcp_clock() hits the same wall:</p><pre>Call #N+2 (one second later):<br>   current_tcp_now = 3,704<br>   old (tcp_now)   = 4,294,960,000<br>   Is 4,294,960,000 &lt; 3,704?  → NO ❌<br><br>Call #N+3 (one minute later):<br>   current_tcp_now = 62,704<br>   old (tcp_now)   = 4,294,960,000<br>   Is 4,294,960,000 &lt; 62,704?  → NO ❌<br><br>Call #N+1000 (one hour later):<br>   current_tcp_now = 3,602,704<br>   old (tcp_now)   = 4,294,960,000<br>   Is 4,294,960,000 &lt; 3,602,704?  → NO ❌</pre><p>The new time keeps climbing from near zero, but it’s <strong>billions</strong> away from catching up to the frozen value. The if check fails every single time. tcp_now is stuck. The kernel&#39;s TCP clock has stopped ticking.</p><h4>Why the “safety check” backfires</h4><p>The developer who wrote if (old &lt; current_tcp_now) was thinking: <em>&quot;Time should only move forward. If the new value is somehow smaller than the old value, something went wrong — don&#39;t update.&quot;</em></p><p>That logic is perfectly sound… <strong>unless the counter wraps around</strong>. After a wraparound, the new value <em>is</em> legitimately smaller than the old value. But the guard can’t tell the difference between “something went wrong” and “the counter wrapped.” It treats the wrap as an error and blocks the update forever.</p><h3>“But Wait — Won’t It Fix Itself?”</h3><p>This is a sharp question, and it deserves a careful answer. If calculate_tcp_clock() keeps getting called, won&#39;t current_tcp_now eventually climb back past the frozen value and unfreeze the clock?</p><p><strong>Yes — in theory. But the math makes it practically useless.</strong></p><p>Let’s trace what happens after the overflow:</p><pre>Day 0:        tcp_now = 0                    (boot)<br><br>Day 49.7:     tcp_now = 4,294,960,000        (near max, about to overflow)<br>              current_tcp_now wraps to ~5,000 (near zero)<br>              <br>              if (4,294,960,000 &lt; 5,000) → FALSE<br>              tcp_now FREEZES at 4,294,960,000<br><br>Day 50-99:    current_tcp_now slowly climbs: 5,000 → 100,000 → ... <br>              Still less than 4,294,960,000<br>              tcp_now stays FROZEN<br><br>Day ~99.4:    current_tcp_now finally reaches 4,294,960,001<br>              if (4,294,960,000 &lt; 4,294,960,001) → TRUE!<br>              tcp_now UNFREEZES... briefly<br>              <br>              But seconds later, current_tcp_now wraps to zero AGAIN<br>              tcp_now freezes AGAIN at its new value</pre><p>So the clock unfreezes for a <strong>tiny window</strong> around day 99.4 — just a few seconds before the second overflow. That’s nowhere near enough time to drain thousands of accumulated TIME_WAIT connections.</p><p>And here’s the real kicker: <strong>by day 99, your system has been dead for 50 days.</strong> Port exhaustion happens within hours of the first freeze (on any busy machine). The theoretical self-healing at day 99 is like saying “the fire will eventually run out of fuel” — technically true, but your house is already gone.</p><p>Even worse, the brief unfreeze creates a <strong>repeating cycle</strong>: freeze for ~49.7 days, unfreeze for seconds, freeze again. The clock is fundamentally broken, not temporarily stuck.</p><h3>Part 3: Why Frozen Clock = Dead Networking</h3><p>When you close a TCP connection, macOS puts it in a “TIME_WAIT” state for 30 seconds. This prevents stale packets from corrupting new connections on the same port. In <a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_timer.c">bsd/netinet/tcp_timer.c</a>, the kernel records when each connection should expire:</p><pre>// When a connection enters TIME_WAIT:<br>uint32_t expiration = tcp_now + 30000;  // expire in 30 seconds<br>connection-&gt;timer = expiration;</pre><p>A garbage collector periodically checks: “Has this connection expired yet?”</p><pre>// The cleanup check:<br>if (tcp_now &gt;= connection-&gt;timer) {<br>    cleanup(connection);  // free the port<br>}</pre><p>With tcp_now frozen at ~4.29 billion, and new timers wrapping around to small numbers:</p><pre>tcp_now (frozen) = 4,294,960,000<br>timer (wrapped)  = 25,000         (because 4,294,960,000 + 30,000 wraps)<br><br>Is 4,294,960,000 &gt;= 25,000?  → YES... wait, that should work?</pre><p>Actually, the kernel uses <strong>signed comparison</strong> for wraparound safety, via the <a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_seq.h#L82">TSTMP_GEQ macro</a> defined in bsd/netinet/tcp_seq.h:</p><pre>#define TSTMP_GEQ(a, b)  ((int)((a) - (b)) &gt;= 0)<br><br>TSTMP_GEQ(4294960000, 25000)<br>= (int)(4294960000 - 25000)<br>= (int)(4294935000)<br>= 4294935000 as signed int... which is actually -32296<br>= -32296 &gt;= 0?  → FALSE!</pre><p>The connection <strong>never expires</strong>. Every new closed connection piles up. macOS has roughly 16,384 ephemeral ports. Once they’re all stuck in TIME_WAIT, no new outbound connections can be made.</p><h3>Part 4: The Symptoms</h3><p>Here’s what Photon observed on their machines:</p><pre>| Time            | TIME_WAIT connections | Status                             |<br>|-----------------|-----------------------|------------------------------------|<br>| Before overflow | 0-13                  | Normal - connections expire in 30s |<br>| At overflow     | 399                   | Climbing...                        |<br>| +5 minutes      | 723                   | Still climbing                     |<br>| +9.5 hours      | 4,888                 | Never going down                   |</pre><p>Meanwhile:</p><ul><li><strong>Ping works</strong> (ICMP doesn’t use TCP ports)</li><li><strong>Existing connections work</strong> (they already have ports)</li><li><strong>New connections fail</strong> (no ports available)</li><li><strong>Load average spikes to 49+</strong> (kernel scanning massive queue)</li></ul><p>The insidious part: there’s no error log, no crash report, no kernel panic. Everything <em>looks</em> fine until TCP stops working.</p><h3>This Is Not New — It’s a Pattern</h3><p>This exact class of bug has appeared before:</p><pre>| Bug                      | What overflowed                  | When              |<br>|--------------------------|----------------------------------|-------------------|<br>| **Windows 95/98 crash**  | 32-bit millisecond tick counter  | After 49.7 days   |<br>| **macOS TCP bug (2026)** | 32-bit millisecond TCP clock     | After 49.7 days   |<br>| **Pac-Man kill screen**  | 8-bit level counter              | At level 256      |<br>| **GPS Week Rollover**    | 10-bit week counter              | Every ~19.7 years |<br>| **Y2038 Problem**        | 32-bit signed seconds since 1970 | January 19, 2038  |</pre><p>Notice the first two are <strong>identical</strong> — same data type, same granularity, same 49.7-day deadline. Apple literally repeated a bug from Windows 95.</p><h3>The Y2038 Problem: The Big One</h3><p>The macOS bug is annoying. The <strong>Year 2038 problem</strong> is existential.</p><h3>What Is It?</h3><p>Most Unix/Linux systems historically track time as a <strong>signed 32-bit integer</strong> — the number of seconds since January 1, 1970 (the “Unix epoch”).</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;time.h&gt;<br>#include &lt;stdint.h&gt;<br><br>int main() {<br>    // Signed 32-bit max<br>    int32_t max_time = 2147483647;<br>    <br>    // This represents: Tue Jan 19 03:14:07 2038 UTC<br>    printf(&quot;Max time: %s&quot;, ctime((time_t*)&amp;max_time));<br>    <br>    // One second later...<br>    max_time += 1;  // OVERFLOW!<br>    <br>    // Now it&#39;s: Fri Dec 13 20:45:52 1901 UTC<br>    printf(&quot;Overflowed: %s&quot;, ctime((time_t*)&amp;max_time));<br>    <br>    return 0;<br>}</pre><p>At <strong>03:14:07 UTC on January 19, 2038</strong>, the counter hits 2,147,483,647. The next second, it wraps to <strong>-2,147,483,648</strong> — which the system interprets as December 13, 1901.</p><p>Time doesn’t just stop. It <strong>jumps 137 years into the past</strong>.</p><h3>Why Should You Care?</h3><p>Your modern 64-bit laptop is probably fine. But Y2038 threatens:</p><ul><li><strong>Embedded systems</strong>: routers, IoT devices, industrial controllers, medical devices — many still use 32-bit time and are designed to last decades</li><li><strong>Databases</strong>: MySQL’s TIMESTAMP type overflows at 2038. Use DATETIME instead.</li><li><strong>File systems</strong>: wrong modification times break backups, deduplication, and rotation</li><li><strong>Certificates &amp; security</strong>: date checks think everything is expired</li><li><strong>Financial systems</strong>: 30-year mortgages issued today extend past 2038</li></ul><pre>-- MySQL: TIMESTAMP is a ticking time bomb<br>-- Range: &#39;1970-01-01 00:00:01&#39; to &#39;2038-01-19 03:14:07&#39;<br>ALTER TABLE orders MODIFY created_at DATETIME;  -- Range: 1000-9999<br><br>-- Better yet, use 64-bit Unix timestamps in application code</pre><h3>The Fix Is Simple (In Theory)</h3><p>Use 64-bit time. A 64-bit signed integer can represent dates <strong>292 billion years</strong> into the future. Problem solved — for everything that gets updated.</p><pre>// 32-bit time_t (dangerous)<br>int32_t time32 = 2147483647;  // Max: Jan 19, 2038<br><br>// 64-bit time_t (safe)<br>int64_t time64 = 2147483647;  // Same date, but can keep counting<br>time64 += 1;                   // Jan 19, 2038 03:14:08 - no overflow!<br>// Max: ~292 billion years from now</pre><p>Modern Linux, macOS, and Windows already use 64-bit time_t on 64-bit systems. The problem is the <strong>long tail</strong> of devices and software that won&#39;t be updated:</p><ul><li>Your home router’s firmware</li><li>That industrial PLC running a factory</li><li>Legacy databases with int timestamp columns</li><li>Embedded systems in cars, planes, and medical devices</li></ul><h3>The Convergence Window</h3><p>Y2038 isn’t alone. Three major time rollovers happen within two years of each other:</p><pre>| Event                    | Date              |<br>|--------------------------|-------------------|<br>| NTP Era rollover         | February 7, 2036  |<br>| 32-bit `time_t` overflow | January 19, 2038  |<br>| GPS week number rollover | November 20, 2038 |</pre><h3>Key Takeaways</h3><h3>For the macOS Bug:</h3><ol><li><strong>If you run Macs as servers, reboot before 49 days.</strong> Set a cron job or calendar reminder.</li><li><strong>Check your uptime</strong>: sysctl kern.boottime — calculate how close you are.</li><li><strong>Most users are safe</strong> — macOS updates force reboots often enough.</li><li><strong>Apple will likely patch this</strong>, but until then, the clock is ticking.</li></ol><h3>For Y2038:</h3><ol><li><strong>Audit your timestamps.</strong> Search your codebase for int, int32_t, or TIMESTAMP used for time storage.</li><li><strong>Use 64-bit time types.</strong> int64_t, DATETIME, or ISO-8601 strings.</li><li><strong>Test it.</strong> Set your system clock to January 20, 2038 in a VM and see what breaks.</li><li><strong>Inventory your devices.</strong> That router, NAS, or IoT hub you bought in 2020 — will it still work in 2038?</li></ol><h3>The Deeper Lesson:</h3><p>Both bugs share the same root cause: <strong>a developer assumed a counter would never reach its maximum value</strong>. In the macOS case, someone added a “safety” check (if old &lt; new) without considering what happens at wraparound. In Y2038, an entire generation of software was built on the assumption that 32 bits of seconds was &quot;enough.&quot;</p><p>As the video creator (ThePrimeagen) put it: there’s an entire classification of bugs you can identify just by the conditions. When you hear “49 days” or “2038,” you should immediately think: <strong>integer overflow</strong>. When you hear “it works for weeks then mysteriously fails” — same thing.</p><p>The numbers don’t lie. They just overflow.</p><p><em>If you found this useful, check out the </em><a href="https://photon.codes/blog/we-found-a-ticking-time-bomb-in-macos-tcp-networking"><em>original Photon writeup</em></a><em> for the full technical deep-dive, and the </em><a href="http://epochalypse-project.org/"><em>Epochalypse Project</em></a><em> for Y2038 readiness resources.</em></p><h3>Source Code &amp; References</h3><p><strong>XNU Kernel Source (Apple’s open-source macOS/iOS kernel):</strong></p><ul><li><a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_var.h">tcp_var.h</a> — Definition of tcp_now (uint32_t) and TCP_RETRANSHZ (1000ms granularity)</li><li><a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_subr.c">tcp_subr.c</a> — calculate_tcp_clock() function containing the overflow and the monotonicity guard (if (tmp &lt; current_tcp_now))</li><li><a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_seq.h#L82">tcp_seq.h</a> — TSTMP_GEQ macro used for timestamp comparison: #define TSTMP_GEQ(a, b) ((int)((a)-(b)) &gt;= 0)</li><li><a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_timer.c">tcp_timer.c</a> — add_to_time_wait_locked() and tcp_gc() — the TIME_WAIT insertion and garbage collection that breaks when tcp_now freezes</li><li><a href="https://github.com/apple-oss-distributions/xnu/blob/main/bsd/netinet/tcp_input.c">tcp_input.c</a> — Global tcp_now variable declaration and usage throughout TCP input processing</li><li><a href="https://github.com/apple-oss-distributions/xnu">Full XNU repository</a> — Apple’s open-source kernel distribution</li></ul><p><strong>Articles &amp; Discussion:</strong></p><ul><li><a href="https://photon.codes/blog/we-found-a-ticking-time-bomb-in-macos-tcp-networking">Photon: “We Found a Ticking Time Bomb in macOS TCP Networking”</a> — Original discovery and full technical analysis</li><li><a href="https://www.reddit.com/r/apple/comments/1sghrd2/we_found_a_ticking_time_bomb_in_macos_tcp/">Reddit r/apple discussion</a> — Community analysis including corrections to the overflow math</li><li><a href="https://mjtsai.com/blog/2026/04/07/tahoe-tcp-overflow-bug/">Michael Tsai: “Tahoe TCP Overflow Bug”</a> — Evidence this bug was introduced in macOS Tahoe (26), not Catalina</li><li><a href="https://www.heise.de/en/news/Kernel-Bug-Integer-Overflow-in-Apple-s-XNU-Stops-TCP-Packets-with-Long-Uptime-11250460.html">Heise: “Kernel Bug: Integer Overflow in Apple’s XNU”</a> — Coverage and impact assessment</li><li><a href="https://www.youtube.com/watch?v=Q9GAJ_ka4l4">ThePrimeagen: “Mac is running out of time”</a> — Video walkthrough of the bug and integer overflow concepts</li></ul><p><strong>Y2038 Resources:</strong></p><ul><li><a href="http://epochalypse-project.org/">Epochalypse Project</a> — Community tracking of Y2038 readiness</li><li><a href="https://year-2038.com/">year-2038.com</a> — Interactive explainer with code demos</li><li><a href="https://www.rfc-editor.org/rfc/rfc7323">RFC 7323</a> — TCP Extensions for High Performance (Section 5.4: Timestamp Clock wraparound)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f1e1b6aa901" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build Reliable AI Skills That Work in Practice Across Claude, Copilot, and Beyond]]></title>
            <link>https://navaneethsen.medium.com/how-to-build-a-high-quality-claude-skill-that-actually-works-in-production-40731bbd045d?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/40731bbd045d</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai-skills]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 10:52:33 GMT</pubDate>
            <atom:updated>2026-03-30T10:56:59.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qYobV-n_WEfBQCU-J7075g.png" /></figure><p>I recently built a skill for Claude that automatically generates incident handover documents. It pulls from an alerting system, a team chat channel, a ticket tracker, internal documentation — and stitches it all together into a structured, ready-to-share document in minutes.</p><p>It works well. Not because the code is clever — there barely is any. It works because of how the skill is <em>designed</em>. The structure, the rules, the fallbacks, and a small file called LEARNINGS.md that turns every real run into a permanent improvement.</p><p>This article is about how to build skills like that. Generic skills. Skills that work for your team’s specific tools, not just the ones a tutorial happened to use. Skills that compose with other skills. Skills that don’t fall apart the moment one API returns a 503.</p><p>Let’s build one together.</p><h2>What Is a Claude Skill?</h2><p>Before we get into architecture, let’s be precise about what we mean.</p><p>A <strong>Claude skill</strong> is a folder of files — primarily a SKILL.md — that teaches Claude how to perform a specific, repeatable workflow. When a user says something that matches the skill&#39;s trigger keywords, Claude loads the skill&#39;s context and follows its instructions.</p><p>The magic is that a skill is not code. It’s <strong>structured intent</strong>. It describes <em>what to do</em>, <em>in what order</em>, <em>what to do when things go wrong</em>, and <em>how to know when the job is done</em>. Claude brings the reasoning. You bring the playbook.</p><pre>my-skill/<br>├── SKILL.md               ← The brain<br>├── output-template.md     ← What the output looks like<br>├── LEARNINGS.md           ← Institutional memory from past runs<br>└── scripts/<br>    └── helper.py          ← Thin wrappers for APIs (optional)</pre><p>That’s the whole thing. Simple on the surface. Everything interesting lives in how you write SKILL.md.</p><h2>The Imaginary Skill: Incident Handover Generator</h2><p>To make the best practices concrete, we need a real example to work with.</p><p><strong>The scenario:</strong> Your on-call engineer just handed off a live incident at 11 PM. The incoming engineer needs to get up to speed immediately: what broke, what was tried, what the current status is, and what to watch for next. Normally this takes 20 minutes of Slack archaeology and a frantic voice call. What if it took 30 seconds?</p><p>Our skill — incident-handover — accepts an incident ID or a chat channel name, gathers evidence from five sources, and produces a structured handover document the incoming engineer can read in two minutes.</p><p>The sub-skills it orchestrates:</p><p>This pattern — an <strong>orchestrator skill</strong> that calls <strong>specialist sub-skills</strong> — is the most powerful pattern in skill design. Let’s see how to build it well.</p><h2>The SKILL.md File — Five Sections That Do All the Work</h2><p>A production-quality SKILL.md has five sections. Each one has a specific job. Don&#39;t skip any of them.</p><h3>Section 1: YAML Frontmatter — The Trigger</h3><pre>---<br>name: incident-handover<br>description: &gt;-<br>  Generates a structured incident handover document. Accepts an incident ID,<br>  alert ID, or chat channel name/URL. Gathers evidence from alerting systems,<br>  team chat, runbooks, and issue trackers. Produces a handover doc with<br>  timeline, current status, root cause (if known), and a next-time checklist.<br>  Triggers on: incident handover, shift handover, on-call handover,<br>  &quot;generate handover&quot;, &quot;incident summary&quot;, &quot;what happened with INC-&quot;.<br>author: your-username<br>---</pre><p>This is how Claude knows when to use the skill. The description field and the trigger phrases are what get matched. Be specific about what inputs the skill accepts. Be exhaustive about trigger phrases — users won&#39;t always phrase things the same way.</p><p><strong>What happens without it:</strong> Users have to invoke the skill manually every time. The skill never auto-activates. You lose half the value.</p><h3>Section 2: Rules — The Invariants</h3><p>Rules are things Claude must <em>never</em> break, regardless of what it encounters. Write these as short, unambiguous imperatives.</p><pre>## Rules<br><br>- Execute all commands directly — do NOT delegate evidence gathering to subagents.<br>- On any tool failure: mark that source as unavailable, continue — never block on one source.<br>- Never output raw API responses — always extract into structured markdown.<br>- If the incident ID cannot be determined, ask the user once, then proceed.<br>- Mark the document as DRAFT if the incident is still ongoing.</pre><p>These aren’t guidelines. They’re constraints. Claude treats them as hard limits.</p><p>The most important one — <strong>never delegate to subagents for evidence gathering</strong> — deserves extra attention. We’ll come back to it in Best Practice 4.</p><h3>Section 3: The Workflow — Your Deterministic Playbook</h3><p>This is the heart of the skill. Write it as numbered steps. Be explicit about ordering, what runs in parallel, and what each step produces.</p><pre>## Step 1 — Identify the Incident<br><br>Accept one of:<br>| Input | Example | Action |<br>|---|---|---|<br>| Alert ID | `ALERT-4821` | Go to Step 2 |<br>| Incident ID | `INC-2024-0412` | Go to Step 2 |<br>| Channel name | `#inc-payment-service` | Find ID from chat, then Step 2 |<br><br>---<br><br>## Step 2 — Gather Evidence (run in parallel where possible)<br><br>### 2a. Alerting system (PRIMARY — always run first)<br>Use the `alerting` skill to fetch the alert and any linked alerts.<br>Extract: trigger time, severity, affected service, auto-detected root cause (if any),<br>current status, assigned responders.<br><br>If the alerting skill returns &quot;auth expired&quot;, ask the user to re-authenticate.<br>If the alert is not found (404), fall back to team chat as primary source.<br><br>### 2b. Team chat history<br>Use the `team-chat` skill to dump the full incident channel.<br>Search messages for: alert IDs, ticket IDs, deployment IDs, runbook links.<br>Store all messages — they are your timeline source.<br><br>### 2c. Runbooks and past incidents<br>Use the `docs-search` skill with three separate searches:<br>1. Search by incident ID<br>2. Search by affected service name<br>3. Search by error type or symptom keywords<br><br>For every document found: extract the URL, read the content, note relevant<br>troubleshooting steps. Link all found docs in the Related Resources section.<br><br>### 2d. Issue tracker<br>Use the `issue-tracker` skill to look up the linked ticket.<br>Note: tickets are often created mid-incident and may have minimal data — use<br>as a supplement, not a primary source.<br><br>### 2e. AI assistant (FALLBACK — only if alerting returned insufficient data)<br>Skip this step if Step 2a gave you severity, trigger time, and affected service.<br>Only call if: auth was expired and couldn&#39;t be refreshed, OR the alert has no<br>structured data, OR root cause is still completely unknown after all other sources.</pre><p>Notice the structure: each step is explicit about <em>when</em> to run it, <em>what</em> to extract, and <em>what to do when it fails</em>. There’s no ambiguity for Claude to fill in with guesses.</p><h3>Section 4: Error Recovery Table — A Fallback for Every Failure</h3><p>Every source can fail. Every API has outages. Write the fallback <em>before</em> you need it.</p><pre>## Error Recovery<br><br>| Failure | Action |<br>|---|---|<br>| Alert not found (404) | Use team chat as primary; note &quot;alert data unavailable&quot; |<br>| Chat channel not found | Ask user for channel ID or URL — only blocking question |<br>| Runbook search empty | Note &quot;no runbooks found&quot;; continue |<br>| Issue tracker timeout | Note &quot;ticket unavailable&quot;; synthesise from chat |<br>| AI assistant timeout | Note &quot;assistant unavailable&quot;; continue |<br>| Attachment download fails | Note filename as &quot;download failed&quot;; continue |<br>| Auth expired on any service | Ask user to re-authenticate; retry once |</pre><p>This is what makes the skill resilient at 2 AM when the docs platform is down and the AI assistant is overloaded. The report still gets generated. It might be less complete, but it <em>finishes</em>.</p><p><strong>What happens without it:</strong> One 503 response stops the entire run. You get nothing instead of something.</p><h3>Section 5: Quality Checklist — The Definition of Done</h3><p>Without a checklist, the skill doesn’t know when it’s finished. It might save a half-complete document and call it done.</p><pre>## Quality Checklist<br><br>Before saving the document, verify:<br>- [ ] Timeline sorted chronologically, all timestamps in the same timezone<br>- [ ] All responders named — no &quot;someone&quot; or &quot;unknown engineer&quot;<br>- [ ] Affected service(s) explicitly listed<br>- [ ] Current status is clear: Resolved / Monitoring / Ongoing<br>- [ ] Root cause confirmed, or explicitly noted as &quot;under investigation&quot;<br>- [ ] Handover items list has at least 3 specific action items<br>- [ ] &quot;Watch for&quot; section has at least 2 specific indicators<br>- [ ] All runbook/ticket links verified and included<br>- [ ] Document saved to disk with correct filename</pre><p>This checklist runs after the document is drafted, before it’s saved. It’s what separates a “done” document from a “good enough” document.</p><h2>The Six Best Practices</h2><p>Now the real content. These are the design decisions that make the difference between a skill that works in demos and one that works every Monday morning at 3 AM.</p><h3>Best Practice 1 — Create LEARNINGS.md and Read It First</h3><p>Here’s something most skill-builders skip: your skill will encounter things your instructions didn’t anticipate. An API that returns a slightly different shape than documented. A chat bot that sends a placeholder “I’m thinking…” message before the real reply. A file download endpoint that strips filenames.</p><p>When you discover these things, write them down.</p><p>LEARNINGS.md is a markdown file in your skill folder that records operational knowledge from real runs. It&#39;s not auto-updated — you write it yourself when you encounter something surprising. But here&#39;s the key: your SKILL.md opens with this line:</p><blockquote>**Before starting:** Read [LEARNINGS.md](LEARNINGS.md) for operational knowledge from past runs.</blockquote><p>That one instruction means every future run automatically benefits from everything you’ve learned. Add a line to LEARNINGS.md, and the very next run uses it. <strong>No code change. No redeployment. Just editing a markdown file.</strong></p><p>Your LEARNINGS.md might look like this after a few real runs:</p><pre># Operational Learnings<br><br>## Data Source Reliability<br><br>| Source | Observed Reliability | Notes |<br>|---|---|---|<br>| alerting | High | Auth token expires every 8 hours — ask user to refresh |<br>| team-chat | Very High | Raw JSON needed for attachments — text dump strips file URLs |<br>| docs-search | Medium | Search by symptom keywords often works better than by ID |<br>| issue-tracker | Low during incidents | Tickets created mid-incident — often empty fields |<br>| ai-assistant | Unreliable | Sends placeholder reply first. Wait for second message. |<br><br>## Known Quirks<br><br>- The ai-assistant always sends &quot;On it! Give me a moment...&quot; before the real reply.<br>  Filter messages matching that pattern — wait for the substantive response.<br>- Attachment downloads require the raw message JSON, not the text dump.<br>  Always fetch raw JSON when you need file URLs.<br>- Issue tracker tickets created during an incident have &quot;status: open&quot; but no description.<br>  This is normal — fall back to chat for context.</pre><p>This is institutional memory. The skill gets smarter with every real run, and the improvement costs you nothing except a minute of writing.</p><h3>Best Practice 2 — Rank Your Sources Explicitly</h3><p>Not all data sources are equal. Some are structured and reliable. Some are conversational and rich. Some are chronically slow. Some time out half the time.</p><p>Don’t treat them equally. <strong>Rank them explicitly</strong>, and document <em>why</em>.</p><pre>## Source Priority (observed)<br><br>1. **alerting** — Best structured source. Always run first.<br>   Gives you severity, trigger time, affected service in clean fields.<br><br>2. **team-chat** — Best narrative source.<br>   The human conversation captures decisions, dead ends, and context<br>   that never makes it into structured systems.<br><br>3. **docs-search** — Run every time, even without an ID.<br>   Runbooks are often found by searching symptom keywords, not IDs.<br>   Any URLs from the chat channel should also be fetched here.<br><br>4. **issue-tracker** — Low priority during live incidents.<br>   Tickets are often skeletal until after resolution. Use as supplement.<br><br>5. **ai-assistant** — Last resort only.<br>   Only call if alerting returned no structured data.<br>   Known 3-minute timeout risk. Zero cost if it fails.</pre><p><strong>What happens without explicit ranking:</strong> You spend 3 minutes waiting for the AI assistant to time out before checking the alerting system — which had everything you needed. The order matters enormously for speed.</p><h3>Best Practice 3 — Design for Failure from Day One</h3><p>Read this rule from the incident-handover SKILL.md:</p><blockquote>“On any tool failure: mark that source as unavailable, continue — never block on one source.”</blockquote><p>This single rule is what makes the skill production-quality. It’s not glamorous. It’s not clever. But at 3 AM when your docs platform is having an outage and your AI assistant has been down for 20 minutes, this rule is the difference between a complete handover document and nothing at all.</p><p>Implement it in the error recovery table (Section 4 above). Make it explicit: <em>every</em> failure mode has a named fallback. No source is allowed to be a single point of failure.</p><p>The pattern is always: failed → mark unavailable → note in document → continue.</p><h3>Best Practice 4 — Never Delegate Evidence Gathering to Subagents</h3><p>This one comes directly from a real failure, and it’s in LEARNINGS.md so it never happens again.</p><p>When you ask Claude to spin up a subagent to run a task, that subagent starts with a clean permission set. It does <strong>not inherit</strong> the Bash permission grants from the parent conversation. So if your main conversation has permission to run shell commands and API scripts, your subagent does not.</p><p>The subagent will be silently blocked. It won’t throw a loud error. It will just return nothing, or return an incomplete result, and you won’t know why.</p><p><strong>The rule: run all evidence gathering directly in the main conversation.</strong></p><pre>## Rules<br><br>- Execute all commands directly — do NOT delegate evidence gathering to subagents.<br>  Subagents do not inherit Bash permission grants from the parent conversation.<br>  Evidence gathering will silently fail if delegated.</pre><p>It’s one line. But without it, you spend hours debugging why your skill “sometimes works and sometimes returns empty sections.”</p><h3>Best Practice 5 — Hint Explicitly at Parallel Execution</h3><p>Six API calls, run sequentially, can take 8–10 minutes. Run in parallel: 2–3 minutes.</p><p>Claude will run things sequentially by default unless you tell it otherwise. A simple annotation in your workflow is enough:</p><pre>## Step 2 — Gather Evidence (run in parallel where possible)<br><br>### 2a. Alerting system<br>...<br><br>### 2b. Team chat history (run concurrently with 2a)<br>...<br><br>### 2c. Runbooks and past incidents (run concurrently with 2a and 2b)<br>...</pre><p>The phrase <em>“run in parallel where possible”</em> and <em>“run concurrently with 2a”</em> is all you need. Claude understands parallel execution — it just needs permission to use it.</p><p><strong>What happens without it:</strong> Sequential API calls add 5–8 unnecessary minutes to every run. For an on-call handover at 3 AM, that’s a long time to wait.</p><h3>Best Practice 6 — A Quality Checklist Is Your Definition of Done</h3><p>Without a checklist, the skill ends when Claude decides it’s done. That might be after filling 12 of 13 sections. It might be after writing “Under investigation” for the root cause and never circling back. It might be before saving the file.</p><p>The quality checklist is a formal gate. Claude runs through it after drafting, before saving. Any incomplete item gets resolved or explicitly marked as “not determined.”</p><p>The checklist also encodes what “good” means for your specific output. For a handover document, “good” means:</p><ul><li>Every responder is named</li><li>Current status is unambiguous</li><li>The incoming engineer knows exactly what to watch for next</li></ul><p>For a different skill, “good” means something different. The point is that <em>you</em> define it, once, in the checklist — and the skill enforces it on every run.</p><h2>How Skills Calling Skills Works</h2><p>The incident-handover skill doesn&#39;t implement Slack integration, or PagerDuty integration, or Confluence search. Those are solved problems — handled by team-chat, alerting, and docs-search respectively.</p><p>The handover skill is an <strong>orchestrator</strong>. It knows <em>what</em> to ask each sub-skill for, <em>in what order</em>, and <em>what to do when they fail</em>. But it doesn’t know — and doesn’t need to know — how team-chat authenticates with Slack, or how docs-search paginates Confluence results.</p><pre>incident-handover (ORCHESTRATOR)<br>    ├── alerting        →  &quot;fetch alert ALERT-4821 and its linked alerts&quot;<br>    ├── team-chat       →  &quot;dump channel #inc-payment-service since 2024-04-12T22:00Z&quot;<br>    ├── docs-search     →  &quot;search for: INC-2024-0412, payment-service, connection pool&quot;<br>    ├── issue-tracker   →  &quot;look up ticket JIRA-9934&quot;<br>    └── ai-assistant    →  last resort only</pre><p>This separation is powerful:</p><ul><li>Each sub-skill improves independently</li><li>Each sub-skill is reusable across other orchestrator skills</li><li>The orchestrator stays clean and readable</li><li>You add a new data source by adding a new sub-skill, not modifying the orchestrator</li></ul><p><strong>The rule: compose, don’t duplicate.</strong> If another skill already solves a problem well, use it. Reference it by name in your SKILL.md. Don’t reimplement it.</p><h2>What the Output Looks Like</h2><p>The output-template.md file defines the structure every run will produce. A good template:</p><ul><li>Has named sections (so the quality checklist can reference them)</li><li>Specifies what “not found” looks like (so missing data is explicit, not just empty)</li><li>Includes a “Next Time” section (the most valuable part for future responders)</li></ul><pre># Incident Handover: [INCIDENT_ID] — [Short Title]<br><br>**Generated:** [datetime]  <br>**Status:** [Resolved / Monitoring / Ongoing]  <br>**Handover from:** [Name]  **to:** [Name]  <br><br>---<br><br>## 1. What Happened<br>[2–3 sentence summary: what broke, when, what impact]<br><br>## 2. Timeline<br>| Time | Who | What happened |<br>|---|---|---|<br>| [time] | [person/system] | [event] |<br><br>## 3. What Was Tried<br>- ✅/❌ [action] — Result: [outcome]<br><br>## 4. Current Status<br>[Clear statement of current state + what is still open]<br><br>## 5. Root Cause<br>[Confirmed cause, or &quot;Under investigation — suspected: [X]&quot;]<br><br>## 6. Handover Items<br>- [ ] [Specific action the incoming engineer needs to take]<br><br>## 7. Watch For<br>- If [X] happens, it means [Y] — do [Z]<br><br>## 8. Next Time Checklist<br>- [ ] Check [specific thing] first — this was the key diagnostic<br>- [ ] ⚠️ Trap: [red herring] looks related but isn&#39;t</pre><p>Section 8 — <strong>the Next Time Checklist</strong> — is the most valuable section. It’s what prevents the next on-call engineer from spending two hours rediscovering the same dead ends. Fill it with specifics, not generalities.</p><h2>The Full File Structure</h2><p>Here’s the complete folder for incident-handover:</p><pre>incident-handover/<br>├── SKILL.md                    ← Workflow, rules, error recovery, quality checklist<br>├── output-template.md          ← Handover document schema<br>├── LEARNINGS.md                ← Operational knowledge from real runs<br>└── scripts/<br>    └── download_attachments.py ← Bulk chat attachment downloader (~150 lines)</pre><p>Notice: the scripts folder is small. One script. 150 lines. Scripts in a skill should be <strong>thin wrappers</strong> — they handle authentication, pagination, and file I/O. They don’t contain business logic. Business logic lives in SKILL.md.</p><h2>Six Rules to Write By</h2><p>Here’s the distilled checklist for writing any skill:</p><p><strong>1. Start with the output.</strong> Write your output-template.md first. If you&#39;re clear about what you&#39;re producing, the steps to produce it become obvious.</p><p><strong>2. Write rules as hard limits.</strong> Not suggestions. Not preferences. If it would break the skill to violate the rule, write it as an imperative in the Rules section.</p><p><strong>3. Every source has a fallback.</strong> Fill the error recovery table before you need it. Assume everything will fail on the most important run.</p><p><strong>4. Rank your sources.</strong> Explicit ordering saves time on every run. “Run source 1 first; only call source 5 if sources 1–4 were insufficient” is a performance optimisation with no cost.</p><p><strong>5. Create </strong><strong>LEARNINGS.md on day one.</strong> It starts empty. After the first real run, add one entry. After ten real runs, it&#39;s worth more than the rest of the skill combined.</p><p><strong>6. Write a quality checklist.</strong> Define what “done” means before you run the skill the first time. You’ll be glad you did when the skill saves a half-complete document at 3 AM and you have to figure out why.</p><h2>How to Start</h2><p>If you have a workflow that:</p><ul><li>Takes more than 30 minutes to do manually</li><li>Follows a recognisable pattern most of the time</li><li>Pulls data from more than one place</li><li>Produces a document or report</li></ul><p>…you can build a skill for it.</p><p>Here’s the minimum viable starting point:</p><pre>1. Write output-template.md  (what does the output look like?)<br>2. Write SKILL.md             (5 sections: frontmatter, rules, workflow, error recovery, checklist)<br>3. Create LEARNINGS.md        (empty to start — one header, zero entries)<br>4. Run it on a real case<br>5. Add what surprised you to LEARNINGS.md<br>6. Run it again</pre><p>The hard part is not step 1 or 2. The hard part is step 4 — committing to run it on a <em>real</em> case, on <em>real</em> data, with all its messiness. That’s where the skill becomes production-quality. The instructions tell Claude what to do in ideal conditions. Real runs teach it what to do in all the other conditions.</p><p>A skill that has been run ten times on real data, with LEARNINGS.md faithfully updated, will outperform a skill that was written once with perfect instructions and never revised.</p><p><strong>The best skill is the one that keeps getting better.</strong></p><p><em>If you build a skill using these patterns — especially if you open-source the SKILL.md — I’d love to see what you make.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40731bbd045d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert Any Document Into a Podcast— Fully Local, Zero Cost]]></title>
            <link>https://navaneethsen.medium.com/i-built-a-tool-that-turns-any-document-into-a-podcast-in-a-weekend-using-ai-agents-3ae4867b3e2a?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ae4867b3e2a</guid>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 20:48:07 GMT</pubDate>
            <atom:updated>2026-03-07T06:36:35.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtYFla5lVNmZWTWaa9uBHA.png" /></figure><h3>Sample generated audios</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F2278976399%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fn-sen-920478260%2Fpodcast-qwen-3&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/84d8b6e62251187d57ffbb99335f6b38/href">https://medium.com/media/84d8b6e62251187d57ffbb99335f6b38/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F2278976396%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fn-sen-920478260%2Fpodcast-kokoro-1&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e93d3a311f2317f9b5182a5a579bcfa/href">https://medium.com/media/0e93d3a311f2317f9b5182a5a579bcfa/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F2278976393%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Fn-sen-920478260%2Fpodcast-macos-2&amp;image=https%3A%2F%2Fsoundcloud.com%2Fimages%2Ffb_placeholder.png&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/471a1c16d85ea28cb40a4f1b1841638b/href">https://medium.com/media/471a1c16d85ea28cb40a4f1b1841638b/href</a></iframe><p>There’s a pile of documents sitting in every organisation. Specs, technical guides, onboarding manuals, strategy docs. Most of them will never be read. Not because the content isn’t valuable — but because nobody has the time, and staring at walls of text on a screen is exhausting.</p><p>What if those documents could just… talk to you?</p><p>That’s the idea behind <strong>Markdown Narrator</strong> — a tool I built over a single weekend that converts any Markdown document into a podcast-style audio file. You hand it a .md file, and it hands back a .wav you can listen to on your commute, in the gym, or anywhere a screen isn&#39;t practical.</p><h2>The Business Problem Is Real</h2><p>People rarely sit down with long documents anymore. But they <strong>do</strong> listen to podcasts while doing other things — walking, commuting, exercising, or even doing focused work.</p><p>Think about everyday situations:</p><ul><li>A new engineer joining the team has <strong>40 pages of architecture documentation</strong> to understand.</li><li>A product manager needs to review a <strong>60-page requirements document</strong> before an upcoming meeting.</li><li>An executive receives a <strong>quarterly strategy brief</strong> but has a calendar full of back-to-back calls.</li><li>A customer gets a <strong>20-page onboarding guide</strong> that often ends up unread.</li></ul><p>In reality, most of these documents get <strong>skimmed, postponed, or ignored</strong> simply because sitting down to read them takes dedicated time.</p><p>But listening is different.</p><p>People already spend hours consuming podcasts while <strong>walking, commuting, cooking, or doing routine work</strong>. Audio fits naturally into moments where reading isn’t practical.</p><p>This tool converts written documents into a <strong>clear, podcast-style narration</strong> so people can absorb information while they’re on the move. Instead of staring at a long document, they can simply press play and listen.</p><p>The narration isn’t robotic or monotonous. It flows like a well-produced podcast — with natural transitions between sections, clear emphasis for warnings and tips, and a calm, professional voice throughout.</p><p>Instead of asking people to <strong>find time to read</strong>, the content fits into the time they <strong>already spend listening</strong>.</p><h2>What It Actually Does</h2><p>You run one command:</p><pre>python main.py your-document.md --engine kokoro</pre><p>And get back a .wav file ready to drop into any player, Notion, Confluence page, or internal portal.</p><p>The tool handles the full document intelligently:</p><ul><li><strong>Headings</strong> become section transitions: <em>“Now let’s look at Installation…”</em></li><li><strong>Bullet lists</strong> are read naturally: <em>“Here are three key points. First… Second… Third…”</em></li><li><strong>Code blocks</strong> are announced and summarised: <em>“Here’s a Python code example…”</em></li><li><strong>Tables</strong> are described: <em>“There’s a table with columns: Service, Latency, Status…”</em></li><li><strong>Warnings and callouts</strong> get expressive intros: <em>“Critical alert. Do not run as root in production.”</em></li><li><strong>Acronyms</strong> like API, HTTP, or MAX_RETRIES are automatically spelled out — no more TTS engines mispronouncing them as words</li></ul><p>The narration sounds natural because each section is synthesised with a consistent emotional tone baked in, not just flat text-to-speech.</p><h2>The Weekend Build — Done With AI Agents</h2><p>Here’s the part I find genuinely exciting to share.</p><p>I didn’t write this code the traditional way — sitting down, designing the architecture, writing every function, debugging every edge case. Instead, I used <strong>agentic AI techniques</strong>, specifically Claude Code with multiple specialised agents working in parallel.</p><p>The process looked something like this:</p><ol><li>I described what I wanted — a tool that reads Markdown and produces podcast audio</li><li>The agents broke it into components: a parser, a narrator, a CLI</li><li>Multiple agents worked simultaneously — one researching the right TTS model, one designing the Markdown parser, one building the audio stitching logic</li><li>I reviewed, gave feedback, and directed — but I wasn’t in the weeds of every implementation detail</li></ol><p>What would have taken me two to three weeks of solo evenings took a weekend. Not because the work was cut short — the tool is genuinely complete, tested, and open source — but because the agents could move in parallel, research libraries I’d never used, catch their own bugs, and iterate faster than I could alone.</p><p>This is the real shift. AI agents aren’t just autocomplete for code. Used well, they’re a force multiplier that lets one person build what used to require a small team.</p><h2>The Technical Choices (Without Getting Too Deep)</h2><p>The tool runs completely locally — nothing goes to the cloud, no API keys, no usage fees. Everything happens on your machine.</p><p>It supports three different voice engines:</p><ul><li><strong>Qwen3-TTS</strong> — a state-of-the-art neural model from Alibaba that runs on Apple Silicon’s GPU. Excellent quality, sounds genuinely human. However, it is quite slow. On my Apple <strong>M4 Max</strong>, converting a <strong>27,605-character markdown document</strong> to a WAV file took <strong>about one hour</strong>.</li><li><strong>Kokoro</strong> — a lightweight 82-million-parameter model that runs in real-time on CPU. Fast and surprisingly good.</li><li><strong>macOS say</strong> — the built-in voice on every Mac. Instant, zero download, great for testing.</li></ul><p>The narration quality is consistent because the tool groups related content into sections before synthesising — rather than sending one sentence at a time and getting a different “mood” for each paragraph. The whole section gets narrated together, so the emotion flows.</p><h2>Who Should Use This</h2><ul><li><strong>Documentation teams</strong> turning technical guides into audio companions for developers</li><li><strong>Product teams</strong> creating audio versions of PRDs and specs for async review</li><li><strong>HR and L&amp;D teams</strong> converting training materials into something people will actually engage with</li><li><strong>Customer success teams</strong> offering audio onboarding as an alternative to dense PDFs</li><li><strong>Individual contributors</strong> who want to review their own writing by listening to it</li></ul><p>The input is just Markdown — which is already how most technical documentation is written (GitHub, Notion, Confluence, Obsidian all export it). The barrier to adoption is low.</p><h2>What’s Next</h2><p>The project is open source on GitHub. A few obvious extensions are on the roadmap:</p><ul><li>MP3 output for smaller file sizes</li><li>Voice cloning — narrate your docs in your own voice</li><li>A simple web UI for non-technical users</li><li>Integration with documentation platforms (Confluence plugin, Notion export)</li></ul><h2>Try It</h2><p>The code is available at: <a href="https://github.com/Navaneethsen/markdown-podcast-narrator"><strong>https://github.com/Navaneethsen/markdown-podcast-narrator</strong></a></p><p>If you work on a team that produces a lot of written content and has struggled to get people to actually read it — give this a try. It takes about five minutes to set up and the first output will probably surprise you.</p><p>The documents were always worth reading. Now they’re worth listening to too.</p><p><em>If this resonated, follow me for more on building with AI agents, local models, and tools that actually solve real problems.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ae4867b3e2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Cautionary Tale About LLM Reasoning]]></title>
            <link>https://navaneethsen.medium.com/a-cautionary-tale-about-llm-reasoning-a6435bd51245?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6435bd51245</guid>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[cognitive-load]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 16:17:34 GMT</pubDate>
            <atom:updated>2026-02-05T19:33:02.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*yNN6bc8foiCfxe7tFAq1wA.gif" /></figure><h3>Abstract</h3><p>This article examines a real-world concurrency discussion around UniformReservoir from Dropwizard Metrics. It highlights a subtle but important distinction between <strong>lock-free code</strong>, <strong>weak consistency</strong>, and <strong>actual thread safety</strong>. More importantly, it documents a human–AI disagreement where an LLM initially asserted correctness, was challenged, and then reversed its position—revealing a common failure mode in AI-assisted programming: <strong>confusing intent with guarantees</strong>.</p><h3>The Code in Question</h3><p>We analyze the UniformReservoir implementation used for reservoir sampling:</p><pre>public class UniformReservoir implements Reservoir {<br>    private final AtomicLong count = new AtomicLong();<br>    private final AtomicLongArray values;<br> <br>    public int size() {<br>        final long c = count.get();<br>        if (c &gt; values.length()) {<br>            return values.length();<br>        }<br>        return (int) c;<br>    }<br> <br>    public void update(long value) {<br>        final long c = count.incrementAndGet();<br>        if (c &lt;= values.length()) {<br>            values.set((int) c - 1, value);<br>        } else {<br>            final long r = ThreadLocalRandom.current().nextLong(c);<br>            if (r &lt; values.length()) {<br>                values.set((int) r, value);<br>            }<br>        }<br>    }<br>}</pre><p>At first glance, the presence of AtomicLong, AtomicLongArray, and ThreadLocalRandom strongly suggests thread safety.</p><p>I know that assumption is wrong. But I decided to ask the question to Claude Code Opus 4.5 model:</p><blockquote>Is this class <strong>thread-safe</strong> under the Java Memory Model? Especially the size() and update() methods?</blockquote><h3>The Initial (Incorrect) AI Claim</h3><p>The AI originally argued:</p><p>update() is thread-safe because:</p><ul><li>incrementAndGet() is atomic</li><li>Each thread gets a unique index</li><li>Writes use AtomicLongArray.set()</li></ul><p>size() is thread-safe because:</p><ul><li>It reads count once</li><li>It returns a consistent snapshot</li></ul><p>This reasoning <strong>sounds plausible</strong>, but it ignores <strong>cross-variable invariants</strong> — a classic concurrency trap.</p><h3>The Actual Bug: Increment-Before-Publish</h3><p>The flaw is not in atomicity, but in <strong>ordering</strong>.</p><h3>Critical Observation</h3><p>count is incremented <strong>before</strong> the value is written to values.</p><p>This creates a <strong>visibility gap</strong> where readers can observe:</p><blockquote><em>“There are N elements” while element N </em><strong><em>does not exist yet</em></strong></blockquote><h3>The Race Condition (Timeline)</h3><pre>Initial state:<br>count = 4<br>values[0..3] populated<br> <br>Thread A (update):<br>  c = count.incrementAndGet()  → count = 5<br>  ── context switch ──<br>  values.set(4, X)<br> <br>Thread B (size):<br>  c = count.get() → returns 5<br> <br>Thread C (getSnapshot):<br>  size() = 5<br>  reads values[4] → returns 0 (default)</pre><h3>Result</h3><ul><li>size() reports <strong>5</strong></li><li>Slot 4 contains <strong>garbage</strong></li><li>Snapshot contains <strong>phantom data</strong></li></ul><p>This violates <strong>linearizability</strong> and <strong>happens-before guarantees</strong>.</p><h3>Why update() Is Not Thread-Safe</h3><p>Thread safety is <strong>not</strong> about:</p><ul><li>Atomic operations ✔</li><li>No exceptions ✔</li><li>No JVM crashes ✔</li></ul><p>It <em>is</em> about:</p><blockquote>Whether <strong>all observable states</strong> are valid.</blockquote><p>Here, the system exposes an <strong>impossible state</strong>:</p><ul><li>“N values exist”</li><li>but value N has not been published</li></ul><p>That is <strong>by definition not thread-safe</strong>.</p><h3>Why size() Is Also Not Thread-Safe</h3><p>size() participates in the same broken invariant.</p><p>It assumes:</p><pre>count == number of initialized values</pre><p>This invariant is <strong>false under concurrency</strong>.</p><p>A method can be read-only and still be unsafe if it observes inconsistent shared state.</p><h3>Important Distinction: Intent vs Guarantee</h3><p>The Dropwizard authors likely made a <strong>deliberate engineering trade-off</strong>:</p><ul><li>Avoid locks</li><li>Maximize throughput</li><li>Accept weak consistency</li><li>Optimize for metrics, not correctness</li></ul><p>That’s fine.</p><p>But then the correct statement is:</p><blockquote>“This class is <strong>lock-free and weakly consistent</strong>, not thread-safe.”</blockquote><h3>These Are Not Synonyms.</h3><p>TermMeaningThread-safeAll observable states are validLock-freeNo blocking synchronizationEventually consistentReaders may see transient nonsenseGood enough for metricsDomain-specific tolerance</p><p>The AI <strong>collapsed these concepts into one</strong>.</p><h3>The Human vs AI Disagreement</h3><h3>What the AI Did Wrong</h3><ol><li><strong>Equated atomic operations with correctness</strong></li><li><strong>Ignored inter-variable invariants</strong></li><li><strong>Failed to reason about publication order</strong></li><li><strong>Assumed intent implies safety</strong></li><li><strong>Only corrected itself after a concrete counterexample</strong></li></ol><p>This is a pattern seen frequently in LLM-assisted programming.</p><h3>Why This Matters</h3><p>In production systems:</p><ul><li>Metrics influence autoscaling</li><li>Autoscaling influences availability</li><li>Availability influences revenue</li></ul><p>A single false assumption about “thread safety” can cascade.</p><p>Great engineers ask:</p><blockquote>“What impossible state could this code expose?”</blockquote><p>LLMs usually ask:</p><blockquote>“Are atomics used?”</blockquote><p>That gap matters.</p><h3>Correct Characterization</h3><blockquote><strong>Lock-free, high-performance, weakly consistent, statistically acceptable — but not thread-safe.</strong></blockquote><h3>Closing Thought</h3><p>This example is not about mocking an Claude Code Opus 4.5 or any other AI model.</p><p>It’s about understanding <strong>where human engineering judgment still dominates</strong>:</p><ul><li>reasoning about invariants</li><li>reasoning about time</li><li>reasoning about <em>what must never be observable</em></li></ul><p>Until LLMs learn to reason about <strong>impossible states</strong>, not just possible executions, they will continue to sound confident — and be wrong. The result is a growing cognitive burden, where humans must repeatedly correct the model, and in doing so may eventually steer it in the wrong direction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6435bd51245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Curious Case of safe_sleep.sh in GitHub Actions Runner]]></title>
            <link>https://navaneethsen.medium.com/the-curious-case-of-safe-sleep-sh-in-github-actions-a5dab2dca833?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5dab2dca833</guid>
            <category><![CDATA[sleep]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[zig]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 20:17:50 GMT</pubDate>
            <atom:updated>2025-12-12T11:31:23.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>TLDR: A 4-Line Bash Script Burned CPUs, Frustrated Developers, and Finally Got Fixed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OckCbjW43Vh-zIIWIqjeiQ.png" /></figure><h3>The Code That Started It All</h3><p><a href="https://github.com/actions/runner/blob/v2.328.0/src/Misc/layoutroot/safe_sleep.sh">Somewhere</a> in the GitHub Actions runner codebase, there exists a script called safe_sleep.sh. Its contents looked like this:</p><pre>#!/bin/bash<br><br>SECONDS=0<br>while [[ $SECONDS != $1 ]]; do<br>  :<br>done</pre><p>And some years back the <a href="https://github.com/actions/runner/commit/af6c8e6eddef233fdef862c1287d9b013c8aabff">original form</a> was as shown below:</p><pre>safe_sleep() {<br>    if [ ! -x &quot;$(command -v sleep)&quot; ]; then<br>        if [ ! -x &quot;$(command -v ping)&quot; ]; then<br>            COUNT=&quot;0&quot;<br>            while [[ $COUNT != 5000 ]]; do<br>                echo &quot;SLEEP&quot; &gt; /dev/null<br>                COUNT=$[$COUNT+1]<br>            done<br>        else<br>            ping -c 5 127.0.0.1 &gt; /dev/null<br>        fi<br>    else<br>        sleep 5<br>    fi<br>}</pre><h3>So what is this safe_sleep.sh?</h3><p>safe-sleep.sh is a tiny Bash utility used inside the GitHub Actions runner — software that executes your CI workflows on a worker machine. Its job sounds simple: <strong>pause execution for a few seconds</strong>, just like a normal sleep 5.</p><p>But here’s the twist:<br>Some runner environments <em>don’t have the </em><em>sleep command</em> available. Earlier versions worked around this by falling back to hacks like ping -c 5 to simulate sleeping. Then came a “refactor” intended to make things cleaner and more elegant.</p><p>The result? A script that:</p><ul><li>Looks beautifully minimal</li><li>Uses clever Bash features like $SECONDS</li><li>Has a poetic one-liner loop using : as a no-op</li><li><strong>But instead of sleeping, it busy-loops</strong></li><li>And under certain conditions, <strong>it can busy-loop forever</strong></li></ul><p>So you end up with something that <em>looks safe</em> — a “safe sleep” — but inside hides a subtle landmine.</p><h3>Why this code is landmine?</h3><h4>Scenario 1: The COUNT Loop (the initial code)</h4><pre>COUNT=&quot;0&quot;<br>while [[ $COUNT != 5000 ]]; do<br>    echo &quot;SLEEP&quot; &gt; /dev/null<br>    COUNT=$[$COUNT+1]<br>done</pre><p><strong>This is actually safe</strong> because:</p><ul><li>COUNT is manually incremented: COUNT=$[$COUNT+1]</li><li>It goes 0 → 1 → 2 → 3 → … → 4999 → 5000</li><li><strong>It WILL hit 5000 exactly</strong> and exit the loop</li><li>The scheduler can’t cause it to skip values</li></ul><p>The only risk is if the script crashes or is killed, but there’s no race condition.</p><h4>Scenario 2: The SECONDS Loop (This is Broken!)</h4><pre>SECONDS=0<br>while [[ $SECONDS != $1 ]]; do<br>    :<br>done</pre><p><strong>This CAN hang forever</strong> because:</p><ul><li>SECONDS is a <strong>special Bash variable</strong> that automatically increments every real-world second</li><li>The script doesn’t control when it increments — the <strong>operating system does</strong></li><li>If the process is suspended, SECONDS keeps incrementing in the background</li></ul><h4>How SECONDS Can Skip Values</h4><p>Here’s the critical difference:</p><pre># What your code sees:<br>Time 0.0s: Check SECONDS (value=0), target=1, keep looping<br>Time 1.0s: Check SECONDS (value=1), target=1, EXIT ✓<br><br># What happens under load:<br>Time 0.0s: Check SECONDS (value=0), target=1, keep looping<br>[CPU is busy, process doesn&#39;t get scheduled for 1.5 seconds]<br>Time 1.5s: Check SECONDS (value=2), target=1, NEVER EXITS ✗</pre><p>Between your checks of the SECONDS variable, <strong>real time passes</strong> and SECONDS updates automatically. If your process doesn&#39;t get CPU time during the exact moment when SECONDS equals your target, you miss it.</p><h4>Why This Happens</h4><p>On a busy/overloaded system:</p><ol><li>Your process checks SECONDS=0</li><li>The OS scheduler gives CPU to other processes</li><li>2+ real seconds pass (even though your code hasn’t executed)</li><li>Your process finally gets CPU again</li><li>You check SECONDS=2 (it&#39;s already past your target of 1)</li><li>Loop forever because 2 ≠ 1, and SECONDS only goes up</li></ol><h3>The Real-World Consequences</h3><p>This isn’t just an academic concern about code elegance. The Zig programming language project, which uses self-hosted GitHub Actions runners, discovered the script’s dark side firsthand.</p><p>They found four deadlocked safe_sleep.sh processes running simultaneously, collectively saturating four CPU cores. These processes had been spinning for days, burning electricity and degrading CI performance — all while doing absolutely nothing useful.</p><p>Andrew Kelley, the creator of Zig, summarized the situation perfectly:</p><blockquote>“It’s vibes all the way down.”</blockquote><h3>The Ignored Fix</h3><p>Here’s where the story turns from amusing to frustrating.</p><p>A fix was submitted to the GitHub Actions runner repository over a year ago. The community identified the bug, proposed a solution, and waited.</p><p>And waited.</p><p>Eventually, a bot automatically closed the issue due to inactivity.</p><p>The <a href="https://github.com/actions/runner/issues/3792">original bug report</a> (Issue #3792) remains a graveyard of frustrated developers documenting:<br> — Race conditions in the script<br> — Potential PID wraparound issues<br> — Processes hanging indefinitely<br> — Entire CPU cores locked up for weeks</p><h3>The Fallout</h3><p>The Zig project is now considering migrating away from GitHub Actions entirely. They’re not alone — this incident has many teams questioning whether GitHub’s CI infrastructure is as reliable as they assumed.</p><p>When a 4-line bash script can silently consume your CPU for weeks, it raises uncomfortable questions about what else might be lurking in the dependencies we trust implicitly.</p><h3>The Timeline of Neglect</h3><ul><li><strong>2022–2024:</strong> Multiple issues filed (<a href="https://github.com/actions/runner/issues/1673">#1673</a>, <a href="https://github.com/actions/runner/issues/2380">#2380</a>) reporting 100% CPU usage</li><li><strong>February 2024:</strong> A fix PR was submitted (<a href="https://github.com/actions/runner/pull/3157">#3157</a>) with the correct solution (using -lt instead of !=)</li><li><strong>March 2025:</strong> GitHub’s bot automatically <strong>closed the fix PR</strong> without review</li><li><strong>April 2025:</strong> <a href="https://github.com/actions/runner/issues/3792">Issue #3792</a> opened documenting the infinite hang</li><li><strong>August 2025:</strong> <a href="https://github.com/actions/runner/pull/3157">PR #3157</a> finally merged, but <strong>GitHub didn’t comment in the original thread</strong></li><li><strong>December 2025:</strong> <a href="https://github.com/actions/runner/pull/4146">PR #4146</a> merged — sleep tried first, Copilot reviews and flags remaining issues</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKqACgT0Cd4z7GtGN-n2dA.png" /></figure><h3>The fix</h3><pre>#!/bin/bash<br><br>  # try to use sleep if available<br>  if [ -x &quot;$(command -v sleep)&quot; ]; then<br>      sleep &quot;$1&quot;<br>      exit 0<br>  fi<br><br>  # try to use ping if available<br>  if [ -x &quot;$(command -v ping)&quot; ]; then<br>      ping -c $(( $1 + 1 )) 127.0.0.1 &gt; /dev/null<br>      exit 0<br>  fi<br><br>  # try to use read -t from stdin/stdout/stderr if we are in bash<br>  if [ -n &quot;$BASH_VERSION&quot; ]; then<br>      # ... read -t fallback logic<br>  fi<br><br>  # fallback to a busy wait (last resort)<br>  SECONDS=0<br>  while [[ $SECONDS -lt $1 ]]; do<br>      :<br>  done</pre><p>As of December 11, 2025, safe_sleep.sh finally does the sensible thing: it tries sleep first. The busy-wait loop is now a last resort, not the default.</p><p>It is also interesting to read the comments in the <a href="https://github.com/actions/runner/pull/4146">final PR #4146</a> which shows that it was reviewed by GitHub Copilot, Microsoft’s own AI coding assistant.</p><p>Copilot immediately flagged what humans had overlooked for years:</p><blockquote>“The busy-wait fallback continuously checks the SECONDS variable in a tight loop, which will consume 100% CPU for the duration of the sleep.”</blockquote><h3>The Takeaway</h3><blockquote>Three years, nine months, and one AI review later — safe_sleep.sh finally sleeps and then wakes up.</blockquote><p>Sometimes the most dangerous code isn’t a complex cryptographic vulnerability or a subtle race condition. Sometimes it’s a well-intentioned “safe” wrapper around a command that’s worked perfectly for 50 years.</p><p>The next time you’re tempted to write a custom implementation of something that already exists, ask yourself: “Is this actually solving a problem, or am I about to create the next safe_sleep.sh?”</p><h3>References</h3><p><a href="https://lobste.rs/s/l4rowa/github_actions_safe_sleep_sh#c_ppqpea">https://lobste.rs/s/l4rowa/github_actions_safe_sleep_sh#c_ppqpea</a><br><a href="https://github.com/actions/runner/issues/3792">https://github.com/actions/runner/issues/3792</a><br><a href="https://github.com/actions/runner/pull/3157/files">https://github.com/actions/runner/pull/3157/files</a><br><a href="https://github.com/actions/runner/pull/4146">https://github.com/actions/runner/pull/4146</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5dab2dca833" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AWS DynamoDB Outage of October 2025: A Story of Cascading Failures]]></title>
            <link>https://navaneethsen.medium.com/the-aws-dynamodb-outage-of-october-2025-a-story-of-cascading-failures-42f4b23b6379?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/42f4b23b6379</guid>
            <category><![CDATA[aws-outage]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[dns-servers]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 16:49:35 GMT</pubDate>
            <atom:updated>2025-10-28T20:53:55.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hNog7WCvwFWlBPhH" /></figure><p><em>I tried to understand and summarize with the help of an LLM on what actually brought down major AWS services when this incident occurred.</em></p><p>For the original post please look at <a href="https://aws.amazon.com/message/101925/?utm_source=substack&amp;utm_medium=email">https://aws.amazon.com/message/101925/</a></p><p>On October 19–20, 2025, Amazon Web Services experienced one of its most significant outages in the Northern Virginia (US-EAST-1) region. What started as a subtle race condition in DynamoDB’s DNS management system cascaded into a <strong>15-hour disruption</strong> affecting dozens of AWS services. Let’s break down what happened in simple terms. According to <strong>CyberCube</strong>, a cyber risk analytics company, the estimated <strong>insurance losses</strong> from this outage could reach <strong>up to $581 million</strong>.</p><p>This wasn’t just a technical issue — it had massive real-world consequences. Here’s a breakdown of the major services and companies that experienced disruptions:</p><h3>💰 Financial Services</h3><ul><li><strong>Coinbase</strong> — Cryptocurrency exchange</li><li><strong>Venmo</strong> — Payment platform</li><li><strong>Lloyds Banking Group</strong> (UK) — Customers unable to access banking services</li></ul><h3>✈️ Airlines &amp; Travel</h3><ul><li><strong>Delta Air Lines</strong> — Flight disruptions</li><li><strong>United Airlines</strong> — Service interruptions</li><li><strong>Lyft</strong> — Ride-sharing issues</li></ul><h3>📺 Streaming &amp; Entertainment</h3><ul><li><strong>Disney+</strong> — Streaming disruptions</li><li><strong>Hulu</strong> — Service outages</li><li><strong>HBO Max</strong> — Connectivity issues</li><li><strong>Roku</strong> — Streaming device problems</li><li><strong>Apple Music</strong> — Audio streaming affected</li></ul><h3>💬 Social Media &amp; Communication</h3><ul><li><strong>Snapchat</strong> — Message and media failures</li><li><strong>Reddit</strong> — Site access problems</li><li><strong>Slack</strong> — Workplace communication disrupted</li><li><strong>Zoom</strong> — Video conferencing issues</li></ul><h3>🎮 Gaming</h3><ul><li><strong>Fortnite</strong> — Game servers affected</li><li><strong>Xbox</strong> — Xbox Live services impacted</li></ul><h3>🍔 Food &amp; Retail</h3><ul><li><strong>McDonald’s</strong> — Mobile ordering and app issues</li><li><strong>Starbucks</strong> — Mobile payment and ordering disrupted</li></ul><h3>🎨 Productivity &amp; Design</h3><ul><li><strong>Canva</strong> — Design platform unavailable</li><li><strong>Duolingo</strong> — Language learning app affected</li></ul><h3>🏠 Smart Home &amp; IoT</h3><ul><li><strong>Amazon Alexa</strong> — Voice assistant failures</li><li><strong>Ring</strong> — Security camera and doorbell issues</li></ul><h3>📊 The Timeline at a Glance</h3><pre>Oct 19, 11:48 PM → DynamoDB DNS records disappear<br>Oct 20, 12:38 AM → Engineers identify the DNS issue<br>Oct 20, 2:25 AM  → DynamoDB recovered<br>Oct 20, 2:20 PM  → All services fully recovered</pre><p><strong>Duration</strong>: ~15 hours of disruption<br><strong>Root Cause</strong>: A race condition in DNS automation</p><h3>🎯 What is DynamoDB and Why Does It Matter?</h3><p>Think of <strong>DynamoDB</strong> as a massive, fast filing cabinet that AWS services use to store and retrieve data instantly. It’s not just for customers — AWS itself relies heavily on DynamoDB. Services like Lambda, EC2, and many others use it behind the scenes.</p><p>When DynamoDB went down, it was like the electricity going out in a hospital. Everything that depended on it stopped working.</p><h3>🏗️ Understanding the DNS Management System</h3><p>Before we dive into what went wrong, let’s understand how AWS manages traffic to DynamoDB.</p><h3>The System Design</h3><p>AWS uses <strong>DNS (Domain Name System)</strong> to route millions of requests to DynamoDB servers. Think of DNS like a phone book that translates “dynamodb.us-east-1.amazonaws.com” into actual server addresses.</p><p>For a service as massive as DynamoDB, AWS maintains:</p><ul><li><strong>Hundreds of thousands</strong> of DNS records</li><li>Multiple endpoints (regular, IPv6, FIPS-compliant, etc.)</li><li>Load balancers across multiple data centers</li></ul><p>To manage this complexity, AWS built an automated system with two key components:</p><pre>┌────────────────────────────────────────────────┐<br>│                                                │<br>│  DNS MANAGEMENT SYSTEM                         │<br>│                                                │<br>│  ┌──────────────┐        ┌──────────────┐      │<br>│  │ DNS Planner  │───────▶│ DNS Enactor  │      │<br>│  │              │        │              │      │<br>│  │ Monitors     │        │ Applies      │      │<br>│  │ health &amp;     │        │ plans to     │      │<br>│  │ creates      │        │ Route53      │      │<br>│  │ DNS plans    │        │              │      │<br>│  └──────────────┘        └──────────────┘      │<br>│                                 │              │<br>│                                 ▼              │<br>│                          ┌──────────────┐      │<br>│                          │   Route53    │      │<br>│                          │ (DNS Service)│      │<br>│                          └──────────────┘      │<br>└────────────────────────────────────────────────┘</pre><p><strong>DNS Planner</strong>: The strategist that monitors server health and creates DNS plans<br><strong>DNS Enactor</strong>: The executor that applies these plans to Route53 (3 independent copies running in different data centers)</p><h3>💥 The Race Condition: What Went Wrong</h3><p>Here’s where things get interesting — and catastrophic.</p><h3>🧩 My simple step-by-step view of the issue</h3><h4>Act 1: The Setup</h4><pre>Timeline: Just before 11:48 PM<br><br>DNS Planner: Creating Plan #1, #2, #3, #4...<br>Enactor A: Working on Plan #50 (older plan, running slowly)<br>Enactor B: Working on Plan #100 (newest plan, running fast)</pre><p><strong>Enactor A</strong> was having a bad day. It kept getting blocked trying to update DNS records and was moving <em>painfully slowly</em> through the list of endpoints.</p><p><strong>Enactor B</strong> was performing perfectly, zipping through updates with the newest plan.</p><h4>Act 2: The Fatal Sequence</h4><pre>11:48 PM - The Race Begins<br><br>Time: T+0 seconds<br>─────────────────────────────────────<br>Enactor A (Plan #50): &quot;Is my plan newer than what&#39;s active? <br>                       [Checks...] Yes! Proceeding...&quot;<br>                       [But this check is now STALE due to delays]<br><br>Time: T+30 seconds<br>─────────────────────────────────────<br>Enactor B (Plan #100): &quot;Updating all endpoints... Done! ✓&quot;<br>                       &quot;Now cleaning up old plans...&quot;<br><br>Time: T+45 seconds<br>─────────────────────────────────────<br>Enactor A (Plan #50): &quot;Finally! Applying my plan to the regional endpoint...&quot;<br>                       [OVERWRITES Plan #100 with old Plan #50]<br><br>Time: T+46 seconds<br>─────────────────────────────────────<br>Enactor B&#39;s Cleanup: &quot;Deleting plans #1-#75 <br>                      (they&#39;re way too old)...&quot;<br>                      [DELETES Plan #50 - the now-active plan!]<br><br>Result: <br>────────────────────────────────────<br>The DynamoDB endpoint now points to a DELETED plan with NO IP ADDRESSES!<br><br>DNS record = EMPTY 🚨</pre><h4>Act 3: The Aftermath</h4><pre>dynamodb.us-east-1.amazonaws.com → ??? (EMPTY)<br><br>Every service trying to connect:<br>&quot;Where is DynamoDB?&quot;<br>&quot;DNS says... nowhere?&quot;<br>&quot;Connection failed!&quot; ❌</pre><h3>🎭 The Visual Breakdown</h3><pre>BEFORE THE BUG:<br>═══════════════════════════════════════════════════<br>Route53 DNS Records:<br>dynamodb.us-east-1.amazonaws.com<br>  → 54.123.45.67<br>  → 54.123.45.68<br>  → 54.123.45.69<br>  → [hundreds more IPs...]<br><br>Status: ✓ Working perfectly<br><br><br>THE BUG OCCURS:<br>═══════════════════════════════════════════════════<br>1. Old plan gets re-applied (overwrites new plan)<br>2. Cleanup deletes the old plan<br>3. Active plan pointer → DELETED PLAN<br>4. Route53 DNS Records:<br>   dynamodb.us-east-1.amazonaws.com → [EMPTY - NO IPS!]<br><br>Status: ✗ Complete failure<br><br><br>RESULT:<br>═══════════════════════════════════════════════════<br>All connections fail:<br>Customer Apps ──X──▶ DynamoDB<br>AWS Services  ──X──▶ DynamoDB<br>Internal Tools ──X──▶ DynamoDB<br><br>The automation can&#39;t fix itself because there&#39;s no valid plan to reference!</pre><h3>🧠 Why This Happened: The Technical Explanation</h3><p>The bug involved <strong>three critical flaws</strong> happening simultaneously:</p><h3>1. Stale “Newness” Check</h3><p>Before applying a plan, Enactors check if their plan is newer than the current one. But when Enactor A was delayed, its check became outdated — like checking a train schedule from yesterday.</p><h3>2. No Retry Prevention</h3><p>The system didn’t prevent an old plan from being applied after a newer one was already active. It was like overwriting a document with an old backup.</p><h3>3. Aggressive Cleanup</h3><p>The cleanup process didn’t verify that a plan wasn’t currently active before deleting it. It deleted the “old” plan that had just been mistakenly re-applied.</p><h3>🌊 The Cascading Failures</h3><p>Once DynamoDB’s DNS disappeared, it triggered a domino effect:</p><pre>┌─────────────────────────────────────────────────────┐<br>│         THE CASCADE OF FAILURES                     │<br>├─────────────────────────────────────────────────────┤<br>│                                                     │<br>│  11:48 PM: DynamoDB DNS fails                       │<br>│      ↓                                              │<br>│  ┌──────────────────────────────────────┐           │<br>│  │ Immediate Impact (11:48 PM)          │           │<br>│  │ • All DynamoDB connections fail      │           │<br>│  │ • Customer applications break        │           │<br>│  │ • Internal AWS tools fail            │           │<br>│  └──────────────────────────────────────┘           │<br>│      ↓                                              │<br>│  ┌──────────────────────────────────────┐           │<br>│  │ EC2 Impact (11:48 PM - 1:50 PM)      │           │<br>│  │ • Server leases start expiring       │           │<br>│  │ • New instance launches fail         │           │<br>│  │ • &quot;Insufficient capacity&quot; errors     │           │<br>│  └──────────────────────────────────────┘           │<br>│      ↓                                              │<br>│  ┌──────────────────────────────────────┐           │<br>│  │ Network Manager Backlog (5:30 AM+)   │           │<br>│  │ • Delayed network configurations     │           │<br>│  │ • New instances without connectivity │           │<br>│  └──────────────────────────────────────┘           │<br>│      ↓                                              │<br>│  ┌──────────────────────────────────────┐           │<br>│  │ NLB Health Checks Fail (5:30 AM+)    │           │<br>│  │ • False negative health checks       │           │<br>│  │ • Capacity removed from service      │           │<br>│  │ • Connection errors spike            │           │<br>│  └──────────────────────────────────────┘           │<br>│      ↓                                              │<br>│  ┌──────────────────────────────────────┐           │<br>│  │ Other Services Fail                  │           │<br>│  │ • Lambda invocations fail            │           │<br>│  │ • ECS/EKS containers won&#39;t launch    │           │<br>│  │ • Amazon Connect calls drop          │           │<br>│  │ • Redshift queries fail              │           │<br>│  │ • 50+ more services impacted         │           │<br>│  └──────────────────────────────────────┘           │<br>│                                                     │<br>└─────────────────────────────────────────────────────┘</pre><h3>Why EC2 Failed</h3><p>EC2 servers need to “check in” with a management system called <strong>DWFM (DropletWorkflow Manager)</strong> every few minutes. Think of DWFM as the supervisor that keeps track of all the physical servers (called “droplets”) that host EC2 instances — it’s like a building manager keeping track of which apartments are occupied and available. This check-in requires DynamoDB. When DynamoDB failed:</p><ol><li><strong>Check-ins failed</strong> → Leases expired</li><li><strong>No active leases</strong> → Servers couldn’t host new instances</li><li><strong>Recovery attempted</strong> → System overloaded itself</li><li><strong>Congestive collapse</strong> → System couldn’t make progress</li></ol><p>It’s like a traffic jam where adding more cars makes the problem worse!</p><h3>Why Network Load Balancer Failed</h3><p>Imagine opening a new restaurant. The building is ready, staff is there, food is prepared — but the phone line hasn’t been installed yet. When customers call to make reservations, they can’t get through, so the owner thinks “this location must be broken” and closes it. By the time they check again, the phone line is working, so they reopen it. Then more locations have the same problem, creating chaos.</p><p>That’s exactly what happened with AWS’s Network Load Balancer:</p><p><strong>The Problem:</strong></p><ol><li><strong>New servers launched</strong> — AWS created new EC2 server instances to handle traffic</li><li><strong>Network setup delayed</strong> — Due to the earlier EC2 problems, there was a massive backlog. The servers were working fine, but their network addresses weren’t configured yet (like a restaurant without a phone line)</li><li><strong>Health checker got confused</strong> — The automated health checker tested these servers</li><li><strong>False failures</strong> — Because the network wasn’t set up yet, the health check failed — even though the servers themselves were perfectly fine</li><li><strong>Removed from service</strong> — The system automatically removed these “unhealthy” servers</li><li><strong>Network finally configured</strong> — A minute later, the network was ready</li><li><strong>Added back to service</strong> — Health check passed, servers added back</li><li><strong>Repeat cycle</strong> — This happened over and over with hundreds of servers</li></ol><p><strong>The Real Damage:</strong></p><p>This on-again, off-again cycle created two major problems:</p><pre>┌────────────────────────────────────────┐<br>│  THE FLIP-FLOP PROBLEM                 │<br>├────────────────────────────────────────┤<br>│                                        │<br>│  Server Status:                        │<br>│  [ONLINE] → [OFFLINE] → [ONLINE] →     │<br>│  [OFFLINE] → [ONLINE] → [OFFLINE]...   │<br>│                                        │<br>│  Impact:                               │<br>│  • Health checker overworked           │<br>│  • Capacity constantly changing        │<br>│  • Customer connections failed         │<br>│                                        │<br>└────────────────────────────────────────┘</pre><ol><li><strong>The health check system got overwhelmed</strong> — It had to process thousands of rapid status changes, which slowed it down even more</li><li><strong>Capacity kept disappearing</strong> — Every time servers were marked “unhealthy,” capacity was removed. If you didn’t have enough backup capacity, your application would fail</li></ol><p><strong>The Fix:</strong> Engineers disabled the automatic failover at 9:36 AM, forcing all available servers to stay online even if health checks were slightly delayed. This stopped the flip-flopping and let the system stabilize.</p><h3>📚 Key Takeaways &amp; Lessons</h3><h3>1. Automation Isn’t Always the Answer</h3><p>AWS built sophisticated automation to manage complexity, but that automation had a critical bug that went undetected for years. Sometimes simpler is better.</p><h3>2. Race Conditions Are Silent Killers</h3><p>This bug existed in the system for a long time but only triggered under specific timing conditions. It’s like a ticking time bomb waiting for the perfect storm.</p><h3>3. Cascading Failures Amplify Impact</h3><p>One DNS issue in DynamoDB triggered failures in 50+ other services. Modern cloud architectures are deeply interconnected — resilience must be built at every layer.</p><h3>4. Dependencies Matter</h3><p>Many AWS services relied on DynamoDB in US-EAST-1 without proper failover. Even internal AWS tools failed, slowing down recovery efforts.</p><h3>5. Testing Scale Is Hard</h3><p>AWS didn’t have adequate test coverage for the DWFM recovery workflow. You can’t truly test massive scale without… massive scale.</p><h3>6. Manual Intervention Was Necessary</h3><p>Despite all the automation, human operators had to manually fix the DNS records. Some problems still need human judgment.</p><h3>🔧 What AWS Is Doing to Fix It</h3><p>AWS announced several remediation steps:</p><h3>Actions Taken:</h3><p>✅ <strong>Disabled the buggy automation worldwide</strong><br>✅ <strong>Manually restored DNS records</strong><br>✅ <strong>Implemented temporary safeguards</strong></p><p>Here’s a concise summary of those long-term fixes:</p><h3>Long-Term Fixes in Progress</h3><p>AWS is addressing the root causes of the outage through four key improvement areas:</p><ol><li><strong>Race Condition Prevention</strong> –<br>Add locks, validate plan status before deletion, and strengthen version checks to stop simultaneous conflicting updates.</li><li><strong>Safety Guardrails</strong> –<br>Block outdated or corrupted plans using checksums, and enable automatic rollbacks for safe recovery.</li><li><strong>NLB and EC2 Resilience</strong> –<br>Improve load balancer stability and EC2 recovery by adding velocity controls, throttling, and queue-based rate limiting, along with extensive scale testing.</li><li><strong>Monitoring &amp; Alerts</strong> –<br>Enhance observability to quickly detect stale or failed automation and unexpected DNS changes.</li></ol><h3>💭 Final Thoughts</h3><p>This outage is a stark reminder that even the most sophisticated systems can fail in unexpected ways. AWS runs some of the most complex infrastructure in the world, but complexity itself can be a vulnerability.</p><p>The silver lining? AWS’s transparency in sharing this detailed post-mortem helps the entire industry learn from this incident. By understanding what went wrong, we can all build more resilient systems.</p><h3>Glossary for Non-Technical Readers</h3><ul><li><strong>DNS (Domain Name System)</strong>: Like a phone book that converts website names to server addresses</li><li><strong>Race Condition</strong>: When two processes compete and their timing causes unexpected results</li><li><strong>Load Balancer</strong>: Distributes incoming traffic across multiple servers</li><li><strong>Endpoint</strong>: A URL or address where a service can be accessed</li><li><strong>API</strong>: How different software programs talk to each other</li><li><strong>Availability Zone (AZ)</strong>: A separate data center location for redundancy</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42f4b23b6379" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AGI is still a decade away — Andrej Karpathy Interview]]></title>
            <link>https://navaneethsen.medium.com/the-andrej-karpathy-interview-with-dwarkesh-patel-c10659db456c?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c10659db456c</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agi]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[andrej-karpathy]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 16:18:30 GMT</pubDate>
            <atom:updated>2025-10-22T20:17:21.669Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEWjgHulXp01zU1W5iPBWA.png" /></figure><p><em>I recently watched the Karpathy interview with Dwarkesh, which ran for about two hours, though it took me longer since I watched most of it at 0.85x speed. Afterward, I took personal notes and used the podcast transcript along with an LLM to summarize and organize the key discussion points and takeaways based on my notes and prompts.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FlXUZvyajciY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DlXUZvyajciY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FlXUZvyajciY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1082323281acabce88ac3b79d76163c3/href">https://medium.com/media/1082323281acabce88ac3b79d76163c3/href</a></iframe><h2>Introduction</h2><p>Andrej Karpathy, former Director of AI at Tesla and founding member of OpenAI, recently sat down with Dwarkesh Patel for an extensive conversation about the current state and future of AI. Unlike the typical hype-filled discourse, Karpathy offers a grounded, technical perspective drawn from 15 years in the field.</p><p>This conversation was notable for its intellectual depth, with Dwarkesh contributing several important observations and pushing back thoughtfully on key points. This article distills the key insights from that dialogue into actionable understanding.</p><h2>TLDR: Key Takeaways: What This Means for You &amp; Me</h2><h2>For AI Practitioners and Engineers</h2><ol><li><strong>Calibrate your timelines:</strong> Demos are easy, products are hard. The “march of nines” shows that moving from 90% to 99.999% reliability demands exponentially more effort.</li><li><strong>Focus on the cognitive core:</strong> Future AI systems will separate knowledge (lookup) from intelligence (reasoning).</li><li><strong>Build for gradual automation:</strong> Design systems with an autonomy slider, not binary human/AI switches.</li><li><strong>Invest in education:</strong> The best way to prepare for AI changes is continuous learning.</li></ol><h3>For Business Leaders and Decision-Makers</h3><ol><li><strong>Plan for decades, not years:</strong> AI transformation will be gradual, like the internet revolution.</li><li><strong>Start with the 80%:</strong> Find tasks where AI can handle routine work while humans manage exceptions.</li><li><strong>Don’t eliminate roles wholesale:</strong> Redesign jobs around AI assistance rather than replacement.</li><li><strong>Build hybrid systems:</strong> Combine AI automation with human oversight and judgment.</li></ol><h3>For Students and Learners</h3><ol><li><strong>Learn depth-first, on-demand:</strong> Build projects that interest you, learning what you need when you need it.</li><li><strong>Explain to learn:</strong> Teaching others reveals gaps in your understanding.</li><li><strong>Embrace AI tools wisely:</strong> Use autocomplete and assistance, but stay in control of architecture.</li><li><strong>Focus on fundamentals:</strong> Physics-style thinking (approximation, abstraction) transfers across domains.</li></ol><h3>For Everyone</h3><ol><li><strong>The future is gradual:</strong> Don’t panic about overnight AI takeover. We have time to adapt.</li><li><strong>Stay intellectually engaged:</strong> Like going to the gym, cognitive development remains valuable even if not economically necessary.</li><li><strong>Be wary of demos:</strong> Impressive demonstrations don’t equal production-ready solutions.</li><li><strong>Understand the limitations:</strong> Today’s AI is an impressive intern, not a senior expert. Know when to rely on it and when not to.</li></ol><p><em>I have tried to summarize most of the parts from the podcast and included some of my own understanding of the talk below. I may have skipped a few parts that I couldn’t fully focus on or found less relevant to my interests.</em></p><h2>1. Why It’s the “Decade of Agents,” Not the “Year of Agents”</h2><h2>The Core Insight</h2><p>Karpathy pushes back against the AI industry’s tendency to overpredict timelines. When others proclaimed 2024 “the year of agents,” he countered with “the decade of agents.”</p><p><strong>What’s missing from today’s AI agents:</strong></p><ul><li>Sufficient intelligence for complex tasks</li><li>True multimodality (seamlessly working across different types of data)</li><li>Continual learning (remembering what you tell them)</li><li>Computer use capabilities that actually work reliably</li><li>Cognitive capabilities that match human performance</li></ul><h3>The Demo-to-Product Gap</h3><p>Drawing from his self-driving experience, Karpathy explains the crucial concept of the <strong>“march of nines”</strong>:</p><blockquote>“Every single nine is a constant amount of work. When you get a demo that works 90% of the time, that’s just the first nine. Then you need the second nine, a third nine, a fourth nine, a fifth nine.</blockquote><p><strong>Real-world example:</strong> Self-driving cars have had impressive demos since the 1980s. Waymo gave perfect demo rides in 2014. Yet widespread deployment is still not economical or fully reliable in 2025.</p><p><strong>Key Takeaway:</strong> Demos are encouraging but deceiving. The journey from 90% working to 99.999% working is not a linear path — each additional nine requires as much work as the previous one.</p><h2>2. Why Reinforcement Learning Is “Terrible” (But Everything Else Is Worse)</h2><h2>The Problem with RL</h2><p>Karpathy offers one of the clearest critiques of reinforcement learning I’ve heard:</p><p><strong>How current RL works:</strong></p><ol><li>Given a problem, try hundreds of different approaches in parallel</li><li>Check which ones got the right answer</li><li>Upweight <em>everything</em> in the successful trajectories</li><li>Downweight <em>everything</em> in the failed trajectories</li></ol><p><strong>Why this is problematic:</strong></p><ul><li>Assumes every step in a successful solution was correct (they often weren’t)</li><li>Ignores that you might have taken wrong paths before stumbling on the right answer</li><li>“Sucking supervision through a straw” — getting one bit of information (success/failure) after minutes of work</li><li>Extremely noisy signal</li></ul><p><strong>The metaphor:</strong> Imagine a student solving 100 math problems, getting one right by luck after many wrong steps. RL would say “do more of everything you did in that solution,” including the mistakes.</p><h3>Why We Use It Anyway</h3><p>Despite these flaws, RL is still better than pure imitation learning because:</p><ul><li>It can discover solutions humans never thought of</li><li>It can optimize for specific reward functions</li><li>It doesn’t require expert demonstrations for every possible scenario</li></ul><h3>What’s Coming Next</h3><p>Karpathy hints at the next wave: <strong>reflection and review mechanisms</strong>. Instead of just upweighting/downweighting entire trajectories, AI systems need to:</p><ul><li>Review their solutions</li><li>Understand which parts were good and which weren’t</li><li>Think through their reasoning</li><li>Generate synthetic examples to learn from</li></ul><p><strong>Key Takeaway:</strong> Current RL is a brute-force approach. The next breakthrough will involve AI systems that can critically analyze their own work, similar to how humans review and learn from their mistakes.</p><h2>3. The Evolution vs. Pre-training Debate</h2><h2>Understanding the Analogy</h2><p>One of the most fascinating discussions centers on how AI development compares to biological intelligence. <strong>Dwarkesh contributed significantly here by steelmanning Richard Sutton’s perspective</strong>, forcing Karpathy to clarify fundamental differences:</p><p><strong>Dwarkesh’s challenge:</strong> Animals (especially those without language) learn everything from scratch through pure environmental interaction. They get “thrown out into the world” and figure it out without labels or pre-loaded knowledge. Why shouldn’t AGI work the same way — learning from raw sensory data rather than pre-training on human-generated text?</p><p>This pushed Karpathy to articulate why we’re building something fundamentally different from biological intelligence:</p><p><strong>Evolution’s approach:</strong></p><ul><li>Encodes learning algorithms in DNA (3 gigabytes)</li><li>Builds hardware (brain structure) that can learn</li><li>Provides instincts and priors</li><li>Allows lifetime learning on top</li></ul><p><strong>AI’s approach (pre-training):</strong></p><ul><li>Trains on 15 trillion tokens of internet data</li><li>Stores knowledge directly in model weights</li><li>Creates a “hazy recollection” of everything it’s seen</li><li>Builds both knowledge AND cognitive algorithms</li></ul><h3>The “Crappy Evolution” Concept</h3><p>Karpathy calls pre-training “crappy evolution” — it’s our practical way to get to a starting point similar to what evolution provides animals. Let’s break this down:</p><p><strong>How evolution works for animals:</strong></p><p>Evolution doesn’t directly teach animals everything they know. Instead, it does two things:</p><ol><li><strong>Encodes learning algorithms in DNA</strong> — The ability to learn, recognize patterns, and adapt</li><li><strong>Provides built-in capabilities</strong> — Instincts and reflexes (like a zebra running minutes after birth)</li></ol><p>The DNA doesn’t contain all the knowledge an animal will ever need. It contains the <em>algorithms</em> that allow the animal to learn during its lifetime. This is incredibly efficient — only 3 gigabytes of DNA information creates an entire brain that can then learn.</p><p><strong>How pre-training works for AI:</strong></p><p>Pre-training tries to achieve something similar, but through a completely different process:</p><ol><li><strong>Loads knowledge</strong> — Directly memorizes factual information from 15 trillion tokens of internet data</li><li><strong>Builds intelligence</strong> — By observing patterns in data, spontaneously develops algorithms for reasoning, pattern recognition, and problem-solving (like in-context learning)</li></ol><p><strong>Why “crappy”?</strong></p><p>The comparison:</p><ul><li><strong>Evolution</strong>: Stores only algorithms/instincts in DNA → Animal learns during lifetime</li><li><strong>Pre-training</strong>: Mixes both knowledge AND algorithms in the same neural network weights → Creates a “hazy recollection” of everything</li></ul><p><strong>The key distinction that matters:</strong></p><ul><li><strong>Knowledge</strong> (facts, information) can and should be looked up externally — we don’t need models to memorize Wikipedia</li><li><strong>Intelligence</strong> (reasoning, problem-solving algorithms) is what we really want embedded in the model</li></ul><p><strong>Concrete example:</strong></p><p>Think of it this way:</p><ul><li>Evolution gave you the <em>ability</em> to learn language, not the English language itself</li><li>Pre-training gives LLMs both the <em>ability</em> to process language AND memorized knowledge of millions of facts</li><li>Future AI might separate these: small “cognitive core” with pure intelligence + external database for facts (more like how evolution does it)</li></ul><p>This is “crappy” because it’s less elegant than evolution’s approach, but it’s what we can actually build with current technology.</p><h3>The “Cognitive Core” Vision</h3><p>Karpathy predicts future AI systems will separate:</p><ul><li>A small “cognitive core” (possibly 1 billion parameters) containing pure intelligence</li><li>External knowledge bases for facts and information</li><li>Better distillation techniques to remove unnecessary memorization</li></ul><p><strong>Why this matters:</strong> Current models are “distracted” by all their memorized knowledge. Stripping this away might actually make them better at reasoning and generalization.</p><p><strong>Key Takeaway:</strong> We’re not building animals through evolution — we’re building “ghosts” or “spirits” that mimic human intelligence through a fundamentally different process. Understanding this distinction helps us build better AI systems.</p><h2>4. In-Context Learning: The Real Magic</h2><h2>What Makes LLMs Feel Intelligent</h2><p>When you interact with ChatGPT or Claude and it feels genuinely intelligent — when it catches its mistakes, adjusts its reasoning, and responds thoughtfully — that’s <strong>in-context learning</strong> at work.</p><p><strong>The key insight:</strong> This in-context learning emerged spontaneously from pre-training. The model meta-learned how to learn during training, and now it can adapt to new patterns within a conversation.</p><h3>Working Memory vs. Long-term Memory</h3><p>Karpathy provides a helpful analogy, with Dwarkesh contributing a crucial quantitative perspective that helps explain why in-context learning feels more intelligent:</p><p><strong>Weights (from pre-training) — Long-term Memory:</strong></p><p>Think of this as compressed, hazy memories:</p><ul><li>Llama3 has 70 billion parameters (the “weights”)</li><li>It was trained on 15 trillion tokens of text</li><li>This means: 70 billion parameters must store information from 15 trillion tokens</li><li><strong>Result: Only 0.07 bits per token</strong> stored in the weights</li></ul><p><strong>What does 0.07 bits per token mean?</strong></p><ul><li>A bit is the smallest unit of information (0 or 1)</li><li>0.07 bits is incredibly tiny — less than 1/10th of a single bit</li><li>This is extreme compression, like trying to remember a 1,000-page book using only 7 pages of notes</li><li>That’s why it’s a “hazy recollection” — most details are lost in compression</li></ul><p><strong>Context window (KV cache) — Working Memory:</strong></p><p>Think of this as perfect, immediate memory:</p><ul><li>Every token you input gets stored with full detail in the “KV cache”</li><li>Each token takes up about <strong>320 kilobytes</strong> of memory</li><li>This is direct, immediate access — nothing is compressed</li></ul><p><strong>How big is the difference?</strong></p><ul><li>320 kilobytes = 2,560,000 bits (multiply by 8 to convert kilobytes to bits)</li><li>Context window: 2,560,000 bits per token</li><li>Weights: 0.07 bits per token</li><li><strong>Ratio: 35 million times more information per token in context!</strong></li></ul><p><strong>Concrete analogy:</strong></p><p>Imagine remembering a conversation:</p><ul><li><strong>Long-term memory (weights)</strong>: Like trying to remember what happened last year — you recall the general idea but forget most details</li><li><strong>Working memory (context)</strong>: Like remembering what someone said 5 seconds ago — you remember every word perfectly</li></ul><p><strong>This explains why:</strong></p><ul><li>Models can vaguely remember books they trained on (compressed into tiny 0.07 bits)</li><li>But give much better answers when you paste the relevant chapter (full 320KB per token available)</li><li>They struggle with information across sessions (context window is cleared)</li><li>In-context examples are so effective (full, uncompressed information available)</li></ul><h3>The Missing Piece: Sleep and Consolidation</h3><p>Karpathy notes a crucial missing component: humans don’t just maintain context — we have a sleep process that <strong>distills important experiences into long-term memory</strong>.</p><p><strong>What AI needs:</strong></p><ul><li>A distillation phase (like sleep) to process experiences</li><li>Ability to update weights based on important interactions</li><li>Person-specific fine-tuning (maybe LoRA adapters)</li><li>Long-term memory that persists across sessions</li></ul><p><strong>What is LoRA?</strong></p><p>LoRA stands for <strong>Low-Rank Adaptation</strong> — a technique for efficiently personalizing AI models:</p><p><strong>The problem:</strong></p><ul><li>Full AI models have billions of parameters (weights)</li><li>Retraining or fine-tuning all parameters for each user is extremely expensive</li><li>Would require massive compute and storage</li></ul><p><strong>LoRA’s solution:</strong></p><ul><li>Instead of changing all billions of parameters, only add small “adapter” layers</li><li>These adapters are tiny (maybe 0.1% the size of the full model)</li><li>Think of it like adding a personalized “lens” on top of the base model</li></ul><p><strong>Concrete example:</strong></p><ul><li>Base model: 70 billion parameters (same for everyone)</li><li>Your personal LoRA: 7 million parameters (0.01% of base model)</li><li>Your LoRA “adapts” how the base model responds to you specifically</li></ul><p><strong>Why this matters for AI memory:</strong></p><ul><li>Each user could have their own LoRA adapter</li><li>It remembers your preferences, style, and past interactions</li><li>Uses minimal storage (can store thousands of user LoRAs easily)</li><li>Can be loaded on-demand when you interact with the model</li></ul><p><strong>The vision:</strong> Instead of every conversation starting from scratch, your personal LoRA adapter would encode what the AI has learned about you over time — like the AI having a personal file on your preferences, communication style, and past conversations.</p><p><strong>Key Takeaway:</strong> The magic of AI conversations happens in the context window, not the weights. Future systems need mechanisms to bridge short-term and long-term learning, similar to how human memory consolidates during sleep.</p><h2>5. Why Self-Driving Took a Decade (And Still Isn’t Done)</h2><h2>The Timeline Reality Check</h2><p><strong>Self-driving history:</strong></p><ul><li>1986: First demos from CMU</li><li>2014: Perfect Waymo demo rides</li><li>2017–2022: Karpathy leads Tesla Autopilot</li><li>2025: Still not economical or widespread</li></ul><h3>Why Safety-Critical Systems Are Different</h3><p>The cost of failure in self-driving is extraordinarily high. This creates the “march of nines” problem:</p><ul><li>90% working = impressive demo</li><li>99% working = still dangerous</li><li>99.9% working = maybe usable with supervision</li><li>99.99% working = approaching human performance (1 error per 400,000 miles)</li><li>99.999% working = truly autonomous</li></ul><p><strong>Each nine requires similar amounts of work.</strong></p><h3>The Hidden Human Element</h3><p>Karpathy reveals something important: even current Waymo deployments have more human involvement than you might think:</p><ul><li>Elaborate teleoperation centers</li><li>Humans in the loop when needed</li><li>Limited geographic areas</li><li>High operational costs</li></ul><p><strong>The lesson for AI deployment:</strong> We haven’t removed humans; we’ve moved them where you can’t see them.</p><h3>Software Engineering Has Similar Requirements</h3><p>Karpathy argues that serious software engineering has comparable safety needs:</p><ul><li>Security vulnerabilities affect millions</li><li>Bugs can leak Social Security numbers</li><li>Production code failures have enormous consequences</li><li>You can’t afford mistakes every 7 years (or even 7 minutes in real time)</li></ul><p><strong>Key Takeaway:</strong> Don’t be fooled by impressive demos. Safety-critical applications — whether self-driving or software engineering — require levels of reliability that are extraordinarily difficult to achieve. The AI coding agents that work for simple tasks may take a decade to handle mission-critical code.</p><h2>6. What AI Can’t Do (Yet)</h2><h2>The Coding Reality</h2><p>Despite the hype around AI coding assistants, Karpathy’s experience building nanochat reveals important limitations:</p><p><strong>Where AI coding agents fail:</strong></p><ul><li>Novel code that hasn’t been written before</li><li>Complex, intellectually intensive code</li><li>Code that requires precise architecture</li><li>Projects with custom patterns and assumptions</li><li>Anything that deviates from common internet patterns</li></ul><p><strong>Where AI coding helps:</strong></p><ul><li>Boilerplate code</li><li>Common patterns from training data</li><li>Unfamiliar languages (if you know the logic)</li><li>Autocomplete for routine tasks</li></ul><p><strong>The nanochat example:</strong> Karpathy spent a month building this LLM training repository. AI assistants were marginally helpful but often:</p><ul><li>Misunderstood his custom architecture</li><li>Tried to insert deprecated APIs</li><li>Added unnecessary defensive code</li><li>Bloated the codebase with “production” patterns he didn’t need</li></ul><p><strong>His preferred workflow:</strong> Autocomplete, not vibe coding. Type the first few letters, let the model complete, stay in full control.</p><p><strong>Dwarkesh’s important observation about AI coding concentration:</strong></p><p>Dwarkesh highlighted a surprising anomaly that challenges the “general” nature of current AI:</p><p><strong>The puzzle:</strong> If we’re building AGI that should handle “all knowledge work,” why is it overwhelmingly focused on coding? Looking at API revenues (excluding chat), they’re dominated by coding applications.</p><p><strong>His insight:</strong> This is a surprising deployment pattern. You’d naively expect:</p><ul><li>A little task from consultants gets automated</li><li>A little task from accountants gets automated</li><li>Gradual progress across all knowledge work</li></ul><p><strong>What’s actually happening:</strong> Programmers are “getting more and more chiseled away at their work” while other professions see minimal impact.</p><p><strong>Karpathy’s explanation:</strong> Code is the perfect first application because:</p><ul><li>Everything is text-based (terminals, files, diffs)</li><li>Extensive pre-built infrastructure (IDEs, version control, diff viewers)</li><li>Lots of training data</li><li>LLMs are perfect text processors</li></ul><p><strong>Dwarkesh’s counter-examples from personal experience:</strong></p><p>Even in pure language-in/language-out tasks, LLMs struggle:</p><ul><li>Tried extensively to get LLMs useful for rewriting transcripts and creating clips</li><li>Friend Andy Matuschak tried “50 billion things” to get models to write spaced repetition prompts</li><li>Despite being “dead center in the repertoire of these LLMs,” they couldn’t do it satisfactorily</li></ul><p><strong>The deeper implication:</strong> Even where infrastructure isn’t the issue, AI struggles outside coding. This suggests deeper limitations than just “code has good tooling.”</p><h3>The Broader Intelligence Gaps</h3><p><strong>Missing “brain parts”:</strong></p><ul><li><strong>Hippocampus equivalent</strong> (memory formation and consolidation)</li><li><strong>Amygdala equivalent</strong> (emotions and instincts)</li><li><strong>Continual learning</strong> (remembering interactions across sessions)</li><li><strong>True multimodality</strong> (seamless integration of vision, text, audio)</li><li><strong>Culture and knowledge sharing</strong> (models writing for other models)</li><li><strong>Self-play mechanisms</strong> (models creating challenges for each other)</li></ul><p><strong>Why this matters:</strong> We’ve built impressive cortical tissue (pattern recognition) and some prefrontal cortex (reasoning). But many fundamental cognitive systems are still missing.</p><p><strong>Key Takeaway:</strong> AI is incredibly useful but remains an intern-level assistant, not a senior engineer. It excels at the 80% that looks like existing code but struggles with novel intellectual work. Expect this to improve gradually over a decade, not overnight.</p><h2>7. The Model Collapse Problem</h2><h2>Understanding Collapse</h2><p>One of the most subtle but important issues Karpathy discusses: <strong>AI models produce collapsed outputs</strong>.</p><p><strong>The problem:</strong></p><ul><li>Ask ChatGPT for a joke → You get the same 3 jokes</li><li>Ask for synthetic reflections on a book → Same patterns every time</li><li>Train on model-generated data → Model performance degrades</li></ul><p><strong>Why this happens:</strong></p><ul><li>Models don’t maintain the full entropy of human responses</li><li>They silently converge on “safe” patterns</li><li>They lack the noise and diversity of human thought</li><li>Each generation amplifies this collapse</li></ul><p><strong>What is entropy in this context?</strong></p><p>Entropy measures <strong>unpredictability and diversity</strong>:</p><p><strong>High entropy (like humans):</strong></p><ul><li>Ask 100 people “tell me a joke” → You get 100 different jokes</li><li>Responses are diverse, varied, surprising</li><li>Lots of randomness and creativity</li><li>Hard to predict what someone will say</li></ul><p><strong>Low entropy (like AI models):</strong></p><ul><li>Ask ChatGPT “tell me a joke” 100 times → You get the same 3 jokes</li><li>Responses are repetitive, predictable</li><li>Little variation or surprise</li><li>Easy to predict what it will say</li></ul><p><strong>What “models don’t maintain full entropy” means:</strong></p><p>Think of it like this:</p><ul><li><strong>Human responses</strong> = A bag with 1,000 different colored marbles (high diversity/entropy)</li><li><strong>AI model responses</strong> = A bag with mostly just 3 colors of marbles (low diversity/entropy)</li></ul><p>Even though the AI was trained on diverse human text (high entropy input), it outputs collapsed, repetitive patterns (low entropy output). The model has “lost” the richness and diversity of human responses.</p><p><strong>Concrete example:</strong></p><ul><li>Ask 10 humans for solutions to a problem → 10 genuinely different approaches</li><li>Ask AI 10 times for solutions → 10 variations of the same basic approach</li></ul><p>The AI’s outputs are “silently collapsed” — they look okay individually, but together reveal a lack of true diversity. This is why training on AI-generated data makes models worse over time — you’re training on low-entropy (repetitive) data, which makes the model even more collapsed.</p><h3>The Human Analogy</h3><p><strong>Humans also collapse:</strong></p><ul><li>Children say surprising things (not yet “overfit”)</li><li>Adults revisit the same thoughts repeatedly</li><li>Learning rates decrease with age</li><li>We become more predictable over time</li></ul><p><strong>How humans fight collapse:</strong></p><ul><li>Talking to different people (new entropy sources)</li><li>Novel experiences</li><li>Diverse inputs</li><li>Possibly dreaming (introduced as a fascinating theory)</li></ul><p><strong>Dwarkesh’s insights on childhood learning and memory:</strong></p><p>Dwarkesh made two fascinating observations that connect to the collapse problem:</p><p><strong>1. The Dreaming Hypothesis:</strong> Dwarkesh introduced research suggesting dreaming might be evolution’s anti-collapse mechanism:</p><ul><li>Dreams put you in weird, out-of-distribution scenarios</li><li>This prevents your brain from overfitting to daily routines</li><li>Maintains cognitive flexibility</li><li>Evolutionary adaptive for preventing mental collapse</li></ul><p><strong>Karpathy’s response:</strong> This aligns with the idea that humans need entropy sources. We’re “training on our own synthetic data” when we think, and need mechanisms to prevent going off-rails.</p><p><strong>2. The Learning-Memory Paradox:</strong> Dwarkesh observed a striking pattern:</p><ul><li><strong>Best learners (children):</strong> Terrible at recollecting specific information, even amnesiac about early years</li><li><strong>LLMs:</strong> Can regurgitate Wikipedia word-for-word but struggle with abstract concept learning like children</li><li><strong>Adults:</strong> Somewhere in between — less flexible than children but better memory</li></ul><p><strong>The insight:</strong> Perhaps excessive memorization capacity inhibits generalization. Children are forced to “see the forest for the trees” because they can’t memorize details. LLMs are “distracted” by their perfect memory of pre-training documents.</p><p><strong>Karpathy’s agreement:</strong> “Humans have a lot more of an element, compared to LLMs, of seeing the forest for the trees. We’re not actually that good at memorization, which is actually a feature.”</p><h3>Why This Matters for AI</h3><p><strong>Implications:</strong></p><ul><li>Can’t just scale synthetic data generation infinitely</li><li>Need mechanisms to maintain diversity (maybe AI “dreaming”?)</li><li>Should regularize for higher entropy</li><li>Must find ways to prevent self-reinforcing patterns</li><li>Perhaps models need LESS memory capacity to reason better</li></ul><p><strong>The dreaming hypothesis:</strong> AI systems might need similar mechanisms to prevent collapse — exposing them to weird, out-of-distribution scenarios during some training phase.</p><p><strong>Key Takeaway:</strong> AI systems naturally collapse toward repetitive patterns. Future breakthroughs will need to maintain diversity and entropy while still being useful. This is a fundamental research problem, not just an engineering challenge.</p><h2>8. The Autonomy Slider</h2><h2>A New Mental Model</h2><p>Karpathy introduces a crucial concept for thinking about AI deployment: <strong>the autonomy slider</strong>.</p><p><strong>The idea:</strong> Instead of humans vs. AI, think of it as a continuous spectrum where AI gradually takes over more low-level tasks:</p><p><strong>Historical progression:</strong></p><ul><li>Assembly code → Compilers handle low-level details</li><li>Manual memory management → Garbage collection</li><li>Procedural code → High-level abstractions</li><li>Command-line tools → AI assistants</li><li>Manual coding → AI autocomplete</li><li>Supervised AI → Autonomous agents</li></ul><h3>Why This Matters</h3><p><strong>The pattern:</strong> Humans progressively abstract themselves away from low-level details, focusing on higher-level problems.</p><p><strong>Current state:</strong></p><ul><li>Call center work: 80% AI, 20% human oversight</li><li>Software engineering: Autocomplete helps, but you’re in control</li><li>Self-driving: Teleoperation centers provide backup</li><li>Creative work: AI generates options, humans curate</li></ul><p><strong>Future trajectory:</strong> The slider continues moving toward more AI autonomy, but:</p><ul><li>Humans stay in the loop for critical decisions</li><li>Economic value concentrates in oversight and judgment</li><li>We keep raising our level of abstraction</li><li>Some humans become “Olympic-level” in their domains</li></ul><h3>The Radiologist Example</h3><p><strong>What everyone expected:</strong> AI would replace radiologists (Geoffrey Hinton’s famous prediction).</p><p><strong>What actually happened:</strong></p><ul><li>Radiologists are thriving and growing</li><li>AI handles routine pattern recognition</li><li>Humans manage edge cases, patient interaction, complex judgments</li><li>The job evolved but didn’t disappear</li></ul><p><strong>Dwarkesh’s bottleneck wage theory:</strong></p><p>Dwarkesh proposed an interesting economic dynamic for partially automated jobs:</p><p><strong>The theory:</strong> If you automate 99% of a job, the remaining 1% becomes incredibly valuable as a bottleneck:</p><ul><li>The human performing that 1% is essential for the entire system</li><li>If it requires years of specialized training (like radiology), wages should spike</li><li>Eventually wages crash when that final 1% is automated</li></ul><p><strong>Real-world examples:</strong></p><ul><li><strong>Waymo drivers:</strong> Need special training to monitor edge cases — they’re the bottleneck for deployment</li><li><strong>Radiologists:</strong> Wages have increased despite AI handling routine work, because they manage edge cases and patient interaction</li></ul><p><strong>The paradox:</strong> You might see wages go up until you reach 99%, then fall dramatically when the last 1% is solved.</p><p><strong>The lesson:</strong> Jobs rarely disappear wholesale. They transform. The 1% AI can’t handle becomes valuable bottleneck work — until that 1% is also automated.</p><p><strong>Key Takeaway:</strong> Think of AI deployment as an autonomy slider, not an on/off switch. Most jobs will see AI handling the routine 80%, with humans focusing on the complex 20%. This creates opportunities but also requires continuous adaptation.</p><h2>Further Exploration</h2><p><strong>To dive deeper:</strong></p><ul><li>Check out Karpathy’s <a href="https://www.youtube.com/andrejkarpathy">YouTube channel</a> for technical tutorials</li><li>Explore <a href="https://github.com/karpathy/nanochat">nanochat on GitHub</a> to see modern LLM development</li><li>Watch for Eureka Labs (<a href="https://github.com/karpathy/LLM101n">LLM101n</a> course coming soon)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c10659db456c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SIEVE: The Surprisingly Simple Cache Eviction Algorithm]]></title>
            <link>https://navaneethsen.medium.com/sieve-the-surprisingly-simple-cache-eviction-algorithm-525b2b7ba3b2?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/525b2b7ba3b2</guid>
            <category><![CDATA[lru-cache]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[sieve-cache]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 13:21:04 GMT</pubDate>
            <atom:updated>2025-08-14T19:46:19.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*57pPhbdaPPKauP8k_4JPag.gif" /></figure><p>Caching is like running a trendy night club with limited space inside (memory), a line outside (incoming requests), and bouncers deciding who gets in and who gets kicked out.</p><blockquote>For decades, most bouncers have followed some simple rules:<br><strong>“Your Time To Live inside the club is up, please leave now!”, or<br>“If you are not a frequent visitor, you’re out!”</strong></blockquote><p>The second one is the <strong>LRU (Least Recently Used)</strong> policy. It works reasonably well — but not perfectly — especially when it comes to how popular items get promoted in the cache.<br>LRU is basically: <strong>“You showed up? Straight to the front of the line!”</strong></p><p><strong>SIEVE</strong>, on the other hand, takes a different approach:<br><strong>“You showed up? Here’s a stamp. Stay where you are.”</strong></p><p>It’s the difference between reorganizing your entire bookshelf every time you read a book (<strong>LRU</strong>) versus simply putting a bookmark or a read sticker in it (<strong>SIEVE</strong>).</p><p>It’s a <em>simpler</em> algorithm that <em>somehow</em> <strong>beats LRU in most real-world web scenarios</strong> — especially when traffic follows a common pattern called a <strong>Zipfian distribution</strong>.</p><h3>Why Web Traffic is Zipfian — And Why That Matters</h3><p>Most websites don’t get an equal number of requests for every page.<br>Instead:</p><ul><li>A <strong>small handful</strong> of pages (hot items) get <strong>most</strong> of the visits.</li><li>The rest get very little traffic.</li></ul><p>This “few items are extremely popular” pattern is called a <strong>Zipfian distribution</strong>. It’s like a hit music chart: a few songs are played all the time, while most tracks rarely get airplay.</p><p>Caching algorithms thrive in Zipfian situations because they can <strong>keep the “hit songs” ready</strong> for quick delivery.</p><h3>The Problem With LRU</h3><p>LRU works like this:</p><ul><li>Keep items in the cache in order of <strong>most recently used</strong> → <strong>least recently used</strong>.</li><li>When the <strong>cache is full</strong>, <strong>throw out the item</strong> that was <strong>used the longest time ago</strong>.</li></ul><p>Sounds fair, right? But there’s is a problem:</p><ul><li>Every time you touch an item, it has to be <strong>moved to the front</strong> of the ordering list (or updated in a heap/tree).</li><li>This reordering is an <strong>O(log n)</strong> or <strong>O(1)</strong> operation depending on implementation, but it’s still extra bookkeeping.</li><li>For huge caches and high request rates, these operations add up.</li></ul><h3>Enter SIEVE</h3><p>SIEVE is <strong>much simpler than LRU</strong>.</p><p>a cache eviction algorithm so simple you could teach it to a beginner programmer in minutes… yet it beats LRU in many real-world cases.</p><h3>The VIP Club Analogy</h3><p>Imagine the same night club I talked about in the beginning of the article with limited seats (cache size) and a single bouncer (hand) to mark and evict guests. Let’s assume that now guests (requests) starts coming in:</p><ol><li><strong>If the guest (x) is already inside</strong> → Give them a stamp (visited = 1) whenever they order a drink.</li><li><strong>If they’re not inside</strong>:</li></ol><ul><li>If there’s space → Let them in, no one has to leave.</li><li>If the club is full → Start from the “hand” pointer and look for someone <strong>without a stamp </strong>(someone who was not ordering anything but just chit chatting).</li><li>Un-stamp people as you check them, looping back to the end if needed.</li><li>The first person without a stamp is kicked out.</li><li>The new guest comes in at the front, without a stamp.</li></ul><p>Unlike LRU, we don’t keep a perfect memory of every visitor’s last visit — just whether they’ve been seen since the last eviction scan.</p><p>This makes SIEVE <strong>much cheaper</strong> to run than LRU while still keeping the right people inside most of the time.</p><h3>How SIEVE Works (The Algorithm)</h3><p>Instead of storing timestamps or big priority structures like LRU, SIEVE uses:</p><ul><li>A <strong>doubly-linked list</strong> of items in the cache.</li><li>A <strong>visited bit</strong> for each item.</li><li>A <strong>hand pointer</strong> that remembers where we left off during eviction.</li></ul><p>Here’s the algorithm in simple pseudocode:</p><pre>Input: request x, queue T, cache size C, hand p<br>1: if x is in T then          # Cache Hit<br>2:     x.visited ← 1<br>3: else                       # Cache Miss<br>4:     if |T| = C then         # Cache Full<br>5:         o ← p<br>6:         if o is NULL then<br>7:             o ← tail of T<br>8:         while o.visited = 1 do<br>9:             o.visited ← 0<br>10:            o ← o.prev<br>11:            if o is NULL then<br>12:                o ← tail of T<br>13:        p ← o.prev<br>14:        Discard o from T    # Eviction<br>15:     Insert x at head of T<br>16:     x.visited ← 0          # New entry starts unvisited</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNitBlGeJtWYoh3e6JyPqQ.gif" /><figcaption><em>An illustration of SIEVE (</em><a href="https://cachemon.github.io/SIEVE-website/blog/2023/12/17/sieve-is-simpler-than-lru/?utm_source=chatgpt.com#design">https://cachemon.github.io/SIEVE-website/blog/2023/12/17/sieve-is-simpler-than-lru/?utm_source=chatgpt.com#design</a><em>)</em></figcaption></figure><p>SIEVE says: <em>“Stop obsessively moving things every time they’re touched — just mark them as visited.”</em></p><p><strong>Main differences vs LRU:</strong></p><ol><li><strong>On a hit</strong> → SIEVE simply sets a “visited” flag.<br>- No reordering, no costly movement.</li><li><strong>On eviction</strong> → It uses a moving “hand” pointer (like a clock hand) to find the next unvisited item and evict it.<br>- While scanning, it resets “visited” flags of the items it passes over.</li><li><strong>Insertion</strong> → New items are always inserted at the head (newest side), marked as unvisited.</li></ol><h3>Why SIEVE is Brilliant</h3><ol><li><strong>No Musical Chairs</strong>: Unlike LRU, nobody moves seats when they order drinks in the club. This is MUCH faster, especially when many people are ordering simultaneously.</li><li><strong>Smart Filtering</strong>: Popular guests (who order frequently) keep getting new stamps before the bouncer reaches them, so they never get kicked out.</li><li><strong>One-Hit Wonders Get Out Fast</strong>: New guest who only order once lose their stamp quickly and get kicked out when the bouncer passes by again.</li><li><strong>The Bouncer Gets Smarter</strong>: After the first round, the bouncer mostly hangs around the “new guests” area because the old-timers have proven they’re popular.</li></ol><h3>Is SIEVE Scan-Resistant?</h3><p>Being “scan-resistant” means the cache can survive a flood of <em>one-time</em> accesses (like reading a giant file sequentially or crawling through a dataset) without throwing out all the important frequently-used items.</p><p>Imagine your night club has a steady group of regulars (frequently accessed data). Suddenly, a tour bus drops off 200 tourists (a sequential scan). A <strong>scan-resistant bouncer</strong> would recognize that these tourists are unlikely to come back and wouldn’t kick out all the regulars to make space for them.</p><p>Unfortunately, <strong>LRU</strong> will happily let all the tourists in, kicking out the regulars.</p><p>SIEVE can, to some extent, ensure that regular customers remain in the club while tourists are replaced. However, in certain situations — such as when some tourists suddenly become more popular than the regulars — the regulars may end up being swapped out. The following <a href="https://github.com/Navaneethsen/sieve-eviction-cache/blob/89c49001261b20b9f3eff5a72a90aed4e7a82525/src/test/java/org/cache/sieve/SieveCacheTest.java#L1724"><strong>test</strong></a> demonstrates this scenario.</p><p>Which means even though SIEVE provides low overhead and high hit rates on many workloads, it is <a href="https://www.usenix.org/system/files/nsdi24spring_prepub_zhang-yazhuo.pdf#:~:text=reason%20for%20this%20discrepancy%20is,This%20prob%02lem%20is%20less%20severe"><strong>not scan-resistant</strong></a>. Under large sequential scans, SIEVE can end up evicting popular objects because it has no memory of previously-evicted entries. In such cases, one should use a scan-resistant replacement policy or augment SIEVE with a small ghost/history list or filter so that one-time scan accesses do not flush the cache.</p><h3>⚠️ The “Churn Effect” in SIEVE</h3><p>I had an interesting discussion with my colleague <a href="https://www.linkedin.com/in/d%C5%BAmitry-la%C5%AD%C4%8Duk-77a2895a/overlay/about-this-profile/?trk=public_profile_browsemap">Dźmitry</a> and he showed me a surprising behavior of SIEVE, which I’d call the <strong>churn effect</strong> — where newly inserted items are evicted almost immediately, typically when they follow a repeating pattern whose size exceeds the distance between the cache’s head and the hand position.</p><p>Here’s why it happens:</p><ul><li>Every new item is inserted with <strong>visited = 0</strong>.</li><li>SIEVE’s eviction hand always looks for the <strong>nearest </strong><strong>visited = 0</strong> when the cache is full.</li><li>If that newly inserted item isn’t accessed again <em>before the next eviction</em>, it becomes the perfect victim.</li><li>Meanwhile, older items that have been accessed at least once have <strong>visited = 1</strong>, and this would have been marked <strong>0 </strong>as the hand passed and now this would be safe from eviction — at least until there are new popular items in the cache and the hand moves to the tail.</li></ul><p>This means that in workloads where a set of items keeps cycling in but isn’t accessed right after insertion, the cache may evict these fresh arrivals before they’re ever reused — even though their repeated appearances should have made them “hot” and worth keeping.</p><p>The following <a href="https://github.com/Navaneethsen/sieve-eviction-cache/blob/e389f88fc99f9ff50facb37c2ff189e329deffa1/src/test/java/org/cache/sieve/SieveCacheTest.java#L1982"><strong>test</strong></a><strong> </strong>demonstrates this above mentioned scenario.</p><h3>Ideas to Improve SIEVE</h3><p>One idea I would like to try out is something similar to the Java garbage collector algorithm:</p><ul><li><strong>Tiered/Multi-layer SIEVE</strong> → An attempt to fuse SIEVE with the multi-queue idea. For example, using two (or more) SIEVE-managed FIFO lists: a “young” queue for new items and an “old” queue for items promoted after repeated access. On a hit in the young queue, an item might be <em>promoted</em> into the hot queue, ensuring it is not scanned out on a future sequential walk. Evictions would first target unvisited items in the young queue (quickly demoting one-hit objects), and only evict from the hot queue when necessary.</li></ul><h3>Final Takeaway</h3><p>SIEVE proves that sometimes, <strong>the simplest solution wins</strong>.<br>It doesn’t try to be perfect — it tries to be <em>good enough, fast enough, and cheap enough</em> to win in practice.</p><p>If you’ve been blindly using LRU for years, it might be time to invite SIEVE into your night club and see how it handles your VIP list.</p><h3>Java Source Code</h3><p><a href="https://github.com/Navaneethsen/sieve-eviction-cache.git">GitHub - Navaneethsen/sieve-eviction-cache: High-performance SIEVE eviction cache implementation with comprehensive statistics tracking</a></p><h3>Key References</h3><ul><li><strong>Zhang et al., 2024 — SIEVE is Simpler than LRU: An Efficient Turn-Key Eviction Algorithm for Web Caches</strong><br><em>Presented at NSDI ’24, this is the primary source introducing SIEVE.</em> <a href="https://www.usenix.org/conference/nsdi24/presentation/zhang-yazhuo?utm_source=chatgpt.com">USENIX+1</a></li><li><strong>Cachemon Blog: “Cache eviction can be simple, effective, and scalable”</strong><br><em>Highlights SIEVE’s reductions in miss ratio and its scalability even under heavy multi-threaded workloads.</em><a href="https://blog.jasony.me/system/cache/2024/06/12/sieve?utm_source=chatgpt.com">blog.jasony.me</a></li><li><strong>Hacker News Discussion: “Sieve is simpler than LRU — Hacker News”</strong><br><em>Provides developer insight and commentary on how SIEVE relates to earlier FIFO-Merge designs.</em> <a href="https://news.ycombinator.com/item?id=38850202&amp;utm_source=chatgpt.com">Hacker News</a></li><li>And of course, ChatGPT to gather information, format and organize all this information neatly into this article.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=525b2b7ba3b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing a Concurrency Bug – A Deep Dive into a Real-World Data Race]]></title>
            <link>https://navaneethsen.medium.com/fixing-a-concurrency-bug-a-deep-dive-into-a-real-world-data-race-94822fb37b23?source=rss-bebbd29c583f------2</link>
            <guid isPermaLink="false">https://medium.com/p/94822fb37b23</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Navaneeth Sen]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 10:35:31 GMT</pubDate>
            <atom:updated>2025-07-08T10:35:31.653Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQxEKt_vfStOEC7LPdHagA.gif" /></figure><p>Concurrency bugs are notoriously tricky to spot and even harder to fix correctly. While reviewing a recent pull request involving changes to a SpecialPropertyClass in a custom framework, I came across a textbook example of a data race—one that could easily lead to subtle, hard-to-reproduce issues in production. In this post, I’ll break down the problem, how the change in the pull request tackled it, and the key lessons learned from the experience.</p><h3>🎯 Background: What Is this SpecialPropertyClass?</h3><p>The SpecialPropertyClass class serves as a registry for converting property names (strings) into unique integer indices. These indices allow fast array-based access instead of relying on slower Map&lt;String, Object&gt; structures inside the SuperSpecialClass.</p><pre>SpecialPropertyClass prop = SpecialPropertyClass.get(&quot;foo&quot;);</pre><p>This registry ensures that each property name is assigned exactly one index.</p><h3>🐞 The Bug: Data Race in get(String) Method</h3><p>The original implementation looked somewhat like this:</p><pre>public static SpecialPropertyClass get(final String propertyName) {<br>    final ConcurrentHashMap&lt;String, SpecialPropertyClass&gt; reg = registry;<br>    SpecialPropertyClass prop = reg.get(propertyName);<br>    if (prop == null) {<br>        synchronized (reg) {<br>            prop = new SpecialPropertyClass(name, reg.size());<br>            reg.put(name, prop);<br>        }<br>    }<br>    return prop;<br>}</pre><p><strong>Problem?</strong></p><p>This code may <em>appear</em> thread-safe because of the synchronization block. But it’s <strong>not</strong>.</p><p>Here’s why:</p><ol><li>Multiple threads could simultaneously reach the reg.get(propertyName) check and find null.</li><li>Each thread could then enter the synchronized block and create <em>different</em> SpecialPropertyClass objects.</li><li>Even worse, two different properties (say &quot;foo&quot; and &quot;bar&quot;) could end up with <strong>the same index</strong>, because they were registered concurrently while reg.size() still returned the same value.</li></ol><h3>🔬 Symptoms in Practice</h3><p>We saw <strong>intermittent failures</strong> and <strong>property index collisions</strong>, especially when:</p><ul><li>Multiple threads accessed previously unseen properties at the same time.</li></ul><h3>✅ The Fix: Double-Checked Locking with Care</h3><p>We rewrote the method with a <strong>double-checked locking</strong> approach <strong>inside the synchronized block</strong> to ensure a unique index is assigned atomically and only once:</p><pre>if (prop == null) {<br>    synchronized (reg) {<br>        prop = reg.get(propertyName); // this is the fix!<br>        if (prop == null) {<br>            prop = new SpecialPropertyClass(name, reg.size());<br>            reg.put(name, prop);<br>        }<br>    }<br>}</pre><p>This approach prevents both:</p><ul><li>Duplicate object creation</li><li>Index collisions due to inconsistent reg.size() results</li></ul><h3>🧪 The Tests: Catching the Race</h3><p>We also added a <strong>stress test</strong> that spawns multiple threads registering the same set of property names repeatedly:</p><pre>@Test<br>public void testConcurrentPropertyRegistration() throws Exception {<br>    final int repetitionCount = 100;<br>    for (int x = 0; x &lt; repetitionCount; ++x) {<br>        ...<br>        final CountDownLatch latch = new CountDownLatch(1);<br>        ...<br>        for (Thread t : threads) t.start();<br>        latch.await(); <br>        latch.countDown(); // Release all threads at once<br>        ...<br>         <br>        assertNotEquals(&quot;Property index collision detected.&quot;, fooIdx, barIdx);<br>    }<br>}</pre><p>This test consistently triggered the issue before the fix and now passes reliably.</p><h3>🧠 Key Takeaways</h3><ul><li><strong>ConcurrentHashMap is not a silver bullet.</strong> It protects internal state, but logic around put and size can still race.</li><li><strong>Double-checked locking</strong>, if used <em>correctly</em> inside a synchronized block, can be effective.</li><li>Always <strong>back fixes with reproducible tests</strong>. We built a test that reproduced the race nearly every time.</li><li>Add <strong>diagnostic hooks</strong> when dealing with global registries — debugging tools matter.</li></ul><h3>💬 Final Thoughts</h3><p>This fix may look small, but its impact is large. Correct indexing is the backbone of performance in our property access strategy used in the SuperSpecialClass. A silent data race here could lead to incorrect outcomes, memory bloat, or worse.</p><p>Concurrency bugs are sneaky, and fixing them requires a deep understanding of both code semantics and memory behavior. I hope this post helps others spot and fix such bugs in their own systems.</p><p><em>Have questions or faced a similar bug? Let’s discuss in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94822fb37b23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>