<?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 Amin Rashidi on Medium]]></title>
        <description><![CDATA[Stories by Amin Rashidi on Medium]]></description>
        <link>https://medium.com/@amin.rashidi?source=rss-fc5f63eb2517------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9sy2HcVhn6KPAFJPUKpSCA.jpeg</url>
            <title>Stories by Amin Rashidi on Medium</title>
            <link>https://medium.com/@amin.rashidi?source=rss-fc5f63eb2517------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:58:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amin.rashidi/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[We Tried Two Tools to Cut Our Coding Agent’s Token Bill. The Defaults Worked Against Us.]]></title>
            <link>https://medium.com/@amin.rashidi/we-tried-two-tools-to-cut-our-coding-agents-token-bill-the-defaults-worked-against-us-3e635d578e9a?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e635d578e9a</guid>
            <category><![CDATA[devin-ai]]></category>
            <category><![CDATA[graphify]]></category>
            <category><![CDATA[token-saving]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 16:24:59 GMT</pubDate>
            <atom:updated>2026-11-07T17:07:55.761Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What we learned measuring graphify and rtk with Devin: what they saved, what they hid, and where the docs and the code disagreed.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbOcGpv-y4Z0XoTXpglTtg.png" /><figcaption>The first thing our token-saving tool installed was an instruction file worth about 16,500 tokens.</figcaption></figure><p>We had set up graphify, an open-source tool that turns a codebase into a knowledge graph. The idea is that an AI coding agent can ask the graph how things connect instead of searching through files. graphify’s default setup for Devin is a skill: a file of instructions the agent pulls into the conversation when it decides they’re relevant. That file was 65,859 bytes, or roughly 16,500 tokens each time it loads. For comparison, the answer to our first test query was about 1,600 tokens.</p><p>The agent was also free to load the skill on its own. Its description said to use it “for any question about a codebase”. Yet nothing told the agent to actually prefer the graph over its usual searches. So we had added a large fixed cost without getting the behavior we wanted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcOWNhpC9on0GEdk_8goBA.png" /><figcaption><em>Figure 1. The fixed cost of each graphify setup next to the answer it buys. Estimated from file sizes (bytes ÷ 4).</em></figcaption></figure><p>That turned out to be a theme. We tested two tools that go after different parts of an agent’s token bill. graphify tries to replace reading code, and rtk compresses the output of shell commands. Both did something useful, but neither lived up to its headline out of the box, and the details that mattered were in the source code rather than the README.</p><h3>Two tools, two parts of the bill</h3><p>An agent’s input tokens come from a few places: the system prompt and tool definitions, the files it reads, and the output of the commands it runs. Each turn sends the whole conversation again, so anything that enters early gets paid for again on every later turn.</p><p>graphify goes after file reading. It parses code on your machine with tree-sitter, a fast code parser, and links functions, classes and imports across files. Ask it something like “how does a job reach the worker?” and it returns a trimmed slice of the graph instead of whole files.</p><p>rtk goes after command output. It turns git status into rtk git status and pytest into rtk pytest. Those run the real command and then filter what the agent sees.</p><p>The two shouldn’t overlap, and in our tests they didn’t. rtk has no rule for graphify, so graphify query ran untouched, and graphify never sees shell output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLsw6JDl23pxLq41JuWMpg.png" /><figcaption><em>Figure 2. Where an agent’s input tokens come from, and the part each tool goes after. Skills and rules sit on top as a fixed cost.</em></figcaption></figure><h3>What the graph got right, and one thing it got wrong</h3><p>We built a code-only graph, which runs entirely on the local machine. graphify found 813 code files, and 328 of them ended up in the graph: 248 Python, 35 TypeScript and 28 Terraform files, plus a handful of config files and scripts. Most of the rest were JSON and YAML data files with nothing to extract. The graph had 7,106 nodes and 24,473 edges.</p><p>It respected our .gitignore. We checked every indexed path, and no environment file, virtual environment or Terraform state got in.</p><p>The most-connected nodes in its report were mostly test fixtures. Our database fixture had 267 connections, which is accurate but not very illuminating.</p><p>The “surprising connections” section was more interesting, for the wrong reason. It said a helper in one of our API tests calls a TransportError class from our deployment scripts. In fact the test imports a different TransportError, from Google’s auth library. The two classes share a name, and the graph joined them. To be fair, graphify marks connections it worked out itself as INFERRED and ones it read straight from the code as EXTRACTED, and this one was marked INFERRED. But an agent that trusted it while checking who calls what before a change would have got it wrong.</p><p>Queries were noisy in a similar way. “How does a job reach the worker?” returned about 6.5 KB, roughly 1,600 tokens. graphify found 608 matching nodes and trimmed the answer to 69. The starting points included our job model and worker module, as we’d hoped, but also a _reach() function from our evaluation harness and a job() test fixture. It matches on words, so how you phrase the question matters.</p><p>One more surprise: graphify update, the command that refreshes the graph, isn’t code-only. Our first refresh took the graph from 7,106 to 10,118 nodes because it also parsed 170 Markdown files, mostly specs and docs. It parsed them locally, and the new nodes we looked at were plain headings with line numbers, so nothing left the machine. For a project that runs on written specs, that might even help. It just wasn’t what we’d asked for.</p><h3>The headline number was for a different product</h3><p>The README opens with “Cut agent token spend by 80%.” That line is about Graphify Cloud, the paid hosted product.</p><p>The open-source project’s own benchmark makes a different claim. On one large repository, giving an agent a graphify tool raised its key-fact coverage from 70.8%, using grep and file reads, to 82.0%. That was across six questions, at about 140,000 tokens per query. The only token comparison in that result is against pasting the whole repository into the context, not against grep.</p><p>So it’s a claim about better answers, not a smaller bill. That may well be true, but it isn’t what the banner says.</p><p>We found a few other spots where the docs and the code didn’t match:</p><ul><li>The README describes project installs as a skill plus reference files that load only when needed. For Devin, the install code ships the full skill as a single file, with no reference files. The latest Devin skill is slightly bigger than the one we installed.</li><li>The README says every query is logged to a file in your home directory by default. The code we installed says logging is off unless you turn it on, and no log file showed up after our queries.</li><li>The README says an MCP connection comes with its own usage instructions. The local MCP server sends none, so that line probably describes the hosted service. With the local server, the agent sees only a server name, and you still need a rule telling it when to use the graph.</li></ul><p>None of this is dramatic, but you only find it by checking.</p><h3>What other people measured</h3><p>We went looking for independent evidence that tools like this save tokens in real agent sessions. There’s more than we expected, and it doesn’t agree.</p><p>One benchmark reports graphify cutting tokens by 65.5%. But its methodology says it doesn’t run an LLM at all. It measures how big each tool’s output is for a scripted set of steps. That leaves out the things that drive a real bill: extra turns, tool definitions, and agents that keep grepping anyway.</p><p>The studies that ran real agents were mixed:</p><ul><li>A study of 252 headless Claude Code runs found that a code graph (a different tool) didn’t make sessions cheaper. On a large repository with the larger model, plain read and grep was cheaper on 11 of 12 questions, with the same accuracy. The graph’s clear win was accuracy with a smaller model: 12 of 12 answers right with it, 8 of 12 without.</li><li>A controlled comparison of the Serena code-navigation tool against bare Codex found 10.1% more uncached input and 59.3% more tool calls with the tool. The agent used Serena on top of its usual searches rather than instead of them.</li><li>Another Serena trial, on a refactoring task, used 108k tokens of context with the tool and 83k without. The tool’s definitions alone took about 11,400.</li><li>The most thorough positive result we saw came from the author of a tree-sitter navigation tool. It showed the same answer quality with about half the context tokens across ten large repositories. Most of grep’s extra volume was cheap cached input, though, so the difference in cost was smaller.</li></ul><p>The studies with big savings tended to have one of two things in common. Either the tool replaced grep instead of being added alongside it (sometimes because built-in search was switched off), or the tool’s own author ran the study.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLLXpY3AWdCiR7y26DQIbg.png" /><figcaption><em>Figure 3. Token change reported by each study against its own baseline. A hollow marker means no agent was run. Orange means the tool’s vendor or author ran the study. The studies measure different things (total, uncached or context tokens), so read this for direction, not exact size.</em></figcaption></figure><p>Taken together, they suggest five rules of thumb:</p><ol><li>A tool saves tokens only when it replaces searching and reading, not when it’s added on top.</li><li>Fixed costs, like tool definitions and skills, can cancel out the savings on each query.</li><li>The number of turns matters most. In one study, capping tool responses to save tokens made the agent ask again, and billed input for one answer went from 267k to 708k tokens.</li><li>Simple lookups show little difference. Multi-step questions in large codebases show the most.</li><li>Prompt caching makes extra volume cheaper, so a big token gap can be a small cost gap.</li></ol><p>So we changed our graphify setup. We removed the skill and added a short always-on rule of about 200 tokens. It tells the agent to query the graph first, treat inferred connections as hints and confirm callers with grep before editing, and refresh the graph after changing code. Whether that saves anything in our own sessions is something we’ll measure rather than assume.</p><h3>rtk: real savings, real blind spots</h3><p>We ran rtk’s Apache-2.0 edition from a temporary folder and compared plain and filtered output for real commands in our repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPy-CbP-aoLdl1cIk_JsRw.png" /><figcaption><em>Figure 4. Share of output bytes rtk removed on each command. Red bars hid something we needed. Table 1 has the exact byte counts.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_lauTj57PzCje4H-SapvA.png" /><figcaption><em>Table 1. The output sizes behind Figure 4, in bytes. rtk itself estimates tokens as bytes ÷ 4.</em></figcaption></figure><p>The savings are real, but so are the gaps. Our failing test compared two dictionaries that differed in two fields. rtk showed one difference and hid the other behind “+2 more E lines”. Which one it hid changed from run to run, because pytest printed the fields in a different order each time. The diff showed small files in full but cut down the large one. The grep showed 200 matches and hid 60.</p><p>You can get all of it back. rtk stores the full output and prints a hint like rtk recall &lt;id&gt;. But that costs another turn. And the parts rtk trims, like the rest of a diff or the rest of a list of callers, are exactly what our own review rules say we must read in full.</p><h3>The settings that help, and the ones that don’t</h3><p>rtk has a config file, and some of it works well.</p><ul><li><strong>You can exclude commands, with a catch.</strong> Entries like “git diff” and “git log” stop rtk rewriting those commands, but git -C web log slipped through. A regex entry, ‘^git( +-[Cc] +\S+)* +(diff|log|show)\b’, caught every variant we tried.</li><li><strong>One typo silently turns off every exclusion.</strong> A backslash inside a double-quoted TOML string made the file invalid. rtk config reported the error, but the rewrite step the agent relies on quietly fell back to the defaults. Put patterns in single quotes and run rtk config after every edit.</li><li><strong>One limit setting does nothing.</strong> grep_max_results is defined in the code of the version we tested, but nothing reads it. The real 200-match cap is the default of a command-line flag, — max. The per-file limit does work.</li><li><strong>The pytest limits can’t be changed.</strong> rtk shows at most four error lines per failure and three lines of traceback context. Both are hard-coded, and verbose flags don’t change them.</li><li><strong>rtk changes the test command itself.</strong> Unless you pass — tb, it adds — tb=short to pytest. So the “full” output it keeps for recall is the short version. The local variables in our plain run’s traceback showed up in neither the filtered output nor the recalled one.</li></ul><h3>Wiring rtk into Devin</h3><p>rtk supports 18 coding agents, and Devin isn’t one of them. But Devin supports hooks, small scripts that can rewrite a shell command before it runs. Its docs even use rtk git status as the example. So we wrote a hook that calls rtk rewrite. A hook added in the middle of a session never fired, so we tested it in a fresh session in a throwaway repository.</p><p>It took three runs. The first failed because of our own mistake: the CLI’s -p flag takes an optional value, and our argument order confused it. The next two told us what we needed to know:</p><ol><li><strong>The rewrite works.</strong> The hook turned git status into rtk git status, and the agent got rtk’s compact output.</li><li><strong>Permissions follow the rewritten command.</strong> Devin lets you pre-approve commands with allow rules. With a rule for git status, the rewritten command was rejected as needing confirmation. Adding a rule for rtk git status let it run. That means our repository’s existing rules for uv run pytest, ls and grep would stop applying.</li><li><strong>rtk’s Claude Code hook won’t fire.</strong> Devin does load hook files written for Claude Code, and a catch-all hook we put there fired. But rtk’s hook only matches a tool called Bash, and Devin’s shell tool is called exec.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80XC2QEDU79WDbThoJudLg.png" /><figcaption><em>Figure 5. The path a command takes through our hook. Devin checks permissions against the rewritten command, so allow rules need the rtk form.</em></figcaption></figure><p>There’s one consequence we haven’t tested. rtk also rewrites risky commands like git push — force and git checkout — .. If permissions are checked against the rewritten command, a deny rule for git push probably wouldn’t match rtk git push. If your agent relies on deny rules, test this before you trust them.</p><h3>Where we went wrong</h3><p>We made a few mistakes of our own:</p><ul><li>Our first rtk measurements used our real home directory. rtk created a command history database and a recall store there, holding full copies of output it had trimmed. We deleted them. The history database came back once more during later tests, and we deleted it again.</li><li>At first we noted that rtk had hidden one particular field from a failing test. A second run hid the other one. It was run-to-run ordering, not a rule.</li><li>Our first Devin test session never started, because of the flag mistake above.</li></ul><p>None of these changed our conclusions, but each one would have if we’d stopped at the first result.</p><h3>What we’re keeping</h3><ul><li><strong>graphify:</strong> the command-line tool and a short always-on rule. No auto-loading skill. Inferred connections are hints, not facts.</li><li><strong>rtk:</strong> worth it only if diffs, logs and searches are excluded, with a custom hook and matching allow rules for the rewritten commands. What’s left is compact git status, ls and passing test runs, which is modest. A benchmark that modelled rtk on code-comprehension tasks put its overall saving at about 5%, rising to 36% on command-heavy tasks.</li><li><strong>Measurement:</strong> next we’ll run the same real tasks with and without each tool and compare tokens and answer quality. Until then, we can’t say whether either tool saves us money.</li></ul><h3>If you’re evaluating a token-saving tool</h3><ol><li>Measure the fixed cost first. Tool definitions, skills and rules get paid for on every turn or every load.</li><li>Check whether the tool replaces your agent’s searching or just adds to it.</li><li>Compare plain and filtered output on your own commands. Look at what’s missing, not just how much smaller it is.</li><li>Read the source when the docs make a specific claim.</li><li>Watch for settings that fail silently.</li><li>Keep modelled benchmarks apart from real agent runs, and studies by a tool’s author apart from independent ones.</li></ol><h3>Sources</h3><ul><li>graphify: <a href="https://github.com/Graphify-Labs/graphify">README</a> and <a href="https://github.com/Graphify-Labs/graphify/blob/v8/BENCHMARKS.md">benchmarks</a></li><li>rtk: <a href="https://github.com/rtk-ai/rtk">README</a> and <a href="https://www.rtk-ai.app/docs/getting-started/configuration/">configuration docs</a></li><li>Scripted token benchmark: <a href="https://github.com/vagkaratzas/token-consumption-benchmark">token-consumption-benchmark</a></li><li>252 Claude Code runs with a code graph: <a href="https://github.com/nefayran/claude-code-token-bench">claude-code-token-bench</a></li><li>Serena against bare Codex: <a href="https://byroni.us/blog/testing-serena-against-bare-codex-navigation">Byron Wall’s evaluation</a></li><li>Serena on a refactoring task: <a href="https://zenn.dev/minedia/articles/serena-mcp-token-benchmark">Zenn write-up (Japanese)</a></li><li>grove, grep and LSP across ten repositories: <a href="https://github.com/Entelligentsia/is-grep-enough">is-grep-enough</a></li><li>Code-context servers with built-in search switched off: <a href="https://github.com/Neko1313/agent-context-bench">agent-context-bench</a></li><li>claude-context vendor evaluation: <a href="https://github.com/zilliztech/claude-context/blob/master/evaluation/README.md">evaluation README</a></li></ul><p>Every chart in this post is drawn from the measurements and published figures quoted in the text.</p><p><em>Tested with graphify 0.9.99, rtk-oss 1.1.0 and Devin CLI 3000.12.17 in November 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e635d578e9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Vanity Metric Trap: AI Teams Merge More Code and Ship Less]]></title>
            <link>https://medium.com/decisive-intentions/the-vanity-metric-trap-ai-teams-merge-more-code-and-ship-less-c4886b3ff6a2?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4886b3ff6a2</guid>
            <category><![CDATA[spec-driven-development]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <category><![CDATA[ai-coding]]></category>
            <category><![CDATA[pull-request]]></category>
            <category><![CDATA[vanity-metrics]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 21:07:59 GMT</pubDate>
            <atom:updated>2026-09-30T21:13:11.972Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What 211 million changed lines of code, a surprising randomized trial, and a lot of stuck pull requests tell us about AI and software teams.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWiMfrp8_lq6HcKiXnhItA.png" /><figcaption><em>The chart goes up. The piece that lasts does not.</em></figcaption></figure><p>The pitch was simple. Engineers write code. AI writes code faster. So buy AI seats for everyone, and your team ships twice as fast.</p><p>Then the numbers came in.</p><p>Some teams tried the tools for a few weeks and quietly stopped using them. Others used them heavily and hit a stranger problem: more code than ever, but pull requests piling up, more bugs slipping through, and senior engineers spending their afternoons reviewing code that nobody had really written.</p><p>What went wrong? In most cases, not the tools. The measurement. Companies tracked what was easy to count (lines generated, suggestions accepted, pull requests merged, tokens spent) instead of what actually matters: working software that stays working.</p><p>Here are five measurement mistakes, what the research says about each one, and what to track instead.</p><h3><strong>The five mistakes:</strong></h3><ol><li>Counting keystrokes, pull requests, and tokens instead of understanding</li><li>Trusting demos built from scratch</li><li>Celebrating accepted suggestions while reviews pile up</li><li>Setting the same AI quota for every team</li><li>Rewarding code volume instead of code that lasts</li></ol><h4>Mistake 1: Counting keystrokes, pull requests, and tokens instead of understanding</h4><p>Many AI dashboards lead with lines of code generated, prompts sent, pull requests merged, or tokens spent. Judging engineering by any of those is like judging a novel by weighing the manuscript.</p><p>Typing was never the slow part. Two studies show how little of a developer’s time actually goes to writing code:</p><ul><li><strong>About 5% of time in the editor is spent editing.</strong> Minelli, Mocci, and Lanza tracked about 5 million actions across 740 coding sessions (ICPC 2015). Developers spent roughly 70% of their time understanding code and only about 5% changing it.</li><li><strong>About 11% of the workweek is coding.</strong> In Microsoft’s <em>Time Warp</em> survey (ICSE 2025), 484 developers said coding took about 11% of a typical week. Meetings (about 12%), debugging (about 9%), design (about 6%), and code review (about 5%) took up much of the rest.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NntFcehpXr_82yBP2EApew.png" /></figure><p><em>Approximate share of a typical week. Time Warp survey, 484 developers at Microsoft. These five activities do not fill the whole week.</em></p><p>Most of the day goes to reading unfamiliar code, chasing bugs, and working with other people.</p><p>Here’s the uncomfortable math. If coding is 11% of the week and AI made it instant, the week as a whole would get at most about 12% faster. That’s Amdahl’s Law: speeding up one part of a job can only save as much time as that part takes. Using the 5% figure, the ceiling drops to about 5%.</p><p>That doesn’t mean AI can only ever help by 12%. Good AI tools also help people understand code, find their way around a large codebase, and debug, which is why some studies find bigger gains (more on that below). The point is simpler: if you only measure typing, you’re measuring the smallest part of the job.</p><p>Pull requests and tokens fail the same test. Demirer, Musolff, and Yang (NBER, September 2026 revision) studied more than 500,000 GitHub developers together with their AI usage, in a matched event study. Autocomplete, interactive coding agents, and autonomous agents raised commits by a cumulative 30%, 180%, and 240%. At the top of that stack, the number of projects was up 80% and actual releases only 30%. Across four software marketplaces, new apps jumped and total usage did not. Merged pull requests are the same kind of count: high-AI teams can merge far more of them while company-level delivery does not move (more on that below). Tokens are no better. Bai et al. (2026) ran eight frontier models on SWE-bench Verified, four times each. The same task used up to 30 times as many tokens from one run to the next, and spending more tokens did not raise accuracy. Accuracy often peaked in the middle of the cost range and then flattened.</p><h4>Mistake 2: Trusting demos built from scratch</h4><p>The early headlines were exciting: developers finishing tasks twice as fast! But most of those results came from brand-new projects or from counting output. Few of them timed experienced engineers working in the large, messy codebases where they actually spend their days.</p><p><strong>Starting from zero is easy mode.</strong> In a 2023 GitHub study (Peng et al.), developers with Copilot built a small web server in JavaScript 55.8% faster. It’s a task with no existing code to fit into and thousands of similar examples online.</p><p><strong>Real-world gains are real, but they count output.</strong> The strongest field evidence, Cui et al. (<em>Management Science</em>, 2026), combined randomized trials with 4,867 developers at Microsoft, Accenture, and a Fortune 100 company. Developers with AI completed more tasks — 26% in the combined estimate — and less experienced developers gained the most. The paper treats that estimate as positive but too imprecise to read as a firm 26% gain: the standard error is 10.3 percentage points. It also counts tasks and pull requests. It doesn’t show whether that code lasted, or how much extra review it needed.</p><p><strong>An early-2025 slowdown, and a perception gap that still stands.</strong> The research group METR ran a randomized controlled trial with 16 experienced open-source developers. They worked on 246 real issues in large, mature projects they knew well (on average 23,000 GitHub stars and over 1.1 million lines of code), mostly using Cursor Pro with Claude 3.5 and 3.7 Sonnet. In that early-2025 trial they took 19% longer with AI. METR has since said that result is out of date. A February 2026 follow-up did not reproduce the slowdown: the original developers who returned were estimated about 18% faster, and newly recruited developers about 4% faster. Both ranges include no effect, and METR calls the follow-up only weak evidence. Many developers who most wanted to keep using AI declined to join, and the study paid less than before.</p><p>What still stands is the gap between feeling and reality in the original trial. Developers expected to be 24% faster, believed afterward they had been 20% faster, and had been 19% slower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8J9NPq5cwEtq4ELafZAWQ.png" /><figcaption><em>The original early-2025 trial.</em></figcaption></figure><p>Why the early-2025 slowdown? METR tested 20 possible explanations and found five likely ones:</p><ul><li>people were too optimistic about how much AI would help,</li><li>the developers already knew their projects extremely well,</li><li>the projects were large and complex,</li><li>the AI was unreliable,</li><li>and much of the important context lived in the developers’ heads, where the AI couldn’t see it.</li></ul><p>Developers accepted fewer than 44% of the AI’s suggestions, and often spent time reviewing and fixing code before throwing it away. One said he “wasted at least an hour” on an AI attempt before starting over by hand.</p><p>Economists and machine learning experts had predicted AI would cut task time by 39% and 38%. Even while those developers were slower, they still believed AI had sped them up.</p><p>If you measure AI by asking developers how productive they feel, you may be measuring the wrong thing.</p><h4>Mistake 3: Celebrating accepted suggestions while reviews pile up</h4><p>Many dashboards track <strong>acceptance rate</strong>: how often a developer presses Tab to accept an AI suggestion. But pressing Tab is a moment, not an outcome. GitClear found that in 2024, the share of new code rewritten within a month was 20–25% higher than before AI tools arrived. Accepted code is increasingly not staying accepted.</p><p>The bigger problem shows up later. When code gets written faster but review stays the same speed, everything backs up at review.</p><p>Faros AI, which sells engineering analytics, compared high and low AI adoption in telemetry from more than 10,000 developers on 1,255 teams (<em>AI Productivity Paradox Report</em>, July 2025). These figures are correlations, not a randomized trial. Developers on teams with high adoption completed 21% more tasks. But look at what happened downstream:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*95VL_HK_wvQZ4EToFFnRGQ.png" /></figure><p>At the company level, the gains disappeared: Faros found no link between AI adoption and overall delivery performance. Its 2026 follow-up used the same style of low-versus-high comparison across about 22,000 developers, and the review pileup was worse. These are different cuts from the +91% above, not the same number getting larger: median time a pull request spent in review was up 441.5%, and pull requests merged with no review at all were up 31.3%.</p><p>Call it a <strong>review tax</strong>. A developer can now produce an 800-line change across many files in a few minutes. The reviewer gets no such speedup. They have two options:</p><ol><li><strong>Review it properly,</strong> and lose an afternoon of their own work.</li><li><strong>Skim it, see that the tests pass, and approve it.</strong></li></ol><p>When reviewers start choosing option 2, quality starts to slip.</p><h4>Mistake 4: Setting the same AI quota for every team</h4><p>Few directives do more damage than <em>“Every team must reach 50% AI-generated code by Q4.”</em></p><p>Not all code carries the same risk. A mistake in a button’s color is cheap to fix. A mistake in an access-control rule can become a data breach.</p><p>Here’s an illustration of how different the right level can be. Every figure in this table is a rough estimate for the example that follows, not a measured benchmark. Calibrate any real target against your own data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*FewVoA2_tQtNqTuFeN7CWA.png" /><figcaption><em>Illustration only. Not a measured benchmark.</em></figcaption></figure><p>Now imagine a flat quota in practice. A frontend engineer generating interface components hits 85% and looks like a star. An infrastructure engineer managing access permissions refuses to let an AI guess at security rules, lands at 12%, and gets flagged as a laggard. The quota rewards the wrong person.</p><p>The security research backs up that caution:</p><ul><li><strong>People trust AI code more than they should.</strong> In a Stanford study (Perry et al., 2023), participants with an AI assistant wrote less secure code than those without one, and were more likely to believe their code was secure.</li><li><strong>Nearly half of AI-generated code fails basic security tests.</strong> Veracode tested over 100 AI models on 80 coding tasks. 45% of the code samples contained well-known types of vulnerabilities from the OWASP Top 10 list. Its Spring 2026 update found security pass rates stuck at around 55% for two years, even as models got much better at writing code that runs.</li><li><strong>A specification of what must be true is not the same as a style guide.</strong> Dhuri (2026) ran 50 finance, healthcare, and insurance tasks through five models, once as a bare prompt and once after a 267-word specification of the rules for money, time, retries, and access. Defects fell in every model, by 0.16 to 0.70 findings per task. Where the two versions differed, the specification won 95 of 100 times, and it never made a model worse. Bandit, a scanner that did not see the specification, found 53 medium-or-high issues without it and 11 with it. Repository context files such as AGENTS.md do not do that job. Gloaguen et al. (2026) found that, across 438 tasks, those files did not generally raise task success, while raising inference cost by more than 20%.</li></ul><p>There is a separate risk those studies do not measure. Coding agents such as Claude Code and Aider don’t just suggest code. They run commands and read files. If an agent reads a file full of passwords and sends it to the model while debugging a test, code scanning will not catch it. The leak would already have happened on the developer’s laptop. That scene is an illustration, not a measured study.</p><h4>Mistake 5: Rewarding code volume instead of code that lasts</h4><p>When leaders reward lines of code or number of commits, they get more code, not better software.</p><p>Normal technical debt is a deliberate trade-off: you cut a corner to ship something urgent and plan to clean it up later. AI-generated debt often isn’t a choice at all. It’s code nobody looked at closely, accepted to save a minute of typing.</p><p>The research points to four hidden costs.</p><p><strong>Duplicate code everywhere.</strong> GitClear, which sells code-quality analytics, analyzed 211 million changed lines of code from 2020 to 2024 and compared years as AI use spread. It found that 2024 was the first year on record when copy-pasted code outnumbered moved code. Moved code is a sign of refactoring, meaning cleaning up and reusing what already exists. GitClear’s 2026 follow-up found the trend speeding up:</p><ul><li>moved code fell from 21% of changes in 2022 to 3.8% in early 2026,</li><li>duplicated blocks of code rose 81% since 2023,</li><li>and cross-file function calls, which GitClear uses as a signal of reuse across files, fell 35%.</li></ul><p>AI tools tend to write fresh code on the spot instead of finding the helper function that already exists. Do that across forty services and you end up with forty slightly different copies of the same logic, each one a new place for bugs to hide. Think of it as <strong>digital asbestos</strong>: cheap to put in, invisible for years, and very expensive to remove.</p><p><strong>Code that doesn’t stick.</strong> GitClear also tracks churn: code that gets reverted or rewritten within two weeks of being written. Churn was about 3% of changes in 2020 and about 5.7% in 2024, and GitClear’s 2026 report shows a further 15% rise since 2023.</p><p>A specification file is not proof the code is better, either. Spec-driven tools claim that writing a specification before the code reduces defects and rework. Hill (ESEM 2026) tested that on 88,052 pull requests across 119 open-source repositories, comparing each developer’s spec’d pull requests with their own unspec’d ones. Spec’d changes introduced more defects, not fewer, because developers write specifications for their hardest work. The quality of the specification did not predict fewer defects or less rework, and the specifications did not constrain the scope of AI-written code. The only protective signal was less rework in repositories that were not using AI. Counting specification documents is another way of counting the activity instead of the outcome.</p><p><strong>Developers who understand less.</strong> In an Anthropic study (Shen &amp; Tamkin, 2026), 52 mostly junior developers learned a new Python library, some with an AI assistant and some without. The AI group scored 17% lower on a quiz about what they had just used, with the biggest gap on debugging questions. And they weren’t significantly faster. Now picture that at 2 a.m. during an outage, when the engineer on call can’t explain what their own code does.</p><p><strong>Less stable releases.</strong> DORA, Google Cloud’s long-running research program on software delivery, sums up its 2025 report this way: AI is an amplifier. It makes strong teams stronger and exposes the weaknesses of struggling ones. In the 2025 data, AI adoption was positively associated with delivery throughput, and the association with stability stayed negative. Only the throughput result changed from 2024, when every 25% increase in AI adoption was associated with an estimated 1.5% drop in delivery throughput and a 7.2% drop in delivery stability.</p><h3>What to measure instead</h3><p>The fix is to stop tracking activity and start tracking outcomes: whether AI is used where it makes sense, whether the code lasts, whether review keeps up, and whether releases stay stable.</p><h4>Measure the right opportunities, not raw usage</h4><p>Instead of counting prompts or lines, ask one question: <strong>of the tasks where AI is a good fit, how many did we use it for?</strong> Call this the <em>opportunity capture rate</em>.</p><p>A task is a good fit for AI when it meets three conditions:</p><ul><li><strong>It’s contained.</strong> It touches a small part of the codebase, say no more than three closely related files or packages.</li><li><strong>It’s clearly defined.</strong> It has testable acceptance criteria, such as an API schema or written test cases, rather than a vague description.</li><li><strong>It’s low risk.</strong> It doesn’t touch safety-critical code, cryptography, or security permissions.</li></ul><p>Say an infrastructure engineer has only two tasks in a sprint that fit, and uses AI for both. Their opportunity capture rate is 100%, even if AI wrote less than 1% of their code. They used AI where it was safe and kept it away from where it wasn’t. That’s exactly the behavior you want, and a flat quota would have punished it.</p><p>A flat rule to specify everything has the same shape. Garg’s small pilot, accepted at GAISS 2026, compared three ways of asking a model to write easy functions: just write the code, reason about edge cases first with no specification, and specify first. In the comparison he reports, pass rates were about 59%, 95%, and 92%. Specifying first was not meaningfully better than reasoning first. On a harder banking task, a weaker model gained about 21 points from specification discipline, and a strong model about 2. Spend the specification on the hard, high-stakes work. Skip it where the model already gets the task right.</p><h4>Use a balanced scorecard</h4><p>No single number tells you whether AI is working. Track a small set of measures together. The targets below are suggested starting points, not industry benchmarks, so measure your own baseline first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_HrXXAJPx3ThycxvohHyw.png" /></figure><p>One row is easy to fake. “Does the code last?” is not the same as “did we write a specification?” In the same Garg study, five reviewers caught about the same share of real divergences with an approved specification as without it. What changed was whether a finding could be tied to a named requirement: 81% could with the specification, and none could without it. The review also took longer, about 48 minutes against about 27. The specification is a way to see drift. It is not, by itself, a quality score.</p><p>You probably have most of this data already: your AI vendor’s usage dashboard, Git analytics tools such as GitClear or LinearB, code quality tools such as SonarQube, your deploy and incident history, and security scanners such as Snyk or GitGuardian.</p><h3>The takeaway: measure what survives</h3><p>The hype phase is over. Now comes accountability.</p><p>AI coding tools aren’t magic, and they aren’t useless. They have changed the economics of software: writing code is now cheap.</p><p>That makes everything around the code more valuable: understanding systems, reviewing carefully, testing well, and keeping codebases clean.</p><p>The teams that win won’t be the ones that generate the most code before lunch. They’ll be the ones that check what they ship, keep their codebases clean, and turn fast output into software that keeps working.</p><p>Stop counting keystrokes. Start measuring what survives.</p><h3>References</h3><ol><li><strong>Bai, L., Huang, Z., Wang, X., Sun, J., Mihalcea, R., Brynjolfsson, E., Pentland, A., &amp; Pei, J. (2026).</strong> <em>How Do AI Agents Spend Your Money? Analyzing and Predicting Token Consumption in Agentic Coding Tasks.</em> arXiv:2604.22750. <a href="https://arxiv.org/abs/2604.22750">https://arxiv.org/abs/2604.22750</a></li><li><strong>Becker, J., Rush, N., Barnes, B., &amp; Rein, D. / METR (July 2025).</strong> <em>Measuring the Impact of Early-2025 AI on Experienced Open-Source Developer Productivity.</em> arXiv:2507.09089. <a href="https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/">https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/</a></li><li><strong>Becker, J., Rush, N., Cunningham, T., Rein, D., &amp; Mahamud, K. / METR (February 2026).</strong> <em>We are Changing our Developer Productivity Experiment Design.</em> <a href="https://metr.org/blog/2026-02-24-uplift-update/">https://metr.org/blog/2026-02-24-uplift-update/</a></li><li><strong>Cui, K. Z., Demirer, M., Jaffe, S., Musolff, L., Peng, S., &amp; Salz, T. (2026).</strong> <em>The Effects of Generative AI on High-Skilled Work: Evidence from Three Field Experiments with Software Developers.</em> <em>Management Science.</em> <a href="https://doi.org/10.1287/mnsc.2025.00535">https://doi.org/10.1287/mnsc.2025.00535</a></li><li><strong>Demirer, M., Musolff, L., &amp; Yang, L. (September 2026 revision).</strong> <em>Writing Code vs. Shipping Code: Productivity Effects Across Generations of AI Coding Tools.</em> NBER Working Paper 35275. <a href="https://www.nber.org/papers/w35275">https://www.nber.org/papers/w35275</a></li><li><strong>Dhuri, S. (September 2026).</strong> <em>Specification Before Generation: A Pre-Registered, Five-Model Paired Evaluation of a Specification Frame for LLM-Generated Code in Money, Time, Idempotency, and Access Tasks.</em> arXiv:2609.23270. <a href="https://arxiv.org/abs/2609.23270">https://arxiv.org/abs/2609.23270</a></li><li><strong>Faros AI (July 2025).</strong> <em>The AI Productivity Paradox Research Report.</em> <a href="https://www.faros.ai/blog/ai-software-engineering">https://www.faros.ai/blog/ai-software-engineering</a></li><li><strong>Faros AI (2026).</strong> <em>AI Engineering Report 2026: The Acceleration Whiplash.</em> <a href="https://www.faros.ai/blog/ai-acceleration-whiplash-takeaways">https://www.faros.ai/blog/ai-acceleration-whiplash-takeaways</a></li><li><strong>Garg, N. (September 2026).</strong> <em>When Spec-Driven Development Pays Off.</em> <em>InfoQ.</em> Study accepted at GAISS 2026. <a href="https://www.infoq.com/articles/when-spec-driven-development-pays-off/">https://www.infoq.com/articles/when-spec-driven-development-pays-off/</a></li><li><strong>GitClear (Feb 2025).</strong> <em>AI Copilot Code Quality: 2025 Look Back at 12 Months of Data</em> (211M changed lines, 2020–2024). <a href="https://www.gitclear.com/ai_assistant_code_quality_2025_research">https://www.gitclear.com/ai_assistant_code_quality_2025_research</a></li><li><strong>GitClear (2026).</strong> <em>The Maintainability Gap: 2026 AI Code Quality Research.</em> <a href="https://www.gitclear.com/the_ai_code_quality_maintainability_gap">https://www.gitclear.com/the_ai_code_quality_maintainability_gap</a></li><li><strong>Gloaguen, T., Mündler, N., Müller, M., Raychev, V., &amp; Vechev, M. (2026).</strong> <em>Evaluating AGENTS.md: Are Repository-Level Context Files Helpful for Coding Agents?</em> arXiv:2602.11988. <a href="https://arxiv.org/abs/2602.11988">https://arxiv.org/abs/2602.11988</a></li><li><strong>Google Cloud DORA (2024).</strong> <em>Accelerate State of DevOps Report 2024.</em> <a href="https://dora.dev/research/2024/dora-report/">https://dora.dev/research/2024/dora-report/</a></li><li><strong>Google Cloud DORA (2025).</strong> <em>State of AI-assisted Software Development.</em> <a href="https://dora.dev/research/2025/dora-report/">https://dora.dev/research/2025/dora-report/</a></li><li><strong>Hill, B. (2026).</strong> <em>Does Spec-Driven Development Reduce Defects? An Empirical Test of Industry Claims Across 119 Open-Source Repositories.</em> ESEM 2026 (SEIP). <a href="https://doi.org/10.5281/zenodo.19415187">https://doi.org/10.5281/zenodo.19415187</a></li><li><strong>Kumar, S., Goel, D., Zimmermann, T., Houck, B., Ashok, B., &amp; Bansal, C. (2025).</strong> <em>Time Warp: The Gap Between Developers’ Ideal vs Actual Workweeks in an AI-Driven Era.</em> In <em>Proc. ICSE 2025 (SEIP)</em>; arXiv:2502.15287.</li><li><strong>Minelli, R., Mocci, A., &amp; Lanza, M. (2015).</strong> <em>I Know What You Did Last Summer: An Investigation of How Developers Spend Their Time.</em> In <em>Proc. 23rd IEEE International Conference on Program Comprehension (ICPC 2015)</em>, pp. 25–35. doi:10.1109/ICPC.2015.12</li><li><strong>Peng, S., Kalliamvakou, E., Cihon, P., &amp; Demirer, M. (2023).</strong> <em>The Impact of AI on Developer Productivity: Evidence from GitHub Copilot.</em> arXiv:2302.06590.</li><li><strong>Perry, N., Srivastava, M., Kumar, D., &amp; Boneh, D. / Stanford University (2023).</strong> <em>Do Users Write More Insecure Code with AI Assistants?</em> In <em>Proc. ACM Conference on Computer and Communications Security (CCS)</em>, pp. 2785–2799.</li><li><strong>Shen, J. H., &amp; Tamkin, A. / Anthropic (2026).</strong> <em>How AI Impacts Skill Formation.</em> arXiv:2601.20245. <a href="https://www.anthropic.com/research/AI-assistance-coding-skills">https://www.anthropic.com/research/AI-assistance-coding-skills</a></li><li><strong>Veracode (July 2025; Spring 2026 update).</strong> <em>2025 GenAI Code Security Report.</em> <a href="https://www.veracode.com/blog/genai-code-security-report/">https://www.veracode.com/blog/genai-code-security-report/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4886b3ff6a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/the-vanity-metric-trap-ai-teams-merge-more-code-and-ship-less-c4886b3ff6a2">The Vanity Metric Trap: AI Teams Merge More Code and Ship Less</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding Is Not as Bad as People Think]]></title>
            <link>https://medium.com/decisive-intentions/vibe-coding-is-not-as-bad-as-people-think-74685f3b4726?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/74685f3b4726</guid>
            <category><![CDATA[spec-driven-development]]></category>
            <category><![CDATA[agentic-coding]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 16:01:44 GMT</pubDate>
            <atom:updated>2026-09-30T21:14:55.067Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Series: </em><a href="https://medium.com/decisive-intentions/the-spec-driven-bake-off-six-methods-one-product-hidden-tests-7e4a2930d910?sharedUserId=amin.rashidi"><em>1. The protocol</em></a><em> · </em><strong><em>2. The results</em></strong><em> · 3. The scorecard (next)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSZ0IKIq0PRnff6kqRm0Ow.png" /></figure><p><em>I hid the tests, changed the product twice, then closed the chat. The no-toolkit control passed the fresh-session gate. Four of the five spec-driven methods didn’t.</em></p><p>Six method folders feed colored paths into an empty chat window; only some paths continue to a new session on the other side.</p><p>I went in expecting vibe coding to fail on schedule: a slick v1, a requirement change, and then the slow-motion collapse every thread on the subject had promised me.</p><p>It didn’t happen.</p><p>I built the same app six times. One arm got no toolkit at all, just the brief and ordinary prompts. I call it prompt-and-pray; it’s the vibe-coding control. The other five used Spec Kit, OpenSpec, BMAD, LID, and GSD. Same model, same brief, tests hidden from every agent. Then I changed the product mid-flight, and at the end I did the rude thing — I closed the chat and asked a brand-new session to keep going.</p><p>That last step is the whole point. A first build can coast on conversation history, but a fresh session gets the repository and nothing else, so if a method’s specs are doing real work, this is where you’d see it.</p><p>If they’re theater? This is where the costume comes off.</p><p>One caveat up front. This post covers the automated half (hidden tests and the blank chat), not the final ranking. The human rubric is still ahead, and one greenfield run can’t pick a company standard. What it can tell you is who shipped, who survived the rule changes, and who could pick up the work after I hit New Chat.</p><h3>The scoreboard</h3><p>The short version:</p><ul><li><strong>GSD</strong> never dropped a test. Not once.</li><li><strong>Prompt-and-pray</strong> slipped on the non-functional requirements, then got back to 100% in the fresh session.</li><li><strong>Spec Kit, LID, BMAD, and OpenSpec</strong> all failed the handoff gate.</li></ul><p>Hidden-test pass rates, cumulative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJDHkZiAgVcLXDKoqQF58A.png" /></figure><p>“Cumulative” is doing a lot of work in that table. Each checkpoint stacks new tests on top of the old ones, so a percentage can creep upward without a single bug getting fixed. Look at BMAD: it picked up four failures at the category change and was still carrying the same four at handoff, even as its number drifted from 88 to 91.</p><p>And OpenSpec is the only arm that got <em>worse</em> after I closed the chat. I keep coming back to that number.</p><h3>How the test worked</h3><p>Every arm built the same group expense splitter: login, groups, expenses split evenly, balances that always sum to zero, settlements that can’t overpay, and no peeking at another group’s data. The stack was frozen, and so were the model (grok-4.6, thinking High), the hidden suite, and every change prompt that came later.</p><p>The exam ran in three acts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dALByH8xqso346dZlKDzcg.png" /></figure><p>(The frozen suite has 47 checks. Once shares become percentages, one even-split test stops applying, so the final count is 46.)</p><p>I’m leaving clock time out of this post on purpose. Ceremony costs real hours, and that bill goes in the scorecard. Here I’m asking something narrower: <strong>did the method’s work survive a new session?</strong></p><h3>Act I — Almost everyone can ship</h3><p>Five of six arms hit 100% on the first build. That includes prompt-and-pray, which had no constitution, no PRD, and no planning folder — only the brief.</p><p>LID was the odd one out. Full LID missed two hidden checks on its first score and was still missing the same two at the very end, while every later wave built new features around the gap like a crew paving around a pothole.</p><p>So v1 separated nobody. A strong model plus a tight brief got five arms to a clean build, which is exactly why a bake-off that stops at “the app boots” is really grading the model. The methods only started to look different once the product needed a second version.</p><h3>Act II — Then I moved the rules</h3><p>Three changes, in order:</p><ol><li><strong>Compatible.</strong> Add a category to expenses and let users filter by it.</li><li><strong>Breaking, then corrected.</strong> Start switching to weighted shares. After the first production-code edit, change course: shares are now percentages that must total exactly “100.00”. Only the final rule is scored.</li><li><strong>Non-functional.</strong> A per-user rate limit on writes, plus a settlement audit log nobody can edit.</li></ol><h4>BMAD tripped on the easy one</h4><p>BMAD’s v1 was flawless. Then the category checks arrived, and it went from 30/30 to 30/34: four new tests, zero new passes. Those four failures sat there for the rest of the run.</p><p>Store a category, filter by it. It was the cheapest request in the entire script, and a full virtual team (product manager, architect, developer, all playing their parts) didn’t land it.</p><h4>OpenSpec lost the invert</h4><p>Categories went fine. Then the split rule flipped mid-flight and OpenSpec went from 34/34 to 34/37, with three failures it carried straight through the NFR wave.</p><p>That one stings. This is the exact change OpenSpec is built for, the kind where a lazy patch leaves a stale weight field lying around or cheerfully accepts percentages that add up to 99. A method whose whole vocabulary is ADDED / MODIFIED / REMOVED should shine on a clean replacement like this. Naming the delta didn’t save it.</p><h4>Spec Kit and prompt-and-pray: same bruise</h4><p>Both ran a perfect table through the invert. Both then went from 37/37 to 37/42 on the rate limit and audit log — five new checks, not one new pass.</p><p>Sit with that pairing for a second. The no-toolkit control and the most-starred SDD toolkit hit the same wall on the same production constraints, and what finally split them apart didn’t happen until Act III.</p><p>GSD, meanwhile, kept posting 100s.</p><h3>Act III — I closed the chat</h3><p>New session. Same folder. No recap. One request: add GET /groups/{id}/settlements.csv.</p><p>The official rule has two tripwires. Handoff fails if any hidden test fails, or if the pass rate drops more than 10 points from the previous checkpoint. Only the first one fired this time (OpenSpec fell about 8 points, which would have squeaked by on its own). So a pass means the new session shipped the export <em>and</em> left nothing broken behind; a fail means the CSV missed, an old bug was still open, or both.</p><h4>The two that passed</h4><p><strong>GSD</strong> walked in clean and walked out clean. Starting fresh is basically GSD’s religion: every task goes to a subagent with a clean context, and the state lives on disk. A blank chat was home turf. It added the export and broke nothing.</p><p><strong>Prompt-and-pray</strong> is the uncomfortable pass. It walked into handoff with the same five NFR failures as Spec Kit. The new session fixed all five <em>and</em> shipped the CSV. Final score: 46/46.</p><p>Is that a case for skipping specs? I don’t think so. It’s a reminder that the code is context too — the fresh agent couldn’t see the old conversation, but it could read every file, and in a repo this small that was enough to find the gap and close it.</p><p>It’s also why the human rubric matters. A 100% here proves the code was readable. It doesn’t prove the intent lived anywhere a stranger could find it.</p><p>The four that failed</p><p>Quick warning before the arithmetic: the score files keep totals, not test names. For most of these, I can give you the simplest reading of the numbers, not a certain one. (If the new session fixed one old bug and broke one old test, the totals would look identical.)</p><p><strong>Spec Kit</strong> went from 37/42 to 41/46. Four new checks, four new passes, the same five failures. The simplest reading is that the CSV landed and the rate limit and audit log stayed broken. Constitution, spec, plan, tasks: that pipeline carried Spec Kit through v1 and both functional changes, and then it couldn’t help a stranger finish what the last session left half-done.</p><p><strong>LID</strong> went from 40/42 to 44/46. Four for four on the new checks, both original failures still sitting there. It’s the best of the failing scores. It’s also a rough look for the method with the strongest spec-as-source claim, since the gap it started with outlived every wave.</p><p><strong>BMAD</strong> went from 38/42 to 42/46. Four for four again, with the four category failures untouched. More role documents, same missing behavior.</p><p><strong>OpenSpec</strong> is the one the arithmetic actually pins down. It went from 39/42 to 39/46, meaning four checks were added, zero passes were gained, and failures more than doubled, from three to seven. Whatever lived in its specs didn’t turn into a single net new passing test.</p><p>A spec that doesn’t help the next session is just a note from the last one.</p><h3>What each method was betting on — and how it went</h3><h4>GSD: the clean sheet</h4><p>GSD bets that quality dies during execution, not during planning. Long chats get contaminated, so hand each task to a fresh subagent and keep the state on disk.</p><p>It scored 100 at every gate, blank chat included. I’d filed GSD under “for long backlogs,” where context rot has room to set in, yet on a short product it was already the only arm that never bled.</p><h4>Prompt-and-pray: the control that wouldn’t die</h4><p>The bet: a clear brief and plain prompts are enough.</p><p>Perfect through the invert. Stuck on the NFRs, just like Spec Kit. Clean after the handoff. I predicted it would collapse the moment the rules moved, and it didn’t, not on this product, with this model, at this size. I’m taking that seriously. It’s still not a reason to skip the next cycle.</p><h4>Spec Kit: strong pipeline, short memory</h4><p>The bet: a constitution plus a spec, plan, and task list for every feature keeps each change on rails.</p><p>Through the hardest functional change, it looked like the obvious default for a new internal product. Then the NFR wave stuck. The fresh session couldn’t unstick it. Per-feature scaffolding helps with the next <em>specified</em> change; it’s much less help when the job is finishing an unfinished one.</p><h4>LID: the hole that never closed</h4><p>LID makes the boldest claim of the five. Intent flows from a high-level design down through detailed designs and requirements to tests and code, and if you can’t regenerate behavior from the specs, you’ve got an intent gap.</p><p>It never posted a clean v1. Its failure count never dropped below two. I didn’t even get to test regenerability, because the first build was already wrong and nothing afterward fixed it.</p><h4>BMAD: polished v1, fumbled the small change</h4><p>The bet: a virtual team of roles beats a single agent with a spec file.</p><p>I ran the full method, not Quick Flow. It bought a clean first delivery, then lost the smallest delta in the script. The process docs piled up while the category checks kept failing. In fairness to BMAD, its real claim is discovery (turning a fuzzy idea into a product), and Cycle 1 never tested that.</p><h4>OpenSpec: named the delta, lost the session</h4><p>The bet: quality comes from naming each change precisely. ADDED, MODIFIED, REMOVED.</p><p>Clean v1, clean category change, broke on the invert, then slid backward at handoff. Yes, I ran a brownfield method on a product it had only just generated, which isn’t its home turf. It should still have handled the share-rule replacement. The bigger problem is the fresh session, where the specs bought nothing. Would a messy legacy codebase change that picture? Maybe. This cycle can’t tell you.</p><h4>What I predicted before I ran anything</h4><p>I wrote these down before the first arm started. Here’s the scorecard on my own guesses:</p><ul><li><strong>Prompt-and-pray looks fine at v1, then collapses when the rules invert.</strong> <em>Falsified.</em> It aced the invert, slipped on the NFRs, and recovered.</li><li><strong>Spec Kit or LID leads on a new product with real invariants.</strong> <em>Shaky.</em> LID never cleared v1, and Spec Kit failed the blank chat.</li><li><strong>OpenSpec is good at cheap, compatible changes.</strong> <em>Supported, barely.</em> The category change was clean; the invert and the handoff weren’t.</li><li><strong>BMAD’s strength is discovery.</strong> <em>Not tested.</em> Discovery wasn’t on this exam. The cheap change was, and BMAD lost it.</li><li><strong>GSD only pays off on a long backlog.</strong> <em>Incomplete.</em> It was already the only perfect sheet on a short one.</li><li><strong>LID shows long-lived coherence.</strong> <em>Not shown.</em> Four new passes at handoff, and the original gap never healed.</li></ul><p>One run, one model, one product. However wide that handoff gap looks, it isn’t a ranking yet.</p><h4>So is vibe coding better than people think?</h4><p>Here, yes.</p><p>Prompt-and-pray did far more than boot a shiny v1. It took the category change and the mid-flight rule flip without dropping a test, stumbled on the NFRs, and then a session with zero chat history fixed those failures and shipped the export. I predicted a collapse. I got a comeback.</p><p>“Better than people think” isn’t “best,” though. GSD is the only arm that stayed perfect the whole way, while prompt-and-pray blew an entire checkpoint and left no durable spec for the next person to read — a cost the human rubric will have to put a number on.</p><p>I also wrote the elimination rules before the run, and I’m holding myself to them. A failed handoff plus worse change survival than the control knocks a method out for this product type. Averaged across the three change checkpoints, LID, BMAD, and OpenSpec all trailed prompt-and-pray, so all three are out for greenfield products like this one. Spec Kit tied the control at 96% and survives, barely.</p><p>Out for <em>this</em> job, that is. BMAD’s pitch is discovery; OpenSpec’s is brownfield change. Neither of those was on the exam.</p><p>One cycle gets you medium confidence, tops. Brownfield systems, public APIs, ambiguous products, one-line tickets — all still unmeasured.</p><p>But if you’re picking an SDD stack off a thread, quit asking which toolkit writes the prettiest spec.md. Ask whether a new session can pick up where the last one left off.</p><h3>Next</h3><p>All six runs are done, and this post covered the automated half. Still to score, on a rubric I wrote before I saw any code:</p><ul><li>Do the artifacts match the behavior, or are they souvenirs?</li><li>Did the specs get <em>more</em> accurate after the invert, or did they reset?</li><li>Could a human actually live in this repo?</li></ul><p>After that comes a one-page note for managers and a call on what to run next: Cycle 2 (messy existing code) or Cycle 4 (a tiny ticket). Those are the jobs most teams actually have.</p><p>The first post lays out the full protocol. The short version: freeze the model, hide the tests, change the product on purpose, and don’t let the original chat sit the final exam.</p><p>So I closed it. One repo was clean going in and clean coming out. One walked in broken and walked out fixed. Three added the new passes and kept yesterday’s bugs. And one came out with more bugs than it walked in with.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74685f3b4726" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/vibe-coding-is-not-as-bad-as-people-think-74685f3b4726">Vibe Coding Is Not as Bad as People Think</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Spec-Driven Bake-Off: Six Methods, One Product, Hidden Tests]]></title>
            <link>https://medium.com/decisive-intentions/the-spec-driven-bake-off-six-methods-one-product-hidden-tests-7e4a2930d910?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4a2930d910</guid>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 02:25:05 GMT</pubDate>
            <atom:updated>2026-08-20T02:25:05.923Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I froze the model, changed the product mid-flight, then closed the chat on purpose. Ranking comes later.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0URrp4viccuz-WGkzI155Q.png" /></figure><p><em>Six methods enter. Hidden tests, a mid-flight rule change, and a fresh chat decide what survives.</em></p><p>Spec-driven development rankings are everywhere. Spec Kit wins on GitHub stars. OpenSpec gets called the brownfield choice. BMAD wins on ceremony. GSD promises to beat context rot. LID barely appears. Prompt-and-pray is the joke — until Friday, when everybody uses it anyway.</p><p>That tells me nothing about what happens after v1.</p><p>So I ran a bake-off: one product, one model, six methods, fixed time limits, and hidden tests. Then I changed the requirements and gave the final task to a new chat with no conversation history.</p><p>If the specs were useful, the new session should continue. If they were theater, this is where the costume comes off.</p><p>This is post 1: the protocol, not the ranking. The six runs are complete, but the human scoring is not. I will not crown a winner early.</p><h3>What I am testing</h3><p>Vibe coding is great for a spike. You paste a wish, the app boots, and you feel fast. Trouble starts when the rules move — or when someone who missed the original chat has to continue.</p><p>Spec-driven development (SDD) claims to solve that by keeping intent in durable files instead of chat history. Cycle 1 asks a narrow question:</p><blockquote>Which method best builds and evolves a new product with real business rules?</blockquote><p>It cannot pick a company-wide standard. It says nothing yet about legacy repos, public APIs, or tiny hotfixes. Those need separate cycles.</p><h3>The product</h3><p>Every arm builds the same group expense splitter:</p><ul><li>Email/password login with a session cookie</li><li>Groups with owners and members</li><li>Expenses split across group members</li><li>Balances that always sum to zero</li><li>Settlements that cannot overpay</li><li>Tenant isolation: non-members cannot see group data</li></ul><p>The stack is also fixed: Python, FastAPI, SQLAlchemy, SQLite, pytest, server-rendered HTML, and a JSON API. No Stripe, SPA, or OAuth. It is small enough to finish, but the money math and access rules leave plenty of room for a confident mistake.</p><h3>The six methods</h3><p>Prompt-and-pray is the control: the same brief and model, but no toolkit. The other five are real SDD workflows with different ideas about where quality comes from.</p><p>The links below point to current documentation. The pins show the versions I tested.</p><h4>GitHub Spec Kit</h4><p>Spec Kit moves through a constitution, spec, plan, tasks, and implementation. Its bet is simple: structured artifacts keep each feature on track. <a href="https://github.com/github/spec-kit">Repo</a></p><h4>OpenSpec</h4><p>OpenSpec describes each change as a delta against the current system: ADDED, MODIFIED, or REMOVED. You propose the change, apply it, then archive it into the living specs. <a href="https://github.com/Fission-AI/OpenSpec">Repo</a></p><h4>BMAD (Breakthrough Method for Agile AI-Driven Development)</h4><p>BMAD uses role-based artifacts: product brief, PRD, architecture, epics, and stories. I ran the full method, not Quick Flow, because the full workflow is the method’s distinctive claim. <a href="https://github.com/bmad-code-org/BMAD-METHOD">Repo</a></p><h4>Linked-Intent Development (LID)</h4><p>LID makes the strongest spec-as-source claim. Intent flows from a high-level design to detailed designs, structured requirements, tests, and code. Each phase stops for review before the next begins. <a href="https://github.com/jszmajda/lid">Repo</a></p><h4>GSD (Get Shit Done)</h4><p>GSD argues that long chats fail because context decays. It uses fresh subagents, atomic tasks, and persistent state under .planning/: discuss, plan, execute, verify, ship. <a href="https://github.com/open-gsd/gsd-core">Repo</a></p><p>Cursor Plan Mode is not an arm. It is part of the host, and every method already runs in Cursor. Mixing host experience with method quality would muddy the result.</p><h3>What stays fixed</h3><p>If the model changes between arms, I am grading the model — not the method.</p><p>Every run uses Cursor 3.16.17 and grok-4.6 with thinking set to High. I also froze the product brief, stack, later change prompts, hidden tests, time limits, and arm order.</p><p>One operator runs all six arms. I may approve steps, answer from the brief, or unblock tooling. I may not write production code. Any new clarification is recorded and reused verbatim for later arms.</p><h3>The six-step process</h3><h4>1. Build a private controller</h4><p>The controller holds the brief, evaluator, scoring scripts, and journals. Agents never open it, and hidden tests never enter an arm’s workspace.</p><h4>2. Freeze the oracle</h4><p>Before the first run, I froze the brief, change script, and 47 black-box HTTP checks. A reference app passed them. Planted bugs in split math, authorization, and settlement rules failed as expected.</p><h4>3. Create six isolated workspaces</h4><p>Each method gets its own git repo and Cursor profile. Only that method’s plugin is enabled. Every install is pinned and smoke-tested before the clock starts.</p><h4>4. Run one arm at a time</h4><p>Each arm gets the same sequence:</p><ol><li>Build v1.</li><li>Add a compatible feature.</li><li>Start a breaking change.</li><li>Receive a correction after the first production-code edit.</li><li>Add non-functional requirements.</li><li>Close the chat and complete a small handoff task in a fresh session.</li></ol><p>The total cap is eight hours: five hours for v1, then 45, 60, 45, and 30 minutes for the later segments. Unused time does not carry forward. Method-specific approvals count as human effort.</p><p>After every checkpoint, the controller starts the app, runs the hidden tests, and snapshots the tree.</p><p>If two methods finish within five weighted points, I restore the compatible-change snapshot and rerun only the breaking-change slice — not the whole project.</p><h4>5. Score only after all six runs</h4><p>Automated tests are primary. A pre-written human rubric covers what tests cannot: fidelity between specs and code, whether artifacts compound across changes, handoff quality, and maintainability.</p><h4>6. Choose the next cycle</h4><p>Cycle 1 is greenfield. The next cycle should match the work we actually do: brownfield modernization, public APIs, small tickets, product discovery, or a longer backlog.</p><h3>The changes</h3><p>The exam gets harder in stages:</p><p><strong>Wave 1:</strong> Build the expense splitter with even shares.</p><p><strong>Compatible change:</strong> Add an expense category and exact category filtering.</p><p><strong>Breaking change:</strong> Start replacing even shares with weighted shares. After the first production-code edit, change the requirement to percentage shares totaling exactly “100.00”. Only the final rule is scored.</p><p><strong>NFR change:</strong> Add a per-user write rate limit and an immutable settlement audit log.</p><p><strong>Handoff:</strong> Close the chat. In a new session, add GET /groups/{id}/settlements.csv with no recap of the earlier work.</p><p>That last step matters most. A good first build can ride on chat history. A fresh session has only the repository.</p><h3>How scoring works</h3><p>The 100-point score is weighted toward change and handoff:</p><ul><li><strong>30%:</strong> hidden tests after the changes</li><li><strong>15%:</strong> hidden tests at Wave 1</li><li><strong>15%:</strong> fresh-session handoff</li><li><strong>10%:</strong> spec-code fidelity</li><li><strong>10%:</strong> active human effort</li><li><strong>10%:</strong> artifact compounding</li><li><strong>5%:</strong> completion time</li><li><strong>5%:</strong> maintainability</li></ul><p>The rules were written before I saw results:</p><ul><li>A gap under five weighted points is a <strong>tie</strong>.</li><li>Change survival under 50% eliminates a method for this product type.</li><li>A failed handoff plus worse change survival than vibe also eliminates it.</li><li>A winner must lead the total score without trailing the best change-survival result by more than 10 percentage points.</li><li>Cheap does not win if the product breaks.</li></ul><p>Handoff passes only if its gated tests pass and the applicable suite drops no more than 10 percentage points from the previous checkpoint. Effort and time are scored against targets fixed in advance — not against whichever arm happened to be fastest.</p><p>One cycle is directional evidence, not a company mandate.</p><h3>Where things stand</h3><p>All six implementation runs are finished. Next comes the human rubric and the manager scorecard.</p><p>The rest of this series will cover:</p><ol><li><strong>Wave 1</strong>: who shipped, and what the ceremony cost.</li><li><strong>Change survival</strong>: what happened when the rules moved.</li><li><strong>Handoff</strong>: what a fresh chat could — and could not — recover.</li><li>The final recommendation.</li></ol><p>If you are choosing an SDD stack from a thread, wait for the scorecard. If you are designing your own comparison, steal the constraints: freeze the model, hide the tests, change the product on purpose, and do not let the original chat sit the final exam.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4a2930d910" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/the-spec-driven-bake-off-six-methods-one-product-hidden-tests-7e4a2930d910">The Spec-Driven Bake-Off: Six Methods, One Product, Hidden Tests</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Death of ‘Prompt and Pray’: A Field Guide to AI Spec-Driven Development]]></title>
            <link>https://medium.com/decisive-intentions/the-death-of-prompt-and-pray-a-field-guide-to-ai-spec-driven-development-fb39e9e46a5d?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb39e9e46a5d</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[agentic-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[sdd]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 16:39:56 GMT</pubDate>
            <atom:updated>2026-08-08T16:39:56.192Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How GitHub, Microsoft, AWS, and open-source teams steer AI agents with hard specifications.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJzDCGjCcABwaBgzuibZMw.png" /><figcaption>Scattered business intents are bound into hard executable contracts</figcaption></figure><h3><strong>The Great Prompting Hangover</strong></h3><p><strong>Vibe coding is dead.</strong> We spent two years treating Large Language Models like mystical magic wands, throwing half-baked prompts at a chat window and praying the resulting code wouldn’t collapse when five real users hit the staging server at once.<br>It worked great for 50-line scripts and slick pitch-deck prototypes. Then we tried building actual software with it.<br>The hangover was brutal. Without hard boundaries, AI assistants turn codebases into radioactive waste, slapping together Frankenstein architectures, inventing non-existent API parameters, and burying subtle security flaws that only surface on a Friday night deployment. You spend four hours debugging a hallucinated import that saved you three minutes to generate. That isn’t velocity. It’s technical debt on credit.<br> <strong>Real engineering teams are pivoting to a far stricter discipline: Spec-Driven Development (SDD).</strong></p><h3><strong>Flipping the Power Dynamic</strong></h3><p>Spec-Driven Development flips the traditional relationship between code and documentation entirely on its head.<br>In classic software workflows — and certainly in early AI prompting — code was king. Documentation was an afterthought, written begrudgingly weeks after launch (if at all). <strong>SDD inverts this power structure: code serves the specification.</strong><br>Instead of asking an AI model to guess what you want, you author a precise, version-controlled spec <em>before</em> any compiler or interpreter sees a line of code. <strong>The specification becomes the single source of truth for both human engineers and synthetic agents.</strong> Code is reduced to a downstream derivative: a disposable artifact generated and checked against the spec contract.</p><h3><strong>The 6 Pillars of SDD</strong></h3><p>Strip away the marketing fluff from vendor landing pages, and every working SDD setup relies on six core rules:</p><ol><li><strong>Specs Rule Everything Around Me:</strong> Specifications hold absolute authority. If the generated code doesn’t match the spec, the code is wrong — period.</li><li><strong>Decouple Intent from Execution:</strong> Define what needs to happen and why it matters before arguing over frameworks or tech stacks.</li><li><strong>Specs as Hard Gates:</strong> Specifications act as automated CI/CD brick walls. If a pull request breaks architectural rules defined in the spec, the build fails before unit tests even run.</li><li><strong>Version Control Your Thinking:</strong> Commit your design choices (spec.md, plan.md, .cursorrules) right alongside your source tree.</li><li><strong>Context Engineering Over Chat History:</strong> Stop relying on ephemeral chat windows; persistent steering files pass unambiguous project state directly to the model.</li><li><strong>Humans Hold the Steering Wheel:</strong> AI handles boilerplate churn and context processing, but human engineers sign off on the contracts.</li></ol><h3><strong>A Field Guide to the 9 Frameworks Reshaping AI Engineering</strong></h3><p>Rather than relying on vague chat prompts, engineering teams across the industry have built distinct, production-tested frameworks to bring order to AI code generation. Here is how the top nine methods actually work in practice.</p><h4><strong>1. GitHub Spec Kit: Standardizing the Worktree</strong></h4><p>When you ask an AI agent to add a feature to a 100,000-line codebase, the agent’s natural inclination is to take the path of least resistance, which usually means grafting a messy hack onto your cleanest module. <strong>GitHub’s open-source spec-kit solves this by forcing a three-stage conversation (spec.md, plan.md, tasks.md) before any code is written.</strong><br>First, you collaborate with the agent via /speckit.specify to generate spec.md, defining what the user needs without mentioning tech stacks or frameworks. Next, /speckit.plan analyzes your existing repository to craft plan.md, locking down your design system, API boundaries, and security rules. Finally, the agent breaks the plan into a checklist of micro-tasks in tasks.md and executes them one checkbox at a time. It turns chaotic prompt iteration into a predictable, version-controlled pull request.</p><h4><strong>2. Microsoft Spec-First Engineering: Guardrails for Enterprise Scale</strong></h4><p>The most dangerous code generated by AI isn’t the code that fails; it’s the code that passes local unit tests while quietly violating enterprise compliance, performance budgets, or security policies. <strong>Microsoft’s spec-first approach treats specifications as legally binding technical contracts that automated CI/CD pipelines audit directly against.</strong><br> Before launching generation, engineering teams define non-functional requirements (NFRs), security benchmarks, and edge cases in repo-committed spec files. When AI agents build features, automated CI/CD pipelines audit the generated output directly against those pre-defined contract gates. If an AI agent attempts to bypass a security check or introduce an unapproved dependency, the build breaks automatically, long before a human reviewer ever sees the diff.</p><h4><strong>3. Thoughtworks &amp; Martin Fowler: The 3-Tier Maturation Curve</strong></h4><p>In an industry flooded with buzzwords, Thoughtworks and Martin Fowler cut through the noise by establishing a clear taxonomy based on specification longevity. <strong>They categorize SDD workflows into a three-tier spectrum: Spec-First (ephemeral specs), Spec-Anchored (living Git documentation), and Spec-as-Source (where specs are the primary edited files).</strong><br> Most engineering teams begin at Spec-First for quick experimental spikes, but enterprise applications demand Spec-Anchored workflows where specifications live in Git as living documentation. The ultimate horizon (Spec-as-Source) treats high-level specifications as the source code itself, leaving humans to edit specifications while AI models handle compilation.</p><h4><strong>4. AWS &amp; IBM AI-DLC: Killing the Two-Week Sprint</strong></h4><p>Applying human-centric Scrum ceremonies and two-week sprints to autonomous AI agents is like hooking a jet engine to a horse-drawn carriage. AWS and IBM introduced the AI-Driven Development Lifecycle (AI-DLC) to completely replace obsolete SDLC rituals.<br> <strong>AI-DLC replaces multi-week sprints with “Bolts” (rapid execution cycles lasting hours or days) and replaces epics with “Units of Work” guided by repository Steering Files.</strong> During <em>Mob Elaboration</em> sessions, cross-functional teams work with AI agents to refine steering rules, allowing autonomous agents to build, test, and manage Infrastructure as Code (IaC) deployments under continuous human supervision.</p><h4><strong>5. Augment Code &amp; Academic Multi-Agent Contracts</strong></h4><p>When you deploy multiple AI agents to work on parallel subtasks, they inevitably step on each other’s toes, altering shared API payloads or breaking component boundaries that unit tests miss. <strong>Augment Code enforces strict 6-element contracts managed across Coordinator, Implementor, and Verifier agents to prevent multi-agent contract drift.</strong><br> Grounded in peer-reviewed research (<a href="https://arxiv.org/abs/2602.00180">Piskala et al., arXiv 2026</a>), this architecture uses a Coordinator Agent to map dependencies, Implementor Agents to code inside boundaries, and a Verifier Agent to audit diffs against contract gates before merging.</p><h4><strong>6. Schema-First / API-Driven SDD: The Microservice Foundation</strong></h4><p>Long before generative AI took over headlines, schema-first development served as the backbone for distributed microservices. By making machine-readable contracts (OpenAPI, AsyncAPI, Protobuf) the primary source of truth, teams prevent frontend and backend developers from breaking each other’s builds.<br> <strong>Developers write or edit the machine-readable API schema first, acting as an unyielding boundary that keeps frontend teams, backend teams, and AI agents aligned across network boundaries.</strong> AI agents immediately ingest the contract to generate server stubs, client SDKs, mock endpoints, and automated contract test suites (using tools like Specmatic).</p><h4><strong>7. Open-Source Agentic Protocols: OpenSpec, BMAD, and GSD</strong></h4><p>Proprietary AI IDEs are great until your team switches tools or wants to run local terminal agents. To avoid vendor lock-in, the open-source community created agentic spec protocols like OpenSpec, the BMad Method, and GSD (Get Stuff Done).<br> <strong>Open steering files (CLAUDE.md, .cursorrules) allow developers to run terminal CLI agents across any editor without vendor lock-in.</strong> Whether you’re running Claude Code in a terminal, Cursor on a desktop, or Aider in a container, the agent reads the same steering files, executes task checklists incrementally, and logs state transitions directly to your Git commit history.</p><h4><strong>8. IDE-Embedded Real-Time SDD: Kiro &amp; Cursor Plan Mode</strong></h4><p>Switching back and forth between external documentation dashboards and your code editor introduces friction that kills developer flow. IDE-embedded SDD solves this by baking spec synchronization directly into the editing interface (as seen in Amazon Kiro, Cursor Plan Mode, and Windsurf).<br> <strong>Toggle Plan Mode to lock the editor into a read-only research sandbox, where live guardrail hooks monitor file edits in real time to prevent spec deviations.</strong> Once you review and sign off on the plan inside the editor panel, live guardrail hooks monitor every file edit in real time.</p><h4><strong>9. Self-Spec / LLM-Synthesized SDD: Taming Legacy Codebases</strong></h4><p>The biggest practical obstacle to Spec-Driven Development is the cold-start problem: nobody wants to spend three days writing manual specs for a messy, five-year-old legacy codebase. Self-specifying workflows use LLMs to solve their own documentation problem.<br> <strong>LLMs solve the cold-start problem by ingesting legacy code to reverse-engineer underlying business rules and auto-generate structured specs.</strong> The model synthesizes the raw input and auto-generates a clean specification complete with scope boundaries and edge-case test suites for human sign-off.</p><h4><strong>Quick Reference: Which SDD Method Do You Need?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVb-yx_JHjd4eQ7kLVSfrg.png" /></figure><h3><strong>The Hard Truth About Engineering in the AI Era</strong></h3><p>Vibe coding wasn’t a mistake; it was just childhood. It showed us what LLMs could do, but scaling real software requires adult supervision.<br> In the AI era, typing speed is worthless. Syntactic fluency is a solved problem. <strong>Your value as a software engineer now hinges entirely on how clearly, logically, and unambiguously you can express intent through specifications.</strong><br> Mastering SDD means learning how to write tight contracts, enforce architectural boundaries, and treat AI agents as precision tools rather than fortune tellers. <strong>You aren’t writing code anymore; you’re directing it.</strong></p><h3><strong>References &amp; Sources</strong></h3><ul><li><a href="https://github.blog/ai-and-ml/generative-ai/spec-driven-development-with-ai-get-started-with-a-new-open-source-toolkit/">GitHub Blog: Spec-driven development with AI</a></li><li><a href="https://developer.microsoft.com/blog/spec-driven-development-ai-native-engineering/">Microsoft Developer Blog: A Spec-First Approach to AI-Native Engineering</a></li><li><a href="https://martinfowler.com/articles/exploring-gen-ai/sdd-3-tools.html">Martin Fowler / Thoughtworks: Understanding Spec-Driven-Development</a></li><li><a href="https://aws.amazon.com/blogs/devops/ai-driven-development-life-cycle/">AWS DevOps Blog: AI-Driven Development Life Cycle</a></li><li><a href="https://www.ibm.com/think/topics/ai-dlc">IBM Think: AI-DLC: The AI-Driven Development Lifecycle</a></li><li><a href="https://www.augmentcode.com/guides/what-is-spec-driven-development">Augment Code: What Is Spec-Driven Development?</a></li><li><a href="https://arxiv.org/abs/2602.00180">arXiv Research Paper: Spec-Driven Development: From Code to Contract in the Age of AI</a></li><li><a href="https://github.com/bmad-code-org/bmad-method">BMad Method GitHub Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb39e9e46a5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/the-death-of-prompt-and-pray-a-field-guide-to-ai-spec-driven-development-fb39e9e46a5d">The Death of ‘Prompt and Pray’: A Field Guide to AI Spec-Driven Development</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The $2 Trillion AI Disconnect: Why Knowledge Graphs and Semantic Frameworks Will Decide Who Wins…]]></title>
            <link>https://medium.com/decisive-intentions/the-2-trillion-ai-disconnect-why-knowledge-graphs-and-semantic-frameworks-will-decide-who-wins-c986de4fd8bd?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/c986de4fd8bd</guid>
            <category><![CDATA[ontology]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[semantic-layer]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 07:01:15 GMT</pubDate>
            <atom:updated>2026-07-30T07:01:15.377Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The $2 Trillion AI Disconnect: Why Knowledge Graphs and Semantic Frameworks Will Decide Who Wins the Enterprise AI Race</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atAFmDCySmIOMpEBe5yzmw.png" /><figcaption>Architecting certainty: Constructivist representation of the data triad bringing order to autonomous AI systems</figcaption></figure><p>Picture two autonomous AI agents presenting quarterly revenue figures to a CFO:</p><ul><li><strong>Agent A:</strong> <em>“Q3 Net Revenue was $42.5 million.”</em></li><li><strong>Agent B:</strong> <em>“Q3 Net Revenue was $38.2 million.”</em></li></ul><p>Both models cite official corporate databases. Both write clean, error-free SQL. Both deliver their answers with 100% confidence.</p><p>Which one is right?</p><p>Neither. Agent A included unverified trial accounts because Sales defines “revenue” by signed contracts. Agent B deducted pending product returns because Finance counts revenue strictly when cash clears.</p><p>This isn’t a model failure — GPT-4o and Claude 3.5 Sonnet executed their instructions perfectly. It’s a <strong>data architecture failure</strong>. When AI systems lack a shared, governed understanding of core business concepts, they generate <em>confident confusion</em> — authoritative-sounding answers built on silently conflicting definitions.</p><p>Enterprises will pour over $2 trillion into AI by the end of 2026. Yet today, only one in five organizations sees a tangible return. Without a shared semantic foundation, autonomous multi-agent systems are on track to double that failure rate — killing up to 60% of enterprise AI projects by 2028.</p><p>To fix this, leading engineering teams are converging on a unified pattern: the <strong>Unified Truth Layer</strong>. Here is how it works, why the math behind it is indisputable, and how it transforms enterprise AI from a risky gamble into predictable infrastructure.</p><p><strong>1. The Real Bottleneck Isn’t Model Size — It’s “Semantic Drift”</strong></p><p>For the past three years, the enterprise AI playbook was simple: throw larger LLMs at bigger vector databases. If an agent hallucinated, you upgraded the model or tweaked the prompt.</p><p>That strategy has hit a wall.</p><p>Vector search is great at finding fuzzy text matches — like pulling customer service transcripts that sound like “billing complaints.” But it fails completely on deterministic business logic. Embeddings don’t understand that “net revenue” in North America excludes intercompany transfers, or that a customer’s credit risk rating changes the moment a loan officer flags a late payment.</p><p>When identical concepts carry different definitions across departmental silos, you get <strong>semantic drift</strong>. On a dashboard, a human analyst eventually catches the discrepancy. In an autonomous multi-agent pipeline, those tiny definition gaps compound into catastrophic errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*bJffZpbz-QyqLzej-QBv4A.png" /></figure><p><strong>2. Architecting the Triad: Ontology, Knowledge Graph, and Semantic Layer</strong></p><p>The Unified Truth Layer solves semantic drift by placing three deterministic components between your raw data warehouses and your AI agents:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*lnVuXm1Olj6q21ORNeyO8g.png" /></figure><ol><li><strong>The Ontology (The Rulebook):</strong> A machine-readable schema defining what entities exist and how they are logically allowed to interact. It doesn’t store data; it enforces business rules. For example: <em>“A mortgage is a subclass of loan, and every loan must have at least one borrower.”</em></li><li><strong>The Knowledge Graph (The Fact Map):</strong> Connects actual operational data using explicit triples (Subject -&gt; Predicate -&gt; Object). Instead of dumping records into flat SQL tables, it tracks relationships: [Customer_42] -&gt; [purchased] -&gt; [Product_789] -&gt; [manufactured_by] -&gt; [Supplier_Alpha].</li><li><strong>The Enterprise Semantic Layer (The Business Grammar):</strong> Sits on top of the graph to expose governed metrics, dimensions, and KPIs to end consumers via APIs. It ensures that every query for “Gross Margin” uses the exact same mathematical formula, regardless of who asks.</li></ol><p>Together, this triad gives AI agents a deterministic map of your business instead of forcing them to guess table joins on the fly.</p><p><strong>3. The Hard Numbers: How Knowledge Graphs Quadruple LLM Accuracy</strong></p><p>Does adding a formal semantic structure actually improve model output? Juan Sequeda, Dean Allemang, and their team put this exact question to an empirical test using an enterprise insurance schema (13 normalized SQL tables with dense many-to-many joins).</p><p>They fired 43 complex natural language queries at GPT-4 under three different architectural conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*SVV6sc-lc05Wrt33K5GcRg.png" /></figure><ul><li><strong>Raw Text-to-SQL (No Semantics):</strong> Pointing GPT-4 directly at the database yielded a dismal <strong>16.7% accuracy</strong>. On high-complexity queries requiring multi-table joins, accuracy dropped to <strong>0%</strong>.</li><li><strong>Text-to-SPARQL (Knowledge Graph Context):</strong> Querying over a knowledge graph representation boosted accuracy to <strong>54.2%</strong> — a 3.2x improvement.</li><li><strong>KG + Ontology Guardrails (OBQC):</strong> Adding an <em>Ontology-Based Query Check</em> — intercepting queries to validate domain/range rules before execution — drove accuracy to <strong>72.0%</strong>, with an additional 8% safe refusal rate (“I don’t know”).</li></ul><p>That is a <strong>4x improvement in accuracy</strong> simply by giving the LLM a governed semantic map.</p><p><strong>4. Open Semantic Interchange (OSI) and the ai_context Standard</strong></p><p>Historically, semantic logic was trapped inside proprietary BI tools like Tableau or Power BI. If an AI engineer wanted to query a metric from a Python script or an AI agent, they had to reverse-engineer the SQL calculations by hand.</p><p>In late 2025, Snowflake, Salesforce, dbt Labs, BlackRock, and RelationalAI launched the <strong>Open Semantic Interchange (OSI)</strong> initiative to fix this.</p><p>OSI provides an open, vendor-neutral standard for defining semantic models in human-readable YAML. The standout feature is its native ai_context field:</p><pre># Open Semantic Interchange (OSI) Metric Definition<br> semantic_model:<br> name: revenue_analytics<br> measures:<br> - name: gross_arr<br> expr: annual_contract_value<br> agg: sum<br> ai_context:<br> description: &quot;Gross Annual Recurring Revenue, excluding trial accounts and pending refunds.&quot;<br> synonyms: [&quot;ARR&quot;, &quot;Yearly Revenue&quot;, &quot;Annual Sales&quot;]<br> business_rules: &quot;Only count contracts flagged as &#39;active&#39; by Finance.&quot;</pre><p>When an LLM queries an OSI-compliant semantic layer, it ingests this metadata automatically. The ai_context field acts as a translator between messy human prompts (“What’s our yearly sales velocity?”) and precise database queries.</p><p><strong>5. The Financial Return: 551% ROI and 48.9% Cache Deflection</strong></p><p>A semantic layer isn’t just an accuracy play — it’s a massive cloud cost killer.</p><p>An independent study by UserEvidence analyzing enterprise deployments of Strategy’s Mosaic semantic layer revealed eye-popping financial metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*vehrCS4AXxHtKeIL-BY4SA.png" /></figure><p>How does a semantic layer generate millions in net savings so fast?</p><ol><li><strong>Intelligent Query Caching:</strong> Without a semantic layer, every user or AI agent asking for “Daily Sales” triggers a fresh, expensive SQL query in Snowflake or Databricks. A semantic layer caches aggregated subresults in memory. Strategy’s study found that <strong>48.9% of production queries never hit the warehouse at all</strong> — slashing compute costs by 20%.</li><li><strong>Elimination of Redundant Engineering:</strong> Centralizing metric logic drove a <strong>44% reduction in duplicate metrics</strong>, saving technical teams thousands of hours previously spent reconciling conflicting reports.</li></ol><p><strong>6. Advanced Retrieval: Why GraphRAG and DRIFT Search Beat Standard RAG</strong></p><p>For unstructured text — legal contracts, medical reports, regulatory filings — standard vector RAG is rapidly falling out of favor. Chunking text into isolated vector embeddings loses the core connections between documents.</p><p>Microsoft Research introduced <strong>GraphRAG</strong> to bridge unstructured documents into the Unified Truth Layer. During data ingestion, LLMs extract entities and relationships from text, compiling them into a graph structure and running community detection algorithms (like Leiden) to summarize document clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*rFT9Urqxxd5fyBz6f0wNkQ.png" /></figure><p>In benchmark evaluations, DRIFT Search (Dynamic Reasoning and Inference with Flexible Traversal) outperformed standard local retrieval baselines by <strong>78% on response comprehensiveness</strong> and <strong>81% on insight diversity</strong>, making it the gold standard for complex research queries.</p><p><strong>7. Regulatory Compliance: Automated Data Lineage and BCBS 239</strong></p><p>In regulated industries like banking and healthcare, knowing <em>where</em> data came from is just as important as the answer itself.</p><p>The Basel Committee’s <strong>BCBS 239</strong> standard mandates that financial institutions prove the full lineage of every number in their risk reports. Doing this manually across legacy relational databases takes months of billable consultant hours.</p><p>In a Unified Truth Layer, data lineage is recorded automatically as immutable semantic edges inside a metadata knowledge graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*Cj4SgrpretDOdbWqNBIaDA.png" /></figure><p>By leveraging <strong>Temporal Knowledge Graphs (TKGs)</strong>, institutions gain “time-travel” auditing capabilities. When a regulator asks why a loan was approved six months ago, compliance teams can point to the exact graph state and ontology rules active on that day. UBS successfully implemented this pattern to satisfy global BCBS 239 audits.</p><p><strong>8. Inference Economics: The Token Consumption Trap</strong></p><p>By 2030, Gartner estimates that the cost of running LLM inference will fall by over 90%. That sounds like a win for enterprise budgets, but it hides a dangerous economic trap.</p><p>While cost per token drops, total token <strong>consumption</strong> is exploding. Autonomous multi-agent systems use 5x to 30x more tokens per task than simple single-turn chatbots because they iterate through multi-step reasoning, query generation, and self-correction loops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*01s9Vi4L-CuqQJKrIlHcQA.png" /></figure><p>If you deploy un-grounded agents against raw databases, cheaper chips won’t save you — they will simply accelerate the speed at which your enterprise burns budget on hallucinated answers. A governed semantic layer acts as an economic circuit breaker.</p><p><strong>How to Build Your Unified Truth Layer: A 4-Step Roadmap</strong></p><p>You don’t need to rewrite your entire data stack overnight. The most successful engineering teams adopt an incremental approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*E37Z8b9gZS7u2A79rxNYsQ.png" /></figure><ol><li><strong>Formalize Core Metrics:</strong> Sit down with Finance, Operations, and Sales to define your top 10 KPIs in code (YAML). Store these definitions in version-controlled Git repositories.</li><li><strong>Deploy a Universal Semantic Layer:</strong> Implement a headless layer (such as dbt MetricFlow, Cube, or Strategy Mosaic) in front of your data warehouse so every tool and agent shares the same definitions.</li><li><strong>Build a Graph Layer for Relationship-Heavy Domains:</strong> Focus initial knowledge graph investments on domains where multi-hop connections matter most — such as Customer 360, Fraud Detection, or Supply Chain Tracking.</li><li><strong>Enforce Agentic Guardrails:</strong> Implement Ontology-Based Query Checks (OBQC) to intercept and validate LLM-generated queries before they run against live production databases.</li></ol><p><strong>The Bottom Line</strong></p><p>The enterprise AI race won’t be won by the company with the largest LLM prompt window. It will be won by the enterprise that builds the cleanest cognitive foundation.</p><p>Semantic grounding is no longer a luxury data engineering project. It is the fundamental dividing line between AI initiatives that deliver measurable ROI and those that collapse under the weight of their own hallucinations.</p><p><strong>References</strong></p><ol><li><strong>Gartner Press Release</strong> (Sept 2025): “Worldwide AI Spending Forecast.”</li><li><strong>Capital One Software / Gartner Data &amp; Analytics Summit</strong>: “Context is Key to AI Success.”</li><li><strong>Sequeda, J. F., Allemang, D., &amp; Jacob, B.</strong> (2023): “A Benchmark to Understand the Role of Knowledge Graphs on LLM Accuracy for Question Answering on Enterprise SQL Databases.”</li><li><strong>Open Semantic Interchange (OSI)</strong> (2025): “Semantic Model Core Classes Specification.”</li><li><strong>Strategy / UserEvidence Study</strong> (2025): “When 551% ROI on Semantic Layer Changes the Conversation.”</li><li><strong>Microsoft Research</strong> (2024): “DRIFT Search: Combining Global and Local Search Methods for Quality and Efficiency.”</li><li><strong>Neo4j Case Study</strong>: “Data Lineage and BCBS 239 Compliance at UBS.”</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c986de4fd8bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/the-2-trillion-ai-disconnect-why-knowledge-graphs-and-semantic-frameworks-will-decide-who-wins-c986de4fd8bd">The $2 Trillion AI Disconnect: Why Knowledge Graphs and Semantic Frameworks Will Decide Who Wins…</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless OpenAPI for AWS Lambda: Unified Docs & Validation with Powertools]]></title>
            <link>https://medium.com/decisive-intentions/effortless-openapi-for-aws-lambda-unified-docs-validation-with-powertools-1ea7ab9efbfa?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ea7ab9efbfa</guid>
            <category><![CDATA[api-documentation]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 03:41:41 GMT</pubDate>
            <atom:updated>2025-06-04T03:41:41.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EEUicL54z7HYtM2lr9uGQ.png" /></figure><p>The serverless dream — scalability, pay-per-use, rapid development — is interesting. But this dream can hit a documentation snag. In a monolithic world, tools like Swagger UI effortlessly generate API specs from a single FastAPI app. Transition to AWS Lambda, and suddenly you’re juggling many small handlers, each a distinct island, often with production code eager to run on import. Crafting a unified, authoritative API specification feels like a Herculean task.</p><p>But what if it wasn’t? Imagine defining your API <em>once</em> per Lambda and, from that single source of truth, getting both <strong>runtime request validation</strong> <em>and</em> a perfect OpenAPI schema fragment. That’s precisely what AWS Lambda Powertools for Python offers.</p><p>This guide walks you through a complete, production-ready workflow to:</p><ol><li><strong>Generate OpenAPI schemas</strong> from every Lambda function using Powertools.</li><li><strong>Automatically validate incoming requests</strong> based on these schemas, live in your Lambda.</li><li><strong>Merge all schemas</strong> into a single, unified OpenAPI document.</li><li><strong>Render an interactive Swagger UI site</strong> with a single make command.</li><li>Sidestep common pitfalls like import-time side effects and tricky data serialization.</li><li>Understand when Powertools shines compared to alternatives like FastAPI for Lambda.</li></ol><h3>Why Bother with Unified Lambda Documentation?</h3><p>Beyond the obvious “good practice,” a solid documentation strategy delivers tangible benefits:</p><ul><li><strong>Smoother Onboarding:</strong> New team members grasp your API landscape quickly from a single, reliable source.</li><li><strong>Robust Automated Testing:</strong> Drive contract tests from your OpenAPI spec, catching breaking changes before they hit production.</li><li><strong>Clear External Communication:</strong> Easily share an interactive developer portal with partners or the public (hosted on S3/CloudFront, for instance).</li><li><strong>Confidence Through Validation:</strong> With Powertools, the same definitions that build your documentation <em>also validate incoming requests</em>, ensuring your spec always reflects reality and your Lambda fails fast on bad input.</li></ul><h3>AWS Lambda Powertools: The Game Changer for Docs &amp; Validation</h3><p><a href="https://awslabs.github.io/aws-lambda-powertools-python/latest/">AWS Lambda Powertools for Python</a> isn’t just another library; it’s a lean, serverless-native utility belt. For our purposes, two features are transformative:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*IgF8M4wOWFkFiXcukGlVGg.png" /></figure><p>The magic? Describe your API contracts once using Pydantic models with the APIGatewayHttpResolver. Powertools then delivers both robust runtime validation (rejecting invalid requests automatically) <em>and</em> a precise OpenAPI schema fragment. No more drift between your docs and your code.</p><p>Let’s see it in action with a simplified index.py from a User Management Lambda:</p><pre>from typing import TypeVar, Union, List, Dict, Any, Generic<br>from aws_lambda_powertools.event_handler import APIGatewayHttpResolver<br>from aws_lambda_powertools.event_handler.openapi.params import Body<br>from aws_lambda_powertools.event_handler.openapi.models import (<br>    OpenAPI,<br>)  # For type hinting<br>from pydantic import BaseModel, Field<br>from pydantic.generics import GenericModel<br>import json<br>import os<br>T = TypeVar(&quot;T&quot;, bound=Union[BaseModel, List[Any], Dict[str, Any]])<br># Assume user_service and other necessary imports exist<br># Initialize Powertools Resolver with validation enabled<br>app = APIGatewayHttpResolver(<br>    serializer=lambda obj: json.dumps(obj, default=str),  # Handle datetime etc.<br>    enable_validation=True,  # This is key for runtime validation!<br>    debug=True,  # Useful during development<br>)<br># Optionally, enable a self-hosted Swagger UI endpoint for this Lambda<br># app.enable_swagger(path=&quot;/docs&quot;, title=&quot;User API&quot;, version=&quot;1.0.0&quot;)<br><br># Define Pydantic models for requests and responses<br>class CreateUserRequest(BaseModel):<br>    email: str = Field(<br>        ..., description=&quot;User&#39;s email address&quot;, example=&quot;user@example.com&quot;<br>    )<br>    password: str = Field(..., description=&quot;User&#39;s password&quot;, min_length=8)<br>    name: str = Field(..., description=&quot;User&#39;s full name&quot;, example=&quot;Jane Doe&quot;)<br><br>class SuccessResponse(GenericModel, Generic[T]):<br>    status: str = Field(default=&quot;success&quot;)<br>    message: str<br>    data: dict | None = Field(default=None)<br><br>class ErrorResponse(BaseModel):<br>    &quot;&quot;&quot;Standard error response&quot;&quot;&quot;<br>    status: str = Field(default=&quot;error&quot;)<br>    error: str = Field(..., description=&quot;Error details&quot;)<br><br>class User(BaseModel):<br>    &quot;&quot;&quot;User model for API responses&quot;&quot;&quot;<br>    user_id: str = Field(..., description=&quot;Unique user identifier&quot;)<br>    email: str = Field(..., description=&quot;User email address&quot;)<br>    name: str = Field(..., description=&quot;User display name&quot;)<br><br># Define an API endpoint<br>@app.post(<br>    &quot;/users&quot;,<br>    tags=[&quot;Users&quot;],<br>    operation_id=&quot;createUser&quot;,<br>    summary=&quot;Create a new user&quot;,<br>    description=&quot;Creates a new user account in the system.&quot;,<br>    response_description=&quot;Returns the created user data&quot;,<br>    responses={  # type: ignore<br>        201: {<br>            &quot;content&quot;: {&quot;application/json&quot;: {&quot;model&quot;: SuccessResponse[User]}},<br>            &quot;description&quot;: &quot;User created successfully&quot;,<br>        },<br>        409: {<br>            &quot;content&quot;: {&quot;application/json&quot;: {&quot;model&quot;: ErrorResponse}},<br>            &quot;description&quot;: &quot;Conflict – user already exists.&quot;,<br>        },<br>        422: {<br>            &quot;content&quot;: {&quot;application/json&quot;: {&quot;model&quot;: ErrorResponse}},<br>            &quot;description&quot;: &quot;Unprocessable Entity – Pydantic validation failed.&quot;,<br>        },<br>        500: {<br>            &quot;content&quot;: {&quot;application/json&quot;: {&quot;model&quot;: ErrorResponse}},<br>            &quot;description&quot;: &quot;Internal Server Error – unexpected failure.&quot;,<br>        },<br>    },<br>)<br>def create_user(user_data: CreateUserRequest = Body(...)) -&gt; SuccessResponse:<br>    # user_data is now a validated Pydantic model instance<br>    # If validation failed, Powertools would have already returned a 400 error<br>    created_user_details = user_service.create_user(user_data)<br>    return SuccessResponse(<br>        message=&quot;User created successfully&quot;, data=created_user_details<br>    )<br><br># This function will be called by our documentation generator<br>def get_openapi_spec() -&gt; OpenAPI:  # Or &#39;dict&#39; if you prefer<br>    return app.get_openapi_schema()</pre><p>With enable_validation=True, any request to /users with a malformed body (e.g., missing email, password too short) will automatically result in an HTTP 400 response <em>before</em> your create_user logic even runs. And get_openapi_spec() provides the schema based on CreateUserRequest and SuccessResponse.</p><h3>Weaving It All Together: The Master Documentation Script</h3><p>Each Lambda can now offer its OpenAPI fragment. The next step is a script, typically placed at your project’s root, that discovers these fragments, merges them, and renders your final documentation.</p><p>Here’s the generate_docs.py script:</p><pre># generate_docs.py<br>import os<br># Crucial: Set an environment variable to signal &quot;documentation build mode&quot;<br># This allows Lambda code to skip production initializations (e.g., DB connections)<br>os.environ.setdefault(&quot;DOCS_BUILD&quot;, &quot;1&quot;)<br>import sys<br>import json<br>import importlib.util<br>from pathlib import Path<br>from tqdm import tqdm # For a nice progress bar<br>from enum import Enum # For handling enums in OpenAPI specs<br>ROOT = Path(__file__).parent.resolve()<br># Add project root to sys.path to handle absolute imports in Lambda code<br>if str(ROOT) not in sys.path:<br>    sys.path.insert(0, str(ROOT))<br>def all_index_modules() -&gt; list[Path]:<br>    &quot;&quot;&quot;Finds all index.py files in the project.&quot;&quot;&quot;<br>    return list(ROOT.rglob(&quot;index.py&quot;))<br>def flush_cached_app_modules():<br>    &quot;&quot;&quot;<br>    Crucial for projects where multiple Lambdas might define an &#39;app.py&#39;.<br>    This clears Python&#39;s module cache to ensure each Lambda loads its own &#39;app.py&#39;.<br>    &quot;&quot;&quot;<br>    for module_name in list(sys.modules):<br>        if module_name == &quot;app&quot; or module_name.startswith(&quot;app.&quot;):<br>            del sys.modules[module_name]<br>def load_index_module_from_path(path_to_index_py: Path):<br>    &quot;&quot;&quot;Safely loads an index.py module from a given path.&quot;&quot;&quot;<br>    flush_cached_app_modules()<br>    # Temporarily add the Lambda&#39;s parent directory to sys.path<br>    # to resolve its local imports (like its own &#39;app.py&#39;)<br>    parent_dir = str(path_to_index_py.parent.resolve())<br>    if parent_dir not in sys.path:<br>        sys.path.insert(0, parent_dir)<br>        remove_parent_dir_on_exit = True<br>    else:<br>        remove_parent_dir_on_exit = False<br>    # Create a unique module name to avoid collisions<br>    module_name = f&quot;docs_spec_generator.{path_to_index_py.parent.name}&quot;<br>    spec = importlib.util.spec_from_file_location(module_name, path_to_index_py)<br>    if spec is None or spec.loader is None: # Check added for robustness<br>        raise ImportError(f&quot;Could not create module spec for {path_to_index_py}&quot;)<br>        <br>    module = importlib.util.module_from_spec(spec)<br>    sys.modules[module_name] = module # Register module before execution<br>    spec.loader.exec_module(module)<br>    if remove_parent_dir_on_exit:<br>        sys.path.pop(0)<br>    return module<br>def extract_spec_from_module(module) -&gt; dict:<br>    &quot;&quot;&quot;Calls get_openapi_spec() on the module and returns a dict.&quot;&quot;&quot;<br>    get_openapi_spec_func = getattr(module, &quot;get_openapi_spec&quot;, None)<br>    if not callable(get_openapi_spec_func):<br>        return {} # No spec function found<br>    raw_spec_data = get_openapi_spec_func()<br>    # Handle Pydantic model output from Powertools<br>    if hasattr(raw_spec_data, &quot;model_dump_json&quot;): # Pydantic v2+<br>        return json.loads(raw_spec_data.model_dump_json(by_alias=True, exclude_none=True))<br>    if hasattr(raw_spec_data, &quot;model_dump&quot;): # Pydantic v1 (for older Powertools)<br>        return raw_spec_data.model_dump(by_alias=True, exclude_none=True)<br>    if isinstance(raw_spec_data, str): # If it&#39;s already a JSON string<br>        return json.loads(raw_spec_data)<br>    if isinstance(raw_spec_data, dict): # If it&#39;s already a dict<br>        return raw_spec_data<br>    return {} # Fallback<br>def deep_merge_specs(base_spec: dict, new_spec_fragment: dict):<br>    &quot;&quot;&quot;Merges paths and components from the new fragment into the base spec.&quot;&quot;&quot;<br>    for key in [&quot;paths&quot;, &quot;components&quot;]:<br>        if key in new_spec_fragment:<br>            if key not in base_spec:<br>                base_spec[key] = {}<br>            for item_key, item_value in new_spec_fragment[key].items():<br>                # Simple overwrite; more complex merging (e.g., for shared components)<br>                # might require careful key management or deeper inspection.<br>                base_spec[key][item_key] = item_value<br>def json_default_serializer(obj):<br>    &quot;&quot;&quot;Handles non-serializable objects like Enums for json.dumps.&quot;&quot;&quot;<br>    if isinstance(obj, Enum):<br>        return obj.value<br>    raise TypeError(f&quot;Object of type {obj.__class__.__name__} is not JSON serializable&quot;)<br>def generate_swagger_html(openapi_spec_dict: dict) -&gt; str:<br>    &quot;&quot;&quot;Generates the HTML for a self-contained Swagger UI page.&quot;&quot;&quot;<br>    openapi_json_string = json.dumps(<br>        openapi_spec_dict,<br>        indent=2,<br>        default=json_default_serializer<br>    )<br>    return f&quot;&quot;&quot;&lt;!DOCTYPE html&gt;<br>&lt;html&gt;&lt;head&gt;<br>&lt;meta charset=&quot;utf-8&quot;&gt;&lt;title&gt;Combined API Documentation&lt;/title&gt;<br>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/swagger-ui-dist@5/swagger-ui.css&quot;&gt;<br>&lt;/head&gt;&lt;body&gt;&lt;div id=&quot;swagger-ui&quot;&gt;&lt;/div&gt;<br>&lt;script src=&quot;https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://unpkg.com/swagger-ui-dist@5/swagger-ui-standalone-preset.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>window.onload = () =&gt; {{<br>  SwaggerUIBundle({{<br>    spec: {openapi_json_string},<br>    dom_id: &#39;#swagger-ui&#39;,<br>    presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],<br>    layout: &quot;StandaloneLayout&quot;<br>  }});<br>}};<br>&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;&quot;&quot;&quot;<br>def main():<br>    docs_output_dir = ROOT / &quot;docs&quot;<br>    docs_output_dir.mkdir(exist_ok=True)<br>    # Base structure for the combined OpenAPI document<br>    combined_spec = {<br>        &quot;openapi&quot;: &quot;3.0.0&quot;,<br>        &quot;info&quot;: {&quot;title&quot;: &quot;Combined Project API&quot;, &quot;version&quot;: &quot;1.0.0&quot;},<br>        &quot;paths&quot;: {},<br>        &quot;components&quot;: {}<br>    }<br>    lambda_index_files = all_index_modules()<br>    for index_file_path in tqdm(lambda_index_files, desc=&quot;Processing Lambda specs&quot;):<br>        try:<br>            module = load_index_module_from_path(index_file_path)<br>            spec_fragment = extract_spec_from_module(module)<br>            deep_merge_specs(combined_spec, spec_fragment)<br>        except Exception as e:<br>            print(f&quot;Error processing {index_file_path}: {e}&quot;, file=sys.stderr)<br>            # Optionally, decide if you want to continue or halt on error<br>    # Save the combined OpenAPI JSON<br>    openapi_json_path = docs_output_dir / &quot;openapi.json&quot;<br>    with open(openapi_json_path, &quot;w&quot;) as f:<br>        json.dump(combined_spec, f, indent=2, default=json_default_serializer)<br>    # Generate and save the HTML documentation<br>    html_content = generate_swagger_html(combined_spec)<br>    html_docs_path = docs_output_dir / &quot;index.html&quot;<br>    with open(html_docs_path, &quot;w&quot;) as f:<br>        f.write(html_content)<br>    print(f&quot;\nDocumentation successfully generated in: {docs_output_dir.resolve()}&quot;)<br>    print(f&quot;  JSON spec: {openapi_json_path.resolve()}&quot;)<br>    print(f&quot;  HTML docs: {html_docs_path.resolve()}&quot;)<br>    print(f&quot;\nTo view HTML docs, open in browser: file://{html_docs_path.resolve()}&quot;)<br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>And a simple Makefile to tie it together:</p><pre># Makefile<br>.PHONY: docs<br>docs:<br>	python3 generate_docs.py</pre><p>Now, running make docs will scan your project, find all index.py files with a get_openapi_spec() function, merge their outputs, and generate docs/openapi.json along with an interactive docs/index.html.</p><h3>Taming Import-Time Side Effects</h3><p>A common Lambda pattern is to initialize database connections or AWS clients at the module level. This is problematic when our generate_docs.py script imports the code. The os.environ.setdefault(&quot;DOCS_BUILD&quot;, &quot;1&quot;) line at the top of our generator script is the key. Your Lambda code can now check for this:</p><pre># In your Lambda&#39;s app.py or database_manager.py<br>import os<br>if os.getenv(&quot;DOCS_BUILD&quot;) == &quot;1&quot;:<br>    # We&#39;re in documentation mode, provide a mock or None<br>    dynamo_client = None<br>    print(&quot;Documentation build: Skipping real AWS client initialization.&quot;)<br>else:<br>    # Production mode: initialize real clients<br>    import boto3<br>    dynamo_client = boto3.client(&quot;dynamodb&quot;)</pre><p>This simple guard prevents unwanted network calls or resource initializations during the documentation build.</p><h3>FastAPI vs. Powertools: A Pragmatic Choice for Lambda</h3><p>FastAPI is a fantastic framework, and with an adapter like Mangum, it can run on Lambda. It also boasts excellent built-in OpenAPI generation (app.openapi()). So, why might you choose Powertools specifically for a Lambda-centric environment?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*iWHECEBPIPEXHxEbJJ10gw.png" /></figure><p>Powertools often wins for pure Lambda projects due to:</p><ul><li>Minimal cold-start overhead: Critical for latency-sensitive, infrequently called functions.</li><li>Rich serverless-specific utilities: Reduces boilerplate for common Lambda tasks.</li><li>Simplicity: The APIGatewayHttpResolver feels more direct for simple API Gateway integrations.</li></ul><p>However, if your team is already heavily invested in FastAPI, or you are porting an existing FastAPI app, or you need very advanced web framework features (like complex dependency injection beyond what Pydantic offers), then choose FastAPI + Mangum. The generate_docs.py script would still work; you&#39;d just adapt the get_openapi_spec() function in your Lambdas to call fastapi_app.openapi().</p><h3>Beyond Generation: Supercharge Your OpenAPI Spec</h3><p>Your openapi.json is more than just fodder for a static HTML page. Consider these next steps:</p><ol><li>Host Your Docs: Sync your docs/ directory to an S3 bucket, fronted by CloudFront for a professional, shareable developer portal.</li><li>Integrate with CI/CD: Add make docs to your build pipeline. Fail the build if the script errors, catching spec inconsistencies early.</li><li>Generate Client SDKs: Use tools like <a href="https://openapi-generator.tech/">OpenAPI Generator</a> to create client libraries (TypeScript, Java, Python, Go, etc.) directly from your openapi.json.openapi-generator enerate -i docs/openapi.json -g typescript-axios -o ./sdk/typescript</li><li>Automated Contract Testing: Employ tools like <a href="https://schemathesis.readthedocs.io/">Schemathesis</a> to validate that your deployed Lambdas adhere to the generated OpenAPI contract.</li><li>Publish to API Management Platforms: Import your openapi.json into services like SwaggerHub, Postman, or AWS API Gateway itself for enhanced discovery and governance.</li></ol><h3>And… Thant’s it!</h3><p>Building a unified, accurate, and maintainable API documentation system for AWS Lambda functions doesn’t have to be a chore. By leveraging the built-in validation and OpenAPI export capabilities of AWS Lambda Powertools, combined with a straightforward Python script for aggregation, you can achieve documentation nirvana. Your specs will stay in sync with your implementation, your runtime requests will be validated against those same specs, and your team will thank you for the clarity and confidence it brings.</p><p>Happy documenting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ea7ab9efbfa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/effortless-openapi-for-aws-lambda-unified-docs-validation-with-powertools-1ea7ab9efbfa">Effortless OpenAPI for AWS Lambda: Unified Docs &amp; Validation with Powertools</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Pre-Commit Hooks Can Elevate Code Quality in Python Projects]]></title>
            <link>https://medium.com/decisive-intentions/how-pre-commit-hooks-can-elevate-code-quality-in-python-projects-d3b4432dba7b?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3b4432dba7b</guid>
            <category><![CDATA[software-quality-engineer]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[pre-commit]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 00:00:03 GMT</pubDate>
            <atom:updated>2024-10-09T00:00:03.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reXPm3yBud9t42Otdc8wFg.png" /></figure><p>Maintaining a clean, consistent, and bug-free codebase is crucial for any growing Python project. As codebases grow, it becomes harder to ensure that all commits meet quality standards without adding significant time and effort during development. <strong>Pre-commit hooks</strong> provide a way to automate code checks before any new code is added to your repository, saving time and helping developers focus on the logic rather than nitpicky details.</p><p>In this post, we’ll discuss the benefits of pre-commit hooks in Python projects, focusing on powerful tools like <a href="https://docs.astral.sh/ruff/"><strong>Ruff</strong> </a>(a fast linter), <a href="https://pycqa.github.io/isort/"><strong>isort</strong> </a>(for sorting imports), <a href="https://github.com/PyCQA/bandit"><strong>Bandit</strong> </a>(for security checks), and <a href="https://mypy-lang.org/"><strong>mypy</strong> </a>(for static type checking). These tools can drastically improve the quality, security, and maintainability of your codebase.</p><h3>What Are Pre-Commit Hooks?</h3><p>A <a href="https://pre-commit.com/"><strong>pre-commit</strong></a><strong> hook</strong> is a script that runs automatically before a commit is finalized in Git. This script performs various checks (such as code formatting, linting, or even security scans) and blocks the commit if issues are detected. This ensures that low-quality or non-compliant code doesn’t make it into the codebase, preventing problems from snowballing later.</p><p>In Python, you can configure pre-commit hooks to run tools like <strong>Ruff</strong>, <strong>isort</strong>, <strong>Black</strong>, <strong>Bandit</strong>, and <strong>mypy</strong>. These tools catch common bugs, enforce coding standards, and even help prevent security vulnerabilities.</p><h3>Why Pre-Commit Hooks Matter</h3><p>Pre-commit hooks aren’t just about preventing mistakes — they enable <strong>automatic quality control</strong> and foster best practices. Here are some specific ways pre-commit hooks benefit a Python project:</p><ol><li><strong>Ensures Consistent Code Quality<br></strong>Pre-commit hooks enforce standards across the team. Tools like <strong>Black</strong> ensure that your code is formatted uniformly, while <strong>isort</strong> takes care of sorting imports. These checks eliminate small inconsistencies that can make the code harder to read and maintain.</li><li><strong>Catches Bugs and Security Issues Early<br></strong>Tools like <strong>Ruff</strong> and <strong>Bandit</strong> help catch common bugs and potential security vulnerabilities before the code even leaves the developer’s machine. This means fewer bugs get shipped to production, resulting in more reliable and secure code.</li><li><strong>Reduces Technical Debt<br></strong>Each commit is held to a certain level of quality, preventing small issues from accumulating into bigger problems over time. Pre-commit hooks block low-quality code, so developers can be confident that technical debt is being managed incrementally, rather than through large clean-up efforts later.</li><li><strong>Saves Time in Code Reviews<br></strong>When pre-commit hooks automatically fix minor issues (like code formatting or simple bugs), code reviewers can focus on more important things like logic, design, and performance. This results in more productive code reviews and faster feedback loops.</li></ol><h3>Different types of hooks</h3><ol><li><strong>Linters: Enforcing Code Quality and Catching Bugs<br></strong>Linters analyze your code for issues related to syntax, style, potential bugs, and best practices. They do not modify the code but provide warnings or errors to help you maintain high-quality, clean, and bug-free code. Such as Ruff, Flake8, Pylint</li><li><strong>Formatters: Ensuring Consistent Code Style<br></strong>Formatters automatically modify code to conform to a consistent style and structure. Their primary goal is to enforce a uniform coding style across the entire codebase, which can make the code easier to read and maintain. Such as Black, isort</li><li><strong>Type Checkers: Ensuring Type Safety<br></strong>Type checkers analyze your code to ensure that function signatures and variable types are consistent and correctly applied. They help prevent runtime errors by catching type mismatches during development. Such as mypy</li><li><strong>Security Auditors: Identifying Security Vulnerabilities<br></strong>Security tools scan code for vulnerabilities that could be exploited, helping you ensure that <br>your application is safe from common security issues. Such as Bandit</li><li><strong>Code Complexity Analyzers: Monitoring Code Complexity<br></strong>These tools analyze the structure of your code, flagging complex or hard-to-maintain sections. They help developers refactor complex code into more readable, maintainable structures. Such as Radon</li></ol><h3>Key Tools for Pre-Commit Hooks in Python</h3><p>Let’s explore the essential tools you can use to improve code quality in Python projects through pre-commit hooks. By combining these tools, you’ll cover a wide range of checks, from formatting and linting to type safety and security.</p><h4>Ruff: Fast Linting and Bug Detection</h4><p><a href="https://docs.astral.sh/ruff/rules/">Ruff</a> is an ultra-fast linter designed to catch stylistic issues, bugs, and performance problems. It also consolidates many popular linter functionalities (Flake8, Pylint, etc.) into one tool. Ruff is perfect for enforcing Python code standards without adding significant overhead.</p><p><strong>Ruff Highlights:</strong></p><ul><li><strong>Linting and Performance Checks</strong>: Flags things like unused imports, redundant conditions, inefficient comprehensions, and more.</li><li><strong>Autofixing</strong>: Automatically resolves common issues like removing unused variables, correcting formatting, and simplifying redundant code patterns.</li><li><strong>Speed</strong>: Ruff’s speed makes it suitable for large codebases without slowing down commits.</li></ul><h4>Black: Enforce Consistent Code Formatting</h4><p><a href="https://black.readthedocs.io/">Black</a> is the Python code formatter that enforces a consistent style across your project. When added as a pre-commit hook, Black automatically formats your code according to a standard set of rules, removing the need for subjective style discussions during code reviews.</p><p><strong>Black Highlights:</strong></p><ul><li><strong>Opinionated Formatting</strong>: Automatically formats code based on strict rules, ensuring all files follow the same style.</li><li><strong>Zero-Config</strong>: Black doesn’t require custom configuration, making it simple to drop into any project.</li></ul><h4>3. isort: Sorting Imports Automatically</h4><p><a href="https://pycqa.github.io/isort/">isort</a> is a simple but effective tool for automatically sorting imports. Having consistent import order improves code readability and prevents issues caused by unordered imports.</p><p><strong>isort Highlights:</strong></p><ul><li><strong>Customizable Sorting</strong>: It sorts imports by type (standard library, third-party libraries, local modules) and alphabetically, ensuring a consistent and readable structure.</li><li><strong>Automates Import Cleanup</strong>: Avoids errors due to inconsistent import order, particularly in larger projects.</li></ul><p>By combining <strong>isort</strong> with <strong>Black</strong>, you maintain import order and consistent formatting, ensuring that even import statements follow a unified style.</p><h4>4. Bandit: Security Auditing for Python Code</h4><p><a href="https://bandit.readthedocs.io/">Bandit</a> helps identify common security vulnerabilities in Python code. It analyzes code for issues like weak cryptography usage, hardcoded passwords, and SQL injection vulnerabilities, which can make your application less secure.</p><p><strong>Bandit Highlights:</strong></p><ul><li><strong>Security-First</strong>: Scans Python code to detect potential security issues.</li><li><strong>Comprehensive Checks</strong>: Covers a range of vulnerabilities, from weak password practices to insecure file handling.</li></ul><p>By running Bandit on each commit, you can prevent common security vulnerabilities from creeping into your codebase early in the development process.</p><h4>5. mypy: Type Checking for Safer Code</h4><p><a href="http://mypy-lang.org/">mypy</a> is a static type checker for Python. While Python is a dynamically typed language, adding type hints can greatly improve code reliability, catching bugs at the type level before they make it into production.</p><p><strong>mypy Highlights:</strong></p><ul><li><strong>Type Safety</strong>: Enforces that function signatures and variable types are used correctly, preventing common bugs.</li><li><strong>Static Analysis</strong>: It doesn’t require code execution to detect type issues, which means you can catch errors even before running the application.</li></ul><p>With mypy, you gain the advantages of type safety without sacrificing Python’s flexibility, and it can easily integrate with projects at any scale.</p><h3>Drawbacks of Pre-Commit Hooks</h3><p>While pre-commit hooks are a powerful tool, they do come with some drawbacks. Here are a few potential downsides to consider:</p><ol><li><strong>Slow Commit Workflow<br></strong>If pre-commit hooks run too many checks, especially on large codebases, the commit process can slow down. Developers may experience delays before they can actually commit their changes. The trick is to keep pre-commit hooks lightweight and delegate more intensive checks (like running full test suites) to your CI pipeline.</li><li><strong>Maintenance Overhead<br></strong>Keeping your pre-commit configuration and the various tools up-to-date can add maintenance overhead. This can especially be an issue when tools release breaking changes or require new configurations as they evolve.</li><li><strong>Bypassing Hooks<br></strong>Sometimes developers will want to bypass hooks when making work-in-progress or experimental commits. While this can be done using git commit — no-verify, frequent use of this option may allow low-quality code into the repository, defeating the purpose of pre-commit hooks.</li><li><strong>Potential Conflicts Between Tools<br></strong>Different tools (like <strong>Black</strong> and <strong>isort</strong>) may have conflicting rules or configurations. For example, Black and isort sometimes handle import formatting differently. These conflicts can usually be resolved with proper configuration, but it’s something to be mindful of.</li></ol><h3>A sample pre-commit hook</h3><p>This configuration integrates multiple important tools for linting, formatting, type-checking, and security analysis, ensuring that the codebase remains clean, consistent, and safe.</p><pre># pre-commit-config.yaml<br>repos:<br>  # Use Ruff for fast linting and fixing code style issues.<br>  - repo: https://github.com/charliermarsh/ruff-pre-commit<br>    rev: v0.0.287  # Use the latest version<br>    hooks:<br>      - id: ruff<br>        args: [&quot;--fix&quot;]  # Enable automatic fixing of issues.<br><br>  # Use Black for code formatting.<br>  - repo: https://github.com/psf/black<br>    rev: 23.9.1  # Use the latest stable version.<br>    hooks:<br>      - id: black<br>        args: [&quot;--line-length&quot;, &quot;88&quot;]  # Set the line length to match PEP 8 standards.<br><br>  # Use isort to ensure consistent import ordering.<br>  - repo: https://github.com/PyCQA/isort<br>    rev: 5.12.0<br>    hooks:<br>      - id: isort<br>        args: [&quot;--profile&quot;, &quot;black&quot;]  # Ensure isort is compatible with Black.<br><br>  # Use Bandit for security checks.<br>  - repo: https://github.com/PyCQA/bandit<br>    rev: 1.7.5<br>    hooks:<br>      - id: bandit<br>        args: [&quot;--recursive&quot;, &quot;.&quot;]  # Recursively check all files for security issues.<br>        name: bandit-security-check<br><br>  # Use mypy for static type checking.<br>  - repo: https://github.com/pre-commit/mirrors-mypy<br>    rev: v1.5.1<br>    hooks:<br>      - id: mypy<br>        args: [&quot;--ignore-missing-imports&quot;]  # Ignore missing imports for external dependencies.<br><br>  # Use Flake8 for deeper PEP 8 linting and logical error checks.<br>  - repo: https://github.com/pycqa/flake8<br>    rev: 6.1.0<br>    hooks:<br>      - id: flake8<br>        args: [&quot;--max-line-length&quot;, &quot;88&quot;, &quot;--select&quot;, &quot;E,F,W,C90&quot;]  # Customize error codes as needed.<br>        exclude: tests/*  # Exclude specific directories, e.g., tests, migrations, etc.<br><br>  # Use pre-commit hook for ensuring that end-of-file newline is present.<br>  - repo: https://github.com/pre-commit/pre-commit-hooks<br>    rev: v4.5.0<br>    hooks:<br>      - id: end-of-file-fixer<br><br>  # Use pre-commit hook for checking YAML file syntax.<br>  - repo: https://github.com/pre-commit/pre-commit-hooks<br>    rev: v4.5.0<br>    hooks:<br>      - id: check-yaml<br><br>  # Use pre-commit hook for checking if large files are added accidentally.<br>  - repo: https://github.com/pre-commit/pre-commit-hooks<br>    rev: v4.5.0<br>    hooks:<br>      - id: check-added-large-files<br>        args: [&quot;--maxkb=500&quot;]  # Set file size limit to 500 KB.</pre><pre># pyproject.toml<br><br>[tool.black]<br>line-length = 88<br>target-version = [&#39;py38&#39;, &#39;py39&#39;, &#39;py310&#39;]  # Support for Python 3.8, 3.9, 3.10.<br>include = &#39;\.pyi?$&#39;<br>exclude = &#39;&#39;&#39;<br>/(<br>    \.git<br>  | \.venv<br>  | build<br>  | dist<br>  | migrations<br>  | tests/.*<br>)/<br>&#39;&#39;&#39;<br><br>[tool.isort]<br>profile = &quot;black&quot;  # Ensure compatibility with Black&#39;s formatting rules.<br>line_length = 88<br>known_first_party = [&quot;my_project&quot;]  # Specify your project&#39;s package name.<br>known_third_party = [&quot;django&quot;, &quot;flask&quot;]  # Specify known third-party libraries.<br><br>[tool.mypy]<br>python_version = 3.9  # Adjust depending on your project&#39;s Python version.<br>warn_return_any = true<br>warn_unused_ignores = true<br>show_error_codes = true<br>ignore_missing_imports = true  # Ignore errors on third-party imports with no type hints.<br>exclude = &#39;migrations|tests|dist|build&#39;<br><br>[tool.bandit]<br>skips = [<br>    &quot;B101&quot;,  # Skips weak hashing algorithms like MD5 (if your project doesn&#39;t need it).<br>]<br># Bandit uses its own configuration file, but this can be extended.<br><br>[tool.flake8]<br>max-line-length = 88<br>extend-ignore = E203, E266, E501, W503  # Ignore these codes to match Black&#39;s formatting.<br>exclude = .git,__pycache__,build,dist,tests  # Ignore these directories.</pre><h3>Best Practices for Using Pre-Commit Hooks in a Professional Team</h3><p>To ensure pre-commit hooks are useful without disrupting your team’s productivity, here are some best practices:</p><ol><li><strong>Start Small and Expand Gradually<br></strong>Begin with the most essential hooks, such as Ruff for linting and Black for formatting. Once your team is comfortable with the process, gradually introduce additional tools like <strong>isort</strong>, <strong>Bandit</strong>, and <strong>mypy</strong>.</li><li><strong>Leverage Autofix Tools<br></strong>Use autofix features where possible to automatically resolve common issues (e.g., Ruff’s autofix, Black for formatting). This reduces the manual work developers need to do, allowing them to focus on more complex code reviews and tasks.</li><li><strong>Keep Hooks Fast<br></strong>Ensure pre-commit hooks run quickly by limiting them to staged files (the code being committed) rather than the entire codebase. Reserve more time-consuming tasks like running unit tests for your CI pipeline.</li><li><strong>Integrate Pre-Commit Hooks with CI<br></strong>Your pre-commit hooks should complement your CI pipeline, not replace it. While pre-commit hooks handle quick, local checks, your CI system should run more comprehensive tests and validations before code is merged.</li><li><strong>Document Everything<br></strong>Make sure your pre-commit setup is well-documented. Include instructions in your project’s contribution guide so that new team members can get up and running quickly. Clear documentation reduces confusion and helps ensure that everyone follows the same workflow.</li><li><strong>Review and Iterate<br></strong>Regularly review your pre-commit setup to ensure it’s still effective. Gather feedback from your team and adjust the hooks as necessary to balance code quality with developer productivity.</li></ol><h3>Conclusion</h3><p>Pre-commit hooks are a simple yet powerful way to ensure code quality in Python projects. By integrating tools like Ruff, you can catch bugs early, enforce consistent styling, and reduce the burden on code reviews. However, it’s important to strike a balance between enforcing standards and keeping the development workflow smooth. By following the best practices we’ve outlined, you can create a streamlined pre-commit process that improves code quality without slowing your team down.</p><p>Ultimately, pre-commit hooks, when used wisely, can elevate your Python codebase, making it easier to maintain and scale as your project grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3b4432dba7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/how-pre-commit-hooks-can-elevate-code-quality-in-python-projects-d3b4432dba7b">How Pre-Commit Hooks Can Elevate Code Quality in Python Projects</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Data Deluge: Introducing Pipeline Factory (Part 1)]]></title>
            <link>https://medium.com/decisive-intentions/navigating-the-data-deluge-introducing-pipeline-factory-part-1-25467d3e9ab4?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/25467d3e9ab4</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[gda]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 13:06:01 GMT</pubDate>
            <atom:updated>2023-11-06T13:06:01.886Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore challenges in data pipeline management and the promise of the Pipeline Factory (PF) as a solution, with insights into generic pipeline elements</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IYZRzwS_rTalLTLZ" /></figure><h3>Introduction</h3><p>Data is what keeps businesses going in a world that is becoming more and more digital. It is the key to making smart choices, making plans, and giving customers a better experience. But it is not easy to make sense of the huge amounts of data that are flowing through an organization. The creation and management of data pipelines are very important to this project, but they also come with a lot of problems. This two-part blog post series explores the idea of the Pipeline Factory, a complete solution made to make building and managing data pipelines easier.</p><h3>Understanding the Challenge</h3><p>A robust data pipeline, often referred to as a Directed Acyclic Graph (DAG), is a cornerstone of effective data management. Yet, crafting such a pipeline can be a formidable task, even for seasoned software engineers. Teams with limited experience in data engineering face an even greater challenge. It is hard and complicated to go from having to deal with complicated data needs and learning about different data processing and storage systems to putting all of these parts together in a way that can be used in production.</p><p>I have observed teams struggling with the following issues:</p><ol><li>Skills Gap<br>There’s a significant skills gap with limited expertise in leveraging advanced tools necessary for efficient data pipeline construction. This deficiency impedes smooth development and operational workflows.</li><li>Slow Deployment<br>Deployment processes are sluggish and inefficient due to their reliance on cluttered and centralized code repositories. This setup complicates the workflow and makes error detection and resolution time-consuming.</li><li>Code Management Issues<br>The team finds it difficult to manage and reuse code across various projects due to the lack of a systematic structure for code management. This void leads to increased redundancy, inconsistency, and chaos in our codebase, making code management and utilization inefficient and error-prone.</li><li>Complex Deployment and Testing Procedures<br>We are currently dealing with complex, time-consuming, and inefficient data pipeline deployment and testing procedures in real-world production environments. These convoluted processes lengthen operational timelines, consume excessive resources, and contribute to each project&#39;s painstaking and inefficient deployment cycle.</li><li>Sustainability Concerns<br>The accumulation of these challenges not only undermines our team’s productivity and efficiency but also raises critical concerns regarding the sustainability and scalability of our current data engineering practices.</li></ol><h3>The Pipeline Factory Proposition</h3><p>As a solution to these problems, we suggest the Pipeline Factory (PF). The Platform Forge (PF) is a collection of different sets of tools designed to make creating, running, and testing data pipelines easier. It provides organized runtime configuration management and comes with predefined commands and CI/CD scripts to make testing locally and deploying to the development environment easier. The vision is to have a more efficient and accessible process for team members of varying skill levels, thereby saving time, reducing errors, and enhancing the overall value and efficiency of our data engineering projects.</p><p>Core Benefits of the Pipeline Factory:</p><ol><li>Ease of Use<br>PF is meticulously designed with user-friendliness at its core. Team members can easily define and modify pipelines using simple configuration files, significantly lowering the entry barrier.</li><li>Fast Deployment<br>PF brings about a more streamlined and organized project structure that makes pipeline deployment faster and easier. This effective framework gets rid of the slowness that comes with cluttered repositories, which speeds up the deployment phase and makes the team more productive overall.</li><li>Reusable Code<br>PF is not just about encouraging reusability; it’s about embedding it into the system’s architecture. The platform promotes and simplifies the process of code reuse across different projects, minimizing redundancy and reducing the risk of errors commonly associated with manual code copying and pasting.</li><li>Effective Testing<br>PF comes equipped with robust tools designed for efficient and reliable testing of data pipelines, both locally and in remote development environments. These tools simplify the once-complicated and lengthy testing procedures, making it easier for the team to validate the functionality and reliability of data pipelines before they are deployed.</li><li>Sustainable and Scalable Practices<br>PF addresses and resolves the fundamental challenges currently impeding our team, laying the groundwork for sustainable and scalable data engineering practices.</li></ol><h3>A model for Data Pipelines</h3><p>Before delving deeper into the Pipeline Factory’s components, it’s crucial to have a bird’s-eye view of generic data pipeline elements. A data pipeline is a series of automated processes engineered to move data from source systems to a target system for further processing and analysis. A Data pipeline consists of the following components:</p><ul><li>Data: The main objective of running a pipeline is to move and/or process data. e.g. file on s3</li><li>Task: The main part of a data pipeline is a task. It is the way data is touched, e.g. ETL, ML</li><li>DAG: Directed Acyclic Graph (DAG) is the way we connect Tasks within a Data Pipeline</li><li>Task orchestration tool: The software that is in charge of executing Tasks based on the DAG definition. For example, airflow</li><li>Execution environment: the lowest level in the tech stack. It is responsible for running the orchestration tool and the task.</li><li>Platforms, e.g. MacOS, AWS</li><li>Configurations, e.g. helm chart, CI/CD</li></ul><p>The focus of this post is primarily on DAG, tasks, and data, so let’s take a closer look at these three components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R6Jaf-7rKOjx8YUT" /><figcaption>Main elements of data pipeline</figcaption></figure><p><strong>DAG</strong></p><ul><li>Task connections: defines the order in which tasks execute</li><li>Schedule: when and how often the Data Pipelines should get executed</li><li>Events: helps us to handle incidents such as sending a signal on Data Pipeline failure or generating a report when Data Pipeline is done</li><li>vendor-specific configurations: different tools have different configurations for instance, Start date, etc</li><li>Configuration Profile: Depending on the execution environment, Data Pipeline needs to run different sets of configuration</li></ul><p><strong>Task</strong></p><ul><li>Script: the code responsible for transforming the data. For instance, load data from a database and predict a value using an ML model</li><li>Operator: This is an infrastructure-specific configuration that defines how a Script will be run by the orchestration tool on the platform in the execution environment</li><li>Arguments: the configuration the Task needs for running the Script</li><li>Task Group: Task group could be useful when DAG should add a sub-DAG and/or visually distinguish some of the tasks</li><li>Events: events such as `before_run` or `on_finish` could be helpful to perform some repetitive procedures without being worried about them inside the scripts.</li><li>running condition: sometimes tasks should get executed based on a set of conditions.</li><li>return value: something to pass on to the next step(s)</li></ul><p>Data</p><ul><li>connection: where the data is and how to access it</li><li>schema: the expected structure of the data</li><li>check: the expected quality and/or quantity of the data</li></ul><h3>What happens next?</h3><p>Part 1 of our investigation into the Pipeline Factory concludes here, setting the stage for a deeper dive in Part 2. We have laid the groundwork for what promises to be a comprehensive solution to effective data management in the digital age by understanding the challenges at hand and the Pipeline Factory&#39;s proposition. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25467d3e9ab4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/navigating-the-data-deluge-introducing-pipeline-factory-part-1-25467d3e9ab4">Navigating the Data Deluge: Introducing Pipeline Factory (Part 1)</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prediction Model for an unbalanced Dataset]]></title>
            <link>https://medium.com/decisive-intentions/prediction-model-for-an-unbalanced-dataset-92e83e3f63d4?source=rss-fc5f63eb2517------2</link>
            <guid isPermaLink="false">https://medium.com/p/92e83e3f63d4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unbalanced-data]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Amin Rashidi]]></dc:creator>
            <pubDate>Sat, 04 Nov 2023 17:41:24 GMT</pubDate>
            <atom:updated>2023-11-04T17:50:18.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*_HlRYvYdlxgyXnua.jpg" /></figure><p>Brake testing is a time-consuming and costly operation for factories. The plant needs to shut down the robots to perform the test. It is worth exploring to see if it is possible to predict the test results based on historical data. At the time of this writing, we approach this problem as a binary classification problem.</p><h3>Data Preprocessing</h3><p>The receiving data needs to be cleaned and wrangled to be ready to be fed to a machine learning model. In this section, the necessary steps are explained.</p><h3>Feature Engineering</h3><p>Brake test data is in the form of a time series, as it records several features for each robot during the brake test over time. There are limited tools and methods suitable for working with time series, so it would be helpful if we could transform the problem into a classification problem, which is easier to solve. To do that, a <a href="https://en.wikipedia.org/wiki/SQL_window_function">moving window</a> can be used. For example, if you average `torque_peak` for the past 5 days (excluding the current day) and assign it to a variable in the current day, see the table below for more clarity. Please note that we do that for each axis and individual robots separately, so in the below example, all other axes and robots are not shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQg6YWgO0CfUfnxxv5-wrA.png" /></figure><p>The following metrics were calculated: average, standard deviation, and correlation (of the variable and timestamp) for all variables of interest for a 3-day and 5-day time window: [‘avgMotTemp’, ‘observed_brake_torque’, ‘observed_static_friction’, ‘torque_const_move’, ‘torque_limit_cmd’, ‘torque_peak’] =&gt; [‘avgMotTemp_avg_5’, ‘avgMotTemp_stddev_5’, ‘avgMotTemp_corr_5’, ‘observed_brake_torque_avg_5’, …]. <strong>We added an additional 3-day time window because we have a few robots with an available 5-day time window.</strong></p><p>Another variable that was added is `test_timestamp` which is basically the result of `axis_test_date` in seconds.</p><h3>Output variables</h3><p>Dealing with binary class output variables is easier and more efficient than working with multiclass ones. Furthermore, labels other than `BT_BRAKE_TORQUE_OK` and `BT_BRAKE_NOT_OK` are so rare. So we decided to fold other labels into these two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxUPqwh5XI7W7iGzTaXOgA.png" /></figure><h3>Imputation</h3><p>An n-day time window could result in Null values if the rows in the window are less than n. Furthermore, the Corr function could produce Null if one of the variables has zero variance. As a result, we need to impute the Null values:</p><ol><li>Considering 3-day time window instead of a 5-day time window, as most of the robots have no data for 5 consecutive days</li><li>Fill N/A using mean with the same Robot Type and overall_test_result</li><li>Then fill N/A using mean with the same overall_test_resut</li><li>Then drop rows with N/A values as Scikit-Learn can’t handle N/As</li><li>Remove all the robots without any recorded failure to make the dataset more balanced.</li></ol><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa553KU_DWa8OKkxijwofg.png" /></figure><h3>Analytics</h3><p>Predicting brake tests is a classification problem, and because only 0.6 percent of observations are related to brake failure, we are dealing with a highly imbalanced dataset. Based on my initial investigations, Random Forest looks like a good choice for this problem for the following reasons:</p><ul><li>It’s highly parallelizable compared to booster-based models</li><li>In <a href="http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">Scikit Learn</a> the Random Forest function has a large set of parameters, including the ones to deal with imbalanced datasets<br>Note: As mentioned before, the dataset is highly imbalanced, as less than 0.1% of the observations are labeled ‘BT_BRAKE_NOT_OK’ so it makes sense to use some advanced methods, such as undersampling ‘BT_BRAKE_TORQUE_OK’. Spoiler alert: It turned out that Random Forest can manage an imbalanced dataset even without using any balancing techniques.</li><li>The ensembling nature of RF reduce the possibility of overfitting</li></ul><h3>Why undersampling methods would not work?</h3><p>With only around 2000 failed brake tests, <a href="https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis">undersampling</a> provides us with a too small dataset to train a model with. Some of my colleagues did try undersampling and got a great <a href="https://en.wikipedia.org/wiki/F1_score">F1-score</a> of 0.92, but there is a major flaw in their approach. They test the model with undersampled data, which is wrong because it does not represent real-world data. I reproduced their work and got a high F1-score of 0.96, but after testing it with the imbalanced test dataset, the F1-score dropped to 0.2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*VQKs58yQ92Q-M-oV.png" /></figure><p>The main reason for this phenomenon is that even if the model misclassifies 0.5 percent of the passed tests as failing, the <a href="https://en.wikipedia.org/wiki/Precision_and_recall">Precision</a> score falls below 0.5 and results in a low F1-Score.</p><p>Even more complicated methods, such as <a href="https://imbalanced-learn.org/en/stable/under_sampling.html#instance-hardness-threshold">Instance Hardness Threshold</a> do not do better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*SO6ezh_0RPgPuWd-.png" /></figure><h3>Trying oversampling methods</h3><p>Oversampling means generating more observations of the minority class. Just duplicating current observation will not work, so we need to use more advanced methods such as the Synthetic Minority Oversampling Technique (SMOTE) <a href="https://imbalanced-learn.org/en/stable/over_sampling.html#cbhk2002">[CBHK2002]</a> and the Adaptive Synthetic (ADASYN) <a href="https://imbalanced-learn.org/en/stable/over_sampling.html#hbgl2008">[HBGL2008]</a>. All of which perform perfectly on 5-fold cross-validation but poorly on unseen imbalanced data. Here is the recall-precision threshold for a random forest model fitted with oversampled data by ADASYC. Applying SMOTE results in a similar performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*__scDAIeoVkdr7vo.png" /></figure><h3>Leveraging Ensemble Learning</h3><p>The <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">Scikit-learn RandomForest</a> supports three types of weighted sampling: ‘balanced’, ‘balanced subsample’, and no weight assignment. We will see if these methods help us build a better prediction model.</p><p>I tried a randomized hyperparameter grid search to get an idea of the range of hyperparameters values.</p><pre># Number of trees in random forest<br>n_estimators = [int(x) for x in np.linspace(start = 100, stop = 600, num = 10)]<br># Number of features to consider at every split<br>max_features = [&#39;sqrt&#39;, &#39;log2&#39;, None]<br># Maximum number of levels in tree<br>max_depth = [50, 100]<br>max_depth.append(None)<br># Minimum number of samples required to split a node<br>min_samples_split = [10, 20, 40, 80]<br># Minimum number of samples required at each leaf node<br>min_samples_leaf = [1, 2, 4, 8]<br># Method of selecting samples for training each tree<br>bootstrap = [True, False]<br>criterion = [&#39;gini&#39;]<br>class_weight=[&#39;balanced&#39;,&#39;balanced_subsample&#39;, None]</pre><p>This is how the best-performing model trained with all the features looks:</p><pre>Model with rank: 1<br>Mean validation score: 0.734 (std: 0.010)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 100, &#39;min_samples_split&#39;: 80, &#39;min_samples_leaf&#39;: 2, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;max_depth&#39;: 50, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: False}<br><br>Model with rank: 2<br>Mean validation score: 0.734 (std: 0.013)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 377, &#39;min_samples_split&#39;: 40, &#39;min_samples_leaf&#39;: 1, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;max_depth&#39;: 100, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: True}<br><br>Model with rank: 3<br>Mean validation score: 0.715 (std: 0.015)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 211, &#39;min_samples_split&#39;: 10, &#39;min_samples_leaf&#39;: 1, &#39;max_features&#39;: &#39;log2&#39;, &#39;max_depth&#39;: None, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: False}</pre><p>The performance of the model is shown in the form of a learning curve diagram. It helps us check the bias-variance tradeoff and check the progress of the model. The current diagram shows that we cannot do much better with the current model and data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*8HOCIBBokR59Qqp1.png" /></figure><p>Interestingly, “ <strong>class_weight” is None</strong> in the top 3 best-performing models. So, the best model is achieved when we ignore the imbalance problem altogether.</p><h3>Feature Importance</h3><p>Before talking about feature selection, it could be interesting to look at the correlation matrix (for a 3-day time window) to see if variables are correlated or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UZB9jVIdD8tALRZT.png" /></figure><p>Using the sk-learn “ <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectFromModel.html">SelectFromModel</a> “ function, we can find the most important feature in which their score is the above median of all scores. Please bear in mind that, because of the random nature of ensemble methods, the order of the list is not deterministic. I also ran this for the combination of a 3-day and 5-day time window, but as expected, the first 5-day feature (‘observed_static_friction_stddev_5’) appears in 16th place. Here is the correlation matrix of the top features for a 3-day time window.</p><p>Note: “torque_limit_cmd_stddev_3” added later based on a model with a 0.3 threshold. See the threshold tuning section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/0*w2wa2Nb8C76MEill.png" /></figure><h3>Fit the model to the data with selected features</h3><p>I used the same hyperparameter grid as before to narrow the exhaustive search space. Here are the top results:</p><pre>Model with rank: 1<br>Mean validation score: 0.744 (std: 0.010)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 377, &#39;min_samples_split&#39;: 40, &#39;min_samples_leaf&#39;: 1, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;max_depth&#39;: 100, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: True}<br><br>Model with rank: 2<br>Mean validation score: 0.743 (std: 0.013)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 100, &#39;min_samples_split&#39;: 80, &#39;min_samples_leaf&#39;: 2, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;max_depth&#39;: 50, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: False}<br><br>Model with rank: 3<br>Mean validation score: 0.719 (std: 0.014)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 211, &#39;min_samples_split&#39;: 10, &#39;min_samples_leaf&#39;: 1, &#39;max_features&#39;: &#39;log2&#39;, &#39;max_depth&#39;: None, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: False}</pre><p>And the learning curve for the top-performing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*cHcy3PJUUvUgJkso.png" /></figure><p>model. We improved the result slightly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*FS4NT5E4vDGAwB0s.png" /></figure><h3>Threshold tuning</h3><p>Considering that “class_weight” remained None in the top model performers, it is worth checking if changing the decision threshold improves the results. Here is the precision-recall curve:</p><p>Normally, in binary class datasets, sk-learn considers 0.5 as the threshold to decide which class to choose. The above shows that the 0.5 threshold results in low recall. Move the threshold to 0.3 to help us achieve the highest F1 score possible.</p><p>By using the original hyperparameter grid and applying the 0.3 thresholds, the F score increased to 0.751</p><pre>Model with rank: 1<br>Mean validation score: 0.751 (std: 0.015)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 400, &#39;min_samples_split&#39;: 40, &#39;min_samples_leaf&#39;: 4, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;max_depth&#39;: None, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: True}<br><br>Model with rank: 2<br>Mean validation score: 0.750 (std: 0.014)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 366, &#39;min_samples_split&#39;: 40, &#39;min_samples_leaf&#39;: 2, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;max_depth&#39;: None, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: True}<br><br>Model with rank: 3<br>Mean validation score: 0.750 (std: 0.016)<br>Parameters: {&#39;random_state&#39;: 42, &#39;n_estimators&#39;: 100, &#39;min_samples_split&#39;: 80, &#39;min_samples_leaf&#39;: 1, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;max_depth&#39;: 100, &#39;criterion&#39;: &#39;gini&#39;, &#39;class_weight&#39;: None, &#39;bootstrap&#39;: True}</pre><h3>Exhaustive Hyperparameter search</h3><p>After finding out the important features, general values of hyperparameters, and the decision threshold, now it’s time to use an exhaustive search:</p><p>Expand source</p><pre>{&#39;n_estimators&#39;: [395, 400, 410],<br>               &#39;criterion&#39;: [&#39;gini&#39;],<br>               &#39;max_features&#39;: [&#39;sqrt&#39;],<br>               &#39;max_depth&#39;: [50, None],<br>               &#39;class_weight&#39; : [None],<br>               &#39;min_samples_split&#39;: [37,38, 39],<br>               &#39;min_samples_leaf&#39;:[2,3],<br>               &#39;bootstrap&#39;: [True],<br>                &#39;random_state&#39;: [42],<br>              &#39;n_jobs&#39; : [10]}</pre><p>results:</p><pre>Model with rank: 1<br>Mean validation score: 0.754 (std: 0.016)<br>Parameters: {&#39;bootstrap&#39;: True, &#39;class_weight&#39;: None, &#39;criterion&#39;: &#39;gini&#39;, &#39;max_depth&#39;: 50, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;min_samples_leaf&#39;: 3, &#39;min_samples_split&#39;: 38, &#39;n_estimators&#39;: 400, &#39;n_jobs&#39;: 10, &#39;random_state&#39;: 42}<br><br>Model with rank: 1<br>Mean validation score: 0.754 (std: 0.016)<br>Parameters: {&#39;bootstrap&#39;: True, &#39;class_weight&#39;: None, &#39;criterion&#39;: &#39;gini&#39;, &#39;max_depth&#39;: None, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;min_samples_leaf&#39;: 3, &#39;min_samples_split&#39;: 38, &#39;n_estimators&#39;: 400, &#39;n_jobs&#39;: 10, &#39;random_state&#39;: 42}<br><br>Model with rank: 3<br>Mean validation score: 0.753 (std: 0.016)<br>Parameters: {&#39;bootstrap&#39;: True, &#39;class_weight&#39;: None, &#39;criterion&#39;: &#39;gini&#39;, &#39;max_depth&#39;: 50, &#39;max_features&#39;: &#39;sqrt&#39;, &#39;min_samples_leaf&#39;: 3, &#39;min_samples_split&#39;: 38, &#39;n_estimators&#39;: 410, &#39;n_jobs&#39;: 10, &#39;random_state&#39;: 42}</pre><h3>Conclusion</h3><p>Despite all our efforts, we could not reach a F1-score above 0.76. I believe that’s because of the following reasons:</p><ul><li>The data does not cover robots and dates consistently. That results in a low learning rate as the model does not have enough data for a given robot to find the patterns.</li><li>Too many brake tests with inconsistent results are being run on each robot per day. That makes building a classification model harder.</li><li>The low rate of brake test failure results is a highly imbalanced dataset that is hard to approach with common methods.</li></ul><h3>What should I do next?</h3><p>The possible solutions to the mentioned problems could be:</p><ul><li>Trying to clean data by applying more domain knowledge i.e. removing or merging multiple test results per day per robot into one observation</li><li>Acquiring more consistent brake tests from manufacturers</li><li>Extracting more variables and information from the brake test logs currently, we use “[‘avgMotTemp’, ‘observed_brake_torque’, ‘observed_static_friction’, ‘torque_const_move’, ‘torque_limit_cmd’, ‘torque_peak’]”, There are as many more.</li><li>Trying new ways to deal with the time series problem other than folding it by aggregate functions e.g. Recurrent Neural Networks</li></ul><p><em>Originally published at </em><a href="http://aminrashidi.com/engblog/prediction-model-for-an-unbalanced-dataset/"><em>http://aminrashidi.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92e83e3f63d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/decisive-intentions/prediction-model-for-an-unbalanced-dataset-92e83e3f63d4">Prediction Model for an unbalanced Dataset</a> was originally published in <a href="https://medium.com/decisive-intentions">Decisive Intentions</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>