<?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 Oğuz Kaan Mavice on Medium]]></title>
        <description><![CDATA[Stories by Oğuz Kaan Mavice on Medium]]></description>
        <link>https://medium.com/@enigmaticsolver?source=rss-6e4da2227863------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wVmYPXizk2D7QPyMqJ6kZw.jpeg</url>
            <title>Stories by Oğuz Kaan Mavice on Medium</title>
            <link>https://medium.com/@enigmaticsolver?source=rss-6e4da2227863------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:25:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@enigmaticsolver/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[My AI Agent Failed Once. The Denominator Changed the Diagnosis.]]></title>
            <link>https://levelup.gitconnected.com/my-ai-agent-failed-once-the-denominator-changed-the-diagnosis-21a77ba859eb?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/21a77ba859eb</guid>
            <category><![CDATA[benchmarking]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 14:59:30 GMT</pubDate>
            <atom:updated>2026-07-24T14:59:30.888Z</atom:updated>
            <content:encoded><![CDATA[<h4>The benchmark headline said one failure in 270 attempts. Inside BM25, the path was 90 attempts → 24 exposed cases → 2 missed corrections → 1 stale answer.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaVu7ch7LaExo1J1SWQjRQ.png" /></figure><p>I published one number as if it answered three different questions.</p><p>The number was true: one confirmed stale-memory failure across 270 memory-backed attempts. An agent, handed its own past sessions, answered with a superseded value and cited the superseded session as<br>its source. Once.</p><p>It was also too coarse to diagnose anything. That 270 pools three different memory systems, and no one deploys three memory systems at once. The failure happened in one of them — <strong>BM25 retrieval over chunked past sessions</strong>. Inside that condition, the path looks like this:</p><pre>| Stage                         | Count |<br>|-------------------------------|-------|<br>| Attempts                      | 90    |<br>| Revision-conflict challenges  | 24    |<br>| Missed the correcting session | 2     |<br>| Confirmed stale answer        | 1     |</pre><p>Those counts are not four rival estimates of one quantity. They describe four layers of one system, and the last of them is far too small to estimate anything from.</p><p>By the end you can decompose a single failure count into the rates it conflates, and say which one your role actually owns.</p><h3>Three ratios, three questions, and one of them has no answer yet</h3><pre>| Ratio                             | Observed     | What it supports                                                     |<br>|-----------------------------------|--------------|----------------------------------------------------------------------|<br>| 1 stale answer / 90 BM25 attempts | 1.1%         | benchmark owner: how often did this occur across the full BM25 suite |<br>| 1 / 24 exposed attempts           | 4.2%         | memory owner: what happens when a fact has been revised              |<br>| 1 / 2 missed corrections          | 50% observed | a trace-level observation, not a stable rate estimate                |</pre><p>That third row deserves the space. The observed conversion was 1 of 2, or 50%. That is a valid description of these two traces and <strong>nowhere near enough to estimate the underlying conversion probability.</strong> Under an independent binomial model, the 95% Wilson interval runs from about 9.5% to 90.5%. Because these trials are clustered rather than independent, even that interval is illustrative rather than inferentially valid here.</p><p>A count and an estimate are different objects. <strong>Reporting the first as though it were the second is the whole failure mode this article is about</strong>, and the row above is where I am most tempted to commit it.</p><h3>The aggregate rate is the default for good reasons</h3><p>Errors per attempt is the standard unit, and the case for it is not lazy.</p><p>It resists cherry-picking. If I get to choose which subset of tasks <em>“really counted”</em> after seeing which ones failed, I can move a rate anywhere I like. A denominator fixed at <em>“everything we ran”</em> is the one denominator I cannot quietly tune in my own favour.</p><p>It also compares cleanly. <strong>My benchmark ran four conditions</strong> — <em>no memory, full-history replay, a rolling summary, and BM25 retrieval </em>— over the same 30 tasks in three orderings, 90 attempts each. The full-suite denominator compares them over the complete shared workload; a predeclared exposed<br>subset compares their robustness to revision conflicts specifically. Both stay comparable as long as the definition is shared and fixed in advance. What breaks the comparison is each condition picking its own <em>“relevant subset”</em> after the fact.</p><p>And the aggregate answers a real question. Product risk aggregates over the production workload; mechanism diagnosis is conditional. Those are different jobs, and the first one is not the lesser.</p><p>So the aggregate isn’t the mistake. Publishing it <strong><em>alone</em></strong>, as though it described a mechanism, is.</p><h3>Exposure is a property of the task set, not a label applied afterwards</h3><p>A hazard-specific rate needs a denominator defined by the hazard, and that denominator has to be defined independently of the observed outcomes — <em>ideally before the system runs</em>.</p><p>In my benchmark, 8 of the 30 tasks are <em>“trap”</em> tasks. Each consumes a fact that an earlier session revised. In one ordering, session 1 defines an <em>“engaged customer”</em> as one active in the trailing 45 days, session 6 changes that to 30, and session 28 asks a question whose answer depends on which<br>window is current. Both window values live in the task generator’s fact registry <em>(`tasks/generate.py`),</em> fixed before any run. <strong>Absolute positions change between orderings; the establish → revise → trap order does not.</strong></p><p><strong>How thin that denominator really is.</strong> The 90 BM25 attempts are 30 task templates repeated across three orderings. The 24 exposed attempts are 8 trap templates repeated three times — and those 8 derive from only 2 revised facts, four traps each. Neither denominator contains independent trials. Read every percentage above against that, not against its own n.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZO_kHf0mtak4wSJl24eiw.png" /><figcaption>Nested, not sequential: each population is a subset of the one outside it. Boxes are schematic — they are not drawn to scale, because one attempt in ninety has no visible area.</figcaption></figure><p><strong>One more pairing worth stating, because I got it wrong while drafting this</strong>: 1 error in 270 memory-backed attempts pairs with 1 in 72 exposed attempts across the three memory strategies. Not with 1 in 24, which is a per condition number.</p><p>The evaluations I should have imitated already separate these populations.<br><strong><em>[</em></strong><a href="https://arxiv.org/abs/2406.13352"><strong><em>AgentDojo</em></strong></a><strong><em>]</em></strong> runs 97 realistic tasks and 629 security test cases, defines attack success rate over the security cases, and reports benign utility separately.<br><strong><em>[</em></strong><a href="https://arxiv.org/abs/2506.09038"><strong><em>AbstentionBench</em></strong></a><strong><em>]</em></strong> gives every sample a binary <em>“should abstain” </em>label and scores abstention against that label rather than across all questions.</p><p><strong>What would falsify this:</strong> if <em>“exposed”</em> could only be assigned after seeing which answers were wrong, the whole move collapses into motivated reasoning. So I made it checkable. <em>`scripts/exposure_report.py`</em> checks all 24 trap placements, grouped into six fact-ordering combinations —<em> two revised facts across three orderings</em> — and confirms that every trap falls after its revision, which falls after its establishing session. Zero violations. It prints <em>`CLAIM INVALID`</em> if that stops holding.</p><h3>The path branches, and each branch broke something different</h3><p>I want to be careful about what the four layers establish, because the tempting claim is stronger than the evidence.</p><p>In the one confirmed failure, <strong>the correcting session was absent from the retrieved context.</strong> That does not establish that every stale-memory failure requires a retrieval miss. A model can be handed the correction and ignore it. What I have is one observed path, not a necessary condition.</p><p>The second miss is more interesting than <em>“it recovered.”</em> In seed 1, task `ew_trap_2`,<em>(`experiments/results/rag_anthropic_claude-sonnet 5_seed1/transcripts.jsonl`)</em>, <strong>the agent never retrieved the correcting session</strong>, queried the database twice, and returned the current figure anyway — then attributed that answer to the very session it had not been shown.</p><p>The two misses broke different properties. The first <strong><em>produced a stale answer failure from outdated evidence</em></strong><em>:</em> the agent reasoned faithfully from what it was given, and what it was given was dead. The second <strong><em>produced a provenance failure</em></strong><em>: </em>the number was current, but the attribution was unsupported. My benchmark measured the first property and not the second, <strong>so it scored the second miss as a success — and by its own rules that is correct, and also incomplete.</strong></p><p>Content correctness and source faithfulness are not the same metric, and I only built one of them.</p><p><strong>What would falsify this decomposition:</strong> it loses its diagnostic value if retrieval status changes neither the failure probability nor the intervention a team would choose. That is a testable claim and I have not tested it.</p><p><strong>A correction to the parent article. </strong>In [<a href="https://medium.com/gitconnected/i-benchmarked-3-ai-agent-memory-strategies-only-rag-cited-a-dead-decision-as-current-feb4cce68240">the original benchmark write-up</a>], I described the failing retrieval as four documents, <em>“three of which quietly agreed with each other on the old number.”</em> <strong>That is wrong.</strong> Re-reading the retrieved chunks in <em>`rag_anthropic_claude-sonnet 5_seed0/transcripts.jsonl`</em>, those three carry no lookback figure at all — they are question text and a document header. One chunk carried a number, and it was the stale<br>one. The conclusion stands; that sentence did not.</p><h3>The strongest case against me: production doesn’t know which facts will be revised</h3><p>The objection I find hardest is not that the decomposition is wrong. It’s that it’s a luxury.</p><p>Splitting <em>“exposed”</em> from <em>“not exposed”</em> requires knowing in advance which facts get revised. My benchmark knows because I wrote the revisions. A production system usually doesn’t. You cannot label an incoming request as hazard-exposed without version-aware storage — <em>a fact registry</em>, supersession edges, validity intervals. Most teams don’t have it. For them, errors per attempt isn’t a lazy metric, it’s the only one they can compute honestly.</p><p>There’s a sharper version, and it lands on the number I like most. <strong>1-in-24</strong> is the observed susceptibility across eight synthetic hazard templates drawn from two revised facts, whose composition and severity I chose. I have not shown that those templates represent production revision conflicts. That’s a representativeness problem, not a prevalence one — my <strong>8-in-30</strong> hazard<br>density moves the <strong>1-in-90</strong>, while the <strong>1-in-24</strong> is already conditional on exposure and is limited instead by how narrow and how synthetic those eight templates are.</p><p>And I should say plainly what I went looking for and didn’t find. I expected to argue that benchmarks routinely dilute hazard rates across unrelated tasks. I couldn’t produce a single well-regarded example; the targeted evaluations I checked all separate the populations properly. The closest documented problem is adjacent rather than identical:<br><strong><em>[</em></strong><a href="https://arxiv.org/abs/2601.18076"><strong><em>Chouldechova and colleagues</em></strong></a><strong><em>]</em></strong> argue that</p><blockquote>ASR comparisons often fail to provide a sound evidentiary basis for conclusions about relative system safety or attack method efficacy</blockquote><p>— inconsistent aggregation across studies, not dilution inside one benchmark.</p><p>So the honest shape of this piece isn’t an accusation. It’s a case study in which the outlier is me.</p><h3>If I’m right, the fix is two numbers in your results table</h3><p>Not a new framework. A habit.</p><p>When you report a failure count, report the stage it was measured at, and report the population that could have produced it alongside the population you ran. In a benchmark where the exposure labels already exist, those two numbers cost almost nothing. In production, creating reliable exposure<br>labels may be the expensive part — <em>which is the honest limit on how far this advice travels.</em></p><p>What would change my mind is a team with version-aware memory computing all four layers and finding that every plausible intervention was already implied by the aggregate. Then the decomposition is an accounting exercise and I’m dressing up arithmetic as insight. I haven’t run that experiment.</p><h3>One error, four numbers, one habit</h3><p>I ran 270 memory-backed attempts and found one confirmed stale memory failure. That sentence is true, and on its own it’s close to useless.</p><p><strong>The version that’s worth something:</strong> of 90 BM25 attempts, 24 could have hit a revised fact, retrieval missed the correction in 2, and 1 became a wrong answer attributed to a dead decision —<em> across 30 task templates seen three times, the exposed slice resting on two facts.</em></p><p>Same event. Same data. The first sentence invites a <em>“mostly fine”</em> interpretation. The second tells you which component to investigate first, and how thin the evidence under that instruction really is.</p><p><strong><em>The harness, every run’s transcripts, and the script behind every number above:</em></strong></p><p><a href="https://github.com/EnigmaDevelop/agent-memory-lab">GitHub - EnigmaDevelop/agent-memory-lab: Does agent memory help or hurt? 3 memory strategies vs. a no-memory control, measured across 360 sessions with real accuracy AND cost data.</a></p><h3>Further reading</h3><p><strong>[</strong><a href="https://arxiv.org/abs/2406.13352"><strong>AgentDojo (Debenedetti et al.)</strong></a><strong>]</strong> — the cleanest worked example of the separation this article argues for: 97 tasks and 629 security cases, with attack success rate defined over the security cases and utility reported over the tasks.</p><p><strong>[</strong><a href="https://arxiv.org/abs/2601.18076"><strong>Comparison requires valid measurement (Chouldechova et al.)</strong></a><strong>]</strong> — <br> the source behind my claim that the real, documented problem is inconsistent aggregation across studies rather than dilution inside one benchmark.</p><p><a href="https://levelup.gitconnected.com/i-benchmarked-3-ai-agent-memory-strategies-only-rag-cited-a-dead-decision-as-current-feb4cce68240">I Benchmarked 3 AI Agent Memory Strategies. Only RAG Cited a Dead Decision as Current.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21a77ba859eb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/my-ai-agent-failed-once-the-denominator-changed-the-diagnosis-21a77ba859eb">My AI Agent Failed Once. The Denominator Changed the Diagnosis.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Benchmarked 3 AI Agent Memory Strategies. Only RAG Cited a Dead Decision as Current.]]></title>
            <link>https://levelup.gitconnected.com/i-benchmarked-3-ai-agent-memory-strategies-only-rag-cited-a-dead-decision-as-current-feb4cce68240?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/feb4cce68240</guid>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 15:46:19 GMT</pubDate>
            <atom:updated>2026-07-22T15:46:19.876Z</atom:updated>
            <content:encoded><![CDATA[<h4>Across 270 memory-backed attempts on 30 tasks, one stale-memory failure emerged. The retrieval log shows why.</h4><p>I went into this expecting to write about interference. The working hypothesis, borrowed from every “<strong><em>context rot</em></strong>” post making the rounds this year: <em>give an agent its own conversation history back, verbatim, and it will eventually trust something stale over something true</em>. Retrieval-based memory — chunk it, index it, pull only the relevant piece — was supposed to be the disciplined alternative. Precise. Grounded. Safe.</p><p>I built a small benchmark to check: <strong>three memory strategies, measured against a no-memory control, the same 30-task sequence, three reshuffled orderings</strong>, a judge that doesn’t just mark answers right or wrong but traces <strong><em>which prior session</em></strong> a wrong answer actually came from. Two hundred seventy memory-backed task attempts later, the one strategy that produced a confirmed, citation-traceable false memory wasn’t full-history replay. It was RAG — the one I expected to be the careful one — and I can point to the exact retrieval call that did it.</p><h3>The result in one table</h3><p>Before the setup, so you’re not reading blind — here’s what came out, pooled across three orderings <em>(90 attempts per condition)</em>:</p><pre>| Condition            | Accuracy | Wrong answers | Confirmed false memory |<br>|----------------------|----------|---------------|------------------------|<br>| No memory (control)  | 32.2%    | 61            | —                      |<br>| Full history replay  | 100.0%   | 0             | 0                      |<br>| Rolling summary      | 95.6%    | 4             | 0                      |<br>| RAG (BM25 retrieval) | 97.8%    | 2             | 1                      |</pre><p>Every memory strategy crushes the no-memory control, and on raw accuracy they’re a three-way tie this dataset can’t break apart. The whole story is in that last column: across 270 memory-backed attempts, exactly one wrong answer was a <strong><em>confirmed false memory</em></strong> — the agent citing a specific superseded decision as if it were current. It happened once, under RAG, and the retrieval log shows exactly why. That single trace is what the second half of this piece is about.</p><p>One word I’m deliberately not using for it: <strong><em>hallucination</em></strong>. Everything here turns on a narrow, checkable definition — an answer that matches a specific known-stale value <strong>and</strong> cites the stale session as its source. That’s a much smaller claim than <em>“made something up,”</em> and<strong> it’s the only claim this benchmark can actually support</strong>. <em>(On the loose everyday meaning of the word, rolling-summary’s four wrong answers would count too — so “only RAG” would be false. Precision in the title is doing real work.)</em></p><p>And on <em>“deterministic,”</em> since I’d otherwise be overclaiming: the environment, task set, expected answers, orderings, and judge rules are all fixed and regenerable from a seed. The <strong><em>model </em></strong>is not. Claude Sonnet 5 rejects a non-default temperature outright <em>(see `src/llm.py`)</em>, so generation is unseeded and a re-run won’t reproduce these transcripts token for token. <strong>Everything around the model is deterministic; the model isn’t.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_yFXq-BT8RZ9xnDyazH0g.png" /></figure><h3>The setup: a fictional company, three kinds of questions, one honest control</h3><p>The environment is a small, deterministic fictional B2B SaaS company — 80 customers, employees, support tickets, invoices, campaigns — regenerated identically from a fixed seed every time <em>(`environment/build_env.py`)</em>. An agent with three tools <em>(`sql_query`, `read_doc`, `answer`) </em>answers 30 questions in sequence, one per <em>“session,” </em>under <strong><em>four conditions</em></strong>: <strong>no memory (the control), full-history replay, a rolling LLM-generated summary, </strong>and <strong>RAG over chunked past sessions.</strong> Only the last three are memory <strong><em>strategies</em></strong> in any meaningful sense — the first one exists purely to prove the other three are actually doing something. The 30 tasks split into three types, and<br>the split is the whole point:</p><ol><li><strong>10 independent</strong> tasks need nothing from earlier sessions — the easy floor.</li><li><strong>12 dependent</strong> tasks reference a decision by name only (<em>“using the priority-industries list decided earlier…”</em>) and require recalling its actual value from a prior session.</li><li><strong>8 trap</strong> tasks reference a decision that was <strong>later revised</strong> — the correct answer needs the current value; the pre-revision value is a distinct, wrong, and very tempting number.</li></ol><p>Every trap task ships with both the correct answer and the exact stale distractor it’s designed to catch, computed from the same database, so a wrong answer can be checked against a specific hypothesis instead of just marked “<em>wrong</em>.” A judge module (<em>`src/judge.py`</em>) does the checking: it only labels a trap failure<em> `interference_confirmed`</em> when the agent’s answer matches the <strong><em>stale </em></strong>value <strong>and</strong> the agent explicitly cited the <strong><em>stale</em></strong><em> </em>session as its source. Anything else — a different wrong number, or the stale value reached without citing the stale session — is filed under a separate category. This distinction is the entire methodology of this piece: <strong>I’m not counting every wrong answer on a trap task as <em>“interference.”</em> I’m counting citations that provably point at a dead fact, and treating every other kind of wrong answer as a different, lesser claim.</strong></p><p>The no-memory condition is the control every result below is measured against, and it’s a clean one: <strong>93.3%</strong> on the independent tasks that don’t need memory at all, and <strong>0%</strong> on the trap tasks that exist specifically to require memory. An agent with nothing to remember cannot be fooled by a stale memory — which is exactly what a working control condition should show, and <strong>exactly what a data-platform engineer would want to see before trusting anything measured against it</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CD5uwO6n0prF4MdTTA7H1A.png" /><figcaption>One session’s path through the harness. The judge is what turns a wrong trap-task answer into a<br>provable citation of a specific stale session — the only path highlighted in amber, because it’s<br>the only outcome this piece found evidence for.</figcaption></figure><h3>The results</h3><p>Every number below is the pooled 3-seed dataset — 90 task-attempts per condition <em>(the same 30 tasks, reshuffled into three different valid orderings, since task order can confound a memory strategy independently of what it remembers)</em>. That’s 90 per condition, not 90 total: <strong>360 task-attempts across all four conditions, 270 of them under an actual memory strategy.</strong></p><p>Everything about how these are tested reflects one fact I initially got wrong: <strong>the 90 attempts are 30 task items looked at three times, not 90 independent draws.</strong> Two corrections follow from it, both of which change the published numbers. First, significance is a <strong>paired </strong>two-sided<br>permutation test, matched on <em>`(task_id, seed)` </em>— a test that shuffles the condition label across the pooled 90 rows would be pretending they’re independent. Second, the confidence intervals are a<strong> cluster bootstrap</strong> that resamples whole task-clusters <em>(30 of them)</em>, not individual rows, so each interval reflects the ~30 independent units the design actually has. Where a condition has zero variance <em>(full-history’s 90/90, which no bootstrap can put an interval around) </em>I report a Wilson interval fed one value per task-cluster, so it can’t smuggle the inflated n=90 back in. Both live in <em>`src/stats.py`</em>, run by <em>`scripts/analyze.py`</em>.</p><p>The practical effect is intervals that are wider than a naive per-row bootstrap would give — which is the point. They’re honest about resting on 30 tasks.</p><p><strong>Overall accuracy</strong> <em>(cluster bootstrap over 30 task-clusters; Wilson where noted)</em>:</p><pre>| Condition            | Accuracy      | 95% CI                   |<br>|----------------------|---------------|--------------------------|<br>| No memory (control)  | 32.2% (29/90) | [16.7%, 47.8%]           |<br>| Full history replay  | 100.0% (90/90)| [88.6%, 100.0%] (Wilson) |<br>| Rolling summary      | 95.6% (86/90) | [90.0%, 100.0%]          |<br>| RAG (BM25 retrieval) | 97.8% (88/90) | [94.4%, 100.0%]          |</pre><p>That full-history interval is worth pausing on. Ninety for ninety does not mean <em>“never fails”</em> — on 30 independent tasks the honest lower bound is about <strong>89%</strong>, not 100%. <em>`[100%, 100%]`</em> would have been an artifact of counting 90 correlated rows as 90 clean trials; the wider interval is the real<br>result.</p><p><strong>By task type</strong> — the breakdown that actually answers the question, since the <strong>10/12/8 task mix</strong> is otherwise arbitrary:</p><pre>| Condition       | Independent   | Dependent     | Trap          |<br>|-----------------|---------------|---------------|---------------|<br>| No memory       | 93.3% (28/30) | 2.8% (1/36)   | 0.0% (0/24)   |<br>| Full history    | 100.0% (30/30)| 100.0% (36/36)| 100.0% (24/24)|<br>| Rolling summary | 93.3% (28/30) | 100.0% (36/36)| 91.7% (22/24) |<br>| RAG             | 96.7% (29/30) | 100.0% (36/36)| 95.8% (23/24) |</pre><p>Every memory strategy beats the no-memory control at p&lt;0.0001 in the paired test — and the raw pair counts say it more plainly than the p-value does. Against full-history, the control lost 61 of the 90 matched pairs and won zero. <strong>That isn’t a statistical squint; it’s the design working.</strong></p><p>What’s <strong><em>not </em></strong>significant is more interesting: full-history vs. RAG <strong><em>(p=0.496)</em></strong>,<br>rolling-summary vs. RAG <strong><em>(p=0.628)</em></strong>, full-history vs. rolling-summary <strong><em>(p=0.127)</em></strong>. On raw accuracy, this dataset cannot tell the three memory strategies apart — and the pairing makes the reason concrete rather than mysterious. Full-history beat rolling-summary on exactly <strong>4</strong> matched pairs<br>and lost on none. Four discordant pairs cannot produce a p-value below <strong>0.125</strong> no matter how one-sided they are; that’s a property of the design, not a quirk of the test. When your entire evidence base for <em>“strategy A beats strategy B”</em> is four disagreements out of ninety, <strong>the honest answer is that you don’t have the resolution to say.</strong></p><p>Six total wrong answers across all three memory strategies, out of 270 memory-backed attempts: full-history zero, rolling-summary four <em>(all ordinary counting slips, not stale citations — more below)</em>, RAG two, one of which is the confirmed interference case this piece is about.</p><p>And one clustering fact that I think matters more than any p-value here: <strong>all six of those wrong answers fall in a single task family.</strong> The benchmark has six families; the <em>“engaged window” </em>family accounts for 18 of each condition’s 90 attempts <em>(20%)</em>, and every error the three memory strategies<br>produced landed there. That is not what independent attempts look like. It’s the clearest possible evidence that these 90 attempts are 30 task items looked at three times, and it’s why the tests above are paired. It also means <em>“full history got 90/90”</em> partly reflects that the one genuinely hard family was a fifth of the workload. <em>`scripts/analyze.py`</em> prints this breakdown as section 5.</p><h3>How big did “full history” actually get?</h3><p>This is the number I most want a reader to have before drawing a general conclusion from the 100%, because without it the obvious takeaway — <em>“full history is the safe strategy”</em> — is broader than anything I measured. By the final session, full-history’s memory context reached about <strong>17,000 characters, roughly 4,300 tokens</strong> <em>(17,129 / 17,000 / 17,616 chars across the three seeds)</em>. <strong>Rolling summary landed near 2,200 tokens, RAG near 500.</strong> Nothing was ever truncated — <em>`memory_truncated`</em> is <em>`False`</em> on all 360 rows. <em>`scripts/context_report.py`</em> regenerates this.</p><p><strong>Four thousand tokens is nothing</strong> — a rounding error against a modern context window. To be precise about what that does and doesn’t imply: the revised and stale decisions <strong><em>were</em></strong> both sitting in full-history’s context together, so interference wasn’t structurally impossible. What this study<br>never reached is the regime the context-rot hypothesis is actually about — a context large enough that old material competes with new material for the model’s attention across hundreds of sessions. So the honest reading of the perfect score isn’t <em>“replay resists interference”</em>; it’s that t<strong>his benchmark didn’t meaningfully stress the large-context version of the question.</strong> At 30 sessions and ~4K tokens, verbatim replay had no failures. Whether that holds at 300 sessions or 400K tokens — where the interesting version of this lives — is untested here.</p><h3>The one confirmed false memory</h3><p>Of those six wrong answers, exactly <strong>one </strong>a confirmed case of the agent citing memory it should have known was outdated — a false-memory rate of <strong>4.2% on RAG’s 24 trap-task attempts (1/24)</strong>, zero on the other two strategies’ 24 trap attempts each. The other five wrong answers <em>(four in<br>rolling-summary, one in RAG)</em> were ordinary mistakes — a count off by one or three, not traceable to any stale source — filed under a different judge category precisely so they don’t get bundled into this claim.</p><p><em>“Ordinary mistake”</em> is a claim worth checking rather than asserting, so here’s one. On <em>`ew_trap_4`</em>, rolling-summary answered <strong>55</strong> where the correct answer was 58 and the stale distractor was 70. It missed the count by three; it did not drift toward the dead value. That’s the difference the judge<br>category encodes, and it’s checkable in the transcripts for all five.</p><p>Worth being explicit about what that does and doesn’t mean for the strategies’ overall standing: RAG’s raw accuracy (97.8%) is still <strong><em>higher</em></strong> than rolling-summary’s (95.6%), which had zero confirmed false memories. Summary just made more small, forgettable mistakes instead of one<br>dramatic, traceable one. “Only RAG cited a dead decision” is true and mechanically worth understanding — <strong>it is not the same claim as “RAG performed worse.”</strong> A single well-explained failure is more useful to a reader than four unexplained ones, but it isn’t evidence that the strategy<br>behind it is the weaker choice.</p><p>I can walk through exactly what went wrong in the one confirmed case, because the citation trace is right there in the <a href="http://experiments/results/rag_anthropic_claude-sonnet-5_seed0/"><strong>transcript</strong></a>, <em>task `ew_trap_3`.</em></p><p>The setup: session 1 established that an <em>“engaged customer”</em> means a qualifying usage event in the trailing <strong>45 days</strong>. Session 6 revised that to <strong>30 days</strong>. Session 28 asks how many engaged customers are on the Enterprise plan, under the current (post-revision) definition. The correct answer is 22. The agent answered <strong>28 </strong>— the exact 45-day count for that segment — and cited session 1, the <strong><em>original </em></strong>decision, as its source. Not session 6. Not <em>“no source.”</em> Session 1, specifically, which is exactly the trap’s predefined stale source. That’s what makes it <em>`interference_confirmed`</em> rather than just a wrong number: the citation trace proves which memory the agent trusted.</p><p>Here’s the retrieval call that caused it. <strong>RAG’s top-4 BM25</strong> hits for this task’s query were sessions 15, 22, 11, and 1 — three earlier <strong><em>consumption</em></strong> questions that share almost identical phrasing with this one <em>(“using the ad hoc engaged customer’ lookback window… how many engaged customers are there [in X]?”)</em>, plus the original establishing session. Session 6 — the one session that actually contains the revision, phrased entirely differently <em>(“the team re-reviewed the numbers and decided the… window was too loose… changing it from 45 days to 30 days”)</em> — never made the top 4. Its content was indexed like every other session; nothing about the pipeline skipped it. It’s lexically distant from every consumption question, precisely because a revision<br>announcement doesn’t ask a question at all. For <strong><em>this </em></strong>query, BM25 ranked four sessions that share the question’s vocabulary above the one session that quietly changed the answer — the update announces, once, in different words, and never comes up again. (<em>Whether this generalizes into “BM25<br>buries revisions” is exactly the n=1 problem I flag below — one trace shows the mechanism, not its rate.)</em> The agent didn’t choose to trust a dead fact over a live one. It was handed four documents, three of which quietly agreed with each other on the old number, and the one that mattered wasn’t in the stack it saw.</p><p>That’s a retrieval-<strong><em>ranking </em></strong>failure, and I want to name it precisely:<strong> the correction was in the index the whole time. </strong>Nothing was missing from storage. What failed was recall at k=4 for a chunk whose content matters enormously but whose phrasing doesn’t resemble the questions asked about it afterward — the RAG equivalent of a change-log entry that never gets surfaced because nobody searches using the words a change log uses. Full-history replay doesn’t have this specific failure mode because it has no retrieval step to fail — the revision is just there, in the transcript, whether or not it’s lexically similar to the current question. Whether that makes full-history strictly <em>“safer” </em>in general, or just safer against <strong><em>this </em></strong>one untuned BM25 configuration at top-4, is a question this single trace can’t answer on its own — see the limitations below.</p><p><strong><em>Code, every run’s raw transcripts, and the analysis scripts behind every number above:</em></strong></p><p><a href="https://github.com/EnigmaDevelop/agent-memory-lab">GitHub - EnigmaDevelop/agent-memory-lab: Does agent memory help or hurt? 3 memory strategies vs. a no-memory control, measured across 360 sessions with real accuracy AND cost data.</a></p><h3>The cost surprise</h3><p>I expected memory to cost more — full-history especially, since it resends a growing transcript every session. Per-minute billing data <em>(Anthropic’s usage export, cross-referenced against each run’s exact start/end timestamps)</em> says the opposite, and by a wide margin. These are <strong>per-seed</strong> figures: one 30-session run of one condition, averaged across seeds.</p><pre>| Condition           | Cost per 30-session run (one seed) | Relative to no-memory |<br>|---------------------|------------------------------------|-----------------------|<br>| No memory (control) | $1.15                              | —                     |<br>| Full history        | $0.45                              | 61% less              |<br>| Rolling summary     | $0.32                              | 72% less              |<br>| RAG                 | $0.22                              | 81% less              |</pre><p>So one seed across all four conditions is about $2.1, and the three-seed study landed somewhere near $6–7 — well under the $25 I’d budgeted, with room to spare for the failed experiments I’m not itemizing here. Two caveats I’d rather state than have you find. This is averaged over seeds 1 and<br>2, the two I have complete minute-level billing data for <em>(seed 0’s usage fell in an export window I hadn’t pulled)</em>; they agree within about 7% per condition. And unlike the accuracy numbers, this table is <strong><em>not </em></strong>regenerable from the repo — I never logged per-call token usage, so it’s reconstructed from billing timestamps, not computed from the runs. Treat the ordering as solid and the exact figures as approximate. <em>(I’ll also resist a tempting claim: prompt caching was wired up and demonstrably active, but since I didn’t log cache-read vs. write vs. fresh-input tokens, I can’t tell you how much of the low cost it accounts for versus the retry effect below. Both are real; their split is unmeasured.)</em></p><p>The no-memory control — the condition with the <strong><em>smallest</em></strong> context per call — was the single most expensive to run, by more than double the next strategy. And <strong>here the mechanism isn’t a hypothesis; the transcripts measure it directly.</strong> I capped each session at 8 assistant turns. No-memory used a <strong>median of 8</strong> turns and hit that ceiling on <strong>56 of 90 sessions</strong>— with nothing to reference, it spends every dependent and trap task retrying an answer it has no way to reach, until the budget cuts it off. All three memory strategies ran at a <strong>median of 2</strong> turns and hit the ceiling <strong>zero </strong>times: answer on the first or second try, stop. That’s the whole cost story. A run that gives up after eight failed tries costs more than one that succeeds in two accuracy and cost weren’t a trade-off here, they moved together, for one measurable reason. (<em>`scripts/analyze.py` section 6.</em>)</p><h3>The boring part almost sank the whole measurement</h3><p><strong>None of the numbers above would mean anything if the harness weren’t trustworthy</strong>, and the bugs that threatened that weren’t the loud kind. The dangerous ones returned a <strong><em>plausible wrong number</em></strong> and sailed past 60-plus passing unit tests: the model using SQLite’s live <em>`now()`</em> against data dated to a synthetic “today” <em>(silently zeroing every date-windowed query instead of erroring)</em>, and the agent calling <em>`answer`</em> in the same turn as a SQL query — submitting the column alias as its final value before ever seeing the result. Both took a hard code-level block to close; neither showed up until I ran the pipeline for real and read what came back.</p><p>The statistics had a bug of exactly the same species, which is why the results section labors the point about pairing. The first analysis shuffled condition labels across the pooled 90 rows and produced a fine-looking p-value that was quietly answering a different question than the one I’d asked. Silent-and-wrong is the failure mode worth fearing in an eval harness — in the data or in the analysis of it. The loud bugs are annoying; the quiet ones end up in your chart. Nine years of data-platform work is mostly this: <strong>the unglamorous 80% is where the real risk lives.</strong></p><p>One scoping decision belongs here too. The original plan ran a local model alongside the frontier one, but two small local models <em>(`qwen2.5:3b`, `mistral:7b`)</em> failed the <strong><em>basic</em></strong> tool-use task — one on a genuine small-model SQL ceiling, the other reading a correct query result and then fabricating a different number on the next turn. Neither is a story about memory, so the local arm was retired and the real run moved entirely to Claude Sonnet 5. That debugging trail is its own piece — <strong>see “Up next.”</strong></p><h3>What I’d do differently</h3><ol><li><strong>Retrieve on recency-plus-topic, not topic alone. </strong>A revision event should outrank three lexically-closer consumption questions when the topic overlaps — this is a chunking/retrieval design fix, not a bigger model fix, and it’s directly testable against this same benchmark.</li><li><strong>Measure retrieval recall directly, not just outcome accuracy.</strong> One traced failure explains one event; it doesn’t establish a general rate. Before claiming <em>“BM25 systematically buries revisions,”</em> the next version of this benchmark should compute <strong><em>recall@k</em></strong> for the <strong><em>revision</em></strong> session specifically, across every revisable fact, not infer a pattern from n=1.</li><li><strong>Log a “did the agent re-verify against the live source” signal</strong>, not just the final answer. Right now the judge can prove <strong><em>which </em></strong>stale session got cited; it can’t yet show whether the agent had a chance to catch itself by re-querying the database instead of trusting memory text.</li><li><strong>This is one seed-family of one fixed task set. </strong>Three reshuffled orderings of the same 30 tasks is not 90 independent draws — it’s three looks at one set. Pairing the tests fixes how the evidence is <strong><em>counted</em></strong>; it does nothing about how narrow the evidence is. The error-clustering result above is the sharp version of this: six errors, one task family, and therefore a benchmark whose difficulty is concentrated in about a fifth of its own tasks. A larger and more varied task pool is the only real fix.</li><li><strong>Nothing here tests memory at scale.</strong> Full-history’s context topped out near 4,300 tokens after 30 sessions. The interference risk everyone writes about is a large-context phenomenon, and this study stops several orders of magnitude short of it. <em>A 300-session version</em> — or <em>one that deliberately grows sessions until replay stops fitting</em> — is the experiment that would actually put full-history at risk, and I haven’t run it.</li><li><strong>I logged no token-level data</strong>, which is why the cost table is reconstructed from billing timestamps rather than computed, and why I can’t decompose the cost result into cache reads vs. writes vs. fresh input. Adding usage accounting to the client is cheap; doing it after the fact means re-running the study, which is why it’s on this list instead of in the piece.</li><li><strong>I didn’t tune the RAG chunking or retrieval count at all</strong> — 60-word sliding windows, top-4, first configuration I wrote. This specific recall failure might disappear with a larger top-k or a hybrid recency signal, and I’d want to know that before calling RAG the riskier strategy in any general sense — what this benchmark actually shows is that <strong>this</strong> RAG configuration has <strong>this </strong>failure mode, not that retrieval-based memory is inherently less trustworthy than replay.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUNPHK6V-ZBQvrmkBkv4og.png" /></figure><h3>Takeaways</h3><ol><li><strong>Having memory at all mattered far more than which kind — and skipping it wasn’t even the cheap option. </strong>No-memory control: 32% accuracy, and the most expensive condition to run. All three memory strategies: 96–100% accuracy, indistinguishable from each other on this data, at 61–81% lower cost. <strong><em>If your agent needs to recall its own decisions, no-memory isn’t a cheaper fallback here</em></strong> — it loses on both axes this benchmark measured, and the transcripts show why: the memoryless agent burned its full retry budget (median 8 of 8 turns) failing to guess answers it had no way to reach.</li><li><strong>The one confirmed false memory this benchmark found was a retrieval-ranking miss, not a <em>“trusted stale data over fresh data”</em> failure in the sense most interference writing assumes.</strong> RAG didn’t choose the old number over the new one — it was never shown the new one, because a correction doesn’t read like the questions that get asked about it afterward. That’s a fixable, specific, unglamorous retrieval-tuning problem, which is a more useful finding than “RAG is risky.”</li><li><strong>A citation-trace judge is what turned <em>“wrong answer”</em> into <em>“provably interference”</em> — and what kept five ordinary mistakes from being miscounted as the same thing.</strong> Without it, this piece would have one fewer real number, six unexplained wrong answers instead of one traced failure and five filed-separately slips, and an unfalsifiable guess about why RAG got that trap task wrong.</li><li><strong>The measurement scaffolding was where most of the risk was, not the models. </strong>Two silent harness bugs and one wrong statistical unit would each have produced a publishable-looking number that was answering the wrong question. If you take one operational thing from this: the bugs that survive your unit tests are the ones that return a plausible value.</li></ol><h3>Further reading</h3><ul><li>[<strong>Lewis et al.</strong>, <strong><em>“</em></strong><a href="https://arxiv.org/abs/2005.11401"><strong><em>Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks</em></strong></a><strong><em>”</em></strong>]<br> — the original RAG paper; its own framing of retrieval as the accuracy bottleneck is exactly what session 28’s failure demonstrates in miniature.</li><li>[<a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching"><strong><em>Anthropic’s prompt caching documentation</em></strong></a>]<br> — prompt caching was active for this study; the <em>`cache_control`</em> block placement in<em> `src/llm.py`</em> follows this doc’s rules directly. <em>(It places the markers; it does not count the hits, so I can’t attribute a specific share of the low cost to it — see the limitations above.)</em></li></ul><h3>Up next</h3><p>The two local open-weight models this project tried before moving to Claude — one that hit a real 3B-parameter SQL ceiling, one that read a correct database result and then hallucinated a fake one on the very next turn — are their own story, with their own transcripts. That’s a separate piece: <strong><em>what actually happens when you try to run a real agentic tool-use loop on hardware you already own, and where it breaks.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feb4cce68240" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/i-benchmarked-3-ai-agent-memory-strategies-only-rag-cited-a-dead-decision-as-current-feb4cce68240">I Benchmarked 3 AI Agent Memory Strategies. Only RAG Cited a Dead Decision as Current.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Turned My Resume Into an AI You Can Interrogate]]></title>
            <link>https://levelup.gitconnected.com/i-turned-my-resume-into-an-ai-you-can-interrogate-2ad6c39736b2?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ad6c39736b2</guid>
            <category><![CDATA[side-project]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 14:31:19 GMT</pubDate>
            <atom:updated>2026-07-20T14:46:13.334Z</atom:updated>
            <content:encoded><![CDATA[<h4>No RAG, no vector DB, $0/month — and every answer cites its sources</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfmuP434bs85nM5UkzK_JQ.png" /></figure><p>I’ve spent years on both sides of the hiring table. As a data analytics manager I’ve run more interviews and read more CVs than I can count, and as a candidate I’ve climbed the whole ladder myself: internship screens, junior roles, a multi-stage management-trainee selection, then specialist, senior, and manager interviews. <strong>Every one of those conversations has its own technique and its own language.</strong> And the format we squeeze them into keeps shrinking — a ten-minute phone screen, a thirty-minute video call, decision. That is not enough time to actually know a person.</p><p><strong>Signal Sifter</strong> is my attempt to fix that, in both directions at once.</p><p>Outward, it doesn’t replace the CV; the link goes <strong><em>inside </em></strong>the CV, right under the summary, where a recruiter’s eyes already are. Anyone who clicks it can interrogate my career story before we ever speak — <strong>so the HR screener and the hiring manager can do real preparation</strong>, and the thirty minutes we do get is spent on better questions.</p><p>Inward — and this is the half I care most about — <strong>it’s an interview coach.</strong> A hidden practice mode flips the roles and interviews <strong><em>me </em></strong>about my own story, then coaches every answer against my CV, my narrative data, and five literature-based self-assessments. <strong>Not generic interview advice:</strong> recommendations bound to what I actually claimed about myself, so the preparation happens before the stakes are real.</p><p>There was one problem to solve first, and it’s the reason most “<em>chat with my resume</em>” toys backfire: <strong>an AI that confidently invents a project you never shipped is a bigger red flag</strong> than a plain PDF, because now the recruiter has to wonder what <strong><em>else </em></strong>it made up. So I built the trust in architecturally, not with a disclaimer. The AI never generates facts about my career; it only surfaces things I already wrote down ( resume + career story), and it shows its work on every answer.</p><h3>What I built</h3><p>Signal Sifter is a chat-style resume with two speeds. <strong>Static mode</strong> is a button-driven tour of my experience, projects, and skills: deterministic, no LLM call, can’t hallucinate because nothing is generated. <strong>AI mode</strong>, opened with a ✦ icon, is a free-form conversation with a model answering<strong><em> as me</em></strong>, grounded strictly in my resume and story data, with a source badge under every reply.</p><p>There’s also a third mode nobody visiting the site ever sees, which I’ll get to.</p><p><a href="https://enigmadevelop.github.io/resume-signal-sifter/"><strong>Live demo</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p98bSXZT-3hXDpG_5H_0ZA.png" /></figure><h3>Decision 1 — you don’t need RAG for a resume</h3><p>The first instinct when you say “<em>chat with your data</em>” out loud is to reach for a vector database. I didn’t, and the reason is just arithmetic: one person’s resume plus their career narrative is a few kilobytes of text. That fits inside an LLM’s context window with room to spare, every time, on every request, so there’s nothing to retrieve. The Cloudflare Worker just stringifies the JSON and drops it straight into the system prompt:</p><pre>function buildSystemPrompt(resume, story, lang) {<br>  const resumeJson = JSON.stringify(resume).slice(0, MAX_RESUME_JSON_LENGTH);<br>  const storyJson = story<br>    ? JSON.stringify(story).slice(0, MAX_STORY_JSON_LENGTH)<br>    : null;<br><br>  return `You are ${resume.profile.name}, ${resume.profile.title}.<br>Ground every answer strictly in the résumé (and story, if provided) data below.<br>...<br>Résumé data (JSON):<br>${resumeJson}${storySection}`</pre><p><strong>No embeddings, no chunking, no vector store, no retrieval step to tune or debug.</strong> RAG earns its cost when a corpus is too large to fit in context, changes faster than you can re-embed it, or needs to be queried across many documents at once. None of that is true of a single person’s career data. Reaching for RAG here would be solving a scale problem I don’t have — the same instinct that gets people building a Kubernetes cluster for a script that runs once a day.</p><h3>Decision 2 — make the model cite itself</h3><p>Not hallucinating is necessary but not sufficient. A recruiter still has to <strong><em>trust </em></strong>that the answer is grounded, and “<em>trust me</em>” isn’t a feature. So every reply is forced to open with a machine-readable citation line before a single word of the actual answer:</p><pre>§SRC:story.workStyle,story.values§<br>&lt;the reply text starts here&gt;</pre><p><strong>The system prompt hands the model a closed list of source keys</strong> (<em>`resume.profile`, `resume.experience`, `story.behavioralStories`, `story.selfAssessments:teamRole`, and so on</em>) and it can only cite from that list, never invent a new one. The client strips the header before rendering and turns it into 📄 (résumé) / 📖 (story) badges under the bubble:</p><pre>function sourceBadgeInfo(key, strings) {<br>  const verified = key.match(/^story\.selfAssessments:(.+)$/);<br>  if (verified) return { verified: true, instrument: verified[1], icon: &quot;✓&quot; };<br>  const label = strings.sourceLabels?.[key];<br>  if (!label) return null;<br>  return { verified: false, label, icon: key.startsWith(&quot;resume.&quot;) ? &quot;📄&quot; : &quot;📖&quot; };<br>}</pre><p><strong><em>`none` </em></strong>is a valid citation too, used for greetings or a declined off-topic question, so the badge is honest about <strong><em>not </em></strong>being grounded in anything instead of forcing a citation where there isn’t one. This is the part of the project I’d point to first if someone asked what the actual idea was: <strong>the citation isn’t new information for the model, it’s an audit trail of data it already had, made visible.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hyeB1I5mbHKTPCY8dYN01g.png" /></figure><h3>Decision 3 — real assessments, honestly labeled</h3><p>Here’s a thing I learned reading CVs for a living: “<em>team player with strong communication skills</em>” is noise. Everyone writes it, it costs nothing to claim, and no interviewer has ever updated their opinion because of it. I wanted the soft-skill side of my profile to carry actual information, so I went to the literature instead of adjectives.</p><p><strong>The story data behind the AI includes five structured self-assessments</strong>, each based on a published framework:</p><ul><li><strong>Team role</strong> — Belbin’s nine team roles (Belbin, 1981)</li><li><strong>Conflict style</strong> — the Thomas–Kilmann Conflict Mode Instrument (1974)</li><li><strong>Motivation drivers</strong> — Self-Determination Theory (Deci &amp; Ryan): autonomy, mastery, relatedness</li><li><strong>Personality snapshot </strong>— TIPI, a short published Big Five measure (Gosling et al., 2003)</li><li><strong>Leadership style</strong> — Goleman’s six leadership styles (HBR, 2000)</li></ul><p>I deliberately left MBTI and Enneagram-style typing out: modern comparisons against the Big Five consistently find they add little predictive validity, and I didn’t want fiction dressed as psychology sitting next to real citations.</p><p>Each assessment is scored by answering a short open questionnaire that ships with the repo — not by the AI guessing from a paragraph of prose. When an answer draws on one of them, the badge shows a ✓, and tapping it opens a card naming the instrument, its literature source, and one sentence that matters more than the score: <strong>this is self-report, not certification.</strong> Ask the AI directly whether the assessments are certified and it says no — the system prompt instructs it to explain the self-report framing plainly rather than let a checkmark oversell itself. In my experience, the recruiters who ask that question are exactly the ones paying closest attention, and honesty there earns more trust than a fake credential ever could.</p><h3>The hidden door: `?practice=1`</h3><p>This part isn’t for recruiters; visitors never see it. Open the deployed site with <strong><em>`?practice=1`</em></strong> and the roles flip: the AI stops answering as me and starts <strong><em>interviewing</em></strong> me, running a behavioral interview grounded in my own resume and story data.</p><p>This mode exists because of the second thing I wanted the project to do: <strong>help people represent themselves consciously and professionally, not just decoratively</strong>. That management-trainee selection taught me that an HR screen, a hiring-manager conversation, and a panel case each have a different technique and a different vocabulary — and almost nobody rehearses for that difference. So practice mode ships with two personas: the default HR screener probing motivation and collaboration, and <em>`&amp;persona=manager`</em> for a hiring manager digging into impact, ownership, and judgment.</p><p>What makes the coaching useful is that it’s a recommendation engine grounded in my own declared data, not a list of generic interview tips. The interviewer builds its questions from the gaps in my story (no failure story? it asks for one), demands behavioral evidence for resume claims, and stress-tests the self-assessments against real events — if my conflict-style assessment says “<em>collaborating</em>,” it asks about an actual disagreement and checks whether the behavior I describe matches the style I claimed. The five assessments stop being static badges and become the rubric I’m rehearsed against.</p><p>After every answer comes a short coaching note: which part of STAR I skipped (an unmeasured Result is the usual gap), whether I said “<em>we</em>” when I meant “<em>I,</em>” whether my tone stayed professional, whether I contradicted something I’d already written about myself. Finish with a 🏁 chip and it gives an overall read: two strengths, two growth priorities, one hiring-signal sentence.</p><p>The part I didn’t expect going in: writing <em>`story.json</em>` honestly — including a real failure story and real growth areas — turned out to <strong><em>be </em></strong>interview prep, before the coaching even starts. <strong>The practice mode can only probe the gaps you were willing to write down.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILdco9mqUOAsGUtt5UtxAA.png" /></figure><h3>The $0 stack</h3><ul><li><strong>GitHub Pages</strong>: the static frontend, free.</li><li><strong>Cloudflare Worker</strong>: the only piece that touches an LLM; it owns the system prompt, the citation contract, and a basic per-IP rate limit (10 requests/minute by default).</li><li><strong>Groq’s free tier:</strong> ≈100k tokens/day. Every request re-embeds the full resume+story, so that’s roughly 20–25 visitor Q&amp;As a day, or about two full practice sessions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*or28YFB5bCLnzwf9qizWZA.png" /></figure><p>The Worker speaks the plain OpenAI-compatible chat-completions contract, so swapping providers is a config change, not a rewrite: point <em>`LLM_ENDPOINT`/`LLM_MODEL`</em> at OpenAI, OpenRouter, Together, or anywhere else that speaks the same shape, no frontend code touched.</p><p>And the fallback is the cleanest proof that the two modes are genuinely decoupled: flip one flag in <strong><em>`content/config.json`</em></strong> and AI mode disappears entirely, no Worker required:</p><pre>{<br>  &quot;aiMode&quot;: { &quot;enabled&quot;: false }<br>}</pre><p>The repo template ships with exactly that default, <em>`aiMode.enabled: false`</em>, so a fresh fork has zero runtime surface pointed at any backend until its owner deliberately turns AI mode on.</p><h3>Limitations &amp; what I’d change</h3><ul><li><strong>The free tier is tight.</strong> 100k tokens/day sounds generous until a handful of visitors ask a few questions each; it degrades to a clear “<em>at capacity</em>” message rather than a silent failure, but it’s a real ceiling on a personal site with real traffic.</li><li><strong>Prompt injection is still a live surface.</strong> The system prompt tells the model to stay in character and decline off-topic requests, but a determined visitor can try to talk it out of that; it’s a soft-skill defense, not a sandboxed one.</li><li><strong>The per-IP rate limiter is best-effort.</strong> Cloudflare recycles Worker isolates, so it’s not a globally accurate counter — enough to blunt casual abuse, not a hard guarantee.</li><li><strong>Self-report is exactly that.</strong> The ✓ badges are honest about being self-scored, not third-party validated. That’s the right trade-off for a personal project, but it’s worth restating plainly.</li></ul><h3>Fork it</h3><ol><li><strong>Fork</strong> the repo, clone it, <em>`npm install &amp;&amp; npm run dev`</em>. The demo persona runs in static mode immediately, no keys needed.</li><li><strong>Fill in your own <em>`content/&lt;lang&gt;/resume.json`</em></strong> and, if you want AI mode’s depth, <em>`story.json`</em>. [<a href="https://github.com/EnigmaDevelop/resume-signal-sifter/blob/main/STORY_GUIDE.md"><em>STORY_GUIDE.md</em></a>] walks through the five self-assessments and the STAR stories field by field — filling it in honestly is the first rehearsal.</li><li><strong>Deploy</strong>: GitHub Pages via the included Actions workflow, and optionally a Cloudflare Worker for AI mode (10-minute guide in the repo).</li></ol><p>Then put the link where a recruiter’s eyes already are — right under your CV’s summary — and rehearse with <em>`?practice=1`</em> before the real thing.</p><p><a href="https://github.com/EnigmaDevelop/resume-signal-sifter">GitHub - EnigmaDevelop/resume-signal-sifter: Interactive chat-style resume with an AI grounded in your career story - plus a hidden interview practice simulator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ad6c39736b2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/i-turned-my-resume-into-an-ai-you-can-interrogate-2ad6c39736b2">I Turned My Resume Into an AI You Can Interrogate</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Platform Engineer’s AI Rebuild, Chapter 3]]></title>
            <link>https://levelup.gitconnected.com/a-data-platform-engineers-ai-rebuild-chapter-3-6f440d844cff?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f440d844cff</guid>
            <category><![CDATA[model-evaluation]]></category>
            <category><![CDATA[data-labeling]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 16:36:59 GMT</pubDate>
            <atom:updated>2026-07-15T16:36:59.643Z</atom:updated>
            <content:encoded><![CDATA[<h4>I Hand-Labeled 1,001 Complaints So My LLM Eval Wouldn’t Lie to Me</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnMCvv7g5Qdhmv-4fQqraA.png" /></figure><p><a href="https://medium.com/gitconnected/a-data-platform-engineers-ai-rebuild-chapter-2-4dc89662ae98">Chapter 2</a> ended with a number I refused to trust. My structured-output experiment produced a “<em>loose match rate</em>” that was good enough to prove a point — schema-valid JSON can be confidently wrong — and nowhere near good enough to rank models against each other. The fix has a name, and<br>every AI engineering post repeats it like a mantra: <strong>build an eval harness.</strong></p><p>What those posts mostly don’t tell you is where the time goes. The harness code — metrics, loaders, a judge wrapper, tests — took me an afternoon. Deciding what’s true, 1,001 times, took days. And it bought something worth the days: the first comparison in this project <strong>I can actually trust — a 20-year-old algorithm against a 3B LLM on the same 1,001 real complaints</strong>,<br>where the LLM catches <strong>3× more churn</strong> signals and the old algorithm runs <strong>14,844×</strong> <strong>cheaper.</strong> Neither wins. This chapter is about both halves of that trade, but I want to be honest about which half was the work.</p><h3>No label, no eval</h3><p>My eval task: does a CFPB consumer complaint narrative contain an explicit <strong>churn signal</strong>— a stated account closure, a switch to another provider, a definite threat to leave? Note what that is <strong><em>not </em></strong>: it’s not predicting whether the customer will churn. It’s detection — does the text <strong><em>say </em></strong>it which is exactly the kind of task people bolt LLMs onto in production.</p><p>One problem. The CFPB complaint database, unlike <a href="https://medium.com/gitconnected/a-data-platform-engineers-ai-rebuild-2392bebfd8ee">Chapter 1</a>’s Telco table, has no churn column. Nobody labeled this. If I want ground truth, I have to make it.</p><p>The tempting shortcut is obvious: have a big LLM label the dataset, then evaluate other LLMs against those labels. I’ve watched a version of this movie in my data-platform years — validating an ETL job against numbers produced by the same ETL job. Everything reconciles beautifully, and<br>you’ve measured nothing. An LLM-labeled golden set doesn’t measure accuracy; it measures <strong><em>agreement with the labeler,</em></strong> and every model downstream inherits the labeler’s blind spots invisibly.</p><p>So I split the difference, deliberately. Claude proposed a label, an evidence quote, and a confidence score for every row. Then I reviewed every single row myself. Not a spot check. All 1,001, in 33 review batches, however long it took. And because Claude touched the proposals,<strong><em> Claude is disqualified from being evaluated against this set </em></strong>— the classifier under test is a local<br><em>`llama3.2:3b`</em>, a different model from a different company, running on my own machine. <strong>The circularity rule survives.</strong></p><h3>What labeling 1,001 complaints actually teaches you</h3><p>My rubric started as one clean sentence: <strong><em>positive if the narrative explicitly states the consumer closed the account, switched providers, or definitely intends to leave.</em></strong> I thought I was done writing it. The data disagreed for days.</p><p>Is it a churn signal when the <strong>bank </strong>closed the account and the customer is furious about it? (No — that’s involuntary; nobody chose to leave.) When a consumer cancels a credit card that fraudsters opened in their name? (No — there was never a relationship to end.) When someone mentions, in passing, that they left the bank years ago and now just wants paperwork? (No — a historical fact, not a signal in this complaint.) When they close one account but move the money to another product at the same bank? Each of these showed up in the real rows, each forced a ruling, and each ruling became a rule. Somewhere around the middle of the set I realized I wasn’t<br>labeling anymore — I was maintaining a specification. Anyone who has sat in a meeting deciding what <em>“active customer”</em> means for a KPI knows this exact feeling. The label <strong><em>is </em></strong>the spec, and the edge cases are where it actually lives.</p><p>The strangest finding was structural. I stratified the sample across three CFPB products, and one of them — debt collection — produced <strong>zero positives in 167 human-reviewed rows</strong>. Not bad luck: you never chose your debt collector, so there is no relationship to quit. “<em>Churn</em>” is close to incoherent there. I stopped sampling that product, kept the 167 rows as evidence, and wrote the reasoning down instead of quietly growing the sample until noise produced a positive.</p><p>Final tally: <strong>1,001 rows, 48 positives (4.8%)</strong>. I overrode Claude’s proposal <strong>6 times</strong> in 1,001 rows — a <strong>0.6%</strong> disagreement rate that sounds like Claude did all the work, until you notice that those 6 rows, plus the dozens of edge cases where I confirmed a non-obvious call, are precisely where the definition got made. The cheap 99% was never the point of the review.</p><p>The full set is public on Kaggle — [<a href="https://www.kaggle.com/datasets/oguzkaanmavice/cfpb-churn-signal-golden-set"><em>cfpb-churn-signal-golden-set</em></a>]: labels, the full AI-propose/human-review provenance, both models’ predictions, and the fold assignment — with one explicit request on the card: it’s built for evaluation, please don’t train on it.</p><h3>48 positives is not many — and one fold proved it</h3><p>Here’s the statistics problem nobody warns you about with rare-signal tasks: my first cut at this golden set was ~200 rows with 11 positives. A standard 70/30 split leaves roughly <strong><em>three </em></strong>positives in the test set. One flipped prediction moves recall by ~33 points. Any single number I reported from that would have been a coin flip wearing a lab coat.</p><p>Two fixes, both boring, both necessary. I grew the set to 1,001 rows. And I switched from a single split to <strong>5-fold stratified cross-validation</strong>, with the fold assignment saved to a file so both models are scored on <strong><em>the exact same</em></strong> partitions — every row gets scored exactly once as a held-out case, and I report mean ± std across folds instead of one point estimate.</p><p>Was that overkill? The baseline itself answered. TF-IDF’s five per-fold F1 scores came back as <strong>0.250, 0.429, 0.462, 0.222 — and 0.000</strong>. An entire fold where the classical model found nothing. If I had run one split and happened to draw that partition, this article would be telling you TF-IDF is useless. A different draw, and I’d be telling you it’s fine. Both would have been measurements. Neither would have been true.</p><h3>The result: neither model won, and that’s the finding</h3><p>Same 1,001 rows, same five folds. TF-IDF + logistic regression (the 20-year-old baseline) versus <em>`llama3.2:3b`</em> zero-shot with structured output — <strong><em>deliberately zero-shot, no few-shot examples, no chain-of-thought</em></strong>; prompting techniques are next chapter’s variable, measured with this chapter’s harness.</p><pre>| Metric   | TF-IDF + LR   | LLM zero-shot (llama3.2:3b) |<br>|----------|---------------|-----------------------------|<br>| Accuracy | 0.949 ± 0.013 | 0.871 ± 0.018               |<br>| Precision| 0.387 ± 0.264 | 0.220 ± 0.031               |<br>| Recall   | 0.213 ± 0.122 | **0.647 ± 0.040**           |<br>| F1       | 0.272 ± 0.166 | **0.327 ± 0.036**           |</pre><p>The counts make it concrete. Across all 1,001 held-out predictions, TF-IDF caught <strong>10 of 48</strong> real churn signals and raised 13 false alarms. The LLM caught<strong> 31 of 48</strong> — three times as many — and raised <strong>112 </strong>false alarms to do it.</p><p>Don’t let the accuracy row fool you; it’s Chapter 1’s trap again. On a 95.2%-negative dataset, high accuracy is what you get for saying “<em>no</em>” a lot — the dummy classifier in Chapter 1 scored 73.5% accuracy with literally zero ability to find churn. TF-IDF’s <strong>0.949</strong> accuracy is mostly that same arithmetic. The rows that matter are recall and F1, and there the trade is stark: TF-IDF is precise and mostly blind; the LLM sees two-thirds of the real signals and pays in false positives.</p><p>Notice the standard deviations too, because I almost missed this. The LLM isn’t just the higher-recall model — it’s the <strong><em>more stable</em></strong> one, <strong>± 0.02–0.04</strong> on every metric while TF-IDF’s precision swings <strong>± 0.264</strong> depending on which ten positives land in the test fold. On a rare class, an estimator you can trust fold-to-fold is worth something on its own.</p><h3>Then I measured the price tag</h3><pre>|                 | TF-IDF + LR  | LLM zero-shot                             |<br>|-----------------|--------------|-------------------------------------------|<br>| Throughput      | 4,943 rows/s | 0.333 rows/s                              |<br>| Per row         | ~0.2 ms      | ~3.0 s (± 1.4 s)                          |<br>| Tokens per call | n/a          |~393 prompt + ~33 response (sampled, n=30) |</pre><p><strong>TF-IDF is roughly 14,844× faster per row</strong> on my CPU-bound hardware. Classifying the full set took the LLM <strong>50 minutes of pure compute</strong>; TF-IDF trains <strong><em>and </em></strong>predicts in a fifth of a second. So the honest engineering answer isn’t “<strong><em>the LLM has better F1, ship it.</em></strong>” It’s a routing question: if flagged complaints go to a human for review, the LLM’s 3× recall is probably worth its false-positive rate and its cost. If the label triggers automatic action, or you’re scoring millions of rows, the 20-year-old algorithm is still the right default. Neither answer is embarrassing. Pretending there’s a universal winner would be.</p><h3>The judge experiment that judged me back</h3><p>The chapter’s third piece was LLM-as-judge — using one local model (<em>`qwen2.5:3b`</em>) to grade another’s rationales, the pattern half the industry now uses to grade everything. The MT-Bench paper (<em>Zheng et al., 2023</em>) that legitimized LLM judging also documented its failure modes, so instead of assuming them away I measured them on my own machine, on an earlier, smaller batch of this chapter’s data (61 scored rationales, 8 comparison pairs — bias mechanics don’t need the full set, but I flag the scale rather than let you assume otherwise).</p><p><strong>Position bias is real and I can show it.</strong> Same two rationales, same narrative, shown in both orders: in <strong>1 of 8 pairs</strong> the judge’s winner flipped purely because the order changed.</p><p><strong>“<em>Self-preference</em>” evaporated under the swap test. </strong>In forward order, judges picked their own model’s rationale <strong>11 times out of 16</strong> — looks like self-preference. After swapping positions: <strong>5 out of 16</strong>. Combined, exactly 16 of 32. A coin flip. What looked like a model favoring itself was position bias wearing a costume, and without the swap control I’d have reported the costume as the finding.</p><p><strong>Verbosity bias didn’t show up</strong> — padding rationales with content-free filler raised the judge’s score exactly 0 times in 6 — and the groundedness experiment mostly measured <strong><em>me</em></strong>: I wrote a rubric describing what a well-grounded <strong><em>positive </em></strong>rationale looks like, and the judge obediently handed failing grades to perfectly correct negative rationales for not quoting exit<br>statements that don’t exist. The <strong>1.25/5</strong> average groundedness score isn’t a fact about the model. It’s a fact about my rubric, published as the design flaw it is.</p><h3>What I’d do differently</h3><ol><li><strong>Record token counts during the real classification run.</strong> I logged per-row timing but not tokens, so the token numbers above are a 30-row sampled estimate re-sent through the identical prompt — clearly labeled, but a lesson: decide your cost telemetry <strong><em>before</em></strong> the 50-minute run, not after.</li><li><strong>Design the judge rubric for negatives from day one.</strong> Any grading scheme for a detection task has to describe what a correct “<em>no</em>” looks like, or it will punish every correct “<em>no</em>” it sees.</li><li><strong>One experiment stayed on the bench.</strong> My schema generates the boolean verdict <strong><em>before</em></strong> the rationale (field order is generation order — verified in Chapter 2), which means some rationales may be post-hoc justifications of an already-committed answer. Reversing the field order is a one-line change and a ~50-minute rerun; I scoped it, priced it, and deferred it rather than let the chapter sprawl.</li><li><strong>This golden set has one annotator. </strong>No inter-rater agreement is measurable, and I’d rather state that limitation than hide it behind the effort the labeling took.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUNPHK6V-ZBQvrmkBkv4og.png" /></figure><h3>Takeaways</h3><p><strong>The golden set is the asset; the models are interchangeable.</strong> Every classifier, prompt technique, and judge this project measures from now on runs against these same 1,001 human-verified rows. In data-platform terms: pipelines get rewritten, the test suite and the definitions outlive them all.</p><p><strong>On a 4.8%-positive class, a single train/test split is a coin flip wearing a lab coat. </strong>My baseline’s per-fold F1 ranged from <strong>0.000 to 0.462</strong> on the <strong><em>same data</em></strong>. Report mean ± std across folds, or accept that your number is partly luck.</p><p><strong>Neither model won, and that’s a publishable result.</strong> TF-IDF: <strong>10/48 signals caught, 13 false alarms</strong>, ~<strong><em>0.2 ms</em></strong> per row. LLM: <strong>31/48 caught, 112 false alarms</strong>, <strong><em>~3 seconds</em></strong> and ~426 tokens per row. The right choice depends on what’s downstream of the label — which is an engineering question no leaderboard can answer for you.</p><h3>Further reading</h3><p>[<strong>Zheng et al., “<em>J</em></strong><a href="https://arxiv.org/abs/2306.05685"><strong><em>udging LLM-as-a-Judge with MT-Bench and Chatbot Arena</em></strong></a><strong>”</strong>]<br> — the paper behind LLM judging <strong><em>and</em></strong> the catalog of its biases; the position, verbosity, and self-enhancement effects this chapter measured locally are all documented there.</p><p>[<a href="https://www.consumerfinance.gov/data-research/consumer-complaints/"><strong><em>CFPB Consumer Complaint Database</em></strong></a>]<br> — the real, public source data behind every narrative in this chapter’s golden set.</p><p>The golden set and a [<a href="https://www.kaggle.com/code/oguzkaanmavice/churn-signal-tf-idf-vs-llm-starter-notebook"><strong><em>starter notebook</em></strong></a>] that reproduces this article’s comparison end-to-end (no GPU, no LLM required) are public on Kaggle: [<strong><em>c</em></strong><a href="https://www.kaggle.com/datasets/oguzkaanmavice/cfpb-churn-signal-golden-set"><strong><em>fpb-churn-signal-golden-set</em></strong></a>].</p><h3>Coming in Chapter 4</h3><p>Chapter 3 built the ruler. Chapter 4 finally gets to use it on the thing everyone actually argues about: <strong>prompting</strong>. <strong><em>Few-shot examples, chain-of-thought, context position</em></strong> — each one measured against this same golden set, on the same folds, with the same metrics, so when a technique “<em>works</em>” I’ll be able to say by how much, on what, at what cost. <strong>The harness stops being the chapter and starts being the ruler.</strong></p><p><a href="https://github.com/EnigmaDevelop/ai-engineering/tree/main/chapters/03-eval-harness">ai-engineering/chapters/03-eval-harness at main · EnigmaDevelop/ai-engineering</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f440d844cff" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-data-platform-engineers-ai-rebuild-chapter-3-6f440d844cff">A Data Platform Engineer’s AI Rebuild, Chapter 3</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Platform Engineer’s AI Rebuild]]></title>
            <link>https://levelup.gitconnected.com/a-data-platform-engineers-ai-rebuild-2392bebfd8ee?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/2392bebfd8ee</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 16:22:00 GMT</pubDate>
            <atom:updated>2026-07-10T16:22:00.775Z</atom:updated>
            <content:encoded><![CDATA[<h4>Chapter 1 : What a 73%-Accurate ‘Do-Nothing’ Model Taught Me Before the Real Work Started</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9g-Ds0tDTBPwnuY3FAX8g.png" /></figure><p>I’m spending the next several months rebuilding my career from data platforms into AI engineering, in public, as one evolving system rather than thirteen disconnected demos — a “<strong>Customer Intelligence Platform</strong>” that starts with a churn dataset and ends, chapters from now, as a full<br>pipeline: <em>classical model, local LLMs, RAG over real complaint data, agents, the works</em>. This is chapter one. It doesn’t touch an LLM at all. That was deliberate, and the reason why is itself the first real lesson of the series.</p><p>Because I couldn’t answer a simpler question first: if a later chapter’s LLM tells me it predicted churn with “75% accuracy,” <strong>how would I know if that’s good? Good compared to what?</strong> Nine years of reading dashboards taught me one thing the hard way — a single accuracy number, with no baseline<br>attached, is not evidence of anything. So before writing any LLM code in this repo, I built the thing every later chapter has to beat: a plain XGBoost model on the <em>[</em><a href="http://medium.com/r?url=https%3A%2F%2Fgithub.com%2FIBM%2Ftelco-customer-churn-on-icp4d"><em>IBM Telco Customer Churn dataset</em></a><em>]</em>, and — more importantly — a model that does <strong>nothing at all</strong>, run through the exact same test.</p><h3>The question that actually started this</h3><p>Here’s the experiment I ran before the real one: what happens if I build a “classifier” that never looks at a single customer feature, and just always predicts “this customer will not churn”?</p><p><em>`scikit-learn`</em> has this built in — it’s called <em>`DummyClassifier`</em>, and it exists specifically to answer this question:</p><pre><br>from sklearn.dummy import DummyClassifier<br><br>clf = DummyClassifier(strategy=&quot;most_frequent&quot;, random_state=42)<br>clf.fit(X_train, y_train)      # learns nothing except &quot;which class is more common&quot;<br>y_pred = clf.predict(X_test)   # predicts the same class for every single row</pre><p>On 1,409 held-out customers, this model — which never looks at contract type, tenure, or monthly charges — scored <strong>73.46% accuracy</strong>.</p><p>That’s the whole problem in one number. If you show me only “73% accuracy” on a churn model, I can’t tell whether you built something real or whether you just found the majority class.</p><h3>Why this happens: the data is imbalanced, not close to 50/50</h3><p>The Telco dataset’s churn rate — measured directly from the DuckDB warehouse built in<em> [</em><a href="https://github.com/EnigmaDevelop/ai-engineering/blob/main/chapters/00-setup/README.md"><em>Chapter 0</em></a><em>] </em>— is <strong>26.5%</strong> (1,869 churned out of 7,043 customers).</p><p>A model that always says “no churn” is right about 3 times out of 4 for free, before it has learned anything. This is the same trap I’ve seen in a dozen dashboards over 9 years of data platform work: a “95% accurate” fraud model that never catches fraud, a “98% accurate” defect classifier on a<br>line where 98% of parts pass anyway. Accuracy is only informative when you already know the class balance — and most of the time, it isn’t shown next to the number that would let you check.</p><h3>What I actually built</h3><p>The real model: XGBoost, reading directly from <em>`</em><a href="https://github.com/EnigmaDevelop/ai-engineering/tree/main/data"><em>data/warehouse.duckdb</em></a>` (no CSV re-parsing), with three deliberate, evidence-driven choices:</p><p><strong>1-The 11 blank values in `TotalCharges` aren’t a bug to paper over — they’re a fact to verify</strong></p><p>Querying them directly showed all 11 have <em>`tenure == 0`</em>: brand-new customers with no bill issued yet. Filling them with <em>`0.0`</em> isn’t a guess, it’s arithmetic <em>(`tenure × MonthlyCharges = 0`)</em>.</p><p><strong>2-</strong> <strong>Native categorical handling instead of one-hot encoding</strong></p><p>XGBoost’s <em>`tree_method=”hist”</em>` with <em>`enable_categorical=True`</em> splits directly on <em>`Contract`, `InternetService`</em>, and the other nine categorical columns, cast to pandas <em>`category`</em> dtype — no manual dummy-variable explosion.</p><p><strong>3- <em>`scale_pos_weight`</em> set to the actual class ratio, not left at 1</strong></p><pre>class_ratio = (y_train == 0).sum() / (y_train == 1).sum()  # 2.77<br><br>model = xgb.XGBClassifier(<br>    n_estimators=300, max_depth=4, learning_rate=0.05,<br>    scale_pos_weight=class_ratio,<br>    tree_method=&quot;hist&quot;, enable_categorical=True,<br>    random_state=42,<br>)</pre><p>Without this, XGBoost optimizes for the majority class the same way the dummy model does — and I’d be back to measuring nothing.</p><p>Validation discipline: <em>a stratified 80/20 train/test split, plus 5-fold stratified cross-validation</em> on the training set only, so the reported numbers are a range, not a lucky single split.</p><p><strong>Full code:</strong><br>[`<a href="https://github.com/EnigmaDevelop/ai-engineering/blob/main/chapters/01-baseline/experiments/train_baseline.py">experiments/train_baseline.py</a>`].</p><p><strong>Raw results:</strong><br>[<a href="https://github.com/EnigmaDevelop/ai-engineering/blob/main/chapters/01-baseline/experiments/results.json">`experiments/results.json`</a>].</p><h3>The results</h3><p>5-fold CV on the training set: ROC-AUC <strong>0.844 ± 0.010</strong>, F1 <strong>0.632 ± 0.012</strong> — stable, not a fluke of one split. Held-out test set (1,409 customers, never touched during training or CV):</p><pre>| Metric      | Dummy baseline | XGBoost |<br>|-------------|----------------|---------|<br>| Accuracy    | 0.7346         | 0.7551  |<br>| Precision   | 0.0000         | 0.5264  |<br>| Recall      | 0.0000         | 0.7727  |<br>| F1          | 0.0000         | 0.6262  |<br>| ROC-AUC     | 0.5000         | 0.8405  |<br>| PR-AUC      | 0.2654         | 0.6545  |<br>| Brier score | 0.2654         | 0.1608  |</pre><p>Look at that accuracy row again: <strong>0.7346 → 0.7551</strong>. Two points. If accuracy were the only number I reported, I’d have built a model that barely beats guessing. The real story is everywhere else:</p><p>ROC-AUC goes from exactly 0.5 (no discriminative power at all — mathematically guaranteed for a model that assigns every row the same score) to <strong>0.84</strong>. Recall on the class that actually matters — customers who churn — goes from <strong>0.00 to 0.77</strong>. The dummy model catches zero churners, ever, by definition. The real model catches three out of four.</p><p>And there’s a small, satisfying proof buried in the numbers: for the dummy model, PR-AUC (0.2654) and Brier score (0.2654) both land <strong>exactly</strong> on the test set’s churn rate (0.2654364…). That’s not a coincidence — it’s what the math says should happen when every prediction is an identical constant. Seeing the numbers actually match to the fifth decimal is a nice sanity check that nothing in the pipeline is silently broken.</p><p>One more check, unglamorous but important: the top feature by gain is <em>`Contract`</em> (0.314), followed by <em>`InternetService`</em> (0.138) and <em>`OnlineSecurity`</em> (0.119). These are exactly the drivers churn literature and prior BI dashboards I’ve built point to — month-to-month contracts churn more,<br>security/support add-ons correlate with retention. The model learned something explicable, not noise.</p><h3>What I’d do differently</h3><p>Being honest about the gaps is the point of this exercise, not something to gloss over:</p><ol><li><strong>No feature engineering:</strong> Every column went in close to raw — no tenure bucketing, no charge ratios, no interaction terms. The ceiling on this model is almost certainly higher than 0.84 ROC-AUC.</li><li><strong>No hyperparameter search: </strong><em>`n_estimators=300, max_depth=4, learning_rate=0.05`</em> are reasonable defaults for a dataset this size, chosen by hand, not by grid search or Optuna. That’s deliberate — the goal here was an honest anchor, not a leaderboard score — but it means this number has real headroom left in it.</li></ol><p>Both are legitimate targets for a revisit if a later chapter’s comparison ever hinges on squeezing more out of this specific baseline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUNPHK6V-ZBQvrmkBkv4og.png" /></figure><h3>Takeaways</h3><ol><li><strong>A dummy baseline costs one line of code and tells you whether your headline metric is even meaningful.</strong> Run it before you trust anything else.</li><li><strong>Accuracy is the wrong number to lead with on imbalanced data. </strong>ROC-AUC, PR-AUC, and recall on the minority class told the real story here; accuracy barely moved.</li><li><strong>This 0.84 ROC-AUC is now the number every LLM-based approach in this repo has to beat </strong>— not assume it beats, measure it.</li></ol><h3>Further reading</h3><p><a href="https://xgboost.readthedocs.io/en/stable/parameter.html">XGBoost Parameters - xgboost 3.3.0 documentation</a></p><p>states the exact rule this chapter’s <em>`scale_pos_weight`</em> uses: <em>“a typical value to consider: sum(negative instances) / sum(positive instances)”</em> — worth reading if you’ve got your own imbalanced classification problem and haven’t set this parameter deliberately yet.</p><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html">DummyClassifier</a></p><p>spell out exactly what it’s for: a required sanity check against, not a real model — the same role it played in this chapter.</p><h3>Coming in Chapter 2</h3><p>The next chapter still doesn’t touch a prompt in the <em>“ask an LLM to do my job”</em> sense — it’s about the mechanics underneath one: tokenization, sampling parameters, structured output, and quantization, run entirely on local Ollama models on a 15.4 GB laptop with a 2 GB integrated GPU.<br>Same rule as this chapter: every claim gets measured (latency, output size, quality) on this machine, not assumed from a spec sheet. If chapter one was <strong><em>“know your baseline before you trust a metric,”</em></strong> chapter two is <strong><em>“know what’s actually happening inside the black box before you trust its<br>output.”</em></strong> Same platform, same churn-and-complaints data underneath, one more layer down.</p><p><a href="https://github.com/EnigmaDevelop/ai-engineering">GitHub - EnigmaDevelop/ai-engineering: AI engineering portfolio: from data platforms to production LLM systems - chapter by chapter, evidence first</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2392bebfd8ee" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-data-platform-engineers-ai-rebuild-2392bebfd8ee">A Data Platform Engineer’s AI Rebuild</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Platform Engineer’s AI Rebuild : Chapter 2]]></title>
            <link>https://levelup.gitconnected.com/a-data-platform-engineers-ai-rebuild-chapter-2-4dc89662ae98?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dc89662ae98</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[structured-output]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 16:18:14 GMT</pubDate>
            <atom:updated>2026-07-10T16:18:14.625Z</atom:updated>
            <content:encoded><![CDATA[<h4>My JSON Schema Was 100% Valid — and Still Extracted the Wrong Thing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bCQHQqZn9DuZVkhpeQpNA.png" /></figure><p>Chapter 1 gave this whole project an anchor: a plain XGBoost churn model, measured against a majority-class dummy baseline, so every later chapter has a real number to beat instead of a vibe. Chapter 2 still doesn’t touch an LLM in the “<em>ask it to do real work</em>” sense. It’s about something more<br>basic, and something almost every LLM tutorial skips: before you build anything on top of a local model, <strong>what do you actually know about how it behaves</strong> — not what the docs say it does, but what it does, measured, on your own machine?</p><p>I ran four small experiments to find out: how tokenization actually counts your text, what temperature and <em>top_p </em>really do to an output, whether “<em>structured output</em>” means what I assumed it meant, and what quantization actually costs you. <strong>Three behaved exactly as documented. One didn’t, and<br>it’s the one worth building the rest of this article around.</strong></p><h3>The question that actually started this chapter</h3><p>I’ve been assuming — the way most people assume — that if I hand Ollama a JSON schema and ask it to extract a few fields from some text, and it comes back schema-valid every time, I can trust the extraction. That assumption is the whole reason structured output exists: it’s supposed to turn “<em>the<br>model probably formatted this right</em>” into “<em>the model definitely formatted this right.</em>” So I tested it against something more useful than a toy example: real CFPB consumer complaint narratives, which already carry an official ground-truth label — the complaint’s `<em>Product</em>` category, assigned by the<br>agency itself, not by me.</p><pre>SCHEMA = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;product&quot;: {&quot;type&quot;: &quot;string&quot;},<br>        &quot;issue_summary&quot;: {&quot;type&quot;: &quot;string&quot;},<br>        &quot;urgency&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;low&quot;, &quot;medium&quot;, &quot;high&quot;]},<br>        &quot;mentions_legal_action&quot;: {&quot;type&quot;: &quot;boolean&quot;},<br>    },<br>    &quot;required&quot;: [&quot;product&quot;, &quot;issue_summary&quot;, &quot;urgency&quot;, &quot;mentions_legal_action&quot;],<br>}<br>result = generate(model, prompt, options={&quot;temperature&quot;: 0}, format=SCHEMA)</pre><p>Fifteen real complaints in. Every single response parsed as valid JSON. Every single response had all four required fields, correctly typed. `<em>schema_valid_rate = 1.0</em>`, no exceptions, no retries.</p><p>Then I checked the actual content of the `<em>product</em>` field against CFPB’s own label for that complaint. It matched <strong>once. Out of fifteen</strong>.</p><h3>What “100% schema-valid” actually is — and isn’t</h3><p>This isn’t a prompting failure. Ollama’s structured output (<a href="https://ollama.com/blog/structured-outputs"><em>confirmed on Ollama’s own blog</em></a>) compiles your JSON schema into a grammar via<br>XGrammar and applies it <strong>during token sampling itself</strong> — at every generation step, any token that would break the schema gets its probability set to zero before the model can even consider it. That’s a hard, structural guarantee, the same category of thing as a database `<em>CHECK</em>` constraint: the value is mathematically guaranteed to be one of the permitted shapes. It is not a guarantee that the value is the <strong>correct </strong>one.</p><p>That’s exactly the gap that showed up. The schema said `<em>product</em>` must be a string — it never said which strings. So the model filled that slot with whatever it inferred “<em>product</em>” meant from context: the debt collector’s company name (`<em>D &amp; A Services</em>`), a generic label (`<em>Consumer Complaint</em>`), or a plausible-but-wrong category (<em>`Company Card` for a complaint CFPB had filed under `Credit card`</em>). <strong>Every one of those is schema-valid. </strong>Every one of those, if you were piping this into a dashboard or a routing rule, would silently misfile the complaint.</p><pre>| Metric                             | Value           |<br>|------------------------------------|-----------------|<br>| JSON parse rate                    | 1.000           |<br>| Schema-valid rate                  | 1.000           |<br>| Matched CFPB&#39;s real category label | 0.067 (1 of 15) |</pre><p>I’ve explained this exact gap to stakeholders before, just with a different vocabulary: a `<em>NOT NULL, CHECK (…)</em>` <strong>constraint on a column guarantees the value is one of the allowed options.</strong> It has never once told me the ETL job picked the <strong>right </strong>option for that row. Structured output is the same<br>promise, at the token level instead of the row level — and I’d been quietly assuming it was more than that.</p><h3>Three more things worth measuring before you trust a local model</h3><p><strong>Tokenization isn’t portable across model families.</strong> The same real complaint narrative tokenizes differently on Llama’s vocabulary than on Qwen’s — 96 tokens vs. 102 tokens for the same 430 characters, on one sample. And every single call pays a hidden cost before your prompt even starts: Ollama’s default chat template adds <strong>24 tokens</strong> of overhead on Llama, <strong>29 </strong>on Qwen, for a 6-word probe. If you’re budgeting context windows or per-call cost, “<em>roughly 4 characters per token</em>” is not a number you get to assume — it’s one you measure per model.</p><p><strong>Temperature and top_p do exactly what the math says, with one honest exception.</strong> `<em>temperature=0</em>` produced <strong>the same byte-identical sentence</strong>, eight times in a row, summarizing a real complaint. As temperature rises to <strong>1.5</strong>, output diversity (<em>measured as average word-overlap across </em><strong><em>8 </em></strong><em>runs</em>) falls off in a clean, monotonic line — <strong>0.516</strong> down to <strong>0.315.</strong> `<em>top_p=0.1</em>` shows the identical collapse from the other direction. The one place the tidy story breaks: `<em>top_p</em>` going from <strong>0.9</strong> to <strong>1.0</strong> doesn’t continue the downward trend (0.366 → 0.374) — a small, real, unglamorous exception, reported because it<br>happened, not smoothed over because a clean monotonic line would read better.</p><p><strong>Quantization’s size and speed tradeoff is real; its quality cost, on this test, wasn’t measurable. </strong>`llama3.2:3b` at fp16 is 3.2× the disk size of the default Q4_K_M tag, and costs 5.6× the cold-load time for less than half the tokens/sec (<em>16.2 → 7.1 tok/s</em>). That part is unambiguous. Whether fp16 extracted <strong>better </strong>structured data than Q4_K_M, on this same 15-narrative task — no: the smallest, fastest model actually scored marginally higher on the loose match-rate, which I’m reporting as “<em>too small a sample to mean anything</em>” rather than “<em>smaller is better.</em>” Eight complaints isn’t a quality<br>eval; it’s a sanity check that happened to run three times.</p><h3>What I’d do differently</h3><p><strong>The `<em>loose_product_match_rate</em>` metric used above is intentionally informal</strong> — a substring check against CFPB’s real label, not a scored evaluation. It’s enough to prove the shape-vs-correctness gap exists; it is not enough to rank models or quant levels against each other. That’s a real eval harness’s job, not a side effect of a structured-output smoke test.</p><p><strong>I didn’t tell the model the controlled vocabulary existed</strong> when I wrote the schema above — I suspected that was the real cause of the 6.7% number, not the model’s ceiling. I didn’t leave that as a suspicion. I ran it.</p><h4>I ran the fix — here’s what closing the gap actually cost</h4><p>Did naming the closed set actually work, and what does it cost to do it? Ten more real complaints, same model, `<em>temperature=0</em>`, one call with the original schema and one with `<em>product</em>` constrained to CFPB’s own 11 category names:</p><pre>SCHEMA_ENUM = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;product&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [<br>            &quot;Checking or savings account&quot;, &quot;Credit card&quot;,<br>            &quot;Credit reporting or other personal consumer reports&quot;,<br>            &quot;Debt collection&quot;, &quot;Debt or credit management&quot;,<br>            &quot;Money transfer, virtual currency, or money service&quot;, &quot;Mortgage&quot;,<br>            &quot;Payday loan, title loan, personal loan, or advance loan&quot;,<br>            &quot;Prepaid card&quot;, &quot;Student loan&quot;, &quot;Vehicle loan or lease&quot;,<br>        ]},<br>        # issue_summary, urgency, mentions_legal_action unchanged<br>    },<br>}</pre><p><strong>The accuracy guess held.</strong> Exact matches against CFPB’s real label went from 1 of 15 in the original run to 5 of 10 with `<em>enum</em>` added — a different sample size and a stricter metric (<em>exact match, not the original loose substring check</em>) — but the direction isn’t subtle. Tell the model which strings are legal instead of letting it infer “<em>product</em>” from context, and most of the gap closes.</p><p><strong>The cost guess I didn’t even think to make was wrong.</strong> I assumed a closed set of short category names would cost fewer output tokens than free text. It cost more: mean completion tokens rose from <strong>52.1</strong> to <strong>65.7 </strong>— about 26% more, in all ten pairs, no exceptions. CFPB’s real category names (“<em>Credit<br>reporting or other personal consumer reports</em>”) are longer than the vague, wrong words the unconstrained model reached for (“<em>Consumer Complaint,” “Company Card</em>”). Correct isn’t the same as short.</p><p><strong>One number landed exactly where the mechanism said it would.</strong> Prompt tokens didn’t move at all — <strong>139.8 in, 139.8 out</strong>, zero difference across all ten calls, `<em>enum</em>` or not. `<em>format</em>` travels to Ollama as its own field, never concatenated into the prompt text, so the schema — enum or no enum — never touches the input token stream. That’s not optimism; it’s what [<a href="https://ollama.com/blog/structured-outputs"><em>XGrammar’s grammar-compiled masking</em></a>] is supposed to do. I just hadn’t checked it held on my own machine until now.</p><pre>| Metric                            | Without `enum` | With `enum` |<br>|---                                |---             |---          |<br>| Exact match vs. CFPB label (n=10) | —              | 5/10        |<br>| Mean completion tokens            | 52.1           | 65.7 (+26%) |<br>| Mean prompt tokens                | 139.8          | 139.8 (±0)  |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUNPHK6V-ZBQvrmkBkv4og.png" /></figure><h3>Takeaways</h3><ol><li><strong>Schema-constrained structured output is a shape guarantee, enforced during token sampling, not a correctness guarantee. </strong>100% valid JSON and 6.7% semantically-right JSON are both true at the same time, and neither number tells you the other. Naming the closed set with `<em>enum</em>` closed most of that gap in a follow-up run — but for a real price, about 26% more completion tokens, not for free.</li><li><strong>Sampling parameters behave exactly as their math says they should</strong> — which means you can predict and design around them instead of treating temperature as a vague “<em>creativity dial.</em>”</li><li><strong>Every quality number in this chapter is a proxy, not an eval.</strong> That’s not a caveat to bury in a footnote — it’s the reason Chapter 3 exists.</li></ol><h3>Further Reading</h3><p>[<a href="https://ollama.com/blog/structured-outputs"><strong><em>Ollama’s own blog post on structured outputs</em></strong></a>] explains the JSON-schema-to-grammar compilation this chapter’s 100%-valid, 6.7%-correct result depends on — worth reading before you assume schema validity buys you more than it does.</p><p>[<strong><em>Holtzman et al.</em></strong>, “<a href="https://arxiv.org/abs/1904.09751"><strong><em>The Curious Case of Neural Text Degeneration</em></strong></a>”] is the paper that introduced nucleus (<em>top-p</em>) sampling, and explains exactly why greedy decoding and pure random sampling both fail — the reasoning behind the parameter this chapter measured directly.</p><h3>Coming in Chapter 3</h3><p>This chapter’s biggest finding — <strong>schema-valid isn’t the same as correct</strong> — is also its biggest unfinished business. `<em>loose_product_match_rate</em>` was good enough to prove the gap exists and nowhere near good enough to trust as a real metric. Chapter 3 builds the thing that actually closes that gap:<br>a golden-set eval harness with real ground truth, and an honest look at LLM-as-judge — including its own well-documented biases — measured against a boring TF-IDF baseline on the same CFPB data. Same rule as always: every claim gets measured on this machine, not assumed from a blog post. Chapter 2 asked “<strong>can I trust the shape of what comes back?</strong>” Chapter 3 asks the harder question underneath it: “<strong>can I trust what it means?</strong>”</p><p><a href="https://github.com/EnigmaDevelop/ai-engineering">GitHub - EnigmaDevelop/ai-engineering: AI engineering portfolio: from data platforms to production LLM systems - chapter by chapter, evidence first</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dc89662ae98" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-data-platform-engineers-ai-rebuild-chapter-2-4dc89662ae98">A Data Platform Engineer’s AI Rebuild : Chapter 2</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Low-Allocation Async Gateway for Transactional Ledger Operations]]></title>
            <link>https://levelup.gitconnected.com/designing-a-low-allocation-async-gateway-for-transactional-ledger-operations-308902c1e371?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/308902c1e371</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 10:50:18 GMT</pubDate>
            <atom:updated>2026-07-08T16:23:05.150Z</atom:updated>
            <content:encoded><![CDATA[<h4>An architectural analysis of connection pooling, streaming serialization, and CPU-bound throughput under strict microservice container limits</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t2igUNhMBSERQAFMj6A6Jw.jpeg" /></figure><h3>1. Architectural Intent &amp; The Concurrency Hook</h3><p>When exposing operational relational databases to upstream enterprise applications, backend frameworks confront strict concurrency limits. A common failure pattern appears when parallel internal microservices directly query a transactional cluster. <strong><em>This setup rapidly saturates database connection slots, leading to connection starvation and system-wide service disruptions.</em></strong> Furthermore, traditional approaches to data privacy — such as regular expression processing at the database layer or heavy object validation loops inside the application runtime — frequently trigger severe CPU throttling and latency degradation.</p><p>The objective of this architecture is to deploy and verify an application-level solution to these constraints: a proxy-less, asynchronous data access gateway positioned directly between a live transactional PostgreSQL 16 database and concurrent client workers. Isolated via Linux kernel cgroups restricted to exactly <strong>1 vCPU and 512MB RAM</strong>, this blueprint measures the operational throughput boundaries of an active connection pool matrix combined with low-allocation, string-slice data obfuscation.</p><p>Rather than capturing trivial single-request statistics, this stress tool evaluates system resilience against an intensive over-subscription scenario. We isolate a high-volume data streaming workload where <strong>40 simultaneous, parallel connection tasks</strong> concurrently attempt to extract a combined transactional payload of <strong>200,000 wide rows</strong> (5,000 rows per client) from our operational user table, utilizing a pool with a maximum capacity of 20 slots.</p><h3>2. Infrastructure &amp; Topology Invariants</h3><p>To maintain absolute replication precision and isolate networking constraints under resource starvation, the microservice matrix implements these physical bounds:</p><ul><li><strong>Compute Allocation:</strong> cpus: &#39;1.0&#39; applied independently to both the FastAPI gateway service and the PostgreSQL 16 container (enforced via Linux CFS scheduler constraints to eliminate compute bursting).</li><li><strong>Memory Allocation:</strong> memory: 512M for both container nodes (absolute physical memory allocation boundaries).</li><li><strong>Network Topology:</strong> Communication travels via an isolated virtual Docker bridge network, exposed on host port 8002.</li><li><strong>Data Layer Footprint:</strong> PostgreSQL 16 serves a persistent table populated with 100,000 user rows containing native transactional fields and unmasked PII data.</li></ul><h3>3. Operational Challenges &amp; Lifecycle Calibration</h3><p>System deployment required isolating and fixing a critical transactional lifecycle failure before achieving operational stability:</p><p>System.IO.IOException: Unable to read data from the transport connection: The connection was closed</p><h4>3.1 Resolving the Implicit Context Handle Leak</h4><p>The initial architectural implementation encapsulated the connection handle inside an implicit context manager within the async generator loop:</p><pre>async def async_masked_user_generator(pool: asyncpg.Pool):<br>    async with pool.acquire() as conn:<br>        async for row in conn.cursor(...):<br>            yield json.dumps(record) + &quot;\n&quot;</pre><p>Under this layout, the moment the entry point function returned FastAPI’s native StreamingResponse, the primary runtime context terminated. Python&#39;s async runtime interpreter misidentified the stream pause as an implicit closure, causing the context block to immediately return the active TCP socket back to the pool matrix.</p><p>As the network pipe attempted to stream subsequent chunk segments, the internal database server cursor hit an unallocated, closed transport connection handle, terminating the pipe. To resolve this lifecycle boundary drift, the architecture was refactored to enforce explicit connection acquisition loops coupled with rigid try/finally blocks, securing the active socket lifespan until the generator completely drains:</p><pre>async def async_masked_user_generator(pool: asyncpg.Pool):<br>    conn = await pool.acquire()<br>    try:<br>        async with conn.transaction():<br>            async for row in conn.cursor(...):<br>                yield json.dumps(record) + &quot;\n&quot;<br>    finally:<br>        await pool.release(conn)</pre><h3>4. Verified Empirical Metrics Matrix</h3><p>The automated multi-client stress tool blasted the application gateway with <strong>40 concurrent lines</strong> extracting 5,000 rows per line. Under this specific over-subscription workload (40 tasks hitting a maximum 20-slot pool), the hardware recorded these metrics during a single continuous test lifecycle:</p><ul><li><strong>Total Successful Transactions Processed:</strong> 40 / 40 Connection Lines</li><li><strong>Total Server Block Failures Registered:</strong> 0 Drops</li><li><strong>Total Wall Execution Time (Throughput Window):</strong> <strong>2.6852 seconds</strong></li><li><strong>Calculated Systemic Throughput Capacity:</strong> <strong>74,482 rows / second</strong></li><li><strong>Latency Percentile p50 (Median):</strong> 2,395.29 ms</li><li><strong>Latency Percentile p95 (Tail):</strong> 2,667.12 ms</li><li><strong>Latency Percentile p99 (Peak Tail):</strong> 2,671.62 ms</li><li><strong>Statistical Population Variance (σ²):</strong> 120,564.05 ms²</li><li><strong>Post-Test Connection Pool Status:</strong> pool_free_slots: 20 (0 Leaks Detected)</li></ul><h3>5. System-Level Explanation &amp; The Masking Paradigm</h3><p>The performance trajectory captured across this 200,000-row stress test reveals how connection scheduling and data obfuscation interact under tight resource limits.</p><h4>5.1 Inside the Backpressure Box: Asyncpg Queue Mechanics</h4><p>When 40 simultaneous network requests hit our 20-slot connection maximum limit, the gateway avoids socket exhaustion failures via internal driver boundaries. asyncpg maintains an internal FIFO (First-In, First-Out) scheduling queue built on top of native asyncio.Queue structures.</p><p>Requests exceeding max_size=20 are parked as unresolved asyncio.Future handles inside this memory array. This layout preserves FIFO ordering under load, executing tasks in arrival sequence. Once an active database cursor finishes processing and hits its finally block, the TCP slot is released back to the pool and re-allocated to the next waiting task within microseconds. The post-test health check verifying exactly pool_free_slots: 20 proves that the transaction boundaries scale and drain cleanly without dropping socket allocations or generating connection leaks.</p><h4>5.2 Low-Allocation Serving via String Segmentation</h4><p>Our data governance rule mandates that users authenticated as an Analyst must retrieve masked variations of sensitive fields. To eliminate the database CPU costs of relational regex operators and the memory allocations of bulk validation arrays, our gateway executes pointer-based string slicing straight inside the raw database cursor loop before data formatting occurs:</p><pre>at_idx = raw_email.find(&quot;@&quot;)<br>masked_email = raw_email[:1] + &quot;***&quot; + raw_email[at_idx:]<br>masked_cc = &quot;****-****-****-&quot; + raw_cc[-4:]</pre><p>This slicing method relies on fast pointer offsets in memory, minimizing allocation cycles. By isolating data frames via cursor micro-batches, the single-core CPU smoothly serializes the data streams, maintaining a stable processing line without triggering container crashes.</p><h4>5.3 Empirical Payload Showcases</h4><p>When an inbound network request presents an authorized token mapped to the Analyst role taxonomy, the streaming pipeline outputs the following obfuscated JSON serialization line securely:</p><pre>{<br>  &quot;user_id&quot;: 1,<br>  &quot;username&quot;: &quot;customer_id_1&quot;,<br>  &quot;email&quot;: &quot;u***@architects-ledger.com&quot;,<br>  &quot;credit_card&quot;: &quot;****-****-****-1001&quot;,<br>  &quot;country&quot;: &quot;TR&quot;,<br>  &quot;risk_score&quot;: 0.21<br>}</pre><h3>6. Architectural Boundaries &amp; Operational Assumptions</h3><p>To maintain engineering transparency, the scope and structural boundaries governing this benchmark must be explicitly defined.</p><h4>6.1 Separation of Concerns in Data Governance</h4><p>The optimized masking logic utilizes basic string segmentation primitives without format validation or malformed string exception handling. For instance, if a database record contains an email lacking an @ symbol, the find(&quot;@&quot;) routine returns -1, moving the memory slice pointer backward.</p><p>However, because this data gateway operates downstream over curated, persistent transactional storage, format conformity is treated as an upstream constraint. Enforcing format validation at this layer is an anti-pattern that violates the <strong>Separation of Concerns principle</strong>; data cleaning and schema validation are strictly delegated to upstream ETL/ELT pipelines, leaving the gateway focused entirely on high-throughput serialization performance.</p><h4>6.2 Instrumentation &amp; Serialization Boundaries</h4><p>The overall system bottleneck profiles a CPU-bound state during the serialization loop where raw rows are transformed into formatted JSON strings via json.dumps() over a single-core constraint (cpus: &#39;1.0&#39;). This processing execution profile accounts for the overall latency baseline, proving that serialization performance curves dictate pipeline throughput. Active database-side page cache hits, bare-metal network card physical interface limits, and low-level garbage collection (GC) iteration counts remain out of scope for this instrumentation layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdtljwJKXXwElb0jsejbuw.jpeg" /></figure><h3>7. Key Takeaways</h3><ul><li><strong>Isolate Compute and Allocation States:</strong> Shifting data masking logic to lean streaming filters within your API layer protects your primary transactional storage node from CPU starvation.</li><li><strong>Context Lifespans Dictate Async Pipeline Health:</strong> Asynchronous chunked generators running beneath stream-based response models can easily drop socket states if connection pools are managed implicitly. Ensure connection handles are acquired explicitly and bounded within absolute finally release blocks to guarantee long-running stability.</li><li><strong>Isolate Lightweight Client Requirements:</strong> Separating server-side modules from lightweight client packages preserves testing reproducibility across external deployment machines.</li></ul><h3>8. Next Phase Bridge</h3><p>Our Universal Data Gateway safely manages high-throughput pipelines over transactional pooling infrastructure with stable resource containment and zero connection leaks.</p><p>In our upcoming systems engineering iteration (<strong>Phase 3: AI Engineering</strong>), we will introduce dynamic autonomy to the metadata mesh. We will transcend static database fields and engineer a highly adaptive <strong>Semantic Metadata Search Infrastructure</strong> powered by <strong>LangGraph and Vector Databases</strong>. We will analyze how to deploy autonomous, self-correcting SQL graph state networks capable of dynamically reading unstructured business prompts, compiling schema definitions on the fly, and routing vector search arrays securely without breaking our rigorous hardware resource isolation bounds.</p><p><a href="https://github.com/EnigmaDevelop/the-architects-ledger">GitHub - EnigmaDevelop/the-architects-ledger</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=308902c1e371" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/designing-a-low-allocation-async-gateway-for-transactional-ledger-operations-308902c1e371">Designing a Low-Allocation Async Gateway for Transactional Ledger Operations</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Network Serialization Latency Under Throttled Microservice]]></title>
            <link>https://levelup.gitconnected.com/network-serialization-latency-under-throttled-microservice-5d162d141ddc?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d162d141ddc</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 10:48:23 GMT</pubDate>
            <atom:updated>2026-07-08T16:23:35.977Z</atom:updated>
            <content:encoded><![CDATA[<h4>Servicing 100,000 Rows on 1 vCPU and 512MB RAM: The gRPC Streaming Paradox</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WBXEoMHpE01YMbDeCVLyqg.jpeg" /></figure><h3><strong>1. Introduction: Executive Intent &amp; The Architectural Hook</strong></h3><p>Modern analytics pipelines often default to cloud warehouses for even modest batch workloads. That approach is useful when concurrency, elasticity, and shared access are primary operational requirements. However, it can become unnecessarily expensive and operationally heavy when the workload is bounded, periodic, and local to a single engineering workspace.</p><p>This technical paper is explicitly written <strong>for Senior Data Architects and Core Backend Engineers</strong> who <strong>design high-throughput data access layers but are exhausted by generic production benchmarks</strong>. In real-world microservice topologies, data storage tuning is only half the battle. A distinct, verifiable operational bottleneck occurs during the network serialization phase — the precise runtime loop where raw database arrays are compiled into wire formats like JSON or binary streams before entering the network pipe.</p><p>The primary objective of this blueprint is <strong>to analyze this serialization cost under a strict, resource-starved production sandbox</strong>. Using a container <strong>isolated via Linux kernel <em>cgroups </em>restricted</strong> to exactly <strong>1 vCPU and 512MB RAM,</strong> we benchmark the structural boundaries of <strong>FastAPI (REST)</strong> and <strong>gRPC</strong> (Protocol Buffers) when tasked with serving an analytical payload of <strong>100,000 discrete e-commerce rows</strong>.</p><p>Our controlled, multi-iteration benchmark uncovers a critical system design paradox that <strong>rejects industry generalizations:</strong></p><blockquote>under thin compute footprints, un-batched single-row gRPC Server Streaming degrades transaction efficiency by an order of magnitude due to low-level CPU starvation, while an optimized async REST JSON stream bypasses memory limits to conclude the exact same payload transfer smoothly.</blockquote><h3><strong>2. Infrastructure &amp; Topology Invariants</strong></h3><p>To ensure absolute replication precision and isolate internal serialization memory allocation patterns, the entire gateway environment was isolated within strict compute boundaries:</p><ul><li><strong>Compute Limit:</strong> cpus: ‘1.0’ (Hard thread execution ceiling via the Linux CFS scheduler).</li><li><strong>Memory Limit:</strong> memory: 512M (Absolute container memory allocation envelope).</li><li><strong>Data Source:</strong> Payloads were retrieved via shared read-only mounts pointing directly to the 10,000,000 row DuckDB database file constructed in <a href="https://medium.com/@enigmaticsolver/local-first-storage-compute-separation-346dd477a840"><em>Phase 1.2</em></a>.</li></ul><h3><strong>3. Operational Challenges &amp; Debugging Cycles</strong></h3><p>System deployment required isolating and fixing two critical lower-level runtime and compilation failures before matching execution parity:</p><h4><strong>3.1 The Google Protobuf Gencode/Runtime Major Version Drift</strong></h4><p>During early container boot sequences, the gRPC services terminated with an explicit <em>google.protobuf.runtime_version.VersionError.</em> The root cause was an environment drift between the development host and the container runtime layer. The host machine (running Windows with Python 3.13) compiled the .proto schema utilizing the newest tools, stamping a Major Version 6 (Gencode 6.33.5) signature onto the generated code. However, the application container initialized with a requirements.txt locking the base runtime package to protobuf==5.27.2 (Major v5).</p><p>Because backwards binary deserialization guarantees are omitted between Major v5 and v6, <strong>the container initialization aborted before opening socket connections</strong>. To resolve this runtime drift, t<strong>he dependency grid was refactored to align protobuf==5.29.3 </strong>within the image. Additionally, an in-container compilation routine was <strong>injected directly into the Docker entrypoint command</strong>, automating schema generation synchronization at startup.</p><h4><strong>3.2 Dynamic Python Path Resolution</strong></h4><p>Even with synchronized runtimes, both gRPC containers executed a hard <em>Exited (1)</em> startup abort pattern. Because we split our project directories into distinct <em>monolithic_bulk/</em> and <em>streaming_pipeline/</em> modules <strong><em>to ensure educational audit reproducibility</em></strong>, the internal scripts executed nested relative imports.</p><p>When Python initialized the gRPC server process directly inside the container subprocess, the virtual directory interpreter could not resolve the absolute root directory structure, triggering an immediate <em>ModuleNotFoundError</em>. The solution required <strong><em>explicitly injecting a programmatic sys.path.append enforcer at the top of each server file</em></strong>, binding the execution path directly to the container’s absolute context.</p><h3><strong>4. Methodology &amp; Quantitative Memory Tracking</strong></h3><p>To establish strict mathematical grounds for our analysis, the memory allocation behaviour of <em>Pydantic </em>models was tracked against raw data footprint definitions. Microsecond memory structures were validated internally using Python’s native <em>tracemalloc </em>utility, while aggregate container heap metrics were extracted directly from the host operating system via Linux cgroup memory stats <em>(/sys/fs/cgroup/memory/memory.usage_in_bytes).</em></p><ul><li><strong>Native Storage Footprint:</strong> Within DuckDB’s C++ native columnar array buffer, the targeted 100,000 transactional rows occupy approximately <strong><em>64 to 80 bytes per row</em></strong>, aggregating a clean memory footprint baseline of 6.4 MB to 8.0 MB.</li><li><strong>Pydantic Object Instantiation:</strong> When converted into standard Python objects managed by Pydantic’s BaseModel, each instantiated row structure forces the allocation of localized internal dictionary tables (<em>_dict</em>_), data-type metadata frames, and memory pointer arrays. <em>tracemalloc </em>instrumentation tracks that this layer <strong><em>increases the memory allocation</em></strong> profile of a <strong><em>single row entry to 700 to 850 bytes</em></strong> inside the virtual machine runtime.</li><li><strong>The Allocation Threshold:</strong> Consequently, processing 100,000 records simultaneously via monolithic bulk methods demands an immediate memory reservation spike between 75 MB to 85 MB. Inside a tightly bounded 512MB container which already carries base Python runtime overheads, <strong><em>this aggressive allocation pattern exhausts the available heap space, resulting in a physical crash.</em></strong></li></ul><p>The performance metrics below represent a <strong><em>50-iteration continuous execution loop</em></strong> managed by an automated benchmark client driver. The statistical variance (σ²) across all successful target endpoints was calculated using the population variance formula over the continuous latency array (N=50):</p><p>σ² = (1 / N) × Σ (xᵢ − μ)²</p><p>Where xᵢ profiles the instantaneous latency in milliseconds for loop i, and μ represents the true arithmetic mean of the iteration window.</p><h3><strong>5. Verified Empirical Metrics Matrix</strong></h3><pre>TEST              | Transport Style         | Status            | p50        | p95        | p99         | Variance<br>------------------|-------------------------|-------------------|------------|------------|-------------|--------------<br>REST Bulk         | Monolithic JSON Packet  | Crashed (500)     | —          | —          | —           | N/A (OOM)<br>gRPC Bulk         | Monolithic Binary       | Successful (Up)   | 319.16 ms  | 370.66 ms  | 413.56 ms   | 716.96 ms²<br>REST Stream       | Chunked JSON Async      | Successful (Up)   | 765.66 ms  | 934.41 ms  | 982.63 ms   | 3,659.18 ms²<br>gRPC Stream       | Sequential Binary       | Successful (Up)   | 16,703.44s | 18,932.23s | 19,518.28s  | 822,277.87 ms²</pre><h3><strong>6. System-Level Explanation &amp; The Streaming Paradox</strong></h3><p>Analyzing the divergence between these execution lines reveals how memory boundaries and thread management interact under constrained compute footprints. Lower-level context-switching metrics and thread states were tracked using <em>host-level pidstat -w </em>instrumentation.</p><h4><strong>6.1 The Pydantic Allocation Ceiling (REST Bulk Failure)</strong></h4><p>The <em>Monolithic REST Bulk</em> connection drops during the initialization loop. As demonstrated by our memory tracking benchmarks, forcing a large nested array into <em>Pydantic </em>structures under an enforced <strong>512MB container ceiling causes the allocation boundary to exhaust the remaining heap space</strong>. This triggers a native Python runtime <em>MemoryError</em>, terminating the active <em>Uvicorn </em>worker thread and outputting an internal <em>HTTP 500</em> <em>status </em>back to the client.</p><h4><strong>6.2 The gRPC Bulk Dominance Curve</strong></h4><p>Server side, the <em>Monolithic gRPC Bulk</em> endpoint completed the entire 100,000-row packaging matrix with a median latency of <strong><em>319.16 ms</em></strong> — <strong><em>outperforming the optimized REST Streaming model by 2.4x</em></strong>.</p><p>By applying explicit typecasting <em>(int(), float(), str()) </em>directly onto the database array data prior to <em>Protocol Buffer</em> parsing, <strong><em>the pipeline avoids intermediate text translation wrappers.</em></strong> The underlying C-extension layer packs the data directly into a dense binary <em>Protocol Buffer </em>message frame and flushes it straight down the host socket buffer. The <strong><em>low statistical variance of 716.96 ms²</em></strong> proves that <strong>monolithic packets maintain high stability if written in compact binary wire formats that preserve CPU cache locality.</strong></p><h4><strong>6.3 The Server Streaming gRPC Paradox (The 16-Second Bottleneck)</strong></h4><p>The most important architectural takeaway of this audit lies in the significant performance collapse of TEST 4: <em>gRPC Server Streaming</em>, which registered a <strong><em>peak tail latency (p99) of 19,518.28 ms</em></strong> and a massive statistical variance of 822,277.87 ms². Standard data engineering literature implies that streaming structures are universally superior for processing vast record sets. <strong>These baseline numbers reject that generalization in low-compute, containerized topologies.</strong></p><p>When <em>gateway_grpc_stream.py</em> executes its async generator loop, it yields a raw data row object individually <em>(yield orders_pb2.OrderRow).</em> The underlying <em>gRPC C-core</em> engine must capture every single-row entity, wrap it within independent <em>HTTP/2</em> transport data frames, execute continuous <em>TCP</em> packet network validations, and push them down the pipe.</p><p><strong><em>Because the service is restricted to a single core (cpus: ‘1.0’)</em></strong>, yielding 100,000 discrete messages individually <strong><em>forces the single CPU thread to process continuous state transitions and network packet handshakes</em></strong> rather than processing synchronous batch streams. <em>Host-level pidstat </em>metrics <strong>verify extreme <em>CPU Starvation</em> and voluntary thread context-switching overhead</strong>. The processor spends its microsecond allocation cycles managing state transitions and network packet handshakes rather than processing data streams, inflating statistical variance to 822,277.87 ms² without triggering an Out-Of-Memory failure.</p><h4><strong>6.4 The REST Async Stream Settlement</strong></h4><p>By utilizing <em>FastAPI’s StreamingRespons</em>e backed by an explicit newline<em> (\n)</em> chunk serialization wrapper, <strong><em>we bypassed bulk memory instantiation entirely.</em></strong> The query engine pulled micro-batches via f<em>etchmany(2000)</em> and continuously flushed raw string lines directly into the <em>HTTP </em>channel. <strong><em>Because text manipulation avoids gRPC’s native single-row C-struct packaging lifecycle</em></strong>, the single-core CPU smoothly serialized the data streams in 765.66 ms with a controlled variance of 3,659.18 ms².</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdtljwJKXXwElb0jsejbuw.jpeg" /></figure><h3><strong>7. System Selection Blueprint &amp; Key Takeaways</strong></h3><p>This benchmark converts high-level API design arguments into predictable system selection criteria:</p><ul><li><strong>Serialization Costs Outweigh Query Costs:</strong> In constrained microservice nodes, the processing cost of compiling data for the wire framework is higher than pulling it from an optimized database. If you force extensive <em>Pydantic </em>nested array transformations over wide datasets, your application servers will crash long before your storage engine does.</li><li><strong>Beware of Single-Row gRPC Streaming on Low Compute:</strong> Streaming is not a universal performance lever. If you stream massive record counts individually over native <em>gRPC </em>services without executing custom micro-batching or chunking abstractions, context-switching overhead will completely stall a single-core application container.</li><li><strong>The Production Alignment Rule:</strong></li></ul><p><strong><em>Deploy gRPC Monolithic Bulk</em></strong> if your data payloads are bounded under 100k rows, memory limits are stable, and you require the fastest transport speeds via native binary serialization.</p><p><strong><em>Deploy REST Async JSON Streaming</em></strong> if you must deliver wide datasets over resource-starved microservices (512MB) without risk of memory overflow, and your consuming clients require standard human-readable formats.</p><h3><strong>8. Next Phase Bridge</strong></h3><p>We have mapped low-level storage <a href="https://medium.com/@enigmaticsolver/storage-subsystem-internals-under-strict-resource-isolation-41a0da9e2d5a"><em>primitives inside Fintech clusters</em></a>, optimized local serverless transformations <a href="https://medium.com/@enigmaticsolver/local-first-storage-compute-separation-346dd477a840">over e-commerce parquet lakes,</a> and fully quantified the core network serialization walls of API gateways.</p><p>Yet, our Universal Data Gateway currently operates over static data. In the upcoming architectural iteration (<em>Phase 2: Step 2</em>), we will introduce active production reality back to the data mesh. <strong><em>We will connect our Universal Gateway to a live, transactional PostgreSQL cluster and configure a production-grade Asynchronous Connection Pooling Infrastructure.</em></strong> We will document how to manage dynamic client routing, isolate connection leaks under heavy request pressure, and safely implement Row-Level and Column-Level Data Masking Policies inside our async python endpoints to enforce enterprise data governance without sacrificing network throughput.</p><p><em>The full multi-endpoint container topologies, Protobuf compilation matrices, and reproducible benchmark client drivers are entirely open-sourced on my systems engineering log on GitHub.</em></p><p><a href="https://github.com/EnigmaDevelop/the-architects-ledger">GitHub - EnigmaDevelop/the-architects-ledger</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d162d141ddc" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/network-serialization-latency-under-throttled-microservice-5d162d141ddc">Network Serialization Latency Under Throttled Microservice</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automation Evolution Chapter 4: Apache Airflow]]></title>
            <link>https://medium.com/@enigmaticsolver/automation-evolution-chapter-4-apache-airflow-dc078df86223?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc078df86223</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[workflow-orchestration]]></category>
            <category><![CDATA[dag]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 13:07:18 GMT</pubDate>
            <atom:updated>2026-06-17T13:07:18.805Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enterprise Workflow Orchestration and Environment Isolation</h4><p>Your data pipeline works perfectly inside decentralized task worker nodes — <strong>until your orchestrations demand deterministic and fully traceable workflow visibility</strong>.</p><p>In <a href="https://medium.com/@enigmaticsolver/automation-evolution-chapter-3-celery-beat-7692fb6c2370">Chapter 3,</a> we broke the single-node monolith of our pipeline by introducing Celery Beat and a Redis message broker. This successfully decoupled our ingestion engine into a predictable producer-broker-consumer topology, enabling horizontal scaling across stateless worker nodes.</p><h4>The Operational Breakdown</h4><p>Yet, as data volumes scale and multi-team infrastructures take shape, simple task-distribution frameworks hit a definitive operational ceiling. This production block stems from three systemic architectural limitations:</p><ul><li><strong>Topology Blindness:</strong> Celery is fundamentally an execution engine. It excels at distributing tasks, but it is architecturally blind to workflow topography. It cannot natively enforce complex task sequences, conditional branches, or global failure alerting paths without extensive custom engineering.</li><li><strong>Dependency Management Gap:</strong> Forcing shared analytical models and third-party database drivers into the same global environment as the scheduling orchestrator creates severe runtime version conflicts.</li><li><strong>Observability Collapse:</strong> Diagnosing operational failures across hundreds of concurrent task processes by manually parsing raw text container log streams is a clear metadata bottleneck.</li></ul><p>To resolve these tracking and dependency constraints, <strong>enterprise data stacks must transition from simple task execution engines to a dedicated Data Workflow Orchestrator</strong> like Apache Airflow. Airflow is not a data processing engine — <strong>it is a distributed state coordination system.</strong></p><h3>Architectural Identity Card: Chapter 4</h3><ul><li><strong>Cost: </strong>High infrastructure compute cost (Requires dedicated Scheduler, Webserver, and Metadata Database nodes).</li><li><strong>Company Profile:</strong> Mid-market scale-ups, expanding enterprises, and central data platform teams.</li><li><strong>Team Size:</strong> 2–5 Data Platform / Infrastructure Engineers maintaining the central control plane.</li><li><strong>Maturity:</strong> 10+ Years (The global enterprise standard for programmatic DAG orchestration).</li><li><strong>Alternatives:</strong> Prefect (Modern code-first), Dagster (Asset-oriented), Temporal (Microservice state machine).</li><li><strong>When NOT to Use:</strong> Simple single-script cron intervals, lightweight microservice background operations, or resource-constrained environments where central infrastructure overhead cannot be justified.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IX9IM80ivV95KUmSjxQKxQ.jpeg" /></figure><h3>1. The Core Purpose: Control Plane vs. Data Plane</h3><p>The primary objective of Chapter 4 is <strong>to separate our data pipeline logic from our scheduling mechanism while introducing Directed Acyclic Graph</strong> (DAG) <strong>execution frameworks</strong>. To guarantee structural stability, we divide our system into a clear dual-layer architecture:</p><ul><li><strong>The Control Plane:</strong> The core Apache Airflow environment, managing workflow states, scheduling heartbeats, and metadata transaction logs.</li><li><strong>The Data Plane:</strong> The localized execution space containing <a href="https://github.com/EnigmaDevelop/de-scheduling-evolution/tree/master/shared">our immutable business logic layer</a> (shared/ directory modules), which handles the extraction, Pydantic parsing, and PostgreSQL transactional updates.</li></ul><p>This separation ensures that orchestration concerns never interfere with data processing semantics.</p><h3>2. The Containerized Distributed Ingestion Stack</h3><ul><li><strong>Orchestration Core:</strong> Apache Airflow 2.10.1 (Utilizing Python 3.11 to guarantee enterprise lifecycle stability).</li><li><strong>State Repository:</strong> PostgreSQL 16 (Isolated airflow_metadata database instance).</li><li><strong>Execution Boundary:</strong> Container-Native User-Space Process Isolation.</li><li><strong>Core Data Target:</strong> Both Airflow metadata and application data reside on the same PostgreSQL instance, but are strictly separated at the database level. This approach optimizes resource usage in constrained local environments without compromising logical isolation.</li></ul><h3>3. The Dependency Trap and the Environment Isolation Pattern</h3><p>A common pitfall when deploying enterprise orchestrators is environmental contamination. <strong>Apache Airflow relies on a complex web of internal packages to power its web server and scheduler.</strong> Forcing business logic dependencies (like our modern validation schemas or specific database drivers) into the same global environment triggers immediate package collisions (ResolutionImpossible faults).</p><p>To maintain a production-ready state without compromising our data contract, this step implements an Isolated Environments Architecture Pattern. Airflow’s core environment is left completely unpolluted.</p><p>This pattern can be generalized as a <strong><em>Dual Python Runtime Pattern</em></strong>: one for orchestration, one for execution. Our business ingestion layer is isolated inside an internal, separate virtual environment (/opt/airflow/pipeline_venv) built directly during the container compilation phase:</p><pre># 04-airflow/Dockerfile<br>FROM apache/airflow:2.10.1-python3.11<br>USER root<br>RUN apt-get update &amp;&amp; apt-get install -y --no-install-recommends build-essential &amp;&amp; apt-get clean &amp;&amp; rm -rf /var/lib/apt/lists/*<br>USER airflow<br>RUN python -m venv /opt/airflow/pipeline_venv<br>COPY --chown=airflow:root shared/ /opt/airflow/pipeline_root/shared/<br>RUN /opt/airflow/pipeline_venv/bin/pip install --no-cache-dir pydantic==2.10.6 sqlalchemy==2.0.30 tenacity==8.5.0 structlog==24.4.0 python-dotenv==1.0.1 psycopg2-binary==2.9.10 alembic==1.13.1</pre><p>By cleanly separating these environments, our underlying business code remains completely unchanged, ensuring absolute variable consistency across the entire repository evolution.</p><h3>4. Directing Workflows via the BashOperator Bridge</h3><p>Our workflow definitions leverage a dedicated BashOperator bridge. Instead of executing Python functions inside the orchestrator&#39;s primary thread pool, Airflow triggers a clean operating system subprocess. This subprocess utilizes our isolated internal Python binary to execute the shared loader module, keeping the runtime contexts strictly separated:</p><pre># 04-airflow/dags/weather_dag.py<br>LAUNCH_COMMAND = &#39;&quot;/opt/airflow/pipeline_venv/bin/python&quot; -m shared.loader&#39;<br><br>with DAG(<br>    &#39;de_evolution_weather_orchestration&#39;,<br>    default_args=default_args,<br>    description=&#39;Enterprise Weather Ingestion Pipeline via Container-Isolated Bash Workflows&#39;,<br>    schedule=&#39;* * * * *&#39;, # Explicitly scheduled to fire on every single minute mark<br>    catchup=False,<br>    max_active_runs=1,<br>    tags=[&#39;production&#39;, &#39;stateless_bash_orchestration&#39;]<br>) as dag:<br><br>    orchestrate_isolated_pipeline = BashOperator(<br>        task_id=&#39;execute_container_isolated_shared_layer&#39;,<br>        bash_command=LAUNCH_COMMAND,<br>        env={**os.environ, &#39;PYTHONPATH&#39;: &#39;/opt/airflow/pipeline_root&#39;}<br>    )</pre><p>This configuration introduces a robust compute protection shield.</p><p><em>Crucial Architectural Insight:</em> <strong>This isolation is process-level, not container-level</strong>, meaning resource contention can still occur within the same container boundary. This makes the approach lightweight but not fully resource-isolated. However, if our extraction code encounters an unexpected API failure, the crash is trapped entirely within that local shell process.</p><h3>5. Enterprise Observability and Operational Control</h3><p>Once the ingestion pipeline is integrated into Airflow’s state machine, our operational telemetry shifts from unstructured text logs to granular, real-time control metrics across three pillars of enterprise visibility:</p><h4>A. Pillar 1: State Tracking (Central Automation Panel)</h4><p>The main tracking panel validates that our automated crontab schedule is actively monitored by the scheduler. Historical execution runs are computed cleanly without data duplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4XAAPPQ6cxA9fudOfDVkw.png" /></figure><h4>B. Pillar 2: Temporal Visibility (The Execution Gantt)</h4><p>The execution Gantt metrics confirm the efficiency of our isolation pattern. Because the heavy computational parsing is externalized to our data plane venv, this creates a counterintuitive but powerful effect: Airflow schedules and monitors the task without directly executing its compute workload. The task instance execution window blocks Airflow’s core memory space for a mere fraction of a second (Run Duration: 00:00:01).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-XaON078LcbfNjQfYMvYw.png" /></figure><h4>C. Pillar 3: Failure Auditability (The Centralized Event Log)</h4><p>Airflow’s state repository acts as an ironclad ledger. If a database schema bottleneck occurs, the error is immediately logged as a dagrun_failed instance. As soon as the infrastructure resolves the block, subsequent iterations return to a stable running -&gt; success state transition cycle, tracked down to the exact millisecond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LliZiWorhyU26Ej10oWAA.png" /></figure><p>An execution audit against our live production PostgreSQL database demonstrates completely continuous real-world time-series data storage with zero synthetic noise, capturing the real-world 10-minute caching thresholds of the upstream API gateway :</p><pre>(venv) PS C:\...\de-scheduling-evolution\04-airflow&gt; docker exec -it de_postgres psql -U de_user -d de_scheduling -c &quot;SELECT city, timestamp, temp, weather_main, left(raw::text, 60) FROM weather_records ORDER BY created_at DESC LIMIT 5;&quot;<br><br>   city   |       timestamp        | temp  | weather_main |                             left                            <br>----------+------------------------+-------+--------------+--------------------------------------------------------------<br> Istanbul | 2026-06-17 08:51:22+00 | 25.34 | Clouds       | {&quot;coord&quot;: {&quot;lon&quot;: 28.9833, &quot;lat&quot;: 41.0351}, &quot;weather&quot;: [{&quot;id<br> Istanbul | 2026-06-17 08:41:06+00 | 25.34 | Clouds       | {&quot;coord&quot;: {&quot;lon&quot;: 28.9833, &quot;lat&quot;: 41.0351}, &quot;weather&quot;: [{&quot;id<br> Istanbul | 2026-06-17 08:31:55+00 | 25.61 | Clouds       | {&quot;coord&quot;: {&quot;lon&quot;: 28.9833,&quot;lat&quot;: 41.0351}, &quot;weather&quot;: [{&quot;id</pre><h3>6. Failure Mode Matrix &amp; Architectural Severity</h3><p>By shifting pipeline coordination logic to Airflow’s transactional database layer, our failure matrix centers around state repository availability, filesystem processing bottlenecks, and core architectural engines derived from standard community production guidelines:</p><p><strong>Metadata Database Storage Exhaustion</strong></p><ul><li><strong>Architectural Impact:</strong> Airflow cannot log state transitions or save heartbeat data.</li><li><strong>Severity:</strong> System-wide halt.</li><li><strong>Architectural Mitigation:</strong> Enforce aggressive log rotation policies, prune historical database task instances via automated clean DAGs, and set up continuous storage alerts.</li></ul><p><strong>DAG Parsing Overload</strong></p><ul><li><strong>Architectural Impact:</strong> Heavy filesystem processing or inline imports consume CPU loops, dropping scheduler heartbeats.</li><li><strong>Severity:</strong> Scheduling degradation.</li><li><strong>Architectural Mitigation:</strong> Implement modular DAG designs, reduce heavy runtime dynamic imports, and safely optimize the min_file_process_interval configuration.</li></ul><p><strong>Subprocess Resource Contamination</strong></p><ul><li><strong>Architectural Impact:</strong> Running heavy ingestion logic inside local worker subprocesses consumes shared local RAM pools.</li><li><strong>Severity:</strong> Resource contention.</li><li><strong>Architectural Mitigation:</strong> Transition from local shell commands to container-native operators like <em>DockerOperator </em>or <em>KubernetesPodOperator </em>to externalize all resource usage.</li></ul><h3>7. Real-world Production Use-Cases for Airflow Mappings</h3><h4>A. Telecommunications Data Infrastructure (Large Scale Telecom Ingestion)</h4><ul><li><strong>ARPU</strong> (<em>Average Revenue Per User</em>) <strong>Batch Calculations:</strong> Orchestrating heavy, multi-stage processing dependencies where subscriber session metrics must be locked and processed sequentially across varying account boundaries at night.</li><li><strong>Churn Prediction Feature Aggregation Pipelines:</strong> Executing daily analytical calculations that pull historical usage metrics, verify format integrity, and seed predictive algorithms.</li><li><strong>Network Usage Data ELT (T+1 Reporting):</strong> Scheduling absolute, time-bounded data extractions from low-level call detail records (CDR) and routing them to target analytical tables.</li></ul><h4>B. Fast-Moving Consumer Goods &amp; Enterprise Retail (FMCG Logistics)</h4><ul><li><strong>Distribution Channel Inventory ELT:</strong> Syncing complex store and warehouse inventory updates to keep stock numbers aligned across global point-of-sale endpoints.</li><li><strong>Demand Forecasting Feature Stores:</strong> Managing historical batch lookups to train automated forecasting systems.</li><li><strong>Retail Partner Settlement Pipelines:</strong> Running complex financial ledger pipelines where partner data must complete processing steps before triggering auditing trails.</li></ul><h3>8. The Hard Wall of Enterprise Complexity: Why We Must Leave</h3><p>By establishing this isolated <em>BashOperator </em>bridge under the <strong><em>Dual Python Runtime Pattern</em></strong>, our ingestion loop has achieved maximum operational visibility, running as a highly durable batch orchestration pipeline backed by centralized audit trails and automated failure recovery rules.</p><p>But the moment your business model demands real-time data streaming or agile microservice scaling, this framework hits a definitive wall. This limitation stems from two structural core constraints: <strong>Airflow relies entirely on Pull-Based Scheduling</strong> and <strong>Static File-Based DAG Definitions.</strong> This is not a tooling limitation — it is a paradigm mismatch.</p><ul><li><strong>The Infrastructure and Operational Weight:</strong> Airflow requires a permanent relational database, a web server portal, and a dedicated scheduler daemon just to execute a single-task pipeline. This massive structural footprint is highly inefficient for lightweight, event-driven microservices that need to deploy serverless ingestion workflows instantly on demand.</li><li><strong>The Rigidity of Static File Parsing Loop:</strong> Airflow evaluates workflows by periodically scanning file paths on a fixed background loop. If your data architecture requires dynamic, runtime task generation triggered instantly by an external event (such as a user-driven API call or a cloud storage upload), handling these dynamic execution paths natively under Airflow becomes incredibly complex.</li></ul><p><strong><em>To overcome these static batch limits and establish a modern platform</em></strong> that pairs enterprise observability with a lightweight, code-first, event-driven design, we must shift our scheduling paradigm.</p><p>This brings our enterprise batch tracking phase to its end, setting our course for <strong>Chapter 5 — Prefect</strong>.</p><p><em>You can find the full project and implementation details in my</em><strong><em> </em></strong><em>de-scheduling-evolution</em><strong><em> </em></strong><em>GitHub repository.</em></p><p><a href="https://github.com/EnigmaDevelop/de-scheduling-evolution">GitHub - EnigmaDevelop/de-scheduling-evolution</a></p><p><em>Upvote if you liked this — it helps more data engineers find it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc078df86223" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automation Evolution Chapter 3 : Celery Beat]]></title>
            <link>https://medium.com/@enigmaticsolver/automation-evolution-chapter-3-celery-beat-7692fb6c2370?source=rss-6e4da2227863------2</link>
            <guid isPermaLink="false">https://medium.com/p/7692fb6c2370</guid>
            <category><![CDATA[celery]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[backend-architecture]]></category>
            <dc:creator><![CDATA[Oğuz Kaan Mavice]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 01:13:07 GMT</pubDate>
            <atom:updated>2026-06-17T01:13:07.706Z</atom:updated>
            <content:encoded><![CDATA[<h4>Breaking the Monolith via Asynchronous Task Queues</h4><p>Your pipeline works perfectly inside a single container instance — <strong>until you scale it.</strong></p><p>In <a href="https://medium.com/@enigmaticsolver/automation-evolution-chapter-2-apscheduler-20d66554324f">Chapter 2</a>, the ingestion loop was successfully containerized by pulling the scheduling directives out of the <em>Linux POSIX</em> kernel and embedding them straight into the application runtime boundary using <em>APScheduler</em>. It was a major step forward for cross-platform portability and lifecycle visibility. However, this tight integration pushed the technical design into an inescapable operational bottleneck: <strong>The Single Process Constraint</strong>.</p><p>When the scheduling thread shares the exact same memory footprint and execution process as the extraction logic and database connection factories, <strong>horizontal scaling becomes impossible</strong>. Deploying multiple duplicate instances of that parent container to handle increased traffic causes every instance to spawn an isolated background scheduling thread.</p><p>These uncoordinated threads simultaneously trigger requests to the upstream <em>OpenWeatherMap API</em> at the exact same minute index. The immediate results are severe rate-limit throttling, security credential blocks, and catastrophic transaction collisions inside the PostgreSQL storage engine.</p><p>At this stage, <strong>the production architecture must be decoupled completely</strong>. <strong>The Timekeeper</strong> (<em>The Scheduler</em>) must be split away from the <strong>Compute Fleet</strong> (<em>The Workers</em>). This is the precise engineering rationale behind <strong>introducing Celery Beat backed by a centralized Redis Message Broker</strong>.</p><h3>Architectural Identity Card: Chapter 3</h3><ul><li><strong>Cost:</strong> Low operational compute cost (Requires an isolated Redis container instance).</li><li><strong>Company Profile: </strong>Mid-market startups, rapidly expanding scale-ups, and distributed microservice clusters.</li><li><strong>Team Size:</strong> 1–3 Data/Backend Engineers managing decoupled services.</li><li><strong>Maturity:</strong> 12+ Years (The industry standard for asynchronous Python task distribution).</li><li><strong>Alternatives:</strong> Huey, RQ (Redis Queue), Dramatiq (Modern low-boilerplate alternatives).</li><li><strong>When NOT to Use:</strong> Heavy enterprise workflows requiring complex cross-task data dependencies (DAGs), deep programmatic lineage tracing, or native graphical workflow mapping.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgXOgHki_HpvxBQhgvc9pA.png" /></figure><h3>1. The Core Purpose</h3><p>The objective of Chapter 3 is <strong>to shift the ingestion architecture from a single-node monolith to a fully decoupled, distributed task processing layout.</strong> By stripping the execution logic entirely out of the scheduling daemon, we establish a stateless worker topology that can scale horizontally across thousands of virtual nodes without risking duplicate task invocation or API key collisions.</p><h3>2. The Containerized Distributed Ingestion Stack</h3><ul><li><strong>Scheduling Orchestrator:</strong> Celery Beat 5.4.0 (A single, centralized timekeeping daemon).</li><li><strong>Message Broker Layer:</strong> Redis 7.0 (Chosen over RabbitMQ for its low-latency in-memory transport with minimal operational overhead).</li><li><strong>Compute Workers:</strong> Celery Workers 5.4.0 (Stateless, independent processing nodes).</li><li><strong>Data Sink Target:</strong> PostgreSQL 16 (Relational OLTP Database via <a href="https://github.com/EnigmaDevelop/de-scheduling-evolution/tree/master/shared">de_evolution_network</a>).</li><li><strong>Schema Evolution Enforcer:</strong> Alembic + SQLAlchemy 2.0 ORM (Programmatic synchronization on worker startup).</li><li><strong>Data Boundary Validator:</strong> Pydantic v2 (Strict validation of upstream JSON parameters via universal pre-compiled wheels).</li></ul><h3>3. Execution Model: The Producer-Broker-Consumer Split</h3><p>The architecture no longer executes as a single block of software. It functions as a coordinated triple-layer network topology:</p><pre>+---------------------------+<br><br>|   de_evolution_celery_beat|  --&gt; Evaluates crontab schedules every 60s<br>+-------------┬-------------+  --&gt; Does NOT touch the database or the API<br>              │<br>              │ (Atomic Task Serialization)<br>              ▼<br>+---------------------------+<br><br>|          de_redis (Broker)|  --&gt; In-memory queue storing serialized task payloads<br>+-------------┬-------------+  --&gt; Acts as the decoupled buffer zone<br>              │<br>              │ (Worker Polling &amp; Prefetch Fetching)<br>              ▼<br>+---------------------------+<br><br>| de_evolution_celery_worker|  --&gt; True compute node running shared/ extraction layers<br>+---------------------------+  --&gt; Fires requests to OpenWeatherMap API and writes to DB</pre><p>This split creates a resilient <strong>backpressure boundary</strong>. If the target relational database encounters massive storage locks or connection exhaustion, the scheduler (celery_beat) remains completely unaffected.</p><p>It continues placing lightweight task tokens into the Redis queue. The message broker acts as a <strong>shock absorber</strong> between the compute and storage layers, buffering the ingestion payloads safely until the worker fleet recovers.</p><h3>4. Production Configurations and Micro-Metrics</h3><p>To establish an ironclad data contract across this distributed cluster, we enforce specific production-grade parameters inside our tasks.py initialization layer:</p><pre>app.conf.update(<br>    timezone=&#39;UTC&#39;,<br>    enable_utc=True,<br>    task_acks_late=True,             # Critical for data safety<br>    worker_max_tasks_per_child=100,  # Mitigates memory leak vectors<br>    worker_prefetch_multiplier=1     # Strict workload distribution<br>)</pre><h4>The Engineering Rationale Behind the Parameters:</h4><ul><li>task_acks_late=True: By default, Celery acknowledges a task the exact millisecond it pulls it from Redis (<em>Early Acknowledgment</em>). If the worker container dies mid-execution due to an infrastructure crash, that task vanishes. Setting this parameter to True forces the worker to send the acknowledgment token <em>only after</em> the PostgreSQL transaction has successfully committed. If a node crashes mid-run, Redis keeps the task and safely hands it to the next available worker instance.</li><li>worker_max_tasks_per_child=100: Forces child worker processes to be destroyed and re-instantiated after handling 100 tasks, systematically mitigating potential memory leaks in third-party database drivers. <em>Architectural Trade-off:</em> While this ensures memory safety, high-throughput pipelines will incur a periodic fork latency penalty as new child processes are spawned.</li><li>worker_prefetch_multiplier=1: Prevents a single worker node from greedily grabbing dozens of tasks from the queue at once. It forces each worker instance to pull exactly one job at a time, ensuring a mathematically balanced, highly distributed workload distribution across the processing fleet.</li></ul><p>When launching this distributed topology, the worker logs reflect the transition to an asynchronous compute pool fetching tasks by distinct memory hash handles and routing straight to the transactional API gateway:</p><pre>[2026-06-17 00:15:03,159: INFO/MainProcess] Task 03-celery-beat.tasks.trigger_weather_pipeline[a4a554bd-338a-43d3-a38b-639a68f5a2dd] received<br>[2026-06-17 00:15:03,161: WARNING/ForkPoolWorker-23] 2026-06-17 00:15:03 [info     ] Distributed worker picked up pipeline execution payload celery_task_id=a4a554bd-338a-43d3-a38b-639a68f5a2dd<br>[2026-06-17 00:15:03,161: WARNING/ForkPoolWorker-23] 2026-06-17 00:15:03 [info     ] Executing extraction layer     api_key_status=VALID_ENV_CONFIG city=Istanbul units=metric<br>[2026-06-17 00:15:03,161: WARNING/ForkPoolWorker-23] 2026-06-17 00:15:03 [info     ] Dispatching HTTP request to target API city=Istanbul target_url=https://api.openweathermap.org/data/2.5/weather units=metric<br>[2026-06-17 00:15:03,334: WARNING/ForkPoolWorker-23] 2026-06-17 00:15:03 [info     ] Extraction lifecycle successful city=Istanbul temp=19.82<br>[2026-06-17 00:15:03,339: WARNING/ForkPoolWorker-23] 2026-06-17 00:15:03 [info     ] Distributed task cycle finalized successfully across execution pools celery_task_id=a4a554bd-338a-43d3-a38b-639a68f5a2dd target_city=Istanbul</pre><p>An execution audit against our production PostgreSQL database demonstrates completely continuous real-world time-series data storage with zero synthetic mocking noise, capturing the real-world 10-to-15 minute caching thresholds of the upstream API gateway.</p><pre>(venv) PS C:...\de-scheduling-evolution\03-celery-beat&gt; docker exec -it de_postgres psql -U de_user -d de_scheduling -c &quot;SELECT city, timestamp, temp, weather_main, left(raw::text, 60) FROM weather_records ORDER BY timestamp DESC LIMIT 5;&quot;<br><br>    city   |       timestamp        | temp  | weather_main |                             left<br>----------+------------------------+-------+--------------+--------------------------------------------------------------<br> Istanbul | 2026-06-17 00:15:49+00 | 19.82 | Clouds       | {&quot;coord&quot;: {&quot;lon&quot;: 28.9833, &quot;lat&quot;: 41.0351}, &quot;weather&quot;: [{&quot;id<br> Istanbul | 2026-06-17 00:10:00+00 | 19.82 | Clouds       | {&quot;coord&quot;: {&quot;lon&quot;: 28.9833, &quot;lat&quot;: 41.0351}, &quot;weather&quot;: [{&quot;id<br> Istanbul | 2026-06-17 00:05:51+00 | 19.82 | Clouds       | {&quot;coord&quot;: {&quot;lon&quot;: 28.9833, &quot;lat&quot;: 41.0351}, &quot;weather&quot;: [{&quot;id<br> Istanbul | 2026-06-17 00:00:00+00 | 19.82 | Clouds       | {&quot;coord&quot;: {&quot;lon&quot;: 28.9833, &quot;lat&quot;: 41.0351}, &quot;weather&quot;: [{&quot;id<br> Istanbul | 2026-06-16 23:49:00+00 | 19.82 | Clouds       | {&quot;coord&quot;: {&quot;lon&quot;: 28.9833, &quot;lat&quot;: 41.0351}, &quot;weather&quot;: [{&quot;id</pre><h3>5. The Production Advantages of Task Decoupling</h3><ul><li><strong>True Horizontal Elasticity:</strong> The scheduling daemon (celery_beat) remains a lightweight, single instance. If the system expands to process weather telemetry for 50,000 global cities, you do not upscale the scheduler. Instead, you scale your compute nodes (celery_worker) out from 1 container instance to 50 across separate infrastructure nodes. They dynamically drain the common Redis queue pool concurrently with zero coordination code required.</li><li><strong>Native Fault Isolation:</strong> If an unexpected API shift causes a worker process to panic and crash, it does not bring down the orchestration scheduler. The scheduler continues ticking, and the remaining healthy workers continue consuming jobs from the message broker uninterrupted.</li></ul><h3>6. Failure Mode Matrix &amp; Architectural Severity</h3><p>Asynchronous decoupling moves our failure planes completely out of application code boundaries straight into network and serialization infrastructure layers:</p><ul><li><strong>Redis Broker Crash / Eviction Event</strong><br><strong>Impact: </strong>The communication hub is completely severed. Workers cannot fetch jobs, and the scheduler cannot write triggers, resulting in a complete cluster freeze.<br><strong>Severity:</strong> Catastrophic<br><strong>Mitigation:</strong> Enforce Redis AOF (Append-Only File) persistence and configure strict memory limits with maxmemory-policy noeviction to prevent silent data loss..</li><li><strong>Split-Brain Scheduler Deployment</strong><br><strong>Impact</strong>: If an operational error launches two Celery Beat daemons concurrently, both instances will continuously push duplicate execution tasks into Redis.<br><strong>Severity</strong>: High Risk<br><strong>Mitigation</strong>: Enforce a strict single-instance constraint for the Beat service or use a database-backed scheduler such as django-celery-beat.</li><li><strong>Worker Process Poisoning (Zombi Fork)</strong><br><strong>Impact</strong>: If an extraction task hangs indefinitely due to missing timeout constraints, Celery fork pool workers (e.g., ForkPoolWorker-23) become unresponsive, causing queued tasks to stall.<br><strong>Severity</strong>: Medium Risk<br><strong>Mitigation</strong>: Enforce strict HTTP timeouts in the shared extraction layer and configure Celery execution limits using task_time_limit.</li></ul><h3>7. Real-world Production Use-Cases For Celery Beat Mappings</h3><p><strong>Distributed E-Commerce Daily Inventory Reconciliation </strong>:</p><ul><li><strong><em>The Scenario:</em></strong> An enterprise marketplace platform needs to sync inventory prices and stock levels for 10 million products across 500 external vendor warehouse endpoints every single night at 02:00 UTC.</li><li><strong><em>The Celery Solution:</em></strong> A monolithic scheduler would instantly choke on this IO load. Celery Beat handles this by firing a single “Inventory Sync Master” trigger. This task queries the core database, breaks the 10 million SKUs into small 5,000-item atomic chunks, and dumps thousands of individual micro-task tokens into the Redis queue. A horizontally scaled fleet of 40 independent Celery worker containers deployed across separate EC2 instances immediately starts draining the queue concurrently, processing the entire workload in parallel within minutes without blocking a single web app process.</li></ul><p><strong>Massive User Activity Analytics Batch Aggregation:</strong></p><ul><li><strong><em>The Scenario:</em></strong> A social media platform logs billions of user micro-clicks and ad-interactions inside a temporary cache storage layer. Every hour, the system must parse these logs, calculate total engagement metrics per country, and write the aggregated outputs cleanly into analytical warehouse tables.</li><li><strong><em>The Celery Solution:</em></strong> Celery Beat launches the hourly aggregation task. By utilizing Redis as a highly resilient buffer zone, the pipeline isolates this heavy transactional workload. If a worker node crashes mid-aggregation due to memory pressure while parsing a massive log partition, the late acknowledgment contract (task_acks_late=True) forces Redis to retain that chunk and hand it to a healthy worker pool instance automatically, guaranteeing zero analytical data loss during high-volume transfers.</li></ul><p><strong>Automated Parallelized Multimedia Transcoding Pipelines:</strong></p><ul><li><strong><em>The Scenario:</em></strong> A content streaming service allows creators to upload raw 4K video files. The platform must automatically convert each video into five different resolution layouts (1080p, 720p, 480p, etc.) and compress them before pushing them to public CDN buckets.</li><li><strong><em>The Celery Solution:</em></strong> Web application containers (FastAPI/Django) never run this CPU-bound compression code; they simply place the raw media metadata into Redis. Celery Beat evaluates the ingestion queues and scales out dedicated, specialized worker pools utilizing compute-optimized instance layers. Each sub-resolution transcoding step executes as an independent, decoupled task, ensuring that a massive 50GB file upload by one user never slows down the core website or compromises the ingestion pipeline stability for other users.</li></ul><h3>8. The Hard Wall of Enterprise Complexity: Why We Must Leave</h3><p>By establishing this producer-broker-consumer split, the ingestion loop has achieved maximum structural resilience, running as a stateless, highly stable time-series automation system backed by reliable transactional database state synchronization.</p><p>But the moment your business requirement scales from a simple ingestion loop into an advanced Data Pipeline Workflow, this framework hits a definitive wall. This limitation stems from a fundamental structural boundary: <strong>Celery is purely a Task Execution Engine, not a Task Orchestration Engine.</strong></p><ul><li><strong>The Lack of Task Lineage (No DAGs):</strong> If you need Task B (Schema Transform) to execute <em>only after</em> Task A (Data Extraction) completes successfully, and Task C (Data Quality Slack Alert) to run if either fails, Celery Beat cannot map this natively. It has no structural mechanism to declare complex execution dependency trees.</li><li><strong>The Visual Blind Spot:</strong> In enterprise settings, debugging production pipeline failures across hundreds of complex tasks by looking at raw text container logs is completely unsustainable. We demand central user-interface visibility to inspect individual task duration matrices, visually trigger retrospective backfills, and trace structural parent-child data lineage.</li></ul><p>To resolve these enterprise monitoring and dependency constraints, we are forced to leave task-execution frameworks behind and transition into true Enterprise Data Orchestration Engines.</p><p>This brings our distributed baseline to its end, setting our architectural evolution straight into <strong>Chapter 4 — Apache Airflow.</strong></p><p><em>You can find the full project and implementation details in my</em><strong><em> </em></strong><em>de-scheduling-evolution</em><strong><em> </em></strong><em>GitHub repository.</em></p><p><a href="https://github.com/EnigmaDevelop/de-scheduling-evolution">GitHub - EnigmaDevelop/de-scheduling-evolution</a></p><p><em>Upvote if you liked this — it helps more data engineers find it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7692fb6c2370" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>