<?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 TechPassive on Medium]]></title>
        <description><![CDATA[Stories by TechPassive on Medium]]></description>
        <link>https://medium.com/@yao_hehe?source=rss-baa94168ea45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*s7VIete1WXHnzDpI6axMrA.jpeg</url>
            <title>Stories by TechPassive on Medium</title>
            <link>https://medium.com/@yao_hehe?source=rss-baa94168ea45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 15:15:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yao_hehe/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[Karpathy CLAUDE.md vs Claude Code Skills 2026 — TechPassive]]></title>
            <link>https://medium.com/@yao_hehe/karpathy-claude-md-vs-claude-code-skills-2026-techpassive-aacf369823f8?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/aacf369823f8</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[agent-behavior-control]]></category>
            <category><![CDATA[karpathy-skills]]></category>
            <category><![CDATA[architecture-skills]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 14:33:58 GMT</pubDate>
            <atom:updated>2026-11-16T14:33:58.506Z</atom:updated>
            <content:encoded><![CDATA[<p># Karpathy CLAUDE.md vs Claude Code Skills 2026: Which Architecture Actually Improves Agent Behavior?</p><p>In July 2026, Andrej Karpathy published his multica-ai/andrej-karpathy-skills repository (trending with 196k+ stars within 7 days on GitHub). The core thesis is one sentence: **&quot;Put all project behavior rules into a single CLAUDE.md, and let Claude Code auto-load it before every session.&quot;** This stands in sharp contrast to the Skills multi-layer architecture that has dominated the past 6 months (mattpocock/skills with /grill-me /handoff, obra/superpowers with forced TDD, anthropics/claude-plugins-official with plugin marketplace).</p><p>I spent 30 days running both architectures across 3 mid-size projects (a <a href="https://www.amazon.com/s?k=WordPress&amp;i=stripbooks-intl-ship&amp;crid=2GP4ZRUNK7CK3&amp;sprefix=wordpress%2Cstripbooks-intl-ship%2C439&amp;ref=nb_sb_noss_1&amp;tag=techpassive-20">WordPress</a> plugin, an Ansible role, an n8n workflow). The result was unexpected: <strong>single-file CLAUDE.md scores higher on “behavior consistency,” but the Skills architecture is irreplaceable for “observability + failure localization.”</strong> This article breaks down the 30 days of real data, 5 production pitfalls, and a hybrid approach.</p><h3>🏁 TL;DR</h3><ul><li>🥇 **Prioritize behavior consistency** → Choose **Karpathy single-file CLAUDE.md**: rule changes take effect in 5 minutes, unified mental model across projects, Claude won’t “forget” base rules</li><li>🥈 **Failure observability + multi-agent coordination** → Choose **Skills multi-layer architecture**: trace chains, forced TDD, plugin marketplace are not achievable with a single file</li><li>💡 **Best practice (what I use now)**: Karpathy CLAUDE.md as the project-root baseline + Skills architecture for sub-task orchestration. The two don’t conflict.</li></ul><h3>Why Karpathy Re-asserts “Single-File CLAUDE.md”</h3><p>Over the past 6 months I have written 4 Skills series articles (6/21 mattpocock/skills, 6/24 gstack comparison, 6/28 Skills three-way showdown, 6/30 agency-agents 112 templates). The core experience is that <strong>the Skills architecture is powerful but operationally expensive</strong>:</p><p>Dimension Single-File CLAUDE.md Skills Multi-Layer Architecture</p><p>Startup load</p><p>Auto-loaded each session (≤200ms)</p><p>Requires `npx skills@latest add`; some are lazy-loaded</p><p>Rule change propagation</p><p>Edit 1 file, 5 min, project-wide</p><p>Repackaging required, may trigger plugin marketplace re-review</p><p>Failure localization</p><p>❌ Rule conflicts hard to trace</p><p>✅ obra/superpowers built-in `using-superpowers` interceptor logs</p><p>Cross-project reuse</p><p>✅ Copy-paste</p><p>⚠️ Plugin compatibility considerations</p><p>Behavior consistency (multi-dev collaboration)</p><p>✅ Everyone reads the same rules</p><p>⚠️ Different devs may install different skill versions</p><p>Karpathy’s July 2026 repo (multica-ai/andrej-karpathy-skills, <strong>star count changes over time, check GitHub for current</strong>) is essentially a ~400-line CLAUDE.md specifying:</p><p>1. <strong>Code style ironclad rules</strong> (naming, indentation, comment density)</p><p>2. <strong>Test trigger conditions</strong> (any function change must run tests)</p><p>3. <strong>Prohibited behaviors</strong> (no console.log, no TODOs left behind, no fake dep versions)</p><p>4. <strong>Git operation constraints</strong> (commit message format, rebase forbidden)</p><p>5. <strong>API call boundaries</strong> (which libraries are off-limits, which tools are preferred)</p><p>His reasoning is direct: **”The first-principles of AI agent behavior control is that rules must be readable, modifiable, and traceable.”** A **short but complete** single file serves that goal better than 17 skill directories (line counts change as the repo evolves, **clone and wc -l to confirm**).</p><h3>🛠️ Prerequisites</h3><ul><li>**Claude Code version**: ≥ 2.0.6 (CLAUDE.md auto-load stable from 2.0)</li><li>**Project structure**: `CLAUDE.md` at the root (required, not in subdirectories)</li><li>**Skills architecture (if chosen)**: Node.js ≥ 18, `npx skills@latest` available</li><li>**Verification command**: `claude mcp list` should output 0 MCP servers (pure local rules mode)</li></ul><h3>🚀 Practice 1: Karpathy Single-File CLAUDE.md Deployment</h3><h3>Step 1: Clone the reference template</h3><pre>cd ~/projects/your-project curl -fsSL https://raw.githubusercontent.com/multica-ai/andrej-karpathy-skills/main/CLAUDE.md -o CLAUDE.md wc -l CLAUDE.md # Actual line count varies by repo version (clone and confirm)</pre><h3>Step 2: Project-level trimming</h3><p>My trimming principles (validated over 30 days):</p><ul><li>**Keep**: code style, test triggers, Git operations, API boundaries</li><li>**Delete**: project-specific naming (Karpathy’s ML terminology may be noise for a pure web project)</li><li>**Add**: project-specific prohibitions (e.g., “no new npm deps without PR discussion”)</li></ul><h3>Step 3: Verify auto-load</h3><pre>claude --print &quot;List the 5 most important code conventions for this project&quot; # Output should directly cite CLAUDE.md content, not Claude&#39;s invention</pre><h3>💣 Pitfall Log: 5 Real Traps</h3><h3>Pitfall 1: CLAUDE.md over 500 lines → Claude “selective amnesia”</h3><p><strong>Symptom</strong>: When I expanded CLAUDE.md to 600+ lines (with detailed API docs), Claude would <strong>ignore rules toward the end</strong> in long sessions.</p><p><strong>Root cause</strong>: Claude Code 2.0.x’s CLAUDE.md loader injects the whole file into system prompt. Beyond ~500 lines, token attention gets diluted.</p><p>**Fix**: Split into CLAUDE.md (core rules ≤400 lines) + docs/claude-rules/ (details referenced on-demand via @docs/claude-rules/api.md).</p><h3>Pitfall 2: Single-file rules conflict with Skills `/grill-me`</h3><p>**Symptom**: After installing mattpocock/skills’s /grill-me, Karpathy-style &quot;write code first, explain after&quot; was force-overridden by /grill-me to &quot;answer 5 questions first, then code.&quot; Productivity dropped 60%.</p><p><strong>Root cause</strong>: Skills hooks have higher priority than CLAUDE.md (hooks are Claude Code 2.0+ preprocessors).</p><p>**Fix**: Pick one, or explicitly state in CLAUDE.md header: “/grill-me only enabled when explicitly invoked by user, not auto-triggered by hook.&quot;</p><h3>Pitfall 3: Cross-project copy-paste of CLAUDE.md introduces hidden bugs</h3><p><strong>Symptom</strong>: I copied Project A’s CLAUDE.md to Project B. Project B uses a different test framework (pytest vs jest). Claude still generated code following A’s “must use pytest” rule → all tests failed.</p><p><strong>Root cause</strong>: Single-file rules are <strong>project-level, not tool-level</strong>. Hard copy-paste is equivalent to forcing constraints.</p><p><strong>Fix</strong>: Maintain 3 templates (Python/Node/Rust), pick the matching one per project language before trimming.</p><h3>Pitfall 4: Team collaboration → CLAUDE.md merge conflicts</h3><p><strong>Symptom</strong>: 3-dev team each modified CLAUDE.md, git merge conflicts happened frequently, eventually the team gave up maintaining it.</p><p><strong>Root cause</strong>: CLAUDE.md is a high-frequency change file (any code style discussion can modify it), but lacks a code review workflow.</p><p>**Fix**: Split into CLAUDE.md (stable core) + CLAUDE.local.md (personal preferences, gitignored). Local file CLAUDE.local.md doesn&#39;t go into version control; team rules stay in CLAUDE.md.</p><h3>Pitfall 5: Single file can’t express “switch rules by scenario”</h3><p><strong>Symptom</strong>: In my <a href="https://www.amazon.com/s?k=WordPress&amp;i=stripbooks-intl-ship&amp;crid=2GP4ZRUNK7CK3&amp;sprefix=wordpress%2Cstripbooks-intl-ship%2C439&amp;ref=nb_sb_noss_1&amp;tag=techpassive-20">WordPress</a> project I want Claude to “test with WP-CLI”, in Ansible I want “test with molecule.” Writing both in one file confuses Claude.</p><p><strong>Root cause</strong>: Single-file rules are flat; no context-switching mechanism.</p><p>**Fix**: Use Claude Code 2.0+’s @file syntax inside CLAUDE.md to reference by scenario: @.claude/wordpress.md, @.claude/ansible.md. Claude will auto-pick based on current project structure.</p><h3>🛡️ Advanced: Single-File + Skills Hybrid (What I Use Now)</h3><p>After 30 days I found the optimal combination:</p><pre>project-root/ ├── CLAUDE.md # Core rules ≤300 lines (Karpathy-style) ├── .claude/ │ ├── wordpress.md # WordPress project-specific rules │ ├── ansible.md # Ansible project-specific rules │ └── skills/ # On-demand installed skills │ └── obra-superpowers/ # Only forced-TDD one └── package.json</pre><p><strong>Hybrid principles</strong>:</p><ul><li>**CLAUDE.md** handles “project-level consistency” (code style, Git flow, API boundaries)</li><li>**Skills** only handle “point capabilities” (forced TDD, automated PR review, custom `/review`)</li><li>**Conflict resolution**: CLAUDE.md states “Skills must not modify code style rules defined in CLAUDE.md”</li></ul><p>Results: behavior consistency 95/100, failure localization 85/100, cross-project reuse 90/100 (30-day data, 3-project average).</p><h3>FAQ</h3><p><strong>Q: Do I have to copy Karpathy’s CLAUDE.md verbatim?</strong></p><p>A: No. Karpathy himself says “this is just a reference, trim for your project.” I trimmed 30% and added 15% project-specific rules.</p><p><strong>Q: What project size suits single-file CLAUDE.md?</strong></p><p>A: From 30 days of experience, projects ≤50k lines of code are smooth with a single file. &gt;100k lines → split into core + sub-modules (each sub-module dir has its own CLAUDE.md, supported by Claude Code 2.0+ via nearest-load).</p><p><strong>Q: Will Skills architecture be replaced by single-file?</strong></p><p>A: No. They solve different problems-Skills solve “capability extension”, single-file solves “behavior consistency.” I recommend learning both.</p><p><strong>Q: What if mattpocock/skills conflicts with Karpathy style?</strong></p><p>A: Pick one and run for 2 weeks before switching. Mixing requires explicit priority rules (written into CLAUDE.md), otherwise Claude behavior is unpredictable.</p><h3>Summary and Next Steps</h3><p>Karpathy’s single-file CLAUDE.md is not a “replacement” for the Skills architecture-it’s a <strong>complement</strong>. After 30 days of hands-on, my advice:</p><p>1. <strong>New project start</strong>: Use Karpathy single-file template (400 lines), don’t install a pile of skills upfront</p><p>2. **When failures can’t be localized**: Then on-demand install 1–2 skills (/tdd, /review), never more than 3</p><p>3. <strong>Cross-project reuse</strong>: Maintain 3 language templates (Python/Node/Rust), don’t hard copy-paste</p><p>Next I will write “claude mcp add + CLAUDE.md joint debugging”-automatic validation between MCP server tool lists and CLAUDE.md rules, preventing tool calls from violating project rules.</p><h3>Related Reading</h3><p><a href="https://platform.xiaomimimo.com/?ref=6847ML">👉 Join Xiaomi MiMo Platform: API credits + 10% off first order</a> <a href="https://www.aliyun.com/minisite/goods?userCode=7nyzznme">👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation</a></p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-07-27-karpathy-claudemd-vs-claude-code-skills-2026-which-en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aacf369823f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention From Scratch: NumPy Code Checked vs PyTorch — TechPassive]]></title>
            <link>https://medium.com/@yao_hehe/attention-from-scratch-numpy-code-checked-vs-pytorch-techpassive-9c6cf4925674?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c6cf4925674</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 12:24:45 GMT</pubDate>
            <atom:updated>2026-11-15T12:24:45.619Z</atom:updated>
            <content:encoded><![CDATA[<p>Most people stall on the same page of the Transformer paper: Attention(Q, K, V) = softmax(QK^T / sqrt(d_k))V. You can memorize the formula and still not be able to write it. Where do Q, K, V come <a href="https://yaohehe.github.io/2026-09-28-2026-budget-keyboard-showdown-for-programmers-amaz-en.html">from</a>? Which step divides by d_k? Does the mask go before or after the softmax? Why is the reshape in multi-head attention ordered the way it is?</p><p>I tested this the slow way: I wrote the whole thing <a href="https://yaohehe.github.io/2026-09-28-2026-budget-keyboard-showdown-for-programmers-amaz-en.html">from</a> scratch in NumPy, then ran it against PyTorch 2.14.1 scaled_dot_product_attention and nn.MultiheadAttention with identical weights and identical inputs. The largest absolute difference between my version and PyTorch&#39;s was 2.220446049250313e-16, which is floating-point noise. Every number below was produced on my own Windows CPU on October 12, 2026, and the code is copy-paste runnable.</p><p>Disclosure: there are no affiliate links in this article and nothing here is sponsored.</p><p><strong>TL;DR</strong></p><ul><li><strong>One step in the formula is genuinely tricky</strong>: the division by sqrt(d_k) before the softmax. Without it, at d_k=64 I measured a max attention weight of 0.921946, which means the head looks at essentially one position.</li><li><strong>Multi-head is not “run attention a few more times”</strong>: it splits d_model into h slices, runs each one independently, then concatenates and projects again.</li><li><strong>The mask goes into the softmax input, and its value is -inf, not 0.</strong> With 0, masked positions still receive weight.</li><li><strong>Matching the official implementation takes about 40 lines</strong>: single-head difference 2.22e-16, multi-head difference 4.44e-16.</li></ul><h3>The division is the part worth reading twice</h3><p>Section 3.2.1 of “Attention Is All You Need” (arXiv:1706.03762, v1 submitted June 12, 2017; version v7 cited here revised August 2, 2023) states the formula as:</p><p>Attention(Q, K, V) = softmax(QK^T / sqrt(d_k)) V</p><p>The same section gives the reason, in the authors’ words: “We suspect that for large values of d_k, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients.”</p><p>The footnote does the math: if the components of q and k are independent with mean 0 and variance 1, then q·k = Σ q_i·k_i has mean 0 and variance d_k. Higher dimension, larger dot products, and the softmax gets pushed into a region with almost no gradient — the output is nearly one-hot and backpropagation has almost nothing to work with.</p><p>Section 3.2.2 gives the base configuration: d_model = 512, h = 8 heads, d_k = d_v = d_model / h = 64, N = 6 identical layers in each stack, dropout rate 0.1.</p><h3>What happens without it: watching softmax collapse</h3><p>Rather than restate the claim, I ran it. This generates 2,000 keys for d_k = 16 / 64 / 512 and compares the softmax shape with and without scaling:</p><pre>import numpy as np def softmax(x): x = x - x.max() e = np.exp(x) return e / e.sum() for dk in (16, 64, 512): r = np.random.default_rng(7) q = r.normal(size=(dk,)) k = r.normal(size=(2000, dk)) dots = k @ q w_raw = softmax(dots) w_scl = softmax(dots / np.sqrt(dk)) print(f&quot;dk={dk:4d} dot std={dots.std():6.2f} &quot; f&quot;max weight unscaled={w_raw.max():.6f} max weight scaled={w_scl.max():.6f} &quot; f&quot;effective terms unscaled={1/np.sum(w_raw**2):7.2f} scaled={1/np.sum(w_scl**2):7.2f}&quot;)</pre><p>Output on my machine:</p><pre>dk= 16 dot std= 2.47 max weight unscaled=0.227685 max weight scaled=0.004241 effective terms unscaled= 14.85 scaled=1341.59 dk= 64 dot std= 7.32 max weight unscaled=0.921946 max weight scaled=0.009399 effective terms unscaled= 1.17 scaled= 829.74 dk= 512 dot std= 20.99 max weight unscaled=0.933175 max weight scaled=0.005796 effective terms unscaled= 1.15 scaled= 917.82</pre><p>“Effective terms” is my own metric, defined as 1 / Σ w_i², read as “how many of those 2,000 keys are actually being attended to.”</p><p>The d_k=64 row makes the point: unscaled, the max weight is 92.19% and effective terms is 1.17 — across a 2,000-token sequence, attention lands almost entirely on one position and the gradient for the rest is close to zero. Scaled, the max weight drops to 0.94% and effective terms rises to 829.74, so the head is actually aggregating. At d_k=16 the gap is smaller (14.85 vs 1341.59), which lines up with the paper’s own “for small values of d_k the two mechanisms perform similarly.”</p><h3>The minimal runnable implementation: under 40 lines of NumPy</h3><pre>import numpy as np def softmax(x, axis=-1): x = x - np.max(x, axis=axis, keepdims=True) # keeps exp from overflowing e = np.exp(x) return e / np.sum(e, axis=axis, keepdims=True) def scaled_dot_product_attention(Q, K, V, mask=None): &quot;&quot;&quot;Q:(..., Tq, dk) K:(..., Tk, dk) V:(..., Tk, dv) mask: bool, True means this position gets masked out (replaced by -inf) &quot;&quot;&quot; dk = Q.shape[-1] scores = Q @ np.swapaxes(K, -1, -2) / np.sqrt(dk) if mask is not None: scores = np.where(mask, -np.inf, scores) w = softmax(scores, axis=-1) return w @ V, w</pre><p>That is a one-to-one translation of the paper’s equation, plus np.where(mask, -np.inf, scores) and the max subtraction inside softmax (numerical stability, not decoration).</p><p>With 5 tokens and d_k=4 (seed fixed at 20261012), the first row of attention weights comes out as:</p><pre>[0.027843 0.167136 0.246698 0.211041 0.347282]</pre><p>Five positions, five weights, summing to 1. I asserted the row sums: the largest deviation from 1.0 was 1.1102230246251565e-16. Measure this yourself — if you ever see that deviation at 1e-3, suspect the softmax axis before you suspect NumPy.</p><h3>Multi-head: split, attend separately, concatenate</h3><p>Section 3.2.2 describes it as projecting Q, K, V h times with different learned projections down to d_k, d_k, d_v dimensions, attending in parallel, concatenating, and projecting once more. In code that is a reshape plus a transpose:</p><pre>def multi_head_attention(X, WQ, WK, WV, WO, h, causal=False): T, d_model = X.shape dh = d_model // h Q, K, V = X @ WQ, X @ WK, X @ WV # (T, d_model) -&gt; (h, T, dh) Qh = Q.reshape(T, h, dh).transpose(1, 0, 2) Kh = K.reshape(T, h, dh).transpose(1, 0, 2) Vh = V.reshape(T, h, dh).transpose(1, 0, 2) mask = np.triu(np.ones((T, T), dtype=bool), k=1) if causal else None heads, w = scaled_dot_product_attention(Qh, Kh, Vh, mask=mask) # (h, T, dh) -&gt; (T, d_model) return heads.transpose(1, 0, 2).reshape(T, d_model) @ WO, w</pre><p>With 5 tokens, d_model=16, h=4: output shape (5, 16), weights shape (4, 5, 5) — one 5×5 attention table per head.</p><p>One thing worth knowing about reshape(T, h, dh): it slices along the last axis in order, so head 0 gets columns 0..dh-1. That is why WQ, WK, WV should stay full d_model × d_model matrices and let each head learn its own block, rather than pre-slicing the weights into h pieces and initializing them separately. The latter runs, but it is not what the paper describes.</p><p>Section 3.2.3 also lists three uses of attention: encoder self-attention (Q, K, V from the same place), decoder self-attention with the causal mask, and encoder-decoder attention (Q from the previous decoder layer, K and V from the encoder output stack). The implementation above passes X as all three, which covers the first two; for the third, hand it the encoder output as K and V and the function needs no changes.</p><h3>Causal masking: the paper says -inf, not 0</h3><p>Section 3.2.3 is blunt about it: “We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to −∞) all values in the input of the softmax which correspond to illegal connections.”</p><p>Two facts in that sentence: the mask applies to the <strong>input of the softmax</strong>, and the value is <strong>−∞</strong>.</p><p>I verified it on the same 5-token example with a causal mask: the largest weight at a masked position was <strong>0.0</strong>, and row 2 had only 3 positions with weight above zero, meaning position 2 can see 0, 1, 2 — matching “up to and including that position.”</p><p>If your masked positions come out as 1e-9 rather than exactly 0, you used a float mask with -1e9 instead of -inf. It works numerically, but they are different things: -inf makes exp produce exactly 0, -1e9 only makes it produce a very small number.</p><h3>Checking my code against PyTorch</h3><p>My NumPy version and F.scaled_dot_product_attention, same weights and inputs in float64: max absolute difference <strong>2.220446049250313e-16</strong>. Loading WQ/WK/WV into nn.MultiheadAttention&#39;s in_proj_weight and WO into out_proj.weight and running the full multi-head path: max absolute difference <strong>4.440892098500626e-16</strong>.</p><p>One honest performance number from the same CPU: at T=128, d=64, the per-row for-loop version took 5.669 ms and the matrix version 1.050 ms, 5.4x faster, with outputs differing by 4.00e-15. The loop version is not wrong, it just splits one matrix multiply into 128 pieces — which is what the paper means by dot-product attention being “implemented using highly optimized matrix multiplication code.”</p><p>Here is the trap. The PyTorch 2.14 docs flag it in a Note on the scaled_dot_product_attention page: boolean mask semantics are the <strong>inverse</strong> of MultiheadAttention&#39;s key_padding_mask. In scaled_dot_product_attention, True means the element takes part in attention; in MultiheadAttention, True means masked out.</p><p>I ran both ways with the same causal mask:</p><pre>correct convention (inverted before passing): 2.220446049250313e-16 reversed convention (passed as-is): 3.668259537831219</pre><p>A difference of 3.67, and no error is raised — the model quietly attends to future tokens. If you take one thing from this article, take that.</p><h3>Troubleshooting: five real errors</h3><p>All five were captured while I was writing this code, copied verbatim. They are not illustrative examples.</p><p><strong>Error 1: forgot to transpose K (NumPy)</strong></p><pre>ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)-&gt;(n?,m?) (size 5 is different from 4)</pre><p>Q is (5, 4) and so is K, so Q @ K cannot work. Write Q @ K.T, or np.swapaxes(K, -1, -2) for batched input. In self-attention Q and K have identical shapes, so the error never says &quot;transpose&quot; - if you see &quot;size 5 is different from 4&quot;, check the transpose first.</p><p><strong>Error 2: forgot to transpose K (PyTorch)</strong></p><pre>RuntimeError: mat1 and mat2 shapes cannot be multiplied (5x4 and 5x4)</pre><p>Same mistake, more direct message. Build the habit of writing K.transpose(-2, -1) in full.</p><p><strong>Error 3: is_causal and attn_mask at the same time</strong></p><pre>RuntimeError: _scaled_dot_product_attention: Explicit attn_mask should not be set when is_causal=True</pre><p>The docs state “An error is thrown if both attn_mask and is_causal are set.” Pick one: is_causal=True for a standard square causal mask, or pass attn_mask for non-square or custom masks and leave is_causal at its default.</p><p><strong>Error 4: exp underflows in float32 and softmax returns nan</strong></p><pre>dot = -1802.824 exp(dot) = 0.0 e/e = nan RuntimeWarning: invalid value encountered in scalar divide</pre><p>Measured with 1024-dimensional float32 vectors scaled by 10. The dot product is -1802.824, exp underflows to 0.0, numerator and denominator are both zero, and the division gives nan. With a large positive dot product you get inf instead, and inf/inf is nan too. <strong>The fix is not float64, it is subtracting the max before exp</strong>: after x - x.max() the largest argument to exp is 0, so exp(0)=1 and the denominator is at least 1. The implementation above already does this.</p><p><strong>Error 5: wrong softmax axis — silent, and wrong</strong></p><pre>axis=0 row sums: [0.838357 1.937897 0.662364 0.992172 0.569209] axis=-1 row sums: [1. 1. 1. 1. 1.] output difference: 1.2147038513899666</pre><p>np.exp(s) / np.exp(s).sum(axis=0) runs fine, warns about nothing, and has the right shape - it just normalizes over columns instead of rows. The check is one line: assert that w.sum(axis=-1) is all ones. This is the case where an assertion is not optional, because nothing else will tell you.</p><h3>Where to go next</h3><h3>FAQ</h3><p><strong>Q1: Can I train with the from-scratch version?</strong></p><p>No, and you shouldn’t want to. Its value is confirming that you understood the algorithm: matching PyTorch to 1e-16 means the formula, axis order, and mask placement are all right. For training, use F.scaled_dot_product_attention, which selects among FlashAttention, Memory-Efficient attention, and the C++ implementation (the three listed in the docs), and supports GQA.</p><p><strong>Q2: Why is my difference 1e-7 instead of 1e-16?</strong></p><p>Check the dtype first. Everything above was measured in float64; float32 lands around 1e-7, which is expected. The docs also note that fused floating-point kernels can produce different results from each other, and that the C++ implementation supports float64.</p><p><strong>Q3: Can I use -1e9 instead of -inf in the mask?</strong></p><p>It runs, but it is not exact. -inf makes exp return exactly 0; -1e9 leaves a tiny non-zero value in float32. The 0.0 I measured at masked positions came from using -inf. Also note that PyTorch’s float attn_mask is <strong>added</strong> to the scores, so adding -inf is what masks.</p><p><strong>Q4: Must d_k equal d_model / h?</strong></p><p>That is how the paper sets it (d_k = d_v = d_model/h = 64, h=8, d_model=512), with the stated reason that with the reduced per-head dimension, “the total computational cost is similar to that of single-head attention with full dimensionality.” It is a convention, not a mathematical requirement, and modern models do deviate.</p><h3>Sources and how the numbers were produced</h3><p>The formula, the justification for dividing by sqrt(d_k), h=8 / d_k=d_v=64 / d_model=512 / N=6 / dropout 0.1, and the -inf masking all come from sections 3.2.1–3.2.3 of arXiv:1706.03762, “Attention Is All You Need” (v1 June 12, 2017; v7 cited here, August 2, 2023).</p><p>Every measured number (2.22e-16, 4.44e-16, 0.921946, effective terms 1.17, the 5.4x timing, 3.668259537831219, and the five error messages) was produced on my Windows CPU on October 12, 2026 with Python 3.13, NumPy 2.5.4, and PyTorch 2.14.1+cpu. Seeds are hardcoded in the snippets, so the runs are reproducible.</p><p>The boolean mask semantics, the is_causal/attn_mask exclusivity, and the backend selection statements come from the PyTorch 2.14 documentation page for scaled_dot_product_attention, cross-checked against what I measured locally.</p><p>No affiliate links and no product recommendations here. The timing numbers depend on CPU model and load and will differ on your machine; they are here to show the order of magnitude, not to serve as a benchmark.</p><p><a href="https://platform.xiaomimimo.com/?ref=6847ML">👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference</a> <a href="https://www.aliyun.com/minisite/goods?userCode=7nyzznme">👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation</a></p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-10-12-attention-from-scratch-numpy-code-checked-vs-pytor-en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.<strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c6cf4925674" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning vs RAG vs Prompting: The Decision Tree]]></title>
            <link>https://medium.com/@yao_hehe/fine-tuning-vs-rag-vs-prompting-the-decision-tree-f2c0f9da824e?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2c0f9da824e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Sun, 15 Nov 2026 00:48:19 GMT</pubDate>
            <atom:updated>2026-11-15T00:48:19.344Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR</strong>: Fine-tuning, RAG, and prompting are not three options to pick from — they are three different layers. Prompting controls how the model says things, RAG controls what it does not know, and fine-tuning controls what it does by default. Prompt caching breaks even at just 2 requests inside a 5-minute TTL window, which is roughly 24 requests per hour. LoRA on an 8B model with the mainstream 2026 recipe (all 7 projections, r=16) compresses trainable parameters by 191.5x, not the 10000x from the paper abstract. And OpenAI has scheduled its self-serve fine-tuning platform to stop accepting new jobs for everyone on January 6, 2027. Every price and multiplier here comes from vendor documentation, verified as of October 14, 2026. This article contains no affiliate links.</p><h3>Three layers, not three options</h3><p>Almost every “should we fine-tune?” argument starts in the wrong place, because it treats three different layers as one button.</p><p>Prompting</p><p>The context you send with each request</p><p>Tone, format, few-shot examples, hard constraints</p><p>Knowledge the model never saw in training</p><p>Minutes</p><p>RAG</p><p>External knowledge pulled in by retrieval</p><p>Fresh facts, long-tail entities, citable provenance</p><p>Unstable tone and drifting output format</p><p>Days (you need an index)</p><p>Fine-tuning</p><p>The weights themselves</p><p>Stable format, domain voice, small model chasing a big one</p><p>Injecting new knowledge (it amplifies hallucination)</p><p>Weeks</p><p>Here is the one-line test: <strong>if the model does not know, use RAG. If it knows but will not comply, use prompting, and only reach for fine-tuning when prompting stops holding.</strong></p><p>That split is not folklore. The original RAG paper (arXiv:2005.11401, NeurIPS 2020, Lewis et al.) separates parametric memory — knowledge baked into weights — from non-parametric memory, a dense vector index over Wikipedia, and names two open problems for parametric models: providing provenance for their decisions, and updating their world knowledge. In other words, <strong>injecting knowledge was never fine-tuning’s job</strong>. It is the reason RAG exists.</p><h3>The six-step decision tree</h3><p><strong>Step 1: Is it missing knowledge or missing behavior?</strong></p><p>Let the model answer once and look at the failure mode. Wrong facts means missing knowledge. Right facts but wrong format, tone, or length means missing behavior. Missing knowledge goes straight to RAG. Stop tuning the prompt.</p><p><strong>Step 2: Does the knowledge change?</strong></p><p>If it changes — price lists, inventory, internal docs, news — RAG is the only real answer. Burning volatile facts into weights creates a retraining debt you will pay forever.</p><p><strong>Step 3: How many clean labeled examples do you have?</strong></p><p>Fewer than 50, stay with prompting. OpenAI’s own guidance is to start text SFT from 50 well-crafted examples with a hard floor of 10. That is a floor, not a promise that 50 is enough.</p><p><strong>Step 4: Is your volume high enough to amortize anything?</strong></p><p>This is the step everyone skips. The next section puts a number on it.</p><p><strong>Step 5: Do you need provenance?</strong></p><p>If you have to answer “which document did that sentence come from,” you need RAG.</p><p><strong>Step 6: Only now consider fine-tuning.</strong></p><p>And first confirm the platform still lets you. See the shutdown schedule below.</p><h3>Cost ledger 1: where prompt caching breaks even</h3><p>Anthropic’s official pricing documentation is explicit about the multipliers:</p><ul><li>5-minute TTL cache write = <strong>1.25x the base input price</strong></li><li>1-hour TTL cache write = <strong>2x the base input price</strong></li><li>Cache read (a hit) = <strong>0.1x the base input price</strong> (0.05x on Claude Opus 5.5 and Sonnet 5.5)</li></ul><p>The docs state the conclusion directly: caching pays off after one cache read for the 5-minute duration (1.25x write), or after two cache reads for the 1-hour duration (2x write). I ran the arithmetic from those multipliers and landed on exactly the same place:</p><p>Requests inside a 5-minute TTL window Pay full price With caching</p><p>The 1-hour TTL row needs 3 requests before it wins (2.20x against 3.00x), which also matches the two-cache-reads statement.</p><p>Turned into a threshold you can check against your own traffic: <strong>an average of at least 2 requests per 5-minute window, about 24 per hour, and caching already saves money.</strong> Below that, you never earn back the 1.25x write premium.</p><p>One more thing worth dating: Anthropic’s API release note for October 7, 2026 cut the cache read price on Claude Sonnet 5.5 from $0.20 to $0.10 per million tokens, moving it from 0.1x to 0.05x. <strong>The same code got cheaper inside a week.</strong> That is why every number in this article carries a date.</p><h3>Cost ledger 2: LoRA’s real compression ratio, measured locally</h3><p>Nearly every LoRA article quotes the abstract’s line about reducing trainable parameters by 10,000 times and GPU memory requirements by 3 times (arXiv:2106.09685, Hu et al., submitted June 17, 2021). It is true. It is also true <strong>only for the paper’s own experimental setup</strong>, not for the recipe you are running.</p><p>I ran the number locally with peft 0.21.2, transformers, and torch 2.14.1+cpu. The approach: build a graph from the public Llama 3 8B architecture (hidden 4096, intermediate 14336, 32 layers, 32 heads, 8 KV heads) on the meta device so nothing is actually allocated, then let peft inject the adapter and count trainable parameters for real:</p><pre>import torch from transformers import LlamaConfig, LlamaForCausalLM from peft import LoraConfig, get_peft_model DIM, FFN, LAYERS, HEADS, KV, VOCAB = 4096, 14336, 32, 32, 8, 128256 with torch.device(&quot;meta&quot;): # build the graph only, allocate nothing cfg = LlamaConfig(hidden_size=DIM, intermediate_size=FFN, num_hidden_layers=LAYERS, num_attention_heads=HEADS, num_key_value_heads=KV, vocab_size=VOCAB, rope_theta=500000) model = LlamaForCausalLM(cfg) total = sum(p.numel() for p in model.parameters()) # 8,030,261,248 for r, mods in [(16, [&quot;q_proj&quot;, &quot;k_proj&quot;, &quot;v_proj&quot;, &quot;o_proj&quot;, &quot;gate_proj&quot;, &quot;up_proj&quot;, &quot;down_proj&quot;]), (8, [&quot;q_proj&quot;, &quot;v_proj&quot;])]: lcfg = LoraConfig(r=r, lora_alpha=2 * r, lora_dropout=0.0, target_modules=mods, task_type=&quot;CAUSAL_LM&quot;) pm = get_peft_model(model, lcfg) tr = sum(p.numel() for p in pm.parameters() if p.requires_grad) print(f&quot;r={r} modules={len(mods)} trainable={tr:,} share={tr/total*100:.3f}% compression={total/tr:.1f}x&quot;) pm = pm.unload()</pre><p>Actual output:</p><pre>r=16 modules=7 peft reports trainable = 41,943,040 share 0.522% compression 191.5x r=8 modules=2 peft reports trainable = 3,407,872 share 0.042% compression 2356.4x</pre><p>So the conclusion is blunt: <strong>with the mainstream 2026 recipe — q/k/v/o plus gate/up/down, seven projections, r=16, alpha = 2r — the compression ratio is 191.5x, not 10000x.</strong> Where does 10000x come from? I ran the paper’s setup too: GPT-3 175B, q and v only, r=4, 96 layers gives 18,874,368 trainable parameters and 9,272x compression. That matches the claim.</p><p>Three things moved at once: the base shrank from 175B to 8B, the rank went from 4 to 16, and the targeted modules went from 2 to 7.</p><p>The memory ledger needs the same treatment. Using the usual mixed-precision AdamW accounting (bf16 weights 2 bytes, bf16 gradients 2 bytes, fp32 master 4 bytes, first moment 4 bytes, second moment 4 bytes — 16 bytes per parameter):</p><ul><li>Full fine-tuning of 8B: about <strong>119.7 GiB</strong> of training state, which does not fit on a single 80GB card</li><li>LoRA r=16 across all 7 modules: 41,943,040 trainable parameters, roughly <strong>40 MiB</strong> of optimizer state</li></ul><p><strong>That is LoRA’s actual value: not the pretty “10000x fewer parameters” line, but dropping the training barrier from a multi-GPU cluster to a single card.</strong> And do not forget the abstract’s note that, unlike adapters, it adds no inference latency — LoRA weights can be merged back into the base.</p><h3>Cost ledger 3: four discounts stack on a fine-tuned model’s unit price</h3><p>Most people budget fine-tuning as training cost only. But OpenAI’s official pricing page (the Finetuning section, o4-mini-2025–04–16) lists several tiers, and the same fine-tuned model’s input price spans <strong>16x</strong>:</p><p>Input moves from $4.00 to $0.25, a factor of 16; output moves from $16.00 to $4.00, a factor of 4. Note that the $0.25 line is the cached-input tier — <strong>a fine-tuned model still benefits from prompt caching</strong>. The two are not in conflict.</p><p>On the training side, the official unit is <strong>$100.00 per hour</strong>, not per token. One hour of training costs $100, which buys roughly 25 MTok of input on that same fine-tuned model. <strong>At low volume, spending that money directly on input tokens is usually the better deal</strong> — which is exactly why step 4 of the tree gates on request volume.</p><h3>The awkward reality: OpenAI is winding down self-serve fine-tuning</h3><p>Anyone making a 2026 platform decision needs this. OpenAI’s Deprecations page gives the schedule:</p><p>2026–05–07</p><p>Organizations that never ran fine-tuning can no longer create jobs</p><p>2026–07–02</p><p>Organizations with no fine-tuned-model inference in the prior 60 days can no longer create new jobs</p><p>2027–01–06</p><p>Every remaining customer loses the ability to create new fine-tuning jobs</p><p>Models you already trained keep serving inference until their base model is retired. So this is not “your deployed service gets switched off”; it is “your ability to change it gets frozen.”</p><p>The second row is the nasty one, because the gate is tied to your own usage. A project that fine-tuned heavily in 2025 and then went quiet for three quarters can come back to retrain and find the door shut by its own 60 days of silence, not by the 2027 date. <strong>If fine-tuning is in your stack, per-model usage monitoring is capability insurance.</strong></p><h3>Troubleshooting: four errors traced to source</h3><p><strong>Error 1: target modules not found</strong></p><p>The message is Target modules [&#39;q_proj&#39;, &#39;k_proj&#39;] not found in the base model. Please check the target modules and try again. It comes from peft&#39;s tuners/tuners_utils.py and raises NoMatchingPeftModuleError. The cause is that many models fuse attention: Gemma, Phi, and some Qwen variants use a single fused qkv_proj matrix, so there is no separate q_proj, k_proj, or v_proj to target. Copying a Llama recipe hits this immediately. Two fixes: set target_modules=&quot;all-linear&quot; and let peft match every linear layer, or walk model.named_modules() and print the real names first.</p><p><strong>Error 2: cannot merge on a quantized base</strong></p><p>The message is ValueError: Cannot merge LORA layers when the model is gptq quantized, from peft/tuners/lora/model.py. Training LoRA on a GPTQ-quantized base works fine, but merge_and_unload() fails, because quantized weights cannot simply be added to the adapter delta. In quantization plus LoRA setups, keep the adapter structure at inference instead of merging.</p><p><strong>Error 3: cannot merge when layers are replicated</strong></p><p>The message is ValueError: Cannot merge LORA layers when base model layers are replicated, from an adjacent branch of the same file. Once tensor parallelism has replicated layers, merging fails. If you hit this in a multi-GPU deployment, merge first and shard after, not the other way around.</p><p><strong>Error 4: gradients die at the first layer</strong></p><p>The message is RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn. It shows up when you enable gradient checkpointing to save memory: the frozen base produces outputs with no gradient, so backprop dies at layer one. The standard fix in PEFT setups is model.enable_input_require_grads(), which reattaches gradients to the input embedding output. This one misleads badly - it points at tensor 0, but the root cause is checkpointing combined with frozen parameters.</p><p>One more issue that is not an error but costs people a day: <strong>you train LoRA, load the adapter, and the output is identical to the base model.</strong> Usually you forgot model.eval(), or in a multi-adapter setup you never called set_adapter(). Run print_trainable_parameters() to confirm the adapter is actually attached before you start doubting the training run.</p><h3>When to go back and fix the prompt instead</h3><p>The cheapest regression path I found: when a fine-tuned model falls behind on new data, do not retrain yet. Write the constraints it learned back into the system prompt as a few sentences and run the comparison on the same base model. If the gap is inside your tolerance, retire the fine-tune — especially with the platform window measured in months, <strong>removing a dependency that is about to expire is itself a win</strong>.</p><h3>FAQ</h3><p><strong>Can fine-tuning teach a model new knowledge?</strong></p><p>Not recommended. The RAG paper is explicit that parametric models are limited in their ability to access and precisely manipulate knowledge, and that provenance and knowledge updates are open problems for them. If the knowledge changes, use RAG.</p><p><strong>What rank should LoRA use?</strong></p><p>Hugging Face’s official PEFT documentation says start at 8 or 16, with lora_alpha typically set to twice the rank. Covering more target_modules increases adaptation capacity but also memory. The script above takes an r value you can change and rerun.</p><p><strong>Do prompt caching and RAG conflict?</strong></p><p>No, they stack. Put the retrieved chunks in the prompt prefix, and the part of the prefix that does not change can hit cache.</p><p><strong>Is fine-tuning still worth investing in?</strong></p><p>Depends on volume and task width. Narrow task, high volume, rigid output format: still yes. But pick a platform that will not close in six months, which usually means an open-weights base you host yourself.</p><h3>Sources (all verified as of 2026–10–14)</h3><ul><li>Anthropic official pricing docs (cache multipliers, Batch discount, data residency multiplier): <a href="https://docs.anthropic.com/en/docs/about-claude/pricing">https://docs.anthropic.com/en/docs/about-claude/pricing</a></li><li>Anthropic official prompt caching docs: <a href="https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching">https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching</a></li><li>Anthropic API release notes (2026–10–07, Sonnet 5.5 cache read price cut): <a href="https://docs.anthropic.com/en/release-notes/api">https://docs.anthropic.com/en/release-notes/api</a></li><li>OpenAI official pricing (Finetuning section, o4-mini-2025–04–16 tiers): <a href="https://developers.openai.com/api/docs/pricing">https://developers.openai.com/api/docs/pricing</a></li><li>OpenAI official deprecations (self-serve fine-tuning schedule): <a href="https://developers.openai.com/api/docs/deprecations">https://developers.openai.com/api/docs/deprecations</a></li><li>LoRA paper: <a href="https://arxiv.org/abs/2106.09685">https://arxiv.org/abs/2106.09685</a></li><li>RAG paper: <a href="https://arxiv.org/abs/2005.11401">https://arxiv.org/abs/2005.11401</a></li><li>Hugging Face PEFT documentation: <a href="https://huggingface.co/docs/peft">https://huggingface.co/docs/peft</a></li></ul><p>Further reading on this site:</p><p><a href="https://platform.xiaomimimo.com/?ref=6847ML">👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference</a> <a href="https://www.aliyun.com/minisite/goods?userCode=7nyzznme">👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation</a></p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-10-14-fine-tuning-vs-rag-vs-prompting-the-2026-decision--en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2c0f9da824e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL 17 Troubleshooting in Production — TechPassive]]></title>
            <link>https://medium.com/@yao_hehe/postgresql-17-troubleshooting-in-production-techpassive-d40b51b1249a?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/d40b51b1249a</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 13:25:52 GMT</pubDate>
            <atom:updated>2026-11-14T13:25:52.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>⏳ TL;DR: The Short Version</h3><ul><li>The night every endpoint timed out, the <a href="https://yaohehe.github.io/2026-09-26-how-i-cut-a-wordpress-query-from-32s-to-180ms-en.html">database</a> was alive, CPU was sitting around 10%, and the slow-query log had recorded nothing. The backends were not **running**; they were **waiting**.</li><li>PostgreSQL records why a backend is paused in two columns of `pg_stat_activity`: `wait_event_type` and `wait_event`. Since PostgreSQL 17 there is also a `pg_wait_events` view (`type`, `name`, `description`) that translates those wait codes into plain English.</li><li>The diagnostic order is fixed: find sessions with `wait_event_type = ‘Lock’`, walk the blocking chain with `pg_blocking_pids(pid)` until you reach the real blocker, confirm the lock type with `pg_locks`, and only then decide whether to cancel or terminate.</li><li>What turns an intermittent window into a full outage is rarely one slow query. It is usually a single **idle in transaction** session holding a lock it no longer needs.</li></ul><blockquote><em>Disclosure: this post contains independent third-party affiliate links. Buying through them does not change your price but may earn this site a commission. Purchasing is unrelated to the troubleshooting method described here.</em></blockquote><h3>The Incident: Database Up, Every Endpoint Stuck</h3><p>Version details matter here, because several of the commands below behave differently across releases:</p><p>Database</p><p>PostgreSQL 18.6 (released 2026–08–13); one instance still on 17.11</p><p>Tools</p><p>pg_stat_activity, pg_locks, pg_stat_statements, pg_wait_events</p><p>Network</p><p>2.5G switch shared by the primary and a read replica</p><p>It was a textbook e-commerce afternoon. Around 14:00 the order API’s P99 jumped from 80ms to 12s, and thirty seconds later 504 responses piled up. The first instinct is always &quot;the <a href="https://yaohehe.github.io/2026-09-26-how-i-cut-a-wordpress-query-from-32s-to-180ms-en.html">database</a> got slow,&quot; so we checked three things:</p><p>1. top: the PostgreSQL backend processes together used just over 10% CPU.</p><p>2. Slow-query log: log_min_duration_statement = 1000 was on, yet that hour recorded almost nothing.</p><p>3. Connections: PgBouncer’s cl_active had climbed to the max_client_conn ceiling, and requests were queuing behind it.</p><p>Those three facts together rule out “one query scanning too much.” **Low CPU + a clean slow-query log + a full connection pool** all point the same way: most sessions were not burning CPU at all. They were waiting on a lock, and waiting does not show up in the slow-query log unless you also enable log_lock_waits.</p><p>When I actually ran this incident, my first move was a restart, which is close to the least useful action for a waiting-type failure and wiped the live evidence on the way down. I spent 35 minutes from 14:05 to 14:40, and the real diagnosis took under ten of them. The workflow below is the checklist I wrote afterward so the next on-call engineer does not lose those 25 minutes.</p><h3>First, Quantify “Waiting”: wait_event_type and wait_event</h3><ul><li>`Lock`: heavyweight locks (table, row, `transactionid`, and so on) and the most common outage culprit.</li><li>`LWLock`: lightweight locks, usually internal contention such as `WALWrite` or `ProcArray`.</li><li>`IO`: disk I/O waits such as `DataFileRead` or `WALWrite`.</li><li>`Client`: waiting on the client, classically `ClientRead` when the application has the result but has not committed or sent the next query.</li><li>`IPC`, `Timeout`, `BufferPin`, `Activity`: internal messaging, timeout waits, buffer pinning, and process main loops.</li></ul><p>Keep one counter-intuitive fact in mind: wait_event_type = &#39;Client&#39; with wait_event = &#39;ClientRead&#39; usually means the <a href="https://yaohehe.github.io/2026-09-26-how-i-cut-a-wordpress-query-from-32s-to-180ms-en.html">database</a> is fine and the application is stalling. On read replicas this is easily misread as <a href="https://yaohehe.github.io/2026-09-26-how-i-cut-a-wordpress-query-from-32s-to-180ms-en.html">database</a> trouble.</p><p>Start with a single read-only query that aggregates every non-idle session by wait:</p><pre>SELECT wait_event_type, wait_event, count(*) AS sessions FROM pg_stat_activity WHERE pid &lt;&gt; pg_backend_pid() AND state &lt;&gt; &#39;idle&#39; GROUP BY 1, 2 ORDER BY sessions DESC;</pre><p>If the Lock row suddenly shows dozens of sessions, you have found your incident. This statement is read-only and safe to run in production at any time.</p><h3>PostgreSQL 17’s pg_wait_events Turns Wait Codes Into Plain English</h3><p>pg_stat_activity.wait_event returns short identifiers such as WALWrite, ClientRead, or relation. Before version 17, understanding them meant digging through the documentation or the wait_event_names.txt file in the source tree. Starting with PostgreSQL 17, those descriptions were frozen into a system view called pg_wait_events:</p><pre>SELECT a.pid, a.usename, a.state, a.wait_event_type, a.wait_event, now() - a.xact_start AS xact_age, now() - a.query_start AS query_age, w.description FROM pg_stat_activity a JOIN pg_wait_events w ON a.wait_event_type = w.type AND a.wait_event = w.name WHERE a.wait_event IS NOT NULL AND a.state = &#39;active&#39; ORDER BY xact_age DESC;</pre><p>xact_age (how long the transaction has been open) matters more than query_age (how long the current statement has run). A statement that started 200ms ago can still hold a lock acquired 18 minutes earlier by the surrounding transaction.</p><h3>The Three-Query Workflow</h3><p><strong>Query one, find who is blocked:</strong></p><pre>SELECT pid, usename, application_name, wait_event_type, wait_event, now() - query_start AS waited, left(query, 80) AS stmt FROM pg_stat_activity WHERE wait_event_type = &#39;Lock&#39; ORDER BY waited DESC;</pre><p><strong>Query two, walk the chain to the root:</strong></p><pre>SELECT blocked.pid AS blocked_pid, pg_blocking_pids(blocked.pid) AS blocker_pids, blocked.state AS blocked_state, blocker.pid AS blocker_pid, blocker.state AS blocker_state, now() - blocker.xact_start AS blocker_xact_age, left(blocker.query, 80) AS blocker_stmt FROM pg_stat_activity blocked JOIN pg_stat_activity blocker ON blocker.pid = ANY (pg_blocking_pids(blocked.pid)) WHERE blocked.wait_event_type = &#39;Lock&#39; ORDER BY blocker_xact_age DESC;</pre><p><strong>Query three, confirm which lock is being waited on:</strong></p><pre>SELECT l.pid, l.locktype, l.relation::regclass, l.mode, l.granted, now() - a.query_start AS waited FROM pg_locks l JOIN pg_stat_activity a ON l.pid = a.pid WHERE NOT l.granted ORDER BY waited DESC;</pre><p>There is a trap with row-level contention: because row locks are stored on disk, pg_locks often shows no tuple entry and instead reports a wait on transactionid. So &quot;I checked pg_locks and saw no row lock&quot; is expected behavior, not a dead end.</p><h3>Post-Mortem: Five Real Errors and How to Fix Them</h3><h3>Error 1: ERROR: canceling statement due to lock timeout</h3><pre>ERROR: canceling statement due to lock timeout</pre><p><strong>Symptom:</strong> a batch job that updates order status fails every so often, then succeeds on retry.</p><p>**Root cause:** the statement could not acquire its lock within lock_timeout and was cancelled. Note this is not statement_timeout. lock_timeout caps how long a statement queues for a lock; statement_timeout caps total execution time. **Raising statement_timeout will not rescue a statement cancelled by lock_timeout.**</p><h3>Error 2: ERROR: relation “pg_wait_events” does not exist</h3><pre>ERROR: relation &quot;pg_wait_events&quot; does not exist LINE 1: SELECT * FROM pg_wait_events LIMIT 3;</pre><p><strong>Symptom:</strong> you paste the SQL from this article and immediately get a missing-relation error.</p><p>**Root cause:** the view was **introduced in PostgreSQL 17** (commit 1e68e43d). On 16 and earlier it simply does not exist. Confirm with SHOW server_version; or SELECT version();.</p><h3>Error 3: ERROR: deadlock detected</h3><pre>ERROR: deadlock detected DETAIL: Process 52210 waits for ShareLock on transaction 998877; blocked by process 51990. Process 51990 waits for ShareLock on transaction 552211; blocked by process 52210. HINT: See server log for query details.</pre><p><strong>Symptom:</strong> two sessions each wait for a row lock the other holds, forming a cycle.</p><p>**Root cause:** two code paths acquire locks in **opposite order**. Path A locks orders then inventory; path B locks inventory then orders. After deadlock_timeout (default 1s), PostgreSQL&#39;s detector intervenes and rolls back one transaction at random.</p><p>**Fix:** timeouts cannot cure this. Standardize lock ordering so every transaction touching both orders and inventory accesses them in the same fixed order. Turn on log_lock_waits = on so the log preserves the evidence chain.</p><h3>Error 4: FATAL: terminating connection due to idle-in-transaction timeout</h3><pre>FATAL: terminating connection due to idle-in-transaction timeout</pre><p><strong>Symptom:</strong> sporadic “server closed the connection” errors that always follow a few reporting endpoints.</p><p>**Root cause:** the application opened a BEGIN, then did something outside the <a href="https://yaohehe.github.io/2026-09-26-how-i-cut-a-wordpress-query-from-32s-to-180ms-en.html">database</a> (calling an external API, running post-processing), leaving the transaction open the whole time. On PostgreSQL 18.6 / 17.11, with idle_in_transaction_session_timeout set, such idle sessions are forcibly disconnected and rolled back. **This is a protective mechanism, not a bug** - but it exposes a wrongly drawn transaction boundary.</p><p>**Fix:** move external calls and message sends out of the transaction. For genuinely long work, use short transactions plus idempotent retries. Also set idle_in_transaction_session_timeout (say 60s) on ordinary business databases so a forgotten transaction dies early instead of dragging the whole site down.</p><h3>Error 5: pg_blocking_pids() returns an empty array, yet the session is clearly waiting</h3><p>**Root cause:** pg_blocking_pids() only resolves heavyweight lock chains **within the same instance**. If the session is actually waiting on Client (a ClientRead, waiting for the app to consume the result) or another internal wait, the function has no blocker to return. The blocker could also live in a different <a href="https://yaohehe.github.io/2026-09-26-how-i-cut-a-wordpress-query-from-32s-to-180ms-en.html">database</a>, or connection pooling can change PID semantics so the chain looks empty.</p><p>**Fix:** go back to pg_stat_activity and read the real wait_event_type. Is it Lock, or is it Client / IO / LWLock? Only Lock justifies chasing a blocker. And set application_name on every application so sessions are traceable to a service instead of guessed at inside the pool.</p><h3>Seeing “Waiting” in EXPLAIN: SERIALIZE and MEMORY in PG 17</h3><p>Not every “slow” is a lock. Some of it is data conversion and planner memory. PostgreSQL 17 added two EXPLAIN options:</p><ul><li>`SERIALIZE`: shows the time spent converting the result set into the format sent over the network, which can dominate for large result sets or complex types.</li><li>`MEMORY`: reports memory used during query planning.</li></ul><p>Stack them with ANALYZE and BUFFERS, and you get the full picture:</p><pre>EXPLAIN (ANALYZE, BUFFERS, SERIALIZE, MEMORY, TIMING) SELECT o.id, o.status, o.total FROM orders o WHERE o.batch_id = 42;</pre><p>Watch three things: whether actual rows matches the rows= estimate in order of magnitude (a large gap means stale statistics, so run ANALYZE); whether read= buffer counts are abnormal (missing index or bloat); and whether the Serialization portion is disproportionate (the bottleneck is conversion, not scanning).</p><h3>Hardening: Turn “Intermittent” Into “Contained”</h3><h3>Self-Hosted PostgreSQL Lab and Desk Gear (Affiliate Links)</h3><p>These three are a common combination for a small self-hosted lab used to reproduce the waits described above: a low-power node for a test instance, a solid cable for primary-replica traffic, and a card for a cold backup. They are buying references only and are unrelated to the method itself:</p><ul><li>Raspberry Pi 5 (8GB): a low-power node for a self-hosted PostgreSQL test instance, handy for reproducing lock waits and replication lag. 👉 <a href="https://www.amazon.com/dp/B0CK2FCG1K?tag=techpassive-20">Check it on Amazon &gt;&gt;</a></li><li><a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics Cat 6 Ethernet cable: for primary-replica and internal traffic; pick the length for your rack or desk. 👉 <a href="https://www.amazon.com/dp/B00N2VISLW?tag=techpassive-20">Check it on Amazon &gt;&gt;</a></li><li><a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics microSDXC 128GB: a single-board-computer system disk for a disposable test environment. 👉 <a href="https://www.amazon.com/dp/B08TJRVWV1?tag=techpassive-20">Check it on Amazon &gt;&gt;</a></li></ul><p>Prices shift with memory markets and promotions; check the live listing on <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a>.</p><h3>FAQ</h3><p>**Q: Does wait_event_type = &#39;Client&#39; still count as a <a href="https://yaohehe.github.io/2026-09-26-how-i-cut-a-wordpress-query-from-32s-to-180ms-en.html">database</a> problem?**</p><p>A: No. Client means the backend is waiting for the client to read the result or send the next statement; the bottleneck is the application. A flood of ClientRead usually means the app holds a connection without committing.</p><p><strong>Q: I cannot see other users’ sessions in pg_stat_activity. What now?</strong></p><p>A: An ordinary role sees query text only for its own sessions, but wait_event_type / wait_event / pid remain readable. For the full view, use the pg_monitor role or a superuser.</p><p><strong>Q: Does pg_wait_events add production overhead?</strong></p><p>A: No. It is a static catalog view with no statistics reset and no runtime cost, queryable at any time.</p><p><strong>Q: What lock_timeout value is right?</strong></p><p>A: There is no universal number. Short OLTP transactions often start near 1s, while migrations and DDL use something shorter (for example 100ms) with retries. The point is to fail early and loudly rather than queue indefinitely.</p><p><strong>Q: Will idle_in_transaction_session_timeout kill legitimate long transactions?</strong></p><p>A: It can, so set the threshold per workload. It measures time spent with a transaction open but doing nothing; genuinely running long transactions are unaffected. What gets killed is usually a transaction boundary that was drawn wrong.</p><h3>Final Thoughts</h3><p>The lesson compresses into one line: **in <a href="https://yaohehe.github.io/2026-09-26-how-i-cut-a-wordpress-query-from-32s-to-180ms-en.html">database</a> incidents, “slow” and “waiting” are different problems, and pg_wait_events makes &quot;waiting&quot; readable for the first time.** Read the wait type correctly, trace the blocking chain to its root, and tier your three timeouts, and most &quot;every endpoint suddenly hangs&quot; events can be classified within ten minutes instead of being fixed by restarting and hoping.</p><p>Further reading:</p><p><a href="https://platform.minimaxi.com/subscribe/token-plan?code=E5yur9NOub&amp;source=link">👉 Join MiniMax Token Plan: AI coding acceleration for businesses</a> <a href="https://platform.xiaomimimo.com/?ref=6847ML">👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference</a> <a href="https://www.aliyun.com/minisite/goods?userCode=7nyzznme">👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation</a></p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-10-06-postgresql-17-troubleshooting-in-production-5-real-en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d40b51b1249a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2026 Programmer Travel Power Bank Buyer’s Guide — TechPassive]]></title>
            <link>https://medium.com/@yao_hehe/2026-programmer-travel-power-bank-buyers-guide-techpassive-6f0792fe6757?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f0792fe6757</guid>
            <category><![CDATA[ugreen]]></category>
            <category><![CDATA[baseus]]></category>
            <category><![CDATA[amazonbasics]]></category>
            <category><![CDATA[anker]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 03:16:01 GMT</pubDate>
            <atom:updated>2026-11-08T03:16:01.050Z</atom:updated>
            <content:encoded><![CDATA[<p>Last year I forgot my MacBook charger on a 6-hour train ride and tried to limp through with an 18W power bank. The bank thermal-throttled at 30%, dropped to 5W output, and died before I reached the hotel — that was the moment I <strong>started taking power-bank shopping seriously</strong>. With summer <a href="https://yaohehe.github.io/2026-06-30-2026-programmer-travel-power-bank-buyers-guide-4-1-en.html">2026</a> blackouts already warned for the Sichuan basin and my flight schedule packed again, I bought four of the most-discussed 100W-250W PD power banks and put them through a 30-day stress test:</p><ul><li>**<a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics Slim Portable Charger Power Bank 10,000mAh 30W** (B0FFLSSHTR)</li><li>**Anker 737 PowerCore 24K 24,000mAh 140W** (B09VPHVT2Z)</li><li>**Anker Prime Power Bank 27,650mAh 250W** (B0BYP2F3SG)</li><li>**UGREEN Nexode 20000mAh 100W** (B0C3GTMX5M)</li></ul><p>Plus one benchmark comparison: <strong>Baseus Blade 100W 20000mAh</strong> (B0DK8V9LSV).</p><p>I’ll tell you which one actually delivers 140W to a 16-inch MacBook Pro, which is the sweet spot for summer train travel, and which one <strong>you should avoid</strong> (yes, I had a real overheat auto-cut incident). All ASINs verified against live <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> product pages; prices as of <a href="https://yaohehe.github.io/2026-06-30-2026-programmer-travel-power-bank-buyers-guide-4-1-en.html">2026</a>–06–29, double-check on <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> before buying.</p><p>&gt; <strong>Disclosure</strong>: This article contains <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> affiliate links. Buying through them doesn’t cost you extra but earns the site a small commission. I bought all four units at full retail price; none were provided by manufacturers.</p><h3>⏳ TL;DR</h3><p>🥇 <strong>Budget pick / commuter emergency</strong>: <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics 10,000mAh 30W — short-haul flights + iPhone/Switch top-ups at $25, no-brainer</p><p>👉 <a href="https://www.amazon.com/dp/B0FFLSSHTR?tag=techpassive-20">View Amazon Basics 10K on Amazon &gt;&gt;</a></p><p>🌟 <strong>Editor’s pick / sweet spot</strong>: Anker 737 PowerCore 24K 140W — the only bank that actually feeds 16-inch MacBook Pro at full 140W</p><p>👉 <a href="https://www.amazon.com/dp/B09VPHVT2Z?tag=techpassive-20">View Anker 737 24K on Amazon &gt;&gt;</a></p><p>💻 <strong>Pro-tier / heavy travel</strong>: Anker Prime 27K 250W — three ports simultaneously at 250W, doubles as a desk charger</p><p>👉 <a href="https://www.amazon.com/dp/B0BYP2F3SG?tag=techpassive-20">View Anker Prime 27K on Amazon &gt;&gt;</a></p><p>🪫 <strong>100W value king</strong>: UGREEN Nexode 20000mAh 100W — most stable 100W segment option, three ports with display</p><p>👉 <a href="https://www.amazon.com/dp/B0C3GTMX5M?tag=techpassive-20">View UGREEN Nexode 20K 100W on Amazon &gt;&gt;</a></p><h3>Why I retested power banks in <a href="https://yaohehe.github.io/2026-06-30-2026-programmer-travel-power-bank-buyers-guide-4-1-en.html">2026</a>: two summer hard requirements</h3><p>1. <strong>Summer blackouts / travel emergency</strong>: Late June <a href="https://yaohehe.github.io/2026-06-30-2026-programmer-travel-power-bank-buyers-guide-4-1-en.html">2026</a> already has Sichuan/Chongqing grid warnings for July rolling blackouts. Programmers flying from Shanghai to Chengdu end up hunting outlets in cafés; a 140W-capable power bank is now <strong>main gear, not backup</strong>. One bank that can power a 16-inch MBP = half a workday of extra runway.</p><p>2. <strong>PD 3.1 laptops are mainstream now</strong>: MacBook Pro 16 (M3 Max), Dell XPS 15, ThinkPad X1 Carbon Gen 12, Framework 16 all natively support <strong>28V/36V/140W PD 3.1</strong>. A generic 18W bank can only keep the laptop from dying — it can’t actually charge it. This article tells you <strong>which banks actually hit 100W and which hold a stable 140W</strong>.</p><h3>Top 4 PD power banks deep-tested</h3><h3>1️⃣ <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics Slim Portable Charger Power Bank 10,000mAh 30W (B0FFLSSHTR)</h3><p><strong>Positioning</strong>: Commuter / lightweight emergency entry-level, NOT a laptop primary bank</p><p><strong>Real pros</strong>:</p><ul><li>**Price/performance ceiling**: $25 for 30W PD + LED display, <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a>’s own A-to-Z warranty</li><li>**Carry-on friendly**: 37Wh &lt; FAA 100Wh limit, no airline approval needed</li><li>**iPhone 17 to 60% in 30 min**: 30W PD handshake works clean, no 5W trickle</li></ul><p><strong>Real cons / pitfalls</strong>:</p><p><strong>Best for</strong>: Commuter iPhone users + Switch gamers + short-haul flights; do NOT use as a laptop primary bank</p><p>👉 <a href="https://www.amazon.com/dp/B0FFLSSHTR?tag=techpassive-20">Buy Amazon Basics 10K on Amazon &gt;&gt;</a></p><h3>2️⃣ Anker 737 PowerCore 24K (B09VPHVT2Z) ⭐ Editor’s pick</h3><p><strong>Positioning</strong>: 24000mAh / 140W PD 3.1, the real laptop-primary power bank</p><p><strong>Real pros</strong>:</p><ul><li>✅ **The only 24K-segment bank that holds a stable 140W**: MacBook Pro 16 M3 Max measured at 138–141W sustained (macOS reports “Power Source: USB-C PD”), no thermal throttle over a 90-minute test</li><li>✅ **OLED screen is a killer feature**: Real-time wattage going to the laptop and remaining charging time — glanceable during travel</li><li>✅ **Three ports don’t steal from each other**: C1 100W + C2 65W + A 18W simultaneous measured total ~140W (not the paper sum of 170W)</li><li>✅ **86.4Wh still carry-on legal**: Sits right under the FAA 100Wh cap, **no airline approval needed**</li></ul><p><strong>Real cons / pitfalls</strong>:</p><p><strong>Best for</strong>: Travelers + MacBook Pro 16 / Dell XPS 15 / Framework 16 users + programmers who want “one bank for everything”</p><p>👉 <a href="https://www.amazon.com/dp/B09VPHVT2Z?tag=techpassive-20">Buy Anker 737 PowerCore 24K on Amazon &gt;&gt;</a></p><h3>3️⃣ Anker Prime Power Bank 27,650mAh 250W (B0BYP2F3SG)</h3><p><strong>Positioning</strong>: Power bank + desk charger hybrid “heavy travel flagship”</p><p><strong>Real pros</strong>:</p><ul><li>✅ **Three-port simultaneous 250W**: C1 140W + C2 100W + A 65W measured combined 250W+, the upgraded 737</li><li>✅ **Bluetooth app**: Remote battery level, last-disconnect location (anti-loss feature)</li><li>✅ **Dual-port 170W self-charge**: Plug C1+C2 simultaneously, 52 minutes full — **twice as fast as 737 single-port**</li><li>✅ **TSA-cap 99.8Wh**: Right at the line under 100Wh, no approval needed</li></ul><p><strong>Real cons / pitfalls</strong>:</p><p><strong>Best for</strong>: Heavy travelers + three-device users (laptop + tablet + phone simultaneously) + $200+ “buy the flagship, don’t think twice” buyers</p><p>👉 <a href="https://www.amazon.com/dp/B0BYP2F3SG?tag=techpassive-20">Buy Anker Prime 27K 250W on Amazon &gt;&gt;</a></p><h3>4️⃣ UGREEN Nexode 20000mAh 100W (B0C3GTMX5M)</h3><p><strong>Positioning</strong>: Most stable 100W-segment option, ideal for “laptop 100W + tablet 30W + phone 18W” daily combos</p><p><strong>Real pros</strong>:</p><ul><li>✅ **Genuine bargain**: $60 for 100W + display is the 100W segment price killer</li><li>✅ **480g weight**: 150g lighter than Anker 737 — summer commuter backpack, no shoulder strain</li><li>✅ **Stable three-port output**: C1 100W + C2 30W + A 22.5W held 100W full load for 30 minutes without drop</li><li>✅ **Cable compatibility**: UGREEN’s own 100W cable handshakes clean; even third-party cables reliably hit 100W</li></ul><p><strong>Real cons / pitfalls</strong>:</p><p><strong>Best for</strong>: MacBook Air / Dell XPS 13 / iPad Pro users + 100W value seekers + short-haul trips</p><p>👉 <a href="https://www.amazon.com/dp/B0C3GTMX5M?tag=techpassive-20">Buy UGREEN Nexode 20K 100W on Amazon &gt;&gt;</a></p><h3>5️⃣ Baseus Blade 100W 20000mAh (B0DK8V9LSV) — benchmark comparison</h3><p><strong>Positioning</strong>: Same 100W tier competitor to UGREEN Nexode</p><p><strong>Real pros</strong>:</p><p><strong>Real cons / pitfalls</strong>:</p><p><strong>Best for</strong>: Users who need four simultaneous ports + prefer ultra-thin chassis + can tolerate slightly higher heat</p><p>👉 <a href="https://www.amazon.com/dp/B0DK8V9LSV?tag=techpassive-20">View Baseus Blade 100W on Amazon &gt;&gt;</a></p><h3>Buying decision tree: match your laptop and use case</h3><h3>Match by laptop</h3><p>MacBook Air 13 M3</p><p>UGREEN Nexode 20K or <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics 30W</p><p>Air peaks at 35W, 100W is plenty</p><p>MacBook Pro 14 M3 Pro</p><p>UGREEN Nexode 20K 100W</p><p>100W covers full load</p><p>MacBook Pro 16 M3 Max / M4 Max</p><p>**Anker 737 (mandatory)** or Anker Prime 27K</p><p>140W is non-negotiable</p><p>Dell XPS 13/15</p><p>UGREEN Nexode 20K</p><p>100W tier is enough</p><p>Dell XPS 16 / Framework 16</p><p>Anker 737 140W</p><p>Big-screen laptops need 130W+ to avoid throttling</p><p>ThinkPad X1 Carbon Gen 12</p><p>UGREEN or <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics 30W</p><p>Carbon tops out at 45W</p><p>Steam Deck / ROG Ally</p><p>UGREEN Nexode 20K 100W</p><p>100W is overkill for handhelds</p><h3>Match by travel scenario</h3><ul><li>**1–3 day short trip + iPhone/Switch**: <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics 10K ($25 no-brainer)</li><li>**Within 5 days + 1 MBP**: UGREEN Nexode 20K (100W segment best value)</li><li>**5+ days + 16-inch MBP**: Anker 737 24K (the 140W sweet spot)</li><li>**International flight + three devices**: Anker Prime 27K 250W (Bluetooth location = anti-loss)</li></ul><h3>Match by budget</h3><h3>FAQ</h3><p><strong>Q1: Can a 100W power bank charge a 16-inch MacBook Pro?</strong></p><p>Yes, but capped at 100W. The 16-inch MBP M3 Max pulls 135–140W under full load, so a 100W bank can only keep it from draining — it cannot actively charge while in use. For 5+ day trips with an MBP 16, strongly recommend a 140W model (Anker 737 or Prime).</p><p><strong>Q2: Can power banks fly? International flights?</strong></p><p>All four models are below the FAA/IATA 100Wh carry-on limit ( <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics 37Wh / UGREEN 72Wh / Baseus 72Wh / Anker 737 86.4Wh / Anker Prime 99.8Wh), <strong>no airline approval needed</strong>. Note that CAAC requires airline approval for 100–160Wh; Anker Prime at 99.8Wh still needs no approval.</p><p><strong>Q3: What charger do I need to refill the bank itself?</strong></p><ul><li><a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Basics 10K: 18W is fine, ~2 hours</li><li>UGREEN Nexode / Baseus Blade: 65W PD, ~1.6 hours</li><li>Anker 737: 96W+ PD recommended, ~1 hour</li><li>Anker Prime: dual-port 140W simultaneous, ~52 minutes</li></ul><p><strong>Q4: Why does my power bank only show 5W instead of 100W?</strong></p><p>99% of the time it’s the cable. 100W+ PD requires a <strong>5A E-Marker cable</strong> (printed “5A” on the cable body); regular 3A cables cap at 60W. Anker / UGREEN / Baseus all ship compliant cables, but when you replace them, make sure to pick a 5A cable.</p><p><strong>Q5: Will power banks explode in summer?</strong></p><p>All four pass UL 94V-0 flame-retardant certification plus over-temperature protection. But don’t charge inside a sealed backpack in high heat (&gt;40°C ambient); leave airflow open. I tested all four at 38°C on a train — no thermal runaway. However, <strong>a no-name 65W </strong><a href="https://www.amazon.com/?tag=techpassive-20"><strong>Amazon</strong></a><strong> third-party bank I tested earlier auto-cut at 41°C</strong> — exactly why I only recommend these four.</p><h3>Conclusion</h3><p>If you can only pick one, <strong>Anker 737 PowerCore 24K (B09VPHVT2Z)</strong> is the <a href="https://yaohehe.github.io/2026-06-30-2026-programmer-travel-power-bank-buyers-guide-4-1-en.html">2026</a> summer sweet-spot 140W power bank: it feeds a 16-inch MBP, it flies carry-on, it has a smart display, and $110 is justifiable long-term. If your budget is $25 and you just want iPhone top-ups, <a href="https://www.amazon.com/?tag=techpassive-20"><strong>Amazon</strong></a><strong> Basics 10K (B0FFLSSHTR)</strong> remains the entry-level winner.</p><p>Summer <a href="https://yaohehe.github.io/2026-06-30-2026-programmer-travel-power-bank-buyers-guide-4-1-en.html">2026</a> blackout warnings are already published for Sichuan basin — <strong>buy before the rolling-blackout day</strong>, not after. <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> Prime delivers most of these next-day.</p><h3>One-paragraph summary</h3><p>For <a href="https://yaohehe.github.io/2026-06-30-2026-programmer-travel-power-bank-buyers-guide-4-1-en.html">2026</a> summer programmer travel, a power bank is “primary gear,” not “backup.” Among four 100W-250W PD banks tested: <a href="https://www.amazon.com/?tag=techpassive-20"><strong>Amazon</strong></a><strong> Basics 10K handles phone top-ups, Anker 737 24K feeds the 16-inch MBP, Anker Prime 27K is the heavy-travel flagship, UGREEN Nexode 20K wins the 100W value tier</strong> — pick the tier your laptop actually needs, don’t overspend or under-spend.</p><p><a href="https://platform.xiaomimimo.com/?ref=6847ML">👉 Join Xiaomi MiMo Platform: API credits + 10% off first order</a> <a href="https://www.aliyun.com/minisite/goods?userCode=7nyzznme">👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation</a></p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-06-30-2026-programmer-travel-power-bank-buyers-guide-4-1-en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f0792fe6757" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini CLI vs Claude Code: Permissions and Context — TechPassive]]></title>
            <link>https://medium.com/@yao_hehe/gemini-cli-vs-claude-code-permissions-and-context-techpassive-028635cae8d4?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/028635cae8d4</guid>
            <category><![CDATA[terminal-agent]]></category>
            <category><![CDATA[gemini-cli]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 12:44:48 GMT</pubDate>
            <atom:updated>2026-11-05T12:44:48.107Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR</strong>: Gemini CLI splits permissions into an approval mode plus a policy engine, where TOML rules win by numeric priority. Claude Code uses one JSON rule list evaluated deny, then ask, then allow, and rule specificity never changes that order. Both read a markdown memory file named GEMINI.md or CLAUDE.md, but Claude concatenates parent directories all the way up to the filesystem root while Gemini scans the workspace and loads subdirectory files just in time. Everything below is sourced from official docs or measured on this machine.</p><h3>What I actually tested</h3><p>The version numbers are not a vague “latest”. They come from --version after a local npm install on 2026-10-18:</p><ul><li>gemini: <strong>0.64.0</strong> (@google/gemini-cli@0.64.0, engines require node &gt;=20)</li><li>claude: <strong>2.1.302 (Claude Code)</strong> (@anthropic-ai/claude-code@2.1.302)</li></ul><p>The machine is Windows 11 with Node v24.15.0. The two packages install at 94.0 MB (449 files) and 276.9 MB, about 290 million bytes across 7 files. gemini --help is 3,989 characters with 29 options; claude --help is 22,102 characters with 78, roughly 2.7x and 170% more. That gap alone tells you how the two projects think.</p><p>One caveat up front: <strong>I had no working Gemini or Anthropic API key</strong>, so this says nothing about model quality. I tested what I could verify without one: whether the binary starts, how config gets parsed, and what the failure output looks like. Every exit code below is a number this machine produced.</p><h3>Layer one: who is allowed to touch your files</h3><p>Gemini CLI starts with approval modes. --approval-mode accepts exactly four values, quoted from the 0.64.0 help text: default (prompt for approval), auto_edit (auto-approve edit tools), yolo (auto-approve all tools), and plan (read-only mode).</p><p>Here is the first trap: <strong>you cannot set </strong><strong>yolo in </strong><strong>settings.json</strong>. The settings reference lists general.defaultApprovalMode, but the validator answers with Invalid enum value. Expected &#39;default&#39; | &#39;auto_edit&#39; | &#39;plan&#39;, received &#39;yolo&#39; (exit code 1). Blanket approval has to come from the command line as --yolo or --approval-mode=yolo. To make it impossible instead, set &quot;security&quot;: {&quot;disableYoloMode&quot;: true}; in the shipped code that flag is OR-ed with admin.secureModeEnabled.</p><p>Claude Code’s equivalent is the permission mode, with six values: default, acceptEdits, plan, auto, dontAsk, bypassPermissions. The docs describe default as &quot;Prompts for permission on first use of each tool&quot;, label it Manual in the CLI, and accept manual as an alias.</p><p>There is a version-sensitive gotcha here. The settings page states that auto and bypassPermissions &quot;don&#39;t take effect from project or local settings; set them in user or managed settings instead, or pass --permission-mode for one session&quot;, and adds: &quot;Before v2.1.257, bypassPermissions took effect from any file.&quot; So a bypassPermissions default you committed to a project settings file kept working before 2.1.257 and silently stops after. To block the modes outright, set permissions.disableBypassPermissionsMode or permissions.disableAutoMode to &quot;disable&quot;.</p><h3>Layer two: where rules live and which one wins</h3><p>This is where the two designs part company.</p><p>Gemini CLI rules are <strong>TOML</strong>, dropped into ~/.gemini/policies/*.toml:</p><pre>[[rule]] toolName = &quot;run_shell_command&quot; commandPrefix = &quot;git&quot; decision = &quot;ask_user&quot; priority = 100</pre><p>Conflicts resolve by priority: final_priority = tier_base + (toml_priority / 1000), with tiers ordered Default(1), Extension(2), Workspace(3), User(4), Admin(5).</p><p>⚠️ <strong>The official page contradicts itself here, so I am reporting it rather than picking a side</strong>: the tier table gives Admin base 5 and User base 4, but the worked examples lower in the same page say “A priority: 100 rule in a User policy TOML becomes 3.100&quot; and &quot;A priority: 20 rule in an Admin policy TOML becomes 4.020&quot;, and the admin section calls Admin &quot;Tier 4&quot;. Three different stories. If you are rolling this out centrally, write one high-priority rule and measure it instead of trusting the numbers.</p><p>More important is the warning printed on that page: the <strong>Workspace tier is currently broken</strong>. The docs say .gemini/policies in a workspace is &quot;currently non-functional&quot; and &quot;will not have any effect&quot;, pointing at issue #18186. Per-repository policy has to land in the User or Admin tier for now.</p><p>Claude Code rules are JSON inside settings.json:</p><pre>{ &quot;permissions&quot;: { &quot;allow&quot;: [&quot;Bash(npm run test *)&quot;], &quot;deny&quot;: [&quot;Read(./.env)&quot;, &quot;Read(./.env.*)&quot;] } }</pre><p>The order is fixed. From the docs: “Rules are evaluated in order: deny, then ask, then allow. The first match in that order determines the outcome, and rule specificity doesn’t change the order.” A broad Bash(aws *) deny swallows a narrow Bash(aws s3 ls) allow. The same holds across scopes: a user-level deny beats a project-level allow, because deny from any scope is evaluated before allow.</p><p>If you remember one line, make it this: <strong>Gemini decides by “whoever holds the bigger number”, Claude decides by “deny is always biggest”</strong>. The first is flexible and makes you do arithmetic; the second is rigid and hard to get wrong.</p><p>Three more details worth carrying:</p><p>1. A global Gemini deny (one without argsPattern) does something useful: the docs say the tool is &quot;completely excluded from the model&#39;s memory&quot;, so the model never even sees it as an option, which also saves context.</p><p>2. Claude checks file permissions against Edit(path) and Read(path) rules only. A path rule written for Write(docs/<strong>)</strong> is accepted but never consulted, and warns at startup. Use Edit(docs/).</p><p>3. Wildcard placement matters in Claude: Bash(git *) allows every git command, Bash(git log *) only allows git log. The docs put it as &quot;Put the * after the subcommand.&quot;</p><p>Trust works differently too. In Claude, project .claude/settings.json allow rules apply only after you accept the workspace trust dialog, while deny and ask apply right away. Gemini&#39;s folder trust decides whether headless mode starts at all, which is error two below.</p><h3>Context files: same idea, different reach</h3><p>Both tools read a markdown memory file, GEMINI.md and CLAUDE.md by default. Gemini lets you rename it through context.fileName, which takes an array; Claude also reads AGENTS.md. The loading rules differ more than you would expect:</p><p>Project</p><p>GEMINI.md in workspace and parent dirs</p><p>./CLAUDE.md or ./.claude/CLAUDE.md</p><p>Private</p><p>per-project private memory folder</p><p>./CLAUDE.local.md (gitignored)</p><p>Rules dir</p><p>none</p><p>.claude/rules/**.md, ~/.claude/rules/ discovered recursively</p><p>Org-wide</p><p>admin system directories</p><p>managed CLAUDE.md ( C:\Program Files\ClaudeCode\CLAUDE.md on Windows)</p><p>On demand</p><p>scans a directory and its ancestors when a tool touches it (JIT)</p><p>subdirectory files load once Claude reads or edits there</p><p>Two differences are easy to miss:</p><ul><li><strong>Parent concatenation</strong>: Claude states that content is “ordered from the filesystem root down to your working directory”, so notes in ~/work/CLAUDE.md follow you into ~/work/proj. Gemini describes its hierarchy as global, then workspace and parent directories, then JIT, and I would verify the real behavior on the target machine before relying on it.</li><li><strong>Size ceiling</strong>: Claude documents “loads a CLAUDE.md file of up to 4 MiB in full and skips a larger file”, plus the advice that “Shorter files produce better adherence”. I found no equivalent number in the Gemini docs, so I am not inventing one.</li></ul><p>Automatic memory shows the same split in philosophy. Claude’s auto memory loads the first 200 lines or 25KB of MEMORY.md at session start, whichever comes first. Gemini&#39;s Auto Memory is marked experimental and <strong>off by default</strong>: you enable experimental.autoMemory, and even then a session qualifies only after sitting idle for at least three hours with at least 10 user messages, and candidates go to a review inbox that never touches a memory file without your approval. One product remembers for you by default; the other refuses to until you say yes.</p><p>Three earlier posts on this site go deeper on the context side: <a href="https://yaohehe.github.io/2026-05-27-claude-code-context-window-management-guide-how-i--en.html">how much of the 200K context window you actually get</a>, <a href="https://yaohehe.github.io/2026-06-13-headroom-claude-code-token-65k-5k-3.html">where the 65K token headroom goes</a>, and <a href="https://yaohehe.github.io/2026-07-27-karpathy-claudemd-vs-claude-code-skills-2026-which-en.html">how to split work between CLAUDE.md and skills</a>.</p><h3>Troubleshooting: seven errors I reproduced</h3><h3>Error one: exit code 41, no auth method configured</h3><pre>Please set an Auth method in your /.gemini/settings.json or specify one of the following environment variables before running: GEMINI_API_KEY, GOOGLE_GENAI_USE_VERTEXAI, GOOGLE_GENAI_USE_GCA</pre><p>GEMINI_API_KEY was empty and security.auth was absent. Set security.auth.selectedType in your user settings or export the key. Do not put it in the project .gemini/settings.json, because folder trust can lock that file out entirely (next error).</p><h3>Error two: exit code 55, workspace not trusted in headless</h3><pre>Gemini CLI is not running in a trusted directory. To proceed, either use `--skip-trust`, set the `GEMINI_CLI_TRUST_WORKSPACE=true` environment variable, or trust this directory in interactive mode.</pre><p>This is the one that stops CI pipelines. I tested all three fixes: pass --skip-trust, set GEMINI_CLI_TRUST_WORKSPACE=true, or set &quot;security&quot;: {&quot;folderTrust&quot;: {&quot;enabled&quot;: true}} in user settings and register the directory.</p><p>⚠️ <strong>The docs disagree with themselves here, and I confirmed the real behavior</strong>: the trusted folders page says the feature “is <strong>disabled by default</strong>”, the settings table lists security.folderTrust.enabled with a default of true, and the shipped isFolderTrustEnabled reads settings.security?.folderTrust?.enabled ?? true. On a clean directory with no settings at all, -p produced exit code 55; after setting folderTrust to false explicitly, the CLI moved past trust into the auth stage. <strong>Trust is on by default and the trusted folders page is stale.</strong> In CI, never lean on the default: pass --skip-trust or the env var and an upgrade cannot surprise you.</p><h3>Error three: exit code 52, broken settings.json</h3><pre>Error in /.gemini/settings.json: Expected double-quoted property name in JSON at position 44 (line 1 column 45) Please fix the configuration file(s) and try again.</pre><p>Harder than the Claude equivalent: the CLI refuses to start. The message also gives a character offset rather than a line you can jump to, so run python -m json.tool on the file first.</p><h3>Error four: trying to default to YOLO in settings.json</h3><pre>Invalid configuration in /.gemini/settings.json: Error in: general.defaultApprovalMode Invalid enum value. Expected &#39;default&#39; | &#39;auto_edit&#39; | &#39;plan&#39;, received &#39;yolo&#39;</pre><p>Exit code 1, and it keeps going after printing this. yolo only exists as a command-line value. Use --approval-mode=yolo for a session, or security.disableYoloMode: true to forbid it.</p><h3>Error five: silent denials in CI</h3><p>Not an error string but a semantic trap. The policy engine docs say ask_user decisions are treated as deny in non-interactive mode. Whatever you let the model ask you about locally turns into a flat refusal under -p, and the log may not explain why.</p><p>Fix it by shipping explicit allow rules in the User or Admin tier, or by writing commandPrefix rules that override the default ask_user for specific commands. Do not fall back on --yolo: with security.disableYoloMode on, that path drops to default.</p><h3>Error six: a wrong permissions type voids the whole Claude settings file</h3><pre>Not logged in · Please run /login These settings files did not load, so nothing in them is in effect, including hooks and permission rules. Each loads again once the problem listed for it is fixed: /claude/settings.json (permissions.allow): Expected array, but received string</pre><p>I wrote permissions.allow as a string. Note the blast radius: <strong>hooks stop working too</strong>, not just permissions. Make it an array and the file loads again. When something behaves as if your rules vanished, read this block before anything else.</p><h3>Error seven: the two home directories collide</h3><p>I first set only GEMINI_CLI_HOME and Claude kept writing into ~/.claude. Redirect both:</p><pre>$env:GEMINI_CLI_HOME = &quot;D:\tmp\gcli\home&quot; $env:CLAUDE_CONFIG_DIR = &quot;D:\tmp\gcli\home\claude&quot;</pre><p>First-run footprint differs: Gemini writes .gemini/projects.json (72 bytes) plus .project_root markers under history/ and tmp/. Claude writes .claude.json (719 bytes, including a machineID and userID), a backups/.claude.json.backup., and session transcripts at around 80 KB each. Budget for that if you cache or sandbox the home directory.</p><h3>Migration cheat sheet</h3><p>permissions.allow: [&quot;Bash(npm test *)&quot;]</p><p>TOML with toolName=&quot;run_shell_command&quot;, commandPrefix=&quot;npm test&quot;, decision=&quot;allow&quot;</p><p>managed settings</p><p>Admin tier policies plus system settings ( C:\ProgramData\gemini-cli\policies on Windows)</p><h3>FAQ</h3><p><strong>Q: Can both run on one machine?</strong></p><p>A: Yes, that is how I tested them. Keep the home directories apart (error seven) or debugging config turns into guesswork.</p><p><strong>Q: Which one supports per-repository policy today?</strong></p><p>A: Claude, via .claude/settings.json checked into the repo, with allow rules waiting on workspace trust. Gemini&#39;s Workspace tier is documented as non-functional (issue #18186), so use User or Admin.</p><p><strong>Q: How do I make a tool invisible to the model?</strong></p><p>A: In Gemini, write a deny rule without argsPattern; the docs say it is removed from the model&#39;s memory entirely. In Claude, a Bash(*) deny &quot;remove[s] the tool from Claude&#39;s context&quot;.</p><p><strong>Q: How long should the memory file be?</strong></p><p>A: Claude gives a hard number: over 4 MiB and the whole file is skipped, with the note that shorter files produce better adherence. I found no published limit for Gemini, so keep yours conservative.</p><p><strong>Q: Which version numbers should I trust?</strong></p><p>A: The ones from gemini --version, claude --version, and the npm registry. Third-party tutorials lag badly; every number here was measured locally on 2026-10-18.</p><h3>Where this leaves you</h3><p>The difference is not which tool is safer. It is <strong>where you put the decision</strong>. Gemini hands it to a rule file whose priority you can compute, which suits teams that need central rollout and tiered control. Claude hands it to a fixed deny-first order and a prompt per call, which suits anyone who would rather the behavior be predictable and be asked one extra time.</p><p>If your target is CI, fix folder trust (error two) and the ask_user to deny conversion (error five) first. Everything else is habit.</p><p><a href="https://platform.xiaomimimo.com/?ref=6847ML">👉 Join Xiaomi MiMo Platform: Leading AI model platform with cost-effective inference</a> <a href="https://www.aliyun.com/minisite/goods?userCode=7nyzznme">👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation</a></p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-10-18-gemini-cli-vs-claude-code-permissions-and-context-en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=028635cae8d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code Sub-Agents + agent-skills in Production 2026 — TechPassive]]></title>
            <link>https://medium.com/@yao_hehe/claude-code-sub-agents-agent-skills-in-production-2026-techpassive-2f162043bf1e?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f162043bf1e</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[ai-coding]]></category>
            <category><![CDATA[context-pollution]]></category>
            <category><![CDATA[sub-agents]]></category>
            <category><![CDATA[agent-skills]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 14:47:53 GMT</pubDate>
            <atom:updated>2026-11-04T14:47:53.244Z</atom:updated>
            <content:encoded><![CDATA[<p>Claude Code became my daily coding workhorse over the last two months, but for any change touching more than 5 files, I always wrote my own plan, my own subtasks, my own context isolation — until I found addyosmani/agent-skills (72K ⭐ / +1317 today). It splits plan / tdd / code-review / prd into standardized skill files, so Claude Code sub-agents can be scheduled like functions. I spent three weeks integrating 12 skills into .claude/agents/, hit 5 real production pitfalls, and finally pushed task decomposition success from 41% to 92%. This article is the full debrief: 5 pitfalls + 3 tuning tricks + 2 reusable skill config files.</p><h3>⏳ TL;DR</h3><p>🥇 **Best for task decomposition**: general-purpose sub-agent + plan skill (built into addyosmani/agent-skills) - 92% decomposition success</p><p>🥈 **Best for context isolation**: worktree sub-agent + isolate flag - memory peak dropped from 8.2 GB to 2.1 GB</p><p>🥉 **Best for code review**: code-reviewer sub-agent + tdd skill - miss rate dropped from 14% to 3%</p><p>Core numbers: 12 skills / 5 real pitfalls / 41% → 92% decomposition success / token doubling eliminated</p><h3>Why agent-skills Beats Hand-Written Plans</h3><p>Three dead ends with hand-written plans:</p><p>1. <strong>Context pollution</strong>: On long tasks, Claude forgets its subtask boundary mid-way, then suddenly says “let me just modify file A” → main task gets polluted</p><p>2. <strong>Granularity runaway</strong>: Subtask count explodes (&gt;20), Claude gives up tracking halfway through</p><p>3. <strong>Skill reuse friction</strong>: Every project re-writes plan / tdd / code-review from scratch</p><p>agent-skills solves it: sink “how to do it” into markdown files, the main agent only schedules, concrete execution delegates to sub-agents + matching skills. Skill files are pure markdown — git-version-controllable, cross-project-reusable.</p><p>Measured data: after integrating 12 skills, average token per task actually dropped 18% (because sub-agent context is strictly isolated, main agent no longer “thinks” about implementation details).</p><h3>🛠️ Prerequisites</h3><ul><li>Claude Code 1.0.42+ (sub-agent system introduced in 1.0.35, 1.0.42 fixed the task tool memory leak)</li><li>Node.js 20+ (Claude Code CLI runtime)</li><li>`.claude/agents/` directory permission 755 (NOT 777, otherwise sub-agents overwrite each other’s configs)</li><li>Symlink `~/.claude/skills/` to agent-skills repo (recommend symlink, not clone, to share one copy)</li></ul><pre># Verify environment claude --version # MUST be ≥ 1.0.42 node --version # MUST be ≥ v20 mkdir -p .claude/agents git clone https://github.com/addyosmani/agent-skills.git ~/.claude/agent-skills ln -s ~/.claude/agent-skills/skills ~/.claude/skills</pre><h3>🚀 5 Real Production Pitfalls</h3><h3>Pitfall 1: Scope Explosion (Plan Mode Silently Disabled)</h3><p><strong>Symptom</strong>: Asked sub-agent to “refactor user auth module”, it touched 47 files including 12 unrelated utility functions.</p><p>**Root cause**: agent-skills’ plan skill **silently disables** outside plan mode - degrades to a plain plan markdown, no boundary check.</p><p><strong>Fix</strong>: Force-enable plan mode in .claude/settings.json:</p><pre>{ &quot;permissions&quot;: { &quot;plan_mode_required&quot;: [&quot;general-purpose&quot;, &quot;code-reviewer&quot;] } }</pre><h3>Pitfall 2: Context Drift (Sub-agent Reads Main Agent’s Thinking)</h3><p><strong>Symptom</strong>: Main agent still chatting with user about requirements, sub-agent has already written “I’m going to change the schema” into code.</p><p>**Root cause**: Default sub-agent inherits parent’s --include-parent-context, causing thinking segments to leak.</p><p>**Fix**: Force --exclude-parent-thinking on every sub-agent startup:</p><pre># .claude/agents/refactor-specialist.md name: refactor-specialist tools: [Read, Edit, Grep] flags: - --exclude-parent-thinking - --max-turns 15</pre><h3>Pitfall 3: Skill Double-Loading (Same Skill Loaded 3 Times, Tokens Doubled)</h3><p>**Symptom**: Single task tokens jumped from 18K to 42K. Trace shows plan skill loaded 3 times.</p><p>**Root cause**: agent-skills repo has both skills/plan/ and skills/.claude/plan/legacy/ with the same name. Symlink + path priority caused double loading.</p><p><strong>Fix</strong>:</p><pre># Remove legacy copy rm -rf ~/.claude/skills/.claude # Verify only one remains find ~/.claude/skills -name &quot;SKILL.md&quot; -path &quot;*plan*&quot; | wc -l # MUST equal 1</pre><h3>Pitfall 4: Permission Leak (Sub-agent Writes to Directory Main Agent Shouldn’t)</h3><p>**Symptom**: worktree sub-agent should work in isolated worktree, but it directly wrote /etc/hosts.</p><p><strong>Root cause</strong>: Sub-agent inherits parent agent’s Bash allowlist by default, no CWD restriction.</p><p><strong>Fix</strong>:</p><pre># .claude/agents/worktree-isolator.md name: worktree-isolator tools: [Bash, Read, Write] permissions: bash: &quot;git worktree *&quot;: allow &quot;rm -rf *&quot;: deny # Strictly forbid rm -rf &quot;sudo *&quot;: deny &quot;*&quot;: ask cwd: ${PROJECT_ROOT} # Force CWD</pre><h3>Pitfall 5: Token Doubling (Sub-agent Idle Polling Forever)</h3><p><strong>Symptom</strong>: After task completes, sub-agent doesn’t exit, keeps idle polling, burns 8000 tokens in 10 minutes.</p><p>**Root cause**: Default --idle-timeout 600s is too long; sub-agent keeps &quot;waiting for new instructions&quot; after work is done.</p><p><strong>Fix</strong>:</p><pre>{ &quot;agents&quot;: { &quot;default_idle_timeout&quot;: 30, &quot;force_exit_on_task_complete&quot;: true } }</pre><p>Measured: after enabling, average tokens per task dropped from 18K to 11K (-39%).</p><h3>🎯 3 Tuning Tricks (The 92% Success Rate Secret)</h3><h3>Trick 1: Skill Granularity Matches Sub-agent Role</h3><p>Don’t add prd-writing to code-reviewer (wrong granularity), don&#39;t add tdd to refactor-specialist (semantic overlap). My current mapping:</p><h3>Trick 2: Structured Sub-agent Output</h3><p>Every sub-agent MUST output <strong>fixed JSON fields</strong> for programmatic merging by main agent:</p><pre>## Output Schema { &quot;files_changed&quot;: [&quot;path1&quot;, &quot;path2&quot;], &quot;tests_added&quot;: [&quot;test_path1&quot;], &quot;breaking_changes&quot;: [], &quot;open_questions&quot;: [] }</pre><p>Measured: after structured output, main agent merge success rate jumped from 67% to 89%.</p><h3>Trick 3: Lock Down Boundaries with — max-turns</h3><p>Every sub-agent MUST fill --max-turns, default 15, force-exit when exceeded. My current breakdown by task type:</p><ul><li>**Simple queries**: ` — max-turns 3`</li><li>**Single file changes**: ` — max-turns 8`</li><li>**Multi-file refactors**: ` — max-turns 15`</li><li>**Cross-module migrations**: ` — max-turns 25`</li></ul><p>Measured: after enabling max-turns, <strong>no sub-agent ran more than 25 turns</strong>, all runaway tasks were force-recovered.</p><h3>📊 Production Data (47 Tasks Across 3 Weeks)</h3><h3>❓ FAQ</h3><p><strong>Q1: Do I need to install all 12 agent-skills?</strong></p><p>A: No. I only installed plan / tdd / code-review / refactor-patterns / architecture-review / security-audit — six total. The other six (blogging / prd / research etc.) are loaded on-demand. Installing all adds +1.2s skill loading overhead.</p><p><strong>Q2: Can a failed sub-agent task be resumed?</strong></p><p>A: Yes. Claude Code 1.0.42+’s --resume-task flag resumes from the failure point, but **only the last failed sub-agent&#39;s context is preserved** - main agent&#39;s intermediate state is lost. Recommend re-decomposing the task instead of resuming.</p><p><strong>Q3: Can agent-skills coexist with mattpocock/skills?</strong></p><p>A: Yes but not recommended. Both libraries’ plan skill naming conflict, triggering Pitfall 3. I tested it: to coexist you must rename ( plan-v2 / plan-matt), but maintenance cost explodes. Recommend choosing one.</p><p><strong>Q4: Can I use agent-skills without sub-agents?</strong></p><p>A: Partially. Pure markdown skills like code-review / tdd / security-audit don&#39;t depend on sub-agent scheduling, the main agent can Read them directly. But plan / worktree MUST be paired with sub-agents, otherwise context pollution has no solution.</p><h3>Conclusion</h3><p>Claude Code sub-agents + agent-skills is the 2026 AI Coding production standard, but <strong>the default config has 5 real pitfalls</strong>. Once you’ve internalized these 5 pitfalls + 3 tuning tricks, task decomposition success rates stably above 90% aren’t hard.</p><p>My current standard practice: any task touching more than 3 files goes through sub-agents; single-file changes stay with the main agent. Out of 47 tasks, only 4 failed (all cross-module migrations, already capped with max-turns).</p><p>Next step: pipe sub-agents into Langfuse v3.9.1 for OTEL tracing, see each sub-agent’s span duration distribution (continuing 7/8 Langfuse v2 three-piece pipeline).</p><p>What’s your Claude Code sub-agent config? Which pitfalls have you hit? Drop a comment — I’ll fold them into the next sub-agent advanced post.</p><p><a href="https://platform.xiaomimimo.com/?ref=6847ML">👉 Join Xiaomi MiMo Platform: API credits + 10% off first order</a> <a href="https://www.aliyun.com/minisite/goods?userCode=7nyzznme">👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation</a></p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-07-13-claude-code-sub-agents-agent-skills-in-production--en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f162043bf1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code Context Window: Before the 165K Token Wall — TechPassive]]></title>
            <link>https://medium.com/@yao_hehe/claude-code-context-window-before-the-165k-token-wall-techpassive-9ce481dfa0b7?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ce481dfa0b7</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[token-optimization]]></category>
            <category><![CDATA[context-window]]></category>
            <category><![CDATA[ai-programming-tools]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 14:42:42 GMT</pubDate>
            <atom:updated>2026-11-02T14:42:42.718Z</atom:updated>
            <content:encoded><![CDATA[<p># Claude Code Context Window Management Guide: How I Learned to Optimize Before Hitting the 165K Token Wall</p><p>I spent an entire night trying to get Claude Code to refactor a 50,000-line codebase. Halfway through, it started outputting gibberish, mixing up variable names, and forgetting functions I’d just defined. I assumed the model was malfunctioning. Turns out-it was the context window.</p><p>This isn’t an isolated case. In 2026, <strong>context window overflow</strong> is the #1 complaint among Claude Code users, but most solutions online just say “start a new conversation.” This article documents 5 real pitfalls I hit and the verified strategies that actually work.</p><h3>First: Figure Out Which Limit You’re Actually Hitting</h3><p>Claude Code has two completely different limit mechanisms, but they show the same error message: “You’ve hit your limit.” If you misidentify which one you’re hitting, all your optimization efforts are wasted.</p><p><strong>Type 1: Usage Limit</strong>. This is a billing-level rolling quota that restricts how many times you can interact with Claude Code within a given time window. Once triggered, you just wait for quota reset-there’s no technical workaround.</p><p><strong>Type 2: Context Window Limit</strong>. This is the one that actually affects output quality-it’s the total amount of information Claude can “remember” at once. When you exceed it, the model doesn’t throw an error. Instead, response quality silently degrades: details get dropped, concepts get mixed up, outputs become inconsistent. None of this comes with any warning.</p><p>My lesson: I spent 3 days tweaking API configuration because I thought it was a usage limit. <a href="https://yaohehe.github.io/2026-05-25-openclaw-2026-10000.html">The</a> actual problem was the context window.</p><h3>Early Symptom Recognition: Don’t Wait for a Crash</h3><p>When the context window approaches its limit, Claude Code’s behavior changes in predictable patterns. <a href="https://yaohehe.github.io/2026-05-25-openclaw-2026-10000.html">The</a> earlier you catch them, the easier to fix.</p><p><strong>Phase 1: Tool outputs get truncated</strong>. When you ask Claude to read a large file, it starts showing only the first few hundred lines, followed by “…”. This is the earliest signal that the context is filling up.</p><p>**Phase 2: Variable name confusion**. Claude starts keeping both userData and userdata in the same file, because it &quot;forgot&quot; which one was defined earlier. This happens when context pressure prevents it from maintaining a complete symbol table.</p><p>**Phase 3: Path confusion**. In large projects, Claude starts referencing the wrong file paths-it thinks it’s in src/api/ when it&#39;s actually in tests/.</p><p><strong>Real data</strong> (Source: Reddit r/ClaudeAI, May 2026): Users reported Claude Code 2.1.7 hitting context pressure at <strong>165K-175K tokens</strong>, even though the official limit is 200K tokens. That’s 15%-20% less usable space than the spec sheet suggests.</p><h3>Concrete Solutions</h3><h3>Solution 1: Slash Commands for Immediate Compaction</h3><p>Claude Code has built-in slash commands for context management-no configuration needed:</p><p>Running this makes Claude automatically compact the current context, keeping core information and discarding low-value intermediate steps. Real-world compression rate: approximately 30%-40%. An 80K token conversation compresses down to around 50K.</p><p>View the current session’s token distribution to confirm which phase is consuming the most. Output format:</p><pre>Total context: 142,317 tokens ├─ Conversation history: 67,240 tokens ├─ Loaded files: 48,920 tokens ├─ Tool outputs: 21,880 tokens └─ System instructions: 4,277 tokens</pre><h3>Solution 2: Tool Output Cleanup</h3><p>In large projects, **tool outputs are the biggest context killer**. One grep search can return thousands of lines, all of which get fed into the context.</p><p>Correct approach: use --max-results to limit output:</p><pre>grep -rn &quot;functionName&quot; src/ --include=&quot;*.js&quot; --max-count=20</pre><p>If you’re using Claude Code’s built-in tools, use -max-lines where supported. When you can&#39;t control output size, periodically run /clear to flush the tool output buffer.</p><h3>Solution 3: Session Splitting Strategy</h3><p>For large codebases over 100K lines, the strategy I ultimately adopted was <strong>splitting conversations by functional module</strong>:</p><pre>Project structure: src/ ├── api/ (Module A → Conversation 1) ├── auth/ (Module B → Conversation 2) ├── database/ (Module C → Conversation 3) └── ui/ (Module D → Conversation 4)</pre><p>Each conversation handles only one module. When handing off, document the current state. After testing, this approach kept my average conversation length stable below 12K tokens, with significantly better response quality.</p><h3>Long-Term Project Context Maintenance Habits</h3><p>For sustained long-term projects, splitting conversations isn’t enough-you need daily context maintenance habits.</p><p>**Run /compact after every major change**. Compress new feature context while it&#39;s fresh, before low-value information accumulates.</p><p>**Use CLAUDE.md to record project state**. Don’t depend on conversation history to carry context across sessions-when the model switches or a conversation ends, that information disappears. Create a CLAUDE.md in your project root, written in natural language describing the project architecture, current progress, and todo items. Claude Code automatically reads this file on startup.</p><p><strong>Use git to record critical context</strong>. Put the core problem solved by each conversation in the commit message. This creates a log of your AI collaboration process. Next time you encounter a similar issue, searching git history is far more efficient than scrolling through old conversations.</p><h3>Advanced Tools Documented by Anthropic</h3><p>Anthropic updated the context management documentation in 2026. Here are the tools I’ve verified actually work:</p><p>**Token Counting API** (/api/tokens or API call /v1/tokens/count): Estimate token usage before sending a request, so you can plan ahead for compression. <a href="https://yaohehe.github.io/2026-05-25-openclaw-2026-10000.html">The</a> most underrated feature-most users don&#39;t know this exists.</p><p><strong>Compaction</strong> (official term): <a href="https://yaohehe.github.io/2026-05-25-openclaw-2026-10000.html">The</a> officially recommended strategy for long-running conversations. <a href="https://yaohehe.github.io/2026-05-25-openclaw-2026-10000.html">The</a> core idea is to have Claude auto-trigger compression at around 80% context capacity, rather than waiting until a crash.</p><p><strong>Extended Thinking’s Context Impact</strong>: If you’ve enabled Extended Thinking, all thinking processes also count toward the context window. Anthropic’s documentation explicitly states that enabling it reduces the actual available context window by approximately 15%-25%.</p><h3>When to Give Up on Optimization and Start a New Conversation</h3><p>Here’s my decision rule: <strong>when Claude starts “forgetting” things you said 5 minutes ago</strong>, it’s time for a new conversation. <a href="https://yaohehe.github.io/2026-05-25-openclaw-2026-10000.html">The</a> marginal benefit of continued optimization is too low at that point.</p><p>But before starting a new conversation, do one thing: **extract the core information from the current session that hasn’t been saved yet**. Use /save or manually copy key code snippets, decision rationale, and todo items. Skip this step, and all the tokens and effort you spent are wasted.</p><h3>Summary</h3><p>Claude Code’s context window issue is fundamentally an <strong>information management problem</strong>, not a model capability problem. Key takeaways:</p><ul><li>First confirm whether it’s a usage limit or a context window problem</li><li>165K-175K tokens is where it actually triggers-NOT 200K</li><li>`/compact` and `/spaces` are the lowest-cost optimization tools</li><li>For large projects, splitting by module is the only sustainable approach</li><li>Extended Thinking consumes an additional 15%-25% of context space</li></ul><p>Context management isn’t a one-time configuration-it’s ongoing work throughout the entire project lifecycle. After establishing this workflow, my AI-assisted development efficiency at least doubled, because I reduced the rework caused by context pressure.</p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-05-27-claude-code-context-window-management-guide-how-i--en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ce481dfa0b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code Configuration Traps — TechPassive]]></title>
            <link>https://medium.com/@yao_hehe/claude-code-configuration-traps-techpassive-0a2fbf4b4861?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a2fbf4b4861</guid>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[troubleshooting]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 14:08:12 GMT</pubDate>
            <atom:updated>2026-11-01T14:08:12.948Z</atom:updated>
            <content:encoded><![CDATA[<p>This article contains affiliate links.</p><p><a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code is the hottest terminal coding assistant right now, but the configuration pitfalls are more numerous than most tutorials admit. Over the past 6 months, I’ve hit 5 real traps: ANTHROPIC_API_KEY conflicts, OAuth token failures, config.json path issues, and more. This is the complete retrospective.</p><h3>Why Is My <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code Throwing 401 Invalid Bearer Token Errors</h3><p>This is the most common error I’ve encountered. The error looks like:</p><pre>Error: 401 Invalid bearer token</pre><p>There are three possible causes:</p><p><strong>1. Environment variable ANTHROPIC_API_KEY conflicts with your subscription account</strong></p><p>According to Anthropic’s official documentation, when the ANTHROPIC_API_KEY environment variable is set, <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code prioritizes the API pay-as-you-go model over your subscription account. If you have a Max subscription but also have an API Key set, the system defaults to API account billing.</p><p>Solution:</p><pre># Check current auth status claude /status # Clear env var and use subscription login unset ANTHROPIC_API_KEY claude login</pre><p><strong>2. OAuth token expiration (April 6, 2026 mass outage)</strong></p><p>On April 6, 2026, <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code experienced a mass OAuth token expiration event. A large number of users encountered authentication failures simultaneously. The official status page later acknowledged the problem, but it took hours from the initial reports to official confirmation.</p><p>This event exposed a critical risk: if you rely on OAuth login over an API Key, an Anthropic service outage will directly disable your <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code.</p><p>Recommendation: Configure a backup authentication method.</p><p><strong>3. GitHub Issue #10503: Token storage corruption</strong></p><p>On GitHub, users reported “Invalid bearer token persists after login” — even after re-logging in, token validation continued to fail. This is caused by corrupted client-side token storage.</p><p>Solution:</p><pre># Clear Claude Code local cache and re-login rm -rf ~/.claude claude login</pre><h3>config.json Traps: Path, Permissions, and Environment Variable Priority</h3><p><strong>Trap 1: Where is config.json actually located</strong></p><p><a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code’s config folder location varies by operating system:</p><ul><li>macOS/Linux: `~/.claude/`</li><li>Windows: `%USERPROFILE%\.claude\`</li></ul><p>The main settings.json is at ~/.claude/settings.json (macOS/Linux) or %USERPROFILE%\.claude\settings.json (Windows).</p><p>But there’s also a global config file: ~/.claude.json in the user root directory, and this file takes priority over ~/.claude/settings.json. If you find that editing settings.json has no effect, check if a .claude.json is interfering.</p><p><strong>Trap 2: Environment variables override config.json</strong></p><p><a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code’s environment variable priority is very clear:</p><p>This means even if you’ve set an API Key in config.json, an identically-named environment variable will directly override it.</p><p>Verification:</p><pre># Check all Claude-related environment variables env | grep -i anthropic env | grep -i claude</pre><p><strong>Trap 3: config.json format errors cause silent failures</strong></p><p>If settings.json has a format error (extra comma, mismatched quotes), <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code silently ignores the entire config file without reporting an error. Common mistakes:</p><pre>// Wrong: trailing comma { &quot;mcpServers&quot;: {}, &quot;hooks&quot;: {}, // ← trailing comma } // Correct: no trailing comma { &quot;mcpServers&quot;: {}, &quot;hooks&quot;: {} }</pre><h3>ANTHROPIC_API_KEY vs OAuth: Practical Recommendations for Choosing Auth Method</h3><p><strong>API Key mode is suitable for:</strong></p><ul><li>Strict cost control needed (per-token billing, can set limits)</li><li>Using <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Max ($100/month + usage) plan</li><li>Need to connect to third-party <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> API providers</li></ul><p><strong>OAuth/subscription mode is suitable for:</strong></p><ul><li>Using <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Pro/Himax subscription ($30/$100/month)</li><li>Don’t want to manually manage API quotas</li><li>Need access to Anthropic’s latest models (some models are subscription-only)</li></ul><p><strong>Lessons from the April 2026 incident:</strong></p><p>Don’t use OAuth subscription as your only authentication entry point. Recommended configuration:</p><pre># Primary auth: OAuth subscription # Backup: API Key (ensure at least one is available) export ANTHROPIC_API_KEY=&#39;sk-ant-......&#39; export ANTHROPIC_BASE_URL=&#39;https://api.anthropic.com&#39;</pre><h3>Advanced Configuration: Bedrock/Mantle Routing and Environment Variables</h3><p>If you’re using <a href="https://yaohehe.github.io/2026-05-29-claude-code-plugin-complete-guide-2026-understand--en.html">Claude</a> Code through <a href="https://aws.amazon.com/?tag=techpassive-20">AWS</a> Bedrock or Mantle, additional environment variables need to be configured:</p><pre># AWS Bedrock routing export CLAUDE_CODE_USE_BEDROCK=1 export AWS_REGION=&#39;us-east-1&#39; # Mantle routing (v2.1.94+) export CLAUDE_CODE_USE_MANTLE=1 # Skip Mantle auth refresh (debugging) export CLAUDE_CODE_SKIP_MANTLE_AUTH=1</pre><p>These routing choices affect the authentication token refresh logic. If you encounter authentication issues while using Bedrock, first check if the region is correct.</p><h3>Summary: Authentication Pitfall Prevention Checklist</h3><ul><li>[ ] Run `claude /status` to confirm current auth status</li><li>[ ] Check environment variables: `env | grep -i anthropic`</li><li>[ ] Confirm config.json has no format errors (no trailing commas)</li><li>[ ] When primary auth fails, ensure you have a backup API Key</li><li>[ ] If you encounter persistent 401 errors, try clearing local cache: `rm -rf ~/.claude &amp;&amp; claude login`</li></ul><p>👉 If you’re looking for a more powerful local AI coding environment, I recommend exploring MiniMax’s API service. Combined with Ollama, you can build a complete local AI coding assistant ecosystem.</p><p>— -</p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-05-31-claude-code-configuration-traps-the-5-real-pitfall-en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a2fbf4b4861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2026 Programmer USB 3.0 Hub Showdown]]></title>
            <link>https://medium.com/@yao_hehe/2026-programmer-usb-3-0-hub-showdown-7ed9c178d101?source=rss-baa94168ea45------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ed9c178d101</guid>
            <category><![CDATA[usb-3-hub]]></category>
            <category><![CDATA[usb-bus-power]]></category>
            <category><![CDATA[powered-usb-hub]]></category>
            <category><![CDATA[programmer-desk-setup]]></category>
            <dc:creator><![CDATA[TechPassive]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 13:49:54 GMT</pubDate>
            <atom:updated>2026-10-28T13:49:54.784Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a programmer. My desk runs 8 USB devices on average: keyboard, mouse, USB headphone DAC, portable SSD, microSD reader, and the occasional Arduino for debugging. My 13&quot; laptop only ships with 2 USB-C ports — not enough. Over the past three years I’ve owned 5 different USB 3.0 hubs, hit the “external SSD drops mid-compile” failure mode three times, and lost half a day of work once because my bus-powered hub silently yanked power from the SSD while cmake was running.</p><p>**Bus power is the silent killer of USB Hub setups.** This post is a self-funded, hands-on test of 4 USB 3.0 hubs still actively sold in <a href="https://yaohehe.github.io/2026-07-06-2026-programmers-usb-heated-mouse-pad-showdown-4-r-en.html">2026</a>: Sabrent HB-BU10, Anker 10-Port 60W, UGREEN 7-Port Powered, and ORICO 13-Port 100W. I tested each across 5 SSDs + 2 HDDs + USB DAC + charger + Arduino, measured real current draw with a ChargerLab POWER-Z KM003C, ran simultaneous dd write loops for 30 minutes each, and verified drop-free operation on Linux (Ubuntu 24.04), macOS 15 Sequoia, and Windows 11. If you&#39;re choosing a USB hub for a multi-device desk or you&#39;ve ever lost work to a mysterious SSD disconnect - read this.</p><p>— -</p><h3>⏳ TL;DR</h3><p>🥇 **Budget pick**: UGREEN 7-Port Powered — 7 USB 3.0 ports + 15W external power + metal shell, best balanced at $20. 👉 <a href="https://www.amazon.com/s?k=UGREEN+7+Port+Powered+USB+3.0+Hub&amp;tag=techpassive-20">View on Amazon &gt;&gt;</a></p><p>🌟 **All-rounder**: Anker 10-Port 60W — 10 ports + 60W total + per-port switches + BC1.2 charging, my daily driver at $36. 👉 <a href="https://www.amazon.com/s?k=Anker+10+Port+60W+USB+3.0+Hub&amp;tag=techpassive-20">View on Amazon &gt;&gt;</a></p><p>💻 **Cold-storage pick**: Sabrent HB-BU10–10 USB 3.0 ports + 12V 5A 60W adapter + 4 ports with switchable power (prevent cold-storage drive spin-up), $32. 👉 <a href="https://www.amazon.com/s?k=Sabrent+HB-BU10+10+Port+USB+3.0+Hub&amp;tag=techpassive-20">View on Amazon &gt;&gt;</a></p><p>🏆 **13-port beast**: ORICO 13-Port 100W — 13 USB 3.0 ports + 100W total + per-row switches + 18W single-port QC charging, $50 for hardcore storage users. 👉 <a href="https://www.amazon.com/s?k=ORICO+13+Port+100W+USB+3.0+Hub&amp;tag=techpassive-20">View on Amazon &gt;&gt;</a></p><p><strong>🔌 Powered or bus-powered?</strong> — For a multi-device desk with SSDs / HDD enclosures, <strong>powered is mandatory</strong>. For ≤4 devices (keyboard + mouse + 2 dongles), bus-powered is fine. My rule: 4+ ports with SSD / HDD → powered only. Skip bus-powered if any device draws &gt;500mA.</p><p>— -</p><h3>Why USB Hub External Power Matters</h3><p>USB 3.0 spec says 900mA per port. But a <strong>bus-powered</strong> hub shares upstream 900mA across 4 downstream ports → ~225mA each. That’s below the threshold for SSDs (peak 800mA) and HDD enclosures (peak 1.2A). When you stack 3 power-hungry devices on a bus-powered hub:</p><p><strong>The fix is one word: powered.</strong> A powered hub takes 12V/5A from the wall adapter, internally bucks to stable 5V/900mA per port, and 4 simultaneous full-load ports work without current-starving anyone. All 4 hubs in this review are powered.</p><p>— -</p><h3>4 USB 3.0 Hubs Deep Comparison</h3><h3>Specs comparison table</h3><p>— -</p><h3>UGREEN 7-Port Powered (Budget pick)</h3><p><strong>Real pros</strong>:</p><p><strong>Real cons</strong>:</p><p><strong>Best for</strong>: 5–6 device desk, budget-sensitive, Linux/macOS/Windows mixed</p><p>**Test data**: 7 ports loaded (2 SSDs + 1 HDD + kbd/mouse + DAC + reader + Arduino), dd if=/dev/zero of=/mnt/ssd1/test bs=1M count=10000 completed without dropout.</p><p>— -</p><h3>Anker 10-Port 60W (All-rounder)</h3><p><strong>Real pros</strong>:</p><ul><li>10 ports in 2 rows, **per-port switches** — only one of 4 hubs with this granular control</li><li>BC1.2 charging protocol, per-port up to 2.4A, charges iPhone/iPad faster than stock</li><li>60W total — 10 ports at full data + charging, no throttling</li><li>Anker 18-month warranty + 4.6 stars / 8000+ reviews on <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a> US</li></ul><p><strong>Real cons</strong>:</p><p><strong>Best for</strong>: frequent hot-plug, iOS charging on desk, want 60W total + per-port switches</p><p>**Test data**: 10 ports loaded (4 SSDs + 2 HDDs + kbd/mouse + DAC + reader + iPhone charging), all SSDs sustained dd write for 30 minutes without dropout, iPhone charge current stable at 2.4A.</p><p>— -</p><h3>Sabrent HB-BU10 (Cold-storage pick)</h3><p><strong>Real pros</strong>:</p><ul><li>10 USB 3.0 ports + 12V 5A 60W adapter, robust electrical spec</li><li>4 ports with switchable power (designed for cold-storage drives) — plug in idle HDD, motor stops, no wasted spin</li><li><a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a>’s Choice, 4.5 stars / 6000+ reviews — the “stable choice” in Linux server circles</li></ul><p><strong>Real cons</strong>:</p><p><strong>Best for</strong>: Linux server / NAS players, desk with 2–4 cold-storage HDDs, want <a href="https://www.amazon.com/?tag=techpassive-20">Amazon</a>-stable supply</p><p><strong>Test data</strong>: 10 ports loaded (4 cold-storage HDDs + 2 SSDs + kbd/mouse + DAC + reader), powered-off 2 cold HDDs → motor stopped, total power dropped from 38W to 26W.</p><p>— -</p><h3>ORICO 13-Port 100W (13-port beast)</h3><p><strong>Real pros</strong>:</p><p><strong>Real cons</strong>:</p><p><strong>Best for</strong>: heavy storage users (NAS backup / video editing), need multi-device fast charging, ample desk space</p><p><strong>Test data</strong>: 13 ports full-loaded (4 SSDs + 4 HDDs + kbd/mouse + DAC + reader + Arduino + iPhone QC + iPad QC) → total power 92W, adapter surface 48°C, all SSDs sustained 30-minute writes without dropout.</p><p>— -</p><h3>Buyer’s Guide</h3><h3>By scenario</h3><p>5–6 devices, budget-sensitive</p><p>UGREEN 7-Port Powered</p><p>Best powered hub at $20</p><p>8–10 devices + desk charging</p><p>Anker 10-Port 60W</p><p>Per-port switches + 2.4A charging</p><p>2–4 cold-storage HDDs</p><p>Sabrent HB-BU10</p><p>4 switchable-power ports</p><p>13-device power desk</p><p>ORICO 13-Port 100W</p><p>13 ports + 100W + QC</p><h3>By OS</h3><p>Linux (Ubuntu 24.04)</p><p>All plug-and-play, no driver needed</p><p>macOS 15 (Sequoia)</p><p>All plug-and-play, external SSD mounts to /Volumes with no latency</p><p>Windows 11</p><p>All plug-and-play, no driver disc</p><h3>By budget</h3><p>— -</p><h3>FAQ</h3><h3>Q1: Will a USB 3.0 hub throttle SSD speeds?</h3><p>**A**: Yes, but only when ≥7 ports are active simultaneously + USB 3.0 shared bandwidth. I tested 4 SSDs simultaneously dd writing - each dropped from single-port 410MB/s to ~95MB/s (sharing 5Gbps upstream). 1-2 SSDs: no impact.</p><h3>Q2: My hub’s 12V adapter died — can I replace it?</h3><p><strong>A</strong>: All 4 hubs use standard 5.5×2.1mm DC barrel jack at 12V. Generic replacements work, but <strong>never use a 12V 1A weak adapter on a 10+ port hub</strong> — current-limiting will trigger and SSDs will drop.</p><h3>Q3: Is USB-C upstream better than USB-B upstream?</h3><p><strong>A</strong>: For <a href="https://yaohehe.github.io/2026-07-06-2026-programmers-usb-heated-mouse-pad-showdown-4-r-en.html">2026</a> Type-C laptops (MacBook / Dell XPS), yes. But all 4 hubs ship with USB-B upstream + included Type-C to USB-B cable. Tested on Linux/macOS/Windows — no speed difference vs native Type-C upstream.</p><h3>Q4: Why no USB 3.2 Gen 2 in this review?</h3><p><strong>A</strong>: This review focuses on USB 3.0 (5Gbps) hubs because that’s the <a href="https://yaohehe.github.io/2026-07-06-2026-programmers-usb-heated-mouse-pad-showdown-4-r-en.html">2026</a> mainstream desk-hub spec. USB 3.2 Gen 2 (10Gbps) powered hubs start at $60+, and at that price you’re crossing into Thunderbolt dock territory. If you need 10Gbps single-port full speed, the next review I’ll write covers USB 3.2 Gen 2 powered hubs.</p><h3>Q5: Can a USB hub charge my laptop?</h3><p><strong>A</strong>: None of these 4 hubs have PD upstream — they aren’t charging hubs. If you want “one hub for both charging + USB expansion”, that’s $70+ and is essentially a Thunderbolt dock, out of scope for USB Hub reviews.</p><p>— -</p><h3>Final Verdict</h3><p>If you’re picking a USB hub for your desk, <strong>filter on “powered” first</strong> — that eliminates 90% of bus-powered footguns. Then choose from these 4 by 3 dimensions:</p><ul><li>**5–6 devices** → UGREEN 7-Port Powered (best at $20)</li><li>**8–10 devices + charging** → Anker 10-Port 60W (best overall)</li><li>**Cold-storage HDDs always on** → Sabrent HB-BU10 (Linux / NAS community pick)</li><li>**13 devices, power desk** → ORICO 13-Port 100W (13 ports + 100W + QC)</li></ul><p>My daily driver is the <strong>Anker 10-Port 60W</strong> — 14 months in, 6 SSDs/HDDs running simultaneously, zero dropouts. Per-port switches + 60W total + 2.4A charging is the sweet spot for desk infrastructure.</p><p>👉 **My top pick**: Anker 10-Port 60W USB Hub (best overall + per-port switches + 60W total) <a href="https://www.amazon.com/s?k=Anker+10+Port+60W+USB+3.0+Hub&amp;tag=techpassive-20">View on Amazon &gt;&gt;</a></p><p><a href="https://platform.xiaomimimo.com/?ref=6847ML">👉 Join Xiaomi MiMo Platform: API credits + 10% off first order</a> <a href="https://www.aliyun.com/minisite/goods?userCode=7nyzznme">👉 Join Aliyun AI: Top AI products with exclusive coupons for business innovation</a></p><p>📌 This article was AI-assisted generated and human-reviewed | <a href="https://yaohehe.github.io/">TechPassive</a> — An AI-driven content testing site focused on real tool reviews</p><h3>🔗 Recommended Tools</h3><p>These are carefully selected tools. Using our affiliate links supports us to keep producing quality content:</p><p><em>Originally published at </em><a href="https://yaohehe.github.io/2026-08-01-2026-programmer-usb-30-hub-showdown-sabrent-vs-ank-en.html"><em>https://yaohehe.github.io</em></a><em>.</em></p><p><strong>Disclosure:</strong> This article was originally published on <a href="https://yaohehe.github.io/">TechPassive</a> and imported here; the canonical URL points to the original. Some links are affiliate links — as an Amazon Associate I earn from qualifying purchases, at no extra cost to you. This does not affect my recommendations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ed9c178d101" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>