<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.huijo.xyz/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.huijo.xyz/" rel="alternate" type="text/html" /><updated>2026-11-03T07:55:09+00:00</updated><id>https://www.huijo.xyz/feed.xml</id><title type="html">pile of thoughts</title><subtitle>Huijo Kim — AI engineer and ex-startup CTO. Writing on agents, machine learning, data engineering, and building companies.</subtitle><author><name>Huijo Kim</name><email>ccomkhj@gmail.com</email></author><entry><title type="html">AI Coding: Programming by Coincidence at Scale</title><link href="https://www.huijo.xyz/HappenToWork/" rel="alternate" type="text/html" title="AI Coding: Programming by Coincidence at Scale" /><published>2026-11-02T00:00:00+00:00</published><updated>2026-11-02T00:00:00+00:00</updated><id>https://www.huijo.xyz/HappenToWork</id><content type="html" xml:base="https://www.huijo.xyz/HappenToWork/"><![CDATA[<p>In <em>The Pragmatic Programmer</em>, the authors describe <strong>Programming by Coincidence</strong>: writing code that appears to work without understanding why.</p>

<p>I think AI-assisted coding makes this problem even more relevant.</p>

<p><img src="/assets/images/programming-by-coincidence.gif" alt="An AI rapidly stacks misaligned &quot;??&quot; code blocks; tests pass, then an edge case knocks the tower over. A second tower built deliberately from SPEC, failure tests, small tickets, asking why, and readable code withstands the same edge case." /></p>

<p>With AI, we can generate hundreds of lines of code in seconds. We run it, see the expected output, and move on. But <strong>do we actually understand why it works?</strong></p>

<p>The danger is that AI allows us to accumulate code we don’t understand much faster than before. When something eventually breaks, we’re left debugging a system whose assumptions and behavior we never fully understood.</p>

<p><strong>The problem isn’t that AI writes code. It’s that we mistake working code for correct code.</strong></p>

<p>So how do we avoid this?</p>

<ul>
  <li><strong>Define expected behavior first.</strong> Know what the code should do before asking AI to implement it. (Start with SPEC.md)</li>
  <li><strong>Understand the reasoning.</strong> Question important design decisions and assumptions. (When AI generates lots of code, you should ask AI’s reasoning.)</li>
  <li><strong>Test failure cases.</strong> Don’t just verify the happy path. (Start with TDD)</li>
  <li><strong>Keep changes small.</strong> Review and validate incrementally. (Break SPEC.md into smaller tickets)</li>
  <li><strong>Own the result.</strong> Don’t ship critical code you can’t explain or maintain. (For business critical part of code, If the AI generated code is not readible by you, then rewrite to be understandable by YOU. Asking for diagram &amp; flow chart isn’t sufficient. Longer + Understandable code is better than Concise + hard-to-follow code.)</li>
</ul>

<p>AI can accelerate implementation, but it doesn’t replace engineering judgment.</p>

<p><strong>If we don’t change how we verify and understand code, we’re just programming by coincidence, faster.</strong></p>]]></content><author><name>Huijo</name></author><category term="Engineering" /><category term="Agents" /><category term="Reading" /><summary type="html"><![CDATA[AI lets us pile up code we don't understand faster than ever. Working code is not correct code.]]></summary></entry><entry><title type="html">Is V2 actually better? Paired testing for LLM releases</title><link href="https://www.huijo.xyz/PairedTestForLLMRelease/" rel="alternate" type="text/html" title="Is V2 actually better? Paired testing for LLM releases" /><published>2026-10-24T00:00:00+00:00</published><updated>2026-10-24T00:00:00+00:00</updated><id>https://www.huijo.xyz/PairedTestForLLMRelease</id><content type="html" xml:base="https://www.huijo.xyz/PairedTestForLLMRelease/"><![CDATA[<p>Say we run a RAG chatbot for an online pharmacy. V1 is in production. V2 only changes the system prompt. A few colleagues tried V2 by hand, and they think the answers are better.</p>

<p>Maybe they are right. But a handful of manual checks can’t separate a 6-point improvement from luck, and it says nothing about whether V2 got worse on the questions that matter most. Before V2 replaces V1, I want to know if we are testing the right questions, if the gain is bigger than sampling noise, and if it hides a regression we can’t accept.</p>

<p>I’ll use one example for the whole post: V1 and V2 answer the same 200 questions, and each answer is scored pass or fail. The infographic is the short version.</p>

<p><img src="/assets/images/paired-test-v1-v2.webp" alt="Infographic of a paired test comparing V1 and V2 on the same 200 questions: setup, 2x2 pass/fail table, paired standard error, 95% confidence interval, McNemar p-value, and the ship decision." /></p>

<h2 id="dataset-coverage-vs-standard-error">Dataset coverage vs. standard error</h2>

<p>The first instinct is to ask whether the evaluation set is big enough. But “big enough” mixes two different questions.</p>

<p>One is representativeness: do the evaluation questions look like real traffic? If 80% of production queries are about shipping and 1% are about drug interactions, a set with only shipping questions tells you nothing about safety. Adding more shipping questions doesn’t fix that.</p>

<p>The other is standard error: how much would the measured pass rate move if we ran the evaluation again on a different random set of questions?</p>

<p>More data only helps with the second one. With 10,000 badly sampled questions, you get a very precise estimate of the wrong thing. So I’d sort out coverage first (production queries, past failures, and extra high-risk cases on purpose), and only then ask how many questions we need.</p>

<p>Independence matters too. If 400 questions are paraphrases of 10 originals, you have something closer to 10 observations than 400. All the formulas below assume each question is its own draw.</p>

<p>A small naming thing, because the two terms get mixed up a lot. A paired evaluation means both versions answer the same questions. A pairwise preference evaluation means a human or a judge model picks the better of two answers. You can do both at once, but they are different designs. This post is about the paired one.</p>

<h2 id="standard-error-of-one-pass-rate">Standard error of one pass rate</h2>

<p>Say a model really passes 80% of questions in the target population. Sample 100 questions and you might see 78 passes. Sample another 100 and you might see 83. The model is the same in both cases; the difference comes from which questions were drawn.</p>

<p>Standard error (SE) is the typical size of that wobble. For pass/fail scores:</p>

\[\operatorname{SE}(\hat{p}) = \sqrt{\frac{\hat{p}(1-\hat{p})}{n}}\]

<p>$\hat{p}$ is the observed pass rate and $n$ is the number of questions. For $\hat{p}=0.8$ and $n=100$:</p>

\[\operatorname{SE} = \sqrt{\frac{0.8 \times 0.2}{100}} = \sqrt{0.0016} = 0.04\]

<p>So about 4 percentage points. With 400 questions it goes down to 2.</p>

<p>We used four times more questions and the uncertainty only halved. That’s because</p>

\[\operatorname{SE} \propto \frac{1}{\sqrt{n}}\]

<p>Doubling $n$ multiplies SE by about 0.71. To get SE down to a quarter, you need sixteen times the questions. Labeling gets expensive fast, so I’d rather decide the target before collecting anything.</p>

<h2 id="how-many-questions">How many questions?</h2>

<p>To answer “why 200 and not 500?”, you first have to say what you’re trying to do. Usually it’s one of these:</p>

<ul>
  <li>estimate one version’s pass rate to some precision, or</li>
  <li>detect an improvement of V2 over V1 of at least some size.</li>
</ul>

<p>For a release decision it’s the second. Say V1 passes about 75%, and the team agrees anything under 6 points isn’t worth shipping. Then fix these before running anything:</p>

<ul>
  <li>minimum detectable effect $\delta = 0.06$</li>
  <li>significance level $\alpha = 0.05$</li>
  <li>power $1-\beta = 0.80$</li>
  <li>expected discordance rate $\psi = 0.15$, i.e. the share of questions where V1 and V2 get different results</li>
</ul>

<p>The discordance rate is there because of the pairing. If both versions pass a question, or both fail it, that question says nothing about which one is better. Only the disagreements count. Two prompts on the same RAG system usually agree on most questions, and fewer disagreements means less noise in the difference.</p>

<p>A rough formula for paired pass/fail data:</p>

\[n \approx \frac{\left(z_{1-\alpha/2} + z_{1-\beta}\right)^2 \psi}{\delta^2}\]

<p>With $z_{0.975} \approx 1.96$ and $z_{0.80} \approx 0.84$:</p>

\[n \approx \frac{(1.96 + 0.84)^2 \times 0.15}{0.06^2} \approx 327\]

<p>So I’d plan for around 330 paired questions. Treat this as a planning number. An exact power calculation can come out different, and safety-critical slices need their own sample, usually a bigger one.</p>

<p>80% power means that if the true improvement really is 6 points (and the assumptions hold), the test catches it in about 80% of repeated experiments. It doesn’t mean there’s an 80% chance V2 is better. Power describes the test procedure under a specific alternative, and says nothing directly about the model.</p>

<p>The example below only has 200 questions. I ran a quick simulation of the exact McNemar test under the same assumptions: with 200 questions it detects a real 6-point gain only about 52% of the time. With 327 it’s about 78% (the exact test is a bit conservative). So the example is underpowered. A significant result is still a result, but if it had come out non-significant, we’d have learned very little.</p>

<h2 id="running-both-versions-on-the-same-questions">Running both versions on the same questions</h2>

<p>V1 passes 150 of 200 (75%). V2 passes 162 (81%). The observed lift:</p>

\[\hat{\Delta} = 0.81 - 0.75 = 0.06\]

<p>For a paired analysis you need the per-question results, not just the two totals:</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th style="text-align: right">V2 passes</th>
      <th style="text-align: right">V2 fails</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>V1 passes</strong></td>
      <td style="text-align: right">141</td>
      <td style="text-align: right">9</td>
    </tr>
    <tr>
      <td><strong>V1 fails</strong></td>
      <td style="text-align: right">21</td>
      <td style="text-align: right">29</td>
    </tr>
  </tbody>
</table>

<p>So 141 questions pass on both, 29 fail on both, $b = 9$ pass only on V1, and $c = 21$ pass only on V2.</p>

<p>Only 30 questions changed. The net gain is 12 questions:</p>

\[\hat{\Delta} = \frac{c - b}{n} = \frac{21 - 9}{200} = 0.06\]

<p>Same 6 points as before, but now you can see where they came from. V2 fixed 21 questions and broke 9. I’d read those 9 one by one before computing anything else. That’s usually where you learn what the new prompt actually changed.</p>

<h2 id="standard-error-of-the-difference">Standard error of the difference</h2>

<p>Give each question a score of $+1$ if only V2 passes, $-1$ if only V1 passes, and $0$ otherwise. The average of these scores is $\hat{\Delta}$. Both versions answered the same questions, so their results are correlated, and the SE has to account for that. You can’t treat the two pass rates as independent samples.</p>

<p>For paired pass/fail data:</p>

\[\operatorname{SE}(\hat{\Delta}) \approx \sqrt{\frac{b + c}{n^2} - \frac{(c - b)^2}{n^3}}\]

<p>With $b=9$, $c=21$, $n=200$:</p>

\[\operatorname{SE} \approx \sqrt{\frac{30}{200^2} - \frac{12^2}{200^3}} = \sqrt{0.00075 - 0.000018} \approx 0.0271\]

<p>That’s about 2.7 percentage points.</p>

<p>If you ignore the pairing and use the usual formula for two independent samples, you get:</p>

\[\sqrt{\frac{0.75 \times 0.25}{200} + \frac{0.81 \times 0.19}{200}} \approx 0.0413\]

<p>4.1 points instead of 2.7. Pairing takes question difficulty out of the comparison. A hard question is hard for both versions, so it cancels in the difference.</p>

<p>To be clear about what these numbers mean: 6 points is the estimate, and 2.7 points is the estimated standard deviation of that estimate over repeated samples. It describes typical noise. It doesn’t promise the true value is within 6 ± 2.7.</p>

<h2 id="95-confidence-interval">95% confidence interval</h2>

<p>Multiply SE by a critical value to get an interval. Using the normal approximation:</p>

\[\text{CI}_{95\%} \approx \hat{\Delta} \pm 1.96 \times \operatorname{SE} = 0.06 \pm 1.96 \times 0.0271 \approx [0.007,\ 0.113]\]

<p>So improvements between about 0.7 and 11.3 percentage points fit the data, under this approximation.</p>

<p>The tempting reading is “there’s a 95% chance the true improvement is between 0.7 and 11.3”. That’s not what a frequentist interval says. The true improvement is a fixed number we don’t know. What’s random is the interval: if we repeated the experiment many times, about 95% of the intervals would contain the true value. I wrote more about this in <a href="/Interval/">Prediction Interval, Confidence Interval</a>.</p>

<p>The interval doesn’t include zero, which supports a real gain. But it’s wide. The data are also compatible with an improvement of less than one point, and that matters a lot if V2 is more expensive to run.</p>

<p>With the independent-samples SE instead, $0.06 \pm 1.96 \times 0.0413$ gives roughly -2.1 to 14.1 points. That includes zero. The same 200 questions would look inconclusive just because the pairing was ignored.</p>

<h3 id="comparing-two-separate-intervals">Comparing two separate intervals</h3>

<p>A common mistake is to compute one interval per version and check whether they overlap. Wilson 95% intervals here:</p>

<ul>
  <li>V1: 68.6% to 80.5%</li>
  <li>V2: 75.0% to 85.8%</li>
</ul>

<p>They overlap, so someone concludes there’s no significant difference. But neither interval knows that the two versions answered the same questions. Look at the interval of the paired difference instead.</p>

<p>For a real report, I’d use an interval built for paired binary data, like Newcombe’s or Tango’s score interval. The normal approximation gets rough when $b + c$ is small.</p>

<h2 id="p-value-with-mcnemars-test">p-value with McNemar’s test</h2>

<p>The p-value answers a different question. The null hypothesis is that both versions have the same pass rate:</p>

\[H_0: p_{V2} = p_{V1}
\qquad
H_1: p_{V2} \neq p_{V1}\]

<p>For paired pass/fail data the usual test is McNemar’s test. It only looks at the 30 questions where the versions disagree. If V1 and V2 were equally good, each disagreement would be a coin flip, so the number of V2 wins would follow</p>

\[X \sim \operatorname{Binomial}(30,\ 0.5)\]

<p>We saw $X = 21$. The exact two-sided p-value counts outcomes at least this lopsided in either direction:</p>

\[p = 2P(X \leq 9) \approx 0.0428\]

<p>Since $0.0428 &lt; 0.05$, we reject $H_0$ at the 5% level. The lift is statistically significant.</p>

<p>Put simply: if V1 and V2 really had the same pass rate, and the test’s assumptions hold, a split at least as uneven as 21 to 9 would happen about 4.3% of the time.</p>

<p>It does not mean there’s a 95.7% chance V2 is better. A p-value isn’t the probability that the null is true, or that the alternative is. It tells you how badly the data fit $H_0$ under the model. If you want probabilities for hypotheses, you need a Bayesian setup with an explicit prior. More on that in <a href="/Pvalue/">P Value</a>.</p>

<p>One practical note. With only 30 discordant pairs, I’d use the exact binomial version. The chi-square approximation gives $p \approx 0.028$ without continuity correction and $p \approx 0.045$ with it. Whichever you use, decide before you see the data.</p>

<h2 id="is-it-worth-shipping">Is it worth shipping?</h2>

<p>So far we have a 6-point estimate, an interval that excludes zero, and $p &lt; 0.05$. That’s evidence of an overall improvement. I still wouldn’t ship on that alone.</p>

<p>Say the true gain is only 1 point and V2 doubles token cost or adds noticeable latency. Is it worth it? Statistics can’t tell you. The team has to agree beforehand on the smallest improvement that pays for the extra cost. A significant effect can be too small to care about, and an effect you’d care about can miss significance because the sample was too small.</p>

<p>The opposite mistake happens too. If the lift were still 6 points but $p = 0.12$ and the interval included zero, you can’t say “V1 and V2 are equally good”. You can only say this experiment didn’t give enough evidence of a difference. To show that V2 is no worse than V1, you need a non-inferiority or equivalence test with a margin agreed in advance.</p>

<h2 id="safety-slices">Safety slices</h2>

<p>One more detail. On 30 drug-interaction questions, V1 passes 25 and V2 passes 19.</p>

<p>The overall lift is still real, but I’d block a full rollout and look into it. A wrong drug-interaction answer can hurt a patient. A wrong shipping answer costs a support ticket. The average pass rate weighs them the same.</p>

<p>What if drug-interaction questions are only 1% of traffic, and V2 is clearly better on shipping, which is 80%? For a full rollout, I’d still say no. How bad a failure is can matter more than how often it happens.</p>

<p>So the golden dataset should be split into slices by intent, and each slice evaluated on its own, with explicit thresholds or a no-regression rule for the safety-critical ones.</p>

<p>Also, don’t wait for significance on a safety slice. With 30 questions, a 6-question drop usually won’t reach $p &lt; 0.05$. If the gate only fires on significance, a small slice will almost never fire it. I’d treat the safety gate as a rule the team agreed on beforehand, and keep hypothesis tests out of it.</p>

<p>Another option is a partial rollout: send verified low-risk shipping questions to V2, and send medical questions to a safer workflow, maybe with human review. But then the intent router becomes part of the system and needs its own evaluation. Some dangerous questions will be misclassified, so measure the router’s recall on the medical slice.</p>

<p>And V1 doing better on that slice doesn’t make V1 safe enough for medical advice. It only means V1 is less bad than V2 there.</p>

<h2 id="how-id-run-the-release">How I’d run the release</h2>

<p>Roughly in this order:</p>

<ol>
  <li>Write down the decision rule before anyone sees results: primary metric, smallest improvement worth shipping, significance level, power, sample size, and slice gates.</li>
  <li>Build a versioned golden dataset from production scenarios, with enough high-risk examples in each critical slice. Keep a held-out set that prompt tuning never touches, otherwise repeated tweaking slowly overfits the final measurement.</li>
  <li>Score V1 and V2 on the same questions. For RAG, check more than answer correctness: retrieval, grounding, task success, latency, and cost.</li>
  <li>Analyze the pairs: the paired lift, its interval, and McNemar’s test. Read the individual wins and losses, especially the losses.</li>
  <li>Check the slice gates. An overall win can’t hide an unacceptable regression.</li>
  <li>Roll out gradually with a canary or A/B test, monitor it, and keep a way to roll back.</li>
</ol>

<p>Two more things that are specific to LLMs.</p>

<p>If sampling is on (temperature above zero), a single pass/fail per question is itself noisy. Fix the generation settings where you can, or generate several answers per question and use an analysis that covers both question-level and generation-level variance, for example bootstrapping by question.</p>

<p>If an LLM judge grades the answers, check it against human labels first. Otherwise you can end up with a tight confidence interval around a metric that is simply wrong.</p>

<h2 id="reproducing-the-numbers">Reproducing the numbers</h2>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="nn">scipy</span> <span class="kn">import</span> <span class="n">stats</span>

<span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">,</span> <span class="n">n</span> <span class="o">=</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">21</span><span class="p">,</span> <span class="mi">200</span>  <span class="c1"># V1-only passes, V2-only passes, total questions
</span>
<span class="n">lift</span> <span class="o">=</span> <span class="p">(</span><span class="n">c</span> <span class="o">-</span> <span class="n">b</span><span class="p">)</span> <span class="o">/</span> <span class="n">n</span>
<span class="n">se</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">sqrt</span><span class="p">((</span><span class="n">b</span> <span class="o">+</span> <span class="n">c</span><span class="p">)</span> <span class="o">/</span> <span class="n">n</span><span class="o">**</span><span class="mi">2</span> <span class="o">-</span> <span class="p">(</span><span class="n">c</span> <span class="o">-</span> <span class="n">b</span><span class="p">)</span> <span class="o">**</span> <span class="mi">2</span> <span class="o">/</span> <span class="n">n</span><span class="o">**</span><span class="mi">3</span><span class="p">)</span>
<span class="n">ci</span> <span class="o">=</span> <span class="p">(</span><span class="n">lift</span> <span class="o">-</span> <span class="mf">1.96</span> <span class="o">*</span> <span class="n">se</span><span class="p">,</span> <span class="n">lift</span> <span class="o">+</span> <span class="mf">1.96</span> <span class="o">*</span> <span class="n">se</span><span class="p">)</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">stats</span><span class="p">.</span><span class="n">binomtest</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">b</span> <span class="o">+</span> <span class="n">c</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">).</span><span class="n">pvalue</span>  <span class="c1"># exact McNemar
</span>
<span class="k">print</span><span class="p">(</span><span class="sa">f</span><span class="s">"lift=</span><span class="si">{</span><span class="n">lift</span><span class="si">:</span><span class="p">.</span><span class="mi">3</span><span class="n">f</span><span class="si">}</span><span class="s"> se=</span><span class="si">{</span><span class="n">se</span><span class="si">:</span><span class="p">.</span><span class="mi">4</span><span class="n">f</span><span class="si">}</span><span class="s"> ci=(</span><span class="si">{</span><span class="n">ci</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="si">:</span><span class="p">.</span><span class="mi">3</span><span class="n">f</span><span class="si">}</span><span class="s">, </span><span class="si">{</span><span class="n">ci</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="si">:</span><span class="p">.</span><span class="mi">3</span><span class="n">f</span><span class="si">}</span><span class="s">) p=</span><span class="si">{</span><span class="n">p</span><span class="si">:</span><span class="p">.</span><span class="mi">4</span><span class="n">f</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
<span class="c1"># lift=0.060 se=0.0271 ci=(0.007, 0.113) p=0.0428
</span></code></pre></div></div>

<h2 id="recap">Recap</h2>

<table>
  <thead>
    <tr>
      <th>Concept</th>
      <th>The question it answers</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Golden dataset</td>
      <td>Are we testing the right scenarios?</td>
    </tr>
    <tr>
      <td>Sample size</td>
      <td>How much data do we need to detect the effect we care about?</td>
    </tr>
    <tr>
      <td>Standard error</td>
      <td>How much would the estimate move with a different sample?</td>
    </tr>
    <tr>
      <td>Confidence interval</td>
      <td>Which true improvements are compatible with the data under our method?</td>
    </tr>
    <tr>
      <td>p-value</td>
      <td>How surprising is the result if there were no difference?</td>
    </tr>
    <tr>
      <td>Power</td>
      <td>How likely is the test to detect a specified real improvement?</td>
    </tr>
    <tr>
      <td>Practical significance</td>
      <td>Is the improvement worth its cost?</td>
    </tr>
    <tr>
      <td>Safety gates</td>
      <td>Is there a regression that blocks deployment regardless?</td>
    </tr>
  </tbody>
</table>

<p>If someone shows me $p &lt; 0.05$ and says “ship it”, my next questions are about the safety slices and whether the decision rule was written down before the results came in.</p>]]></content><author><name>Huijo</name></author><category term="Agents" /><category term="Math" /><summary type="html"><![CDATA[How I'd check whether a new prompt really beats production, using 200 pass/fail questions, a paired standard error, and McNemar's test.]]></summary></entry><entry><title type="html">Keycloak Components: Roles, Scopes, Client Scopes, and Audience</title><link href="https://www.huijo.xyz/KeyCloakComponents/" rel="alternate" type="text/html" title="Keycloak Components: Roles, Scopes, Client Scopes, and Audience" /><published>2026-09-12T00:00:00+00:00</published><updated>2026-09-12T00:00:00+00:00</updated><id>https://www.huijo.xyz/KeyCloakComponents</id><content type="html" xml:base="https://www.huijo.xyz/KeyCloakComponents/"><![CDATA[<p>An app wants to call an MCP server that provides SSH tools. For example, a user asks the app to read a log file on a remote machine.</p>

<p>Before running the tool, the MCP server needs two answers:</p>

<ol>
  <li><strong>Who is asking?</strong> This is authentication.</li>
  <li><strong>Are they allowed to do this?</strong> This is authorization.</li>
</ol>

<p><strong>Keycloak handles sign-in and issues an access token. The app sends that token to the MCP server. The MCP server checks it and decides whether to run the tool.</strong> A token is signed data: it lets the server check that the information came from the trusted issuer and was not changed.</p>

<p>In this example, the app connects to the MCP server over HTTPS. The MCP server then uses SSH to reach the remote machine. These are two separate connections, with separate authentication.</p>

<h2 id="the-whole-flow">The whole flow</h2>

<div style="max-width: 620px; margin: 1.5em auto; text-align: center; color: #172b4d;">
  <div style="padding: 18px; border: 2px solid #437bc0; border-radius: 12px; background: #eaf3ff;"><strong>app</strong><br />The user asks: “Read the server log.”</div>
  <div style="padding: 8px;">↓ User signs in through Keycloak</div>
  <div style="padding: 18px; border: 2px solid #8862b4; border-radius: 12px; background: #f3ecff;"><strong>Keycloak</strong><br />Checks the user and issues an access token.</div>
  <div style="padding: 8px;">↓ Token returns to the app</div>
  <div style="padding: 18px; border: 2px solid #437bc0; border-radius: 12px; background: #eaf3ff;"><strong>app → mcp_server</strong><br />Sends the tool request with the access token.</div>
  <div style="padding: 8px;">↓ MCP server checks the token and permissions</div>
  <div style="padding: 18px; border: 2px solid #39805a; border-radius: 12px; background: #e7f6ed;"><strong>mcp_server → remote machine</strong><br />If allowed, uses its configured SSH credentials<br />to read the requested log.</div>
</div>

<p>This diagram focuses on the token’s journey; discovery and the login redirect steps are omitted. For HTTP MCP requests, the app sends the token in the <code class="language-plaintext highlighter-rouge">Authorization</code> header:</p>

<div class="language-http highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">Authorization: Bearer &lt;access-token&gt;
</span></code></pre></div></div>

<p>The MCP server must validate the token and check that it was issued for that server. See the <a href="https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-11-25/basic/authorization.mdx">MCP authorization specification</a>.</p>

<h2 id="what-do-we-create-in-keycloak">What do we create in Keycloak?</h2>

<p>A <strong>user</strong> is the account signing in. A <strong>client</strong> is an application registered in Keycloak. A <strong>realm</strong> holds a set of users, clients, and roles.</p>

<p>For our example, we use two client registrations:</p>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Purpose</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">app</code></td>
      <td>The application that obtains a token for the signed-in user</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">mcp_server</code></td>
      <td>The server whose tools we want to protect; its registration holds the server’s roles</td>
    </tr>
  </tbody>
</table>

<p>Keycloak creates the token. <code class="language-plaintext highlighter-rouge">app</code> requests it. <code class="language-plaintext highlighter-rouge">mcp_server</code> receives and checks it.</p>

<p>The names below are example configuration, not built-in Keycloak or MCP permissions.</p>

<h2 id="four-concepts-four-questions">Four concepts, four questions</h2>

<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px; margin: 1.5em 0; color: #172b4d;">
  <div style="background: #eaf3ff; border: 2px solid #437bc0; border-radius: 14px; padding: 20px;">
    <strong style="font-size: 1.25em;">ROLE</strong><br /><br />
    <strong>What is the user allowed to do?</strong><br />Example: <code>ssh_reader</code>
  </div>
  <div style="background: #fff5d9; border: 2px solid #ac7b10; border-radius: 14px; padding: 20px;">
    <strong style="font-size: 1.25em;">SCOPE</strong><br /><br />
    <strong>What access is the app asking for?</strong><br />Example: <code>ssh:read</code>
  </div>
  <div style="background: #f3ecff; border: 2px solid #8862b4; border-radius: 14px; padding: 20px;">
    <strong style="font-size: 1.25em;">CLIENT SCOPE</strong><br /><br />
    <strong>What should Keycloak put in the token?</strong><br />The settings behind <code>ssh:read</code>
  </div>
  <div style="background: #e7f6ed; border: 2px solid #39805a; border-radius: 14px; padding: 20px;">
    <strong style="font-size: 1.25em;">AUDIENCE</strong><br /><br />
    <strong>Which server is the token for?</strong><br />Our SSH MCP server
  </div>
</div>

<h2 id="role-what-is-the-user-allowed-to-do">Role: what is the user allowed to do?</h2>

<p>Suppose Alice should be able to read logs, but should not be able to restart a service.</p>

<p>We create two roles under the <code class="language-plaintext highlighter-rouge">mcp_server</code> client:</p>

<table>
  <thead>
    <tr>
      <th>Role</th>
      <th>What our MCP server allows</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ssh_reader</code></td>
      <td>Use the tool that reads approved log files</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">ssh_operator</code></td>
      <td>Use the tool that restarts approved services</td>
    </tr>
  </tbody>
</table>

<p>We assign Alice <code class="language-plaintext highlighter-rouge">ssh_reader</code>. We do not assign her <code class="language-plaintext highlighter-rouge">ssh_operator</code>.</p>

<p><strong>A role is a label on an account. The MCP server’s code gives that label meaning.</strong> Creating the role in Keycloak does not automatically restrict SSH commands. Our server must check the role before running the relevant tool.</p>

<p>These are <strong>client roles</strong>, because they belong to <code class="language-plaintext highlighter-rouge">mcp_server</code>. A <strong>realm role</strong> is defined at the realm level instead, such as <code class="language-plaintext highlighter-rouge">employee</code>.</p>

<p>With the usual Keycloak role mappers, Alice’s client role appears here in the access token:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"resource_access"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"mcp_server"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"roles"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"ssh_reader"</span><span class="p">]</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>A role called <code class="language-plaintext highlighter-rouge">ssh_reader</code> under <code class="language-plaintext highlighter-rouge">app</code> is a different role. If the server checks <code class="language-plaintext highlighter-rouge">mcp_server</code>’s roles, putting the same name under <code class="language-plaintext highlighter-rouge">app</code> does not satisfy that check. <a href="https://github.com/keycloak/keycloak/blob/main/docs/documentation/server_admin/topics/clients/oidc/con-token-role-mappings.adoc">Keycloak’s token role mappings</a>.</p>

<h2 id="scope-what-access-is-the-app-asking-for">Scope: what access is the app asking for?</h2>

<p>The app wants to read logs. It requests a scope named <code class="language-plaintext highlighter-rouge">ssh:read</code> when obtaining the token.</p>

<p>For a sign-in using OpenID Connect, the scope part of the request could be:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>scope=openid ssh:read
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">openid</code> requests an OpenID Connect login. <code class="language-plaintext highlighter-rouge">ssh:read</code> is our custom name for the access needed to read logs.</p>

<p><strong>Requesting access does not grant it.</strong> Alice still needs the required role. The server still checks whether the requested tool is allowed.</p>

<p>The distinction is small but useful:</p>

<table>
  <thead>
    <tr>
      <th>Role</th>
      <th>Scope</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Alice has <code class="language-plaintext highlighter-rouge">ssh_reader</code>.</td>
      <td>The app requests <code class="language-plaintext highlighter-rouge">ssh:read</code>.</td>
    </tr>
    <tr>
      <td>Assigned to the account.</td>
      <td>Requested for this access.</td>
    </tr>
  </tbody>
</table>

<p>Even if Alice can both read logs and restart services, an app that only needs to read logs can request narrower access. Our MCP server must enforce that limit using the granted scopes and its tool rules.</p>

<h2 id="client-scope-what-should-keycloak-put-in-the-token">Client scope: what should Keycloak put in the token?</h2>

<p>How does Keycloak know what to do with the name <code class="language-plaintext highlighter-rouge">ssh:read</code>?</p>

<p>We create a <strong>client scope</strong> with that name. It is a saved group of settings in Keycloak. We then link it to <code class="language-plaintext highlighter-rouge">app</code>.</p>

<p>A client scope can contain:</p>

<ul>
  <li><strong>Protocol mappers:</strong> settings that add information to a token, such as the intended audience.</li>
  <li><strong>Role scope mappings:</strong> settings that limit which of the user’s roles may enter the token.</li>
</ul>

<p>Think of the difference this way: <strong><code class="language-plaintext highlighter-rouge">scope=ssh:read</code> is the request. The <code class="language-plaintext highlighter-rouge">ssh:read</code> client scope is the configuration Keycloak applies.</strong> The configuration itself is not sent to the MCP server; the resulting token is.</p>

<p>A linked client scope can be <strong>default</strong>, so it applies without an explicit request, or <strong>optional</strong>, so the app must request it. User role restrictions can still prevent it from applying. Its <strong>Include in token scope</strong> setting controls whether its name appears in the token’s <code class="language-plaintext highlighter-rouge">scope</code> field. <a href="https://github.com/keycloak/keycloak/blob/main/docs/documentation/server_admin/topics/clients/con-client-scopes.adoc">Keycloak’s client scopes</a>.</p>

<h3 id="a-concrete-setup-for-reading-logs">A concrete setup for reading logs</h3>

<p>For this example, configure:</p>

<ol>
  <li>Alice has the <code class="language-plaintext highlighter-rouge">mcp_server</code> client role <code class="language-plaintext highlighter-rouge">ssh_reader</code>.</li>
  <li><code class="language-plaintext highlighter-rouge">app</code> has <strong>Full Scope Allowed</strong> disabled.</li>
  <li>The <code class="language-plaintext highlighter-rouge">ssh:read</code> client scope allows the <code class="language-plaintext highlighter-rouge">mcp_server</code> role <code class="language-plaintext highlighter-rouge">ssh_reader</code> through its role scope mappings.</li>
  <li>That client scope has an Audience mapper adding <code class="language-plaintext highlighter-rouge">https://ssh-mcp.example.com/mcp</code>, our MCP server’s resource identifier.</li>
  <li>Link <code class="language-plaintext highlighter-rouge">ssh:read</code> to <code class="language-plaintext highlighter-rouge">app</code> as <strong>optional</strong>, with <strong>Include in token scope</strong> enabled. Keep the usual role mappers available to <code class="language-plaintext highlighter-rouge">app</code> so eligible roles are written to the access token.</li>
</ol>

<p>The example assumes no other role scope mappings allow extra roles. Here is the role filtering step:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Alice's roles                  Roles allowed for this token
┌────────────────────┐         ┌────────────────────┐
│ ssh_reader         │         │ ssh_reader         │
│ ssh_operator       │         │                    │
└──────────┬─────────┘         └──────────┬─────────┘
           └──────────────┬──────────────┘
                          ▼
                  Role in the token
                 ┌────────────────────┐
                 │ ssh_reader         │
                 └────────────────────┘
</code></pre></div></div>

<p>In this diagram, Alice has both roles to show the filter at work. Only <code class="language-plaintext highlighter-rouge">ssh_reader</code> passes through. A role scope mapping never gives Alice a role she does not already have. With Full Scope Allowed enabled, that role filter does not limit her roles. <a href="https://www.keycloak.org/docs/latest/server_admin/#_role_scope_mappings">Keycloak’s role scope mappings</a>.</p>

<h2 id="audience-which-server-is-this-token-for">Audience: which server is this token for?</h2>

<p>The app may talk to several servers. A token intended for another API should not work at the SSH MCP server just because both trust Keycloak.</p>

<p>The <strong>audience</strong> names the intended receiver. It appears in the token’s <code class="language-plaintext highlighter-rouge">aud</code> field:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"aud"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"https://ssh-mcp.example.com/mcp"</span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Our MCP server checks for that audience. Here we use its resource URL as the identifier. The Keycloak client registration is still named <code class="language-plaintext highlighter-rouge">mcp_server</code>; the Audience mapper connects our configuration to the audience value we want.</p>

<p><strong>Audience answers “Is this token for me?” A role answers “What may this user do?”</strong> The server needs both checks.</p>

<p>Keycloak can set an audience explicitly with an Audience mapper or derive client audiences from eligible client roles using Audience Resolve. A scope name does not automatically become an audience. <a href="https://github.com/keycloak/keycloak/blob/main/docs/documentation/server_admin/topics/clients/oidc/con-audience.adoc">Keycloak’s audience documentation</a>.</p>

<h2 id="put-it-together-app--mcp_server">Put it together: app → mcp_server</h2>

<p>With the example configuration, Alice signs in and the app requests <code class="language-plaintext highlighter-rouge">ssh:read</code> for the SSH MCP resource. A simplified access-token payload could look like this:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"iss"</span><span class="p">:</span><span class="w"> </span><span class="s2">"https://auth.example.com/realms/team"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"sub"</span><span class="p">:</span><span class="w"> </span><span class="s2">"alice-user-id"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"azp"</span><span class="p">:</span><span class="w"> </span><span class="s2">"app"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"aud"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"https://ssh-mcp.example.com/mcp"</span><span class="p">],</span><span class="w">
  </span><span class="nl">"scope"</span><span class="p">:</span><span class="w"> </span><span class="s2">"openid ssh:read"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"resource_access"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"mcp_server"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"roles"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"ssh_reader"</span><span class="p">]</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>This shows selected fields, not a complete usable token. Expiry and signature details are omitted.</p>

<table>
  <thead>
    <tr>
      <th>Field</th>
      <th>Simple meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">iss</code></td>
      <td>Keycloak realm that issued the token</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">sub</code></td>
      <td>User this token represents</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">azp</code></td>
      <td>App that obtained it in this flow</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">aud</code></td>
      <td>Server it is intended for</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">scope</code></td>
      <td>Granted scope names included in the token</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">resource_access.mcp_server.roles</code></td>
      <td>User roles included for the MCP server</td>
    </tr>
  </tbody>
</table>

<p>Before reading the log, our MCP server checks:</p>

<ol>
  <li>The token’s signature, trusted issuer, and expiry are valid.</li>
  <li><code class="language-plaintext highlighter-rouge">aud</code> includes its expected resource identifier.</li>
  <li><code class="language-plaintext highlighter-rouge">scope</code> includes <code class="language-plaintext highlighter-rouge">ssh:read</code>.</li>
  <li><code class="language-plaintext highlighter-rouge">resource_access.mcp_server.roles</code> includes <code class="language-plaintext highlighter-rouge">ssh_reader</code>.</li>
  <li>The requested host and log file are allowed by the tool’s own rules.</li>
</ol>

<table>
  <thead>
    <tr>
      <th>Request</th>
      <th>Result in our example</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Read an approved log with all checks passing</td>
      <td>Allowed</td>
    </tr>
    <tr>
      <td>Read a log with a token intended for a different API</td>
      <td>Rejected</td>
    </tr>
    <tr>
      <td>Read a log with <code class="language-plaintext highlighter-rouge">ssh:read</code> but no <code class="language-plaintext highlighter-rouge">ssh_reader</code> role</td>
      <td>Rejected</td>
    </tr>
    <tr>
      <td>Restart a service with this read-only token</td>
      <td>Rejected</td>
    </tr>
  </tbody>
</table>

<p>After authorization, the MCP server uses its configured SSH credentials. <strong>The Keycloak token controls access to the MCP tool. SSH authentication controls access to the remote machine.</strong> The token is not an SSH key.</p>

<p>To inspect what Keycloak actually produces, use <strong>Client scopes → Evaluate</strong> for <code class="language-plaintext highlighter-rouge">app</code>, select the user and scopes, and look at the generated access token. Check its audience, scopes, and roles against what your MCP server expects. <a href="https://www.keycloak.org/docs/latest/server_admin/#_client_scopes_evaluate">Keycloak’s client scope evaluation</a>.</p>]]></content><author><name>Huijo</name></author><category term="Engineering" /><summary type="html"><![CDATA[A simple explanation of how Keycloak controls access from an app to an SSH MCP server.]]></summary></entry><entry><title type="html">My Thought about the work in the era of AI</title><link href="https://www.huijo.xyz/ThoughtOnWorkInAI/" rel="alternate" type="text/html" title="My Thought about the work in the era of AI" /><published>2026-09-09T00:00:00+00:00</published><updated>2026-09-09T00:00:00+00:00</updated><id>https://www.huijo.xyz/ThoughtOnWorkInAI</id><content type="html" xml:base="https://www.huijo.xyz/ThoughtOnWorkInAI/"><![CDATA[<p>Many companies look for FDEs.
Building is not a bottleneck anymore, but understanding and communicating with customers are.
At the same time, knowing technology is a superpower in understanding and suggesting feasible solutions.
The previous lean startup needs another change because splitting product person and tech person isn’t optimal anymore.
In reality, one needs to get trained to absorb the other’s functionality.
But it’s not as difficult as in the pre-AI era.
Getting customer-mindset comes after understanding how they work and their pain in the process. So, the related basic soft skills: sympathy and communication, and systematized interviews.
Getting product-mindset comes after training on the methodology of managing products, and continuous discovery + practice &amp; time.
Getting in-depth tech-knowledge comes after studying fundamentals (like math), and system architecture + practice &amp; time.</p>

<p>All require some study and practice, but the study part doesn’t require tremendous effort and time in the AI era.
I’d argue about 1-3 months once you have been through the basics (college math and science).
And practice is again about 3-6 months each.</p>

<p>Even if you are responsible for only one part of the task in your organization, you still have a chance to be partially involved.
You are maintaining backend but still it’s mostly encouraged to suggest in product management.
You are researching a forecasting model but still it’s often welcomed to interview customers.
You are customer success but still it’s great to build a micro-service to automate part of internal work.</p>

<p>As a cross-functional talent (not a cross-functional team), you are able to cope with a variety of challenges end-to-end.
When I skim through job postings, most companies do not look for this talent.
These companies look for X-years of experience in Y-tech stacks.
If a talent is expected to work on one function, that’s fine.
However, the team with the old-fashioned structure will have a hard time speeding up in an AI-boosted working environment.</p>

<p>Maybe, it’s difficult to find this talent from CV-screening and an hour of brief interviews.
Checking X-years of experience in Y-tech stacks is relatively easy by giving a case-study problem and asking a couple of conceptual questions.
How can we evaluate the capability of end-to-end functions of product life cycle (customer discovery - pm - build)?</p>

<p>I believe, AI makes each component simple, so there’s huge potential that business can grow multiple times faster than in the pre-AI era.
However, it requires not only different strategy in hiring, but also greater effort to find the talent and give the environment to foster the “complete end-to-end capability”.</p>]]></content><author><name>Huijo</name></author><category term="Career" /><category term="Mindset" /><summary type="html"><![CDATA[TBD]]></summary></entry><entry><title type="html">Customer Interviews: Notes from The Mom Test</title><link href="https://www.huijo.xyz/CustomerInterview/" rel="alternate" type="text/html" title="Customer Interviews: Notes from The Mom Test" /><published>2026-08-23T00:00:00+00:00</published><updated>2026-08-23T00:00:00+00:00</updated><id>https://www.huijo.xyz/CustomerInterview</id><content type="html" xml:base="https://www.huijo.xyz/CustomerInterview/"><![CDATA[<p>I used to interview growers, wholesalers, and farm entrepreneurs when I was a co-founder of hexafarms. Now, as I lead a new project through discovery at VOIDS, I’m interviewing customers again, with more experience, preparation, and structure.</p>

<p>My goal is to listen more and talk less. Ask open-ended questions and listen.</p>

<p>Good founders maintain a direct connection to their users. No middleman!</p>

<h2 id="before-the-conversation">Before the conversation</h2>

<p>Write down the three most important questions you want answered.</p>

<p>Keep it casual. If it feels like they are doing you a favor, then it’s probably too formal.</p>

<p>Don’t open the conversation with your idea. Start with general questions to understand their life.</p>

<h2 id="understand-what-they-do-today">Understand what they do today</h2>

<ul>
  <li>Tell me how you do X today.</li>
  <li>What is the hardest thing about doing X?</li>
  <li>Why is it hard?</li>
  <li>How often do you have to do X?</li>
  <li>Why is it important for your company to do X?</li>
  <li>What do you do to solve this problem yourself?</li>
</ul>

<p>Ideally, ask them to share their screen and show you how they do it. We want to understand their behaviour.</p>

<p>People are not good at predicting what they will do. My goal is to understand their current problems. What workarounds have they built?</p>

<h2 id="talk-specifics-not-hypotheticals">Talk specifics, not hypotheticals</h2>

<p>Ask for specific past examples to get concrete data.</p>

<ul>
  <li>Tell me about the last time you encountered that problem.</li>
  <li>What, if anything, have you done to try to solve it?</li>
  <li>What don’t you love about the solutions you’ve tried?</li>
</ul>

<p>What they have already done helps us understand whether the problem is painful enough to build a product or feature for it.</p>

<p>Learn about their motivation: why do they want to solve it?</p>

<p>Avoid hypotheticals like: “If we build this, would you be willing to use it?”</p>

<h2 id="dig-into-interesting-answers">Dig into interesting answers</h2>

<p>Ask open-ended follow-up questions:</p>

<ul>
  <li>What do you mean by that?</li>
  <li>Can you tell me more about that?</li>
  <li>Why is that important to you?</li>
</ul>

<p>Dig into interesting and unexpected answers. Search for points where the business could fail.</p>

<p>Don’t ask:</p>

<ul>
  <li>Yes/no questions.</li>
  <li>“What would a better product look like to you?”</li>
  <li>Two questions at the same time.</li>
</ul>

<p>Focus on problems, not features! Users have no incentive to say no to features.</p>

<h2 id="dont-believe-everything-you-hear">Don’t believe everything you hear</h2>

<p>Three types of bad data:</p>

<ol>
  <li><strong>Compliments.</strong> You need facts and commitments. A good way to prevent compliments is not to talk about your idea at all.</li>
  <li><strong>Fluff.</strong> “I would do that.” “I might do that.” A good way to avoid fluff is to ask specifically about what they have already done.</li>
  <li><strong>Ideas.</strong> Don’t just follow their ideas. Dig into what is behind them: “What would that let you do?” “Why do you want that?” “Tell me more about what you’re thinking.”</li>
</ol>

<h2 id="after-people-use-your-product">After people use your product</h2>

<p>Once people are using your product, how can you measure product-market fit (PMF) quantitatively?</p>

<p>In <a href="https://review.firstround.com/how-superhuman-built-an-engine-to-find-product-market-fit/">Superhuman’s example</a>, they asked users how they would feel if they could no longer use the product:</p>

<ul>
  <li>A) Very disappointed</li>
  <li>B) Somewhat disappointed</li>
  <li>C) Not disappointed</li>
</ul>

<p>Measure the percentage who answer A. The benchmark is 40%: exceeding it is a signal of product-market fit, rather than a guarantee.</p>]]></content><author><name>Huijo</name></author><category term="Business" /><category term="Reading" /><summary type="html"><![CDATA[Interviewing customers again, from hexafarms to VOIDS, with more experience, preparation, and structure.]]></summary></entry><entry><title type="html">Continuous Discovery Habits</title><link href="https://www.huijo.xyz/ContinuousDiscoveryHabits/" rel="alternate" type="text/html" title="Continuous Discovery Habits" /><published>2026-08-18T00:00:00+00:00</published><updated>2026-08-18T00:00:00+00:00</updated><id>https://www.huijo.xyz/ContinuousDiscoveryHabits</id><content type="html" xml:base="https://www.huijo.xyz/ContinuousDiscoveryHabits/"><![CDATA[<p>Everything in your backlog is a “bet” whether we do discovery or not.
Discover helps us to make a better bet.</p>

<p>Product discovery: Decide why to build. Goal
Product delivery: Building it. Goal -&gt; Ship fast.</p>

<p>Define a clear desired outcome.
Outcome can be very abstract. i.e. reduce churn.
Discover opportunities to drive that desired outcome.
Opportunities are unmet customer needs, painpoints, and desires.
We interview to learn what people did in the past, we uncover the frictions, and we capture all in the opportunity space.
We need to develop the skill to dig in from the stories of users.
Discover solutions that deliver on those opportunities.</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                         ┌─────────────────┐
                         │ Desired Outcome │
                         └────────┬────────┘
                                  │
                                  ▼
                    ┌─────────────────────────┐
                    │ Discover Opportunities  │
                    │ through customer        │
                    │ interviews &amp; research   │
                    └───────────┬─────────────┘
                                │
                                ▼
                         ┌─────────────┐
                         │ Opportunity │
                         └──────┬──────┘
                                │
                    ┌───────────┼───────────┐
                    ▼           ▼           ▼
               ┌────────┐  ┌────────┐  ┌────────┐
               │Solution│  │Solution│  │Solution│
               └────┬───┘  └─────┬──┘  └──────┬─┘
                    └────────────┼────────────┘
                                 │
                                 ▼
                    ┌─────────────────────────┐
                    │ Prototype &amp; Experiment  │
                    └───────────┬─────────────┘
                                │
                                ▼
              ┌──────────────────────────────────┐
              │ Validate four questions:         │
              │                                  │
              │ 1. Is the opportunity a real     │
              │    pain, need, or desire?        │
              │                                  │
              │ 2. Does the solution address     │
              │    the opportunity?              │
              │                                  │
              │ 3. Is the solution usable and    │
              │    feasible?                     │
              │                                  │
              │ 4. Does the solution address     │
              │    the opportunity in a way that │
              │    drives the desired outcome?   │
              └────────────────┬─────────────────┘
                               │
                               ▼
                    ┌─────────────────────────┐
                    │     Learn + Iterate     │
                    │                         │
                    │ • Refine opportunities  │
                    │ • Refine solutions      │
                    │ • Refine understanding  │
                    │   of the outcome        │
                    └───────────┬─────────────┘
                                │
                                └──────────────► Repeat
</code></pre></div></div>

<p>Do not show solution and ask their opinions. It’s terrible, humans are nice, they will say nice things.
People are positive about future, so generally thinking they will use the feature/product.</p>

<p>Start asking: Tell me how you solved the issue with the product as not-designed, so give</p>]]></content><author><name>Huijo</name></author><category term="Reading" /><summary type="html"><![CDATA[Continuous Discovery Habits]]></summary></entry><entry><title type="html">How Modern LLMs Rebuilt Attention</title><link href="https://www.huijo.xyz/VariationOfMHA/" rel="alternate" type="text/html" title="How Modern LLMs Rebuilt Attention" /><published>2026-08-12T00:00:00+00:00</published><updated>2026-08-12T00:00:00+00:00</updated><id>https://www.huijo.xyz/VariationOfMHA</id><content type="html" xml:base="https://www.huijo.xyz/VariationOfMHA/"><![CDATA[<p>I firmly believe I’ve become a power user of AI/agents/LLMs (whatever we call them). Most of what I know about how these things behave comes from: trial and error, every day, at work and at home. 
Running the same prompt through models from different providers — and through different models from the <em>same</em> provider — slowly gave me a feel for the machinery underneath.</p>

<p>So this post is me going one level down. For each of the big architectural tricks of the last few years, I want to answer the same two questions: <strong>what is it, and which model actually shipped it?</strong> 
That second question matters more than it sounds, because for the closed models (OpenAI, Anthropic) we mostly can’t know — the open-weight releases are where the architecture is legible.</p>

<p>My learning and this writing based on <a href="https://www.amazon.de/dp/1633437167">Build a Large Language Model (From Scratch)</a>.
If my writing lits your interest, I highly recommend reading this book!</p>

<hr />

<h2 id="gqa--llama-23-qwen3-gemma-3">GQA — Llama 2/3, Qwen3, Gemma 3</h2>

<p>Grouped-Query Attention is the boring default now. If you pick an open-weight model at random today, it’s probably using GQA as a more compute- and parameter-efficient drop-in for Multi-Head Attention (MHA). It’s not new either — it goes back to the 2023 paper <a href="https://arxiv.org/abs/2305.13245">GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints</a>, and even the larger variants in the good old Llama 2 series used it.</p>

<p><img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/gqa-memory/1.webp?1" alt="GQA" /></p>

<p>Sharing keys and values reduces the total number of key and value computations, which leads to lower memory usage and improved efficiency.</p>

<p>So, to summarize, the core idea behind GQA is to reduce the number of key and value heads by sharing them across multiple query heads. This (1) lowers the model’s parameter count and (2) reduces the memory bandwidth usage for key and value tensors during inference, since fewer keys and values need to be stored and retrieved from the KV cache.</p>

<p>While GQA is mainly a computational-efficiency workaround for MHA, ablation studies (such as those in the <a href="https://arxiv.org/abs/2305.13245">original GQA paper</a> and the <a href="https://arxiv.org/abs/2307.09288">Llama 2 paper</a>) show it performs comparably to standard MHA in terms of LLM modeling performance.</p>

<p>However, this assumes the number of key-value groups is chosen carefully. In the extreme case where all attention heads share a single key-value group — known as multi-query attention — memory usage drops even more drastically, but modeling performance can suffer. And on the other extreme, if we set the number of key-value groups equal to the number of query heads, we’re back at standard multi-head attention.</p>

<blockquote>
  <p><strong>My take:</strong> GQA is the one on this list I never notice as a user, which is exactly the point — it’s a free lunch that everyone quietly took.</p>
</blockquote>

<hr />

<h2 id="mla--deepseek-v2-v3-r1">MLA — DeepSeek V2, V3, R1</h2>

<p>Multi-Head Latent Attention, used in <a href="https://arxiv.org/abs/2412.19437">DeepSeek V2, V3, and R1</a>, offers a different memory-saving strategy that also pairs particularly well with KV caching. Instead of sharing key and value heads like GQA, MLA compresses the key and value tensors into a lower-dimensional space before storing them in the KV cache.</p>

<p>At inference time, these compressed tensors are projected back to their original size before being used, as shown in the figure below. This adds an extra matrix multiplication but reduces memory usage.</p>

<p> </p>

<p><img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/mla-memory/1.webp" alt="MLA" /></p>

<p> </p>

<p>(As a side note, the queries are also compressed, but only during training, not inference.)</p>

<p> </p>

<p><img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/mla-memory/2.webp" alt="MHA vs GQA vs MLA modeling performance" width="500px" /></p>

<p> </p>

<p>As shown in the figure above, GQA appears to perform worse than MHA, whereas MLA offers <em>better</em> modeling performance than MHA — which is likely why the DeepSeek team chose MLA over GQA. (It would have been interesting to see the “KV Cache per Token” savings comparison between MLA and GQA as well.)</p>

<p>So: MLA is a clever trick to reduce KV cache memory use while even slightly outperforming MHA in terms of modeling performance. Not a tradeoff — a win on both axes.</p>

<blockquote>
  <p><strong>My take:</strong> this is the piece that made DeepSeek’s pricing make sense to me. When a provider is an order of magnitude cheaper per token on long inputs..</p>
</blockquote>

<hr />

<h2 id="swa--gemma-2-gemma-3">SWA — Gemma 2, Gemma 3</h2>

<p>What is sliding window attention (SWA)? If we think of regular self-attention as a <em>global</em> mechanism, since each sequence element can access every other sequence element, then SWA is <em>local</em> attention: we restrict the context size around the current query position. This is illustrated in the figure below.</p>

<p><img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/swa-memory/1.webp?2" alt="Sliding Window Attention" width="500px" /></p>

<p>Instead of attending to all previous tokens, each token only attends to a fixed-size local window around its position. This localized attention lowers the size of the KV cache substantially.</p>

<p>Sliding window attention was originally introduced in the <a href="https://arxiv.org/abs/2004.05150">LongFormer paper in 2020</a>, but the reason to focus on Google’s Gemma models is that they’re very good open-weight models showing that SWA is a genuinely feasible approach in recent, capable models — not just a research curiosity.</p>

<p><a href="https://arxiv.org/abs/2408.00118">Gemma 2</a> used a hybrid approach that combined local (sliding window) and global attention layers in a 1:1 ratio, with each token able to attend to a context window of 4k tokens. The reason for the 1:1 split is that it strikes a balance between efficiency and global context modeling — an LLM using <em>only</em> local attention can be too restrictive.</p>

<p><a href="https://arxiv.org/abs/2503.19786">Gemma 3</a> then pushed further toward efficiency: a 5:1 ratio between sliding window and full attention layers, meaning for every five local attention layers there’s one global layer. The window itself also shrank, from 4096 tokens in Gemma 2 to 1024 in Gemma 3.</p>

<blockquote>
  <p><strong>My take:</strong> One global layer holding the line for five local ones suggests most attention work really is local, and that most of the quadratic cost we pay is insurance.</p>
</blockquote>

<hr />

<h2 id="moe--deepseek-v3-qwen3-moe">MoE — DeepSeek-V3, Qwen3-MoE</h2>

<p>Mixture-of-Experts is the odd one out here: it isn’t an attention variant at all, it’s a feed-forward variant. The core idea is to replace each feed-forward module in a transformer block with multiple expert layers, where each expert is itself a feed-forward module. So one feed-forward block becomes many, as illustrated below.</p>

<p> </p>

<p><img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/moe-memory/1.webp" alt="Mixture-of-Experts feed-forward module" width="800px" /></p>

<p>When DeepSeek rattled the stock market in early 2025, a lot of the media described MoE as a panel of specialist AIs conferring with each other — a coding AI, a medical AI, a math AI, voting on an answer. Look at the figure again: an “expert” is a feed-forward network. That’s it. The router is a small learned gate that picks which of those blocks to run for this one token, and whatever specialization exists is whatever training nudged into them — nobody assigned job titles.</p>

<p>Because only a few experts are active at a time, MoE modules are often called <em>sparse</em>, in contrast to <em>dense</em> modules that always use the full parameter set. The large total parameter count increases the capacity of the LLM — it can absorb more knowledge during training — while the sparsity keeps inference efficient, since we don’t use all the parameters at once.</p>

<p>For example, DeepSeek-V3 has 256 experts per MoE module and 671 billion parameters in total. Yet during inference, only 9 experts are active at a time (1 shared expert plus 8 selected by the router). That’s just 37 billion parameters per token inference step instead of all 671 billion.</p>

<p>One notable feature of DeepSeek-V3’s MoE design is the <strong>shared expert</strong>: an expert that is always active for every token. The idea isn’t new — it was already introduced in the <a href="https://arxiv.org/abs/2201.05596">2022 DeepSpeed-MoE</a> and <a href="https://arxiv.org/abs/2401.06066">2024 DeepSeek MoE</a> papers.</p>

<p> </p>

<p><img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/moe-memory/3.webp?1" alt="MoE shared expert" width="500px" /></p>

<p>(An annotated figure from the <a href="https://arxiv.org/abs/2401.06066">DeepSeekMoE: Towards Ultimate Expert Specialization in Mixture-of-Experts Language Models</a> paper.)</p>

<p> </p>

<p>The benefit of a shared expert was first noted in the <a href="https://arxiv.org/abs/2201.05596">DeepSpeed-MoE paper</a>, where they found it boosts overall modeling performance compared to having no shared expert. The likely reason: common or repeated patterns don’t have to be relearned by every individual expert, which leaves each of them more room for specialized patterns.</p>

<blockquote>
  <p><strong>My take:</strong> What MoE really breaks is the assumption that capacity and compute are the same quantity. the shared expert is the honest admission that some of it isn’t.</p>
</blockquote>

<hr />

<h2 id="gated-deltanet--qwen3-next-kimi-linear">Gated DeltaNet — Qwen3-Next, Kimi Linear</h2>

<p>Recently, <a href="https://qwen.ai/blog?id=4074cca80393150c248e508aa62983f9cb7d27cd&amp;from=research.latest-advancements-list">Qwen3-Next</a> and <a href="https://arxiv.org/abs/2510.26692">Kimi Linear</a> proposed hybrid transformers that swap in alternatives to the attention mechanism which scale <em>linearly</em> instead of quadratically with context length.</p>

<p>Both use a 3:1 ratio: for every three transformer blocks employing the linear Gated DeltaNet variant, there’s one block using full attention, as shown in the figure below.</p>

<p>So what is Gated DeltaNet? It’s short for <em>Gated Delta Network</em>, Qwen3-Next’s linear-attention layer, intended as an alternative to standard softmax attention. It was adopted from the <a href="https://arxiv.org/abs/2412.06464">Gated Delta Networks: Improving Mamba2 with Delta Rule</a> paper.</p>

<p>Gated DeltaNet was originally proposed as an improved version of Mamba2, combining Mamba2’s gated decay mechanism with a delta rule. Mamba itself is a state-space model — an alternative to transformers, and a big enough topic that it deserves its own post someday.</p>

<p>The “delta rule” part refers to computing the difference (delta, Δ) between new and predicted values to update a hidden state that’s used as a memory state.</p>

<p><img src="https://sebastianraschka.com/images/LLMs-from-scratch-images/bonus/gated_deltanet/01.webp" alt="Qwen3-Next versus Kimi Linear" /></p>

<blockquote>
  <p><strong>My take:</strong> I’ve been following Mamba for years as <em>the</em> candidate to replace the transformer, and for most of that time state-space models were fascinating but never quite competitive. So the recent wow moment — these models landing in the same conversation as the state-of-the-art from OpenAI and Anthropic — is genuinely satisfying to watch. What I didn’t expect is <em>how</em> they got there: not by winning the argument, but by refusing to have it. Three linear blocks, one full-attention block, both mechanisms in the same stack. And notice the pattern repeating from Gemma — nobody is willing to drop quadratic attention entirely. Whatever those few full layers are doing, it isn’t replaceable yet.</p>
</blockquote>

<hr />

<h2 id="dsa--deepseek-v32">DSA — DeepSeek V3.2</h2>

<p>The DeepSeek-V3.2 model uses Multi-Head Latent Attention <em>alongside</em> DeepSeek Sparse Attention (DSA), with the indexer queries derived from the shared compressed latent representation rather than the raw input. Two techniques from this post, stacked.</p>

<p>What’s DSA? In one line: a cheap learned dot-product scorer that limits each query to the most relevant tokens before the attention softmax.</p>

<p>Standard causal self-attention attends to all previous tokens for each query, yielding O(L²) compute and O(L) KV-cache growth with sequence length L. Sliding Window Attention already showed above that restricting attention to a fixed local window substantially reduces this cost — in SWA, each query token attends only to a local span of nearby previous tokens.</p>

<p>DSA uses the same broad idea of attending to only a subset of previous tokens, but it replaces the <em>fixed</em> window with a <em>learned</em> selection mechanism. For each query token, the model scores candidate past tokens and keeps only the most relevant ones.</p>

<p> </p>

<p><img src="https://sebastianraschka.com/images/blog/2025/technical-deepseek/10.png" alt="DeepSeek Sparse Attention selected-token pattern" width="800px" /></p>

<p><em>DeepSeek Sparse Attention selects a learned subset of past tokens for each query token.</em></p>

<p>DSA adds two components on top of standard attention.</p>

<p><strong>1. Lightning Indexer</strong></p>

<p>For each query token $t$ and every candidate past token $s$, the indexer computes a scalar relevance score. This implementation makes the scale factors from the reference code explicit:</p>

\[I_{t,s} = \sum_{j=1}^{H_I} \frac{w_{t,j}}{\sqrt{H_I}} \cdot \text{ReLU}\left(\frac{q_{t,j} \cdot k_s}{\sqrt{d_I}}\right)\]

<p>where:</p>
<ul>
  <li>$H_I$ is the number of lightweight index heads,</li>
  <li>$q_{t,j}$ is the indexer query vector for token $t$ and head $j$,</li>
  <li>$k_s$ is a shared indexer key vector for past token $s$,</li>
  <li>$w_{t,j}$ is a learned per-head gate scaled by $1 / \sqrt{H_I}$.</li>
</ul>

<p>The ReLU zeroes out negative dot-product contributions, and the gated sum aggregates across index heads into a single relevance score per past token.</p>

<p><strong>2. Token Selector</strong></p>

<p>After computing all indexer scores, only the top-K highest-scoring positions are kept. All other positions are masked to −∞ <em>before</em> the standard softmax, so the model effectively attends to only $k \ll L$ tokens.</p>

<p>The ReLU in the indexer is not where the final sparsity comes from. Since the scores are summed over multiple index heads, most final scores can still be nonzero. The token selector is what creates the sparse pattern, by keeping only the top-K positions.</p>

<p>In a fused production implementation, this can lower attention compute from O(L²) to O(L·k). The book’s reference implementation keeps the standard dense attention score matrix and applies the DSA-selected top-K mask before softmax — which makes the selection logic easy to inspect, but doesn’t deliver the fused-kernel compute savings.</p>

<p>The figure below summarizes the flow: the lightning indexer scores candidate tokens, the selector keeps top-K positions, and the resulting mask restricts the usual attention softmax.</p>

<p> </p>

<p><img src="https://sebastianraschka.com/images/blog/2025/technical-deepseek/11.png" alt="DeepSeek Sparse Attention flowchart" width="700px" /></p>

<p><em>DSA first scores candidate tokens, then keeps the top-K tokens for the final attention mask.</em></p>

<blockquote>
  <p><strong>My take:</strong> SWA guesses that relevance is nearby; DSA learns where relevance actually is — the more honest bet for long documents, where the token you need is often thousands of positions back. What struck me most is how much this resembles sparse retrieval in RAG: the lightning indexer is a cheap first-stage scorer over every candidate, top-K is the retrieval cutoff, and the expensive attention only ever sees the shortlist. Same two-stage shape I keep building <em>around</em> models with a retriever and a reranker — except here it lives inside the model and gets trained end to end instead of bolted on outside.</p>
</blockquote>

<hr />

<h2 id="cross-layer-kv-sharing--gemma-4-e2b-e4b">Cross-layer KV sharing — Gemma 4 E2B, E4B</h2>

<p>We discussed GQA above, where several query heads share the same key and value heads. Cross-layer KV sharing applies a related idea <em>across transformer layers</em> instead of within one.</p>

<p>Instead of computing a fresh key and value projection in every layer, later layers reuse K/V tensors from an earlier layer. They still compute their own queries, so each layer can form its own attention pattern. The main memory saving comes from storing fewer K/V tensors in the cache.</p>

<p>This idea is also called cross-layer attention, and it’s described in Brandon <em>et al.</em>, <a href="https://arxiv.org/abs/2405.12981">Reducing Transformer Key-Value Cache Size with Cross-Layer Attention</a>. Gemma 4 E2B and E4B use a related shared KV-cache scheme, which makes it a natural addition to the GQA, MLA, and SWA techniques above.</p>

<p> </p>

<p><img src="https://raw.githubusercontent.com/rasbt/LLMs-from-scratch/main/ch04/10_kv-sharing/gemma4-kv-sharing.webp" alt="Cross-layer KV sharing" width="800px" /></p>

<p> </p>

<p>In <a href="https://github.com/rasbt/LLMs-from-scratch/tree/main/ch05/17_gemma4">Gemma 4</a>, KV sharing is combined with GQA or MQA <em>and</em> sliding window attention — three of the techniques from this post in one model. The book’s simplified GPT example implements only the cross-layer KV-sharing part, so the code stays focused on the main mechanism.</p>

<p>The simplified rule it uses is:</p>

<ol>
  <li>Early layers compute and cache their own K/V tensors.</li>
  <li>Later layers reuse the most recent K/V tensors from an earlier producing layer.</li>
  <li>All layers still compute their own query projections.</li>
</ol>

<p>This reduces the number of K/V caches that grow with context length. The tradeoff is reduced model capacity, because some layers no longer get their own K/V projections.</p>

<blockquote>
  <p><strong>My take:</strong> stacking GQA + MQA + SWA + cross-layer sharing in one model tells you these tricks are mostly orthogonal — each attacks a different axis of the same cache. Which also means the next efficiency jump probably won’t come from one clever idea, but from someone stacking a fourth.</p>
</blockquote>]]></content><author><name>Huijo</name></author><category term="Machine Learning" /><category term="Reading" /><summary type="html"><![CDATA[GQA, MLA, SWA, MoE, Gated DeltaNet, DSA, KV sharing — and which model actually ships each one.]]></summary></entry><entry><title type="html">AI is everywhere, even in interview</title><link href="https://www.huijo.xyz/AIInInterview/" rel="alternate" type="text/html" title="AI is everywhere, even in interview" /><published>2026-08-11T00:00:00+00:00</published><updated>2026-08-11T00:00:00+00:00</updated><id>https://www.huijo.xyz/AIInInterview</id><content type="html" xml:base="https://www.huijo.xyz/AIInInterview/"><![CDATA[<p>In our everyday life, use of AI has become the new normal.
I heavily use AI in personal life as well as professionally, so it plays a very close role in my life.
However, I notice that as its usage becomes prevalent, some people can’t stop using it.
Here’s the story I just faced TODAY.</p>

<p>In my work, I have been interviewing for a potential teammate.
As this position carries technical responsibility (data engineer), it’s required to utilize AI during the technical interview.
The <strong>live</strong> technical assignment I use has both an AI-supported programming task and an AI-prohibited algorithmic task.
As I highlighted <strong>live</strong>, it’s expected to be impossible to cheat.
However, it happened today: so-called AI-cheating, in person.</p>

<p>As I wanted to assess how the candidate utilizes AI, I started with the AI-assisted problem-solving case.
The candidate had prepared a repository claiming to have helper functions.
I consider this a positive sign, as the candidate had prepared something for this interview.</p>

<p>The candidate starts writing a prompt, and I ask what the intention behind it is.
The candidate writes a prompt full of comprehensive keywords. Okay, it’s a good sign.
It looks a bit unnatural, injecting only keywords, but okay, maybe the candidate is considering how token embedding works by focusing on keywords.</p>

<p>Initially, the candidate couldn’t understand the purpose of the problem; however, in a short time, the candidate provided better context.
I regarded this as fast learning from the problem. Okay, it’s a good sign.</p>

<p>The issue starts with the non-AI-assisted case.
I offered a short 2-minute restroom break before the next phase.
A brief breath of fresh air, then on to the next task.
The candidate read through the problem in detail and understood the case very well.
I heard a few typing sounds, so my suspicion started, but I let the candidate continue.
First, I didn’t want to offend the candidate. Second, if it’s cheating, it’s better to detect it than to give a chance to stop.
It’s better because cheating during an interview means any serious cheating could happen once working together.</p>

<p>Anyhow, the candidate completed the interview quite well. A bit of guidance and support from me as an interviewer was provided, but it was well done. Okay, it’s a good sign.
Time to work on the next problem.
Again, it’s supposed to be a non-AI-assisted problem.
This time, I was sitting next to the candidate, discussing how to solve it.
The brilliant candidate becomes silent.
Nothing progressed, for one reason only: I’m next to the candidate.
Suddenly, a Claude Code artifact pops up during the interview.
Okay, it’s apparent that another agent session is running in parallel with the non-AI-assisted challenge.
Initially, the candidate switches the tab, but when I ask to open it, the candidate is speechless.</p>

<p>I gently ask the candidate to open the running terminal.
It has the whole history of cheating.
Interesting.
The candidate’s brilliant answers in all phases came from this.
The session shows <code class="language-plaintext highlighter-rouge">/rc</code>, which means remote control of the session.
Not 100% sure, but it’s suspicious that the candidate could read the non-AI-assisted problems’ content through the Claude Code app.
The excuse for cheating is apparently: “it’s for my personal learning, I don’t cheat.”
Okay, it’s expected. A quick acknowledgment and apology would have been ideal at the end of this.
However, it’s hard to admit. Denial is easy.</p>

<p>So, what’s my take?
People get dumber by delegating <strong>thinking</strong> to AI.
It’s a great channel to explore knowledge and sharpen ideas.
However, as soon as we give up thinking for ourselves, it becomes a counterproductive tool.
It is easy to make fun of others, but I should observe myself to see if I do the same.</p>]]></content><author><name>Huijo</name></author><category term="Agents" /><category term="Decision-Making" /><summary type="html"><![CDATA[It is expected to use AI in the technical interview, but it is even used when not allowed.]]></summary></entry><entry><title type="html">Attention has four matrices, not three</title><link href="https://www.huijo.xyz/AttentionHasFourMatrices/" rel="alternate" type="text/html" title="Attention has four matrices, not three" /><published>2026-08-02T00:00:00+00:00</published><updated>2026-08-02T00:00:00+00:00</updated><id>https://www.huijo.xyz/AttentionHasFourMatrices</id><content type="html" xml:base="https://www.huijo.xyz/AttentionHasFourMatrices/"><![CDATA[<p>In 2022 I wrote a paper review of <em>Attention Is All You Need</em>. Rereading it, I find one sentence carrying the whole explanation:</p>

<blockquote>
  <p>An attention function can be described as mapping a query and a set of key-value pairs to an output.</p>
</blockquote>

<p>The sentence is the paper’s own and it is accurate. It also explains nothing. It does not say why there are three projections instead of one, what each of them costs when the model is served, or which claims about attention maps survive scrutiny.</p>

<p>This post covers what I skipped. It also corrects the name. We say Q, K, V. The mechanism has four weight matrices and two circuits, and the one the name omits is tied for the largest.</p>

<h2 id="1-the-same-input-different-weights">1. The same input, different weights</h2>

<p>In self-attention, Q, K and V are not three pieces of information about a token. They are one vector passed through three learned matrices.</p>

\[q = xW_Q, \qquad k = xW_K, \qquad v = xW_V\]

<p>Here $x$ is one row of the residual stream, the token’s current representation at this layer. Nothing else enters. No extra data is fetched and no side channel is read. The three outputs differ only because the weights differ.</p>

<p>That changes where to look when you want to know what a head does. The answer is in the matrices, not in the token.</p>

<p>The mechanism built on them is one line:</p>

\[\mathrm{Attention}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V\]

<p>The $\sqrt{d_k}$ divisor is a gradient fix. I used to read it as a normalisation of similarity, which it is not. The paper’s reason is that for large $d_k$, “the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients.”</p>

<h2 id="2-q-and-k-need-separate-matrices">2. Q and K need separate matrices</h2>

<p>If Q and K are both $x$ times a weight, why not use one weight and halve the parameters? The roles already differ by position, since $i$ asks and $j$ is asked.</p>

<p>Set $W_Q = W_K = W$ and the score becomes:</p>

\[\mathrm{score}(i,j) = x_i W W^\top x_j^\top\]

<p>Swapping $i$ and $j$ gives the same number. The affinity matrix is forced symmetric.</p>

<p>The easy version of this argument overstates what that means, and I nearly published it. Symmetric scores are not symmetric attention weights. Softmax normalises row by row, and under a causal mask each row sums over a different set of positions, so $\alpha_{ij}$ and $\alpha_{ji}$ differ either way. What a shared matrix removes is the freedom to set the two affinities independently.</p>

<p>It removes more than symmetry. $WW^\top$ is positive semi-definite, so the diagonal is pinned at $\mathrm{score}(i,i) = \lVert x_i W \rVert^2 \ge 0$, and Cauchy-Schwarz gives:</p>

\[\mathrm{score}(i,j) \le \frac{1}{2}\left(\mathrm{score}(i,i) + \mathrm{score}(j,j)\right)\]

<p>No token can score another above its own self-score unless that other token has a much larger projected norm. A head built on a shared matrix is biased toward attending to itself, which is a poor property for a mechanism whose job is moving information between positions.</p>

<p>Two matrices give a general bilinear form:</p>

\[\mathrm{score}(i,j) = x_i W_Q W_K^\top x_j^\top\]

<p>$W_Q W_K^\top$ carries no symmetry constraint and no definiteness constraint. The relation it encodes is directed, and a token is free to find itself uninteresting. Q is what a position looks for. K is what a position offers as a match target. Both come from the same $x$, so a token’s search and its findability are separate learned functions of identical input.</p>

<p>Those two results are derivations rather than citations. I am not quoting anyone here, and the algebra is short enough to check.</p>

<h2 id="3-what-v-adds-that-k-does-not">3. What V adds that K does not</h2>

<p>The third matrix asks a third question: what gets handed over once a match happens.</p>

<p>K decides how a token gets found. V decides what it contributes. Separating the two lets a token be a strong match target while contributing something unrelated to its own identity.</p>

<p>I held two wrong ideas here until recently, and I suspect they are common.</p>

<p>The first was that V holds the token’s content and must therefore be wider than K. It is not wider. The paper introduces “queries and keys of dimension $d_k$, and values of dimension $d_v$”, which allows them to differ, then sets $d_k = d_v = d_{model}/h = 64$. Standard implementations follow.</p>

<p>The second was that V is the token’s data. It is a learned projection. Nothing requires $v_j = x_j W_V$ to resemble token $j$ at all. That assumption is what makes “the head copies the token” feel true when it usually is not.</p>

<h2 id="4-the-matrix-the-name-leaves-out">4. The matrix the name leaves out</h2>

<p>After the $h$ heads each produce a $d_{head}$-wide result, the paper concatenates them and projects back to model width:</p>

\[\mathrm{MultiHead}(Q,K,V) = \mathrm{Concat}(\mathrm{head}_1, \ldots, \mathrm{head}_h)\, W_O\]

<p>$W_O$ is the fourth matrix. In Llama 2 70B it ties with $W_Q$ as the largest of the four, and the Q, K, V name gives it no billing.</p>

<p>Block matrix multiplication makes concatenate-then-project identical to each head owning its own slice of $W_O$:</p>

\[\mathrm{Concat}(h_1 \ldots h_h)\, W_O = \sum_i h_i W_O^{(i)}\]

<p>with each $W_O^{(i)}$ of shape $d_{head} \times d_{model}$. The concatenation is notation. The structure underneath is per-head and additive, which is why Anthropic’s circuits framework describes heads as “independent operations, each outputting a result which is added into the residual stream”, and why an individual head can be attributed, ablated, or pruned at all.</p>

<p>The ordering matters. $W_V$ maps a source token down into the head’s private $d_{head}$ subspace. $W_O$ maps that payload back up into $d_{model}$ and chooses which directions of the residual stream the head writes into.</p>

<p>V on its own is not in the residual basis. In Llama 2 70B it is 128 numbers in a subspace no other layer reads. $W_O$ is what makes them legible. So what a head writes is $W_O W_V x$, never V alone.</p>

<h2 id="5-four-matrices-two-circuits">5. Four matrices, two circuits</h2>

<p>The four matrices pair up. Anthropic’s circuits framework splits a head into a QK circuit that computes the attention pattern and an OV circuit that computes how each token affects the output if attended to.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                    x  (residual stream)
                    |
        +-----------+-----------+
        |           |           |
      x W_Q       x W_K       x W_V
        |           |           |
        q           k           v
        |           |           |
        +-----+-----+           x W_O
              |                  |
          QK circuit         OV circuit
         W_Q W_K^T            W_O W_V
       "where to look"     "what to write"
</code></pre></div></div>

<p>Every claim about an attention head is one of two kinds, and the two need different evidence.</p>

<table>
  <thead>
    <tr>
      <th>Claim type</th>
      <th>Example</th>
      <th>Evidence required</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>QK</td>
      <td>“This head attends from a pronoun to its antecedent”</td>
      <td>The attention pattern</td>
    </tr>
    <tr>
      <td>OV</td>
      <td>“This head copies the subject forward”</td>
      <td>Measured effect on the output</td>
    </tr>
  </tbody>
</table>

<p>Conflating them is a common failure in writing about attention. “This head handles negation” is two claims stacked: the head finds the negation token, which is QK, and what it writes flips something downstream, which is OV. An attention map supports the first claim only.</p>

<h2 id="6-the-two-circuits-get-equal-budgets">6. The two circuits get equal budgets</h2>

<p>I assumed the value path must be the smaller one, since Q, K, V reads like three peers and $W_V$ is one of them. Then I looked at a real configuration. Llama 2 70B uses <code>hidden_size 8192</code>, <code>num_attention_heads 64</code>, and <code>num_key_value_heads 8</code>, so $d_{head}$ is 128.</p>

<table>
  <thead>
    <tr>
      <th>Matrix</th>
      <th>Shape</th>
      <th>Parameters</th>
      <th>Path</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>$W_Q$</td>
      <td>8192 x 8192</td>
      <td>67.1M</td>
      <td>QK</td>
    </tr>
    <tr>
      <td>$W_K$</td>
      <td>8192 x 1024</td>
      <td>8.4M</td>
      <td>QK</td>
    </tr>
    <tr>
      <td>$W_V$</td>
      <td>8192 x 1024</td>
      <td>8.4M</td>
      <td>OV</td>
    </tr>
    <tr>
      <td>$W_O$</td>
      <td>8192 x 8192</td>
      <td>67.1M</td>
      <td>OV</td>
    </tr>
  </tbody>
</table>

<p>$W_V$ is one eighth the size of $W_Q$. That is grouped-query attention, which I come back to below. The paths still add up to the same total:</p>

\[W_Q + W_K = 75.5\text{M} = W_V + W_O\]

<p>Each path is one wide matrix paired with one narrow one, mirrored. It holds under plain multi-head attention too, where all four are $d_{model} \times d_{model}$. Per head, both circuits are $d_{model} \times d_{model}$ maps of rank at most $d_{head}$.</p>

<p>The architecture spends the same on where to look and on what to write. Nothing in it treats the content path as needing more capacity.</p>

<h2 id="7-only-two-of-the-four-cost-anything-at-inference">7. Only two of the four cost anything at inference</h2>

<p>The four are symmetric in budget and completely asymmetric in behaviour during generation.</p>

<p>In a decoder-only model the causal mask means position $t$ attends only to positions up to $t$. So $x_j$ at every layer depends only on tokens up to $j$. Append a token and nothing about position 3 changes, at any depth. Its $k$ and $v$ are frozen the moment it is in the past. Its $q$ is dead weight, because position 3 already did its lookup and will never repeat it.</p>

<p>That is the derivation of the KV cache. K and V are stored because they are re-read at every future step. Q is discarded because it is used once. Causality does the work here rather than the naming. In a bidirectional encoder, deeper-layer keys for past positions do change when a token is appended, because the layers below attended to it, and caching would be invalid.</p>

<p>The cost of what is kept:</p>

\[\text{KV bytes} \approx 2 \cdot n_{layers} \cdot n_{kv} \cdot d_{head} \cdot \text{seq len} \cdot \text{batch} \cdot \text{bytes}\]

<p>Q does not appear in it. Neither does $W_O$. Only two of the four matrices produce anything that has to be stored.</p>

<p>Storing it is the bottleneck. Training parallelises across the sequence and incremental decoding cannot. Shazeer’s multi-query attention paper puts it plainly: decoding is “often slow, due to the memory-bandwidth cost of repeatedly loading the large ‘keys’ and ‘values’ tensors.” The constraint is moving the cache rather than arithmetic.</p>

<p>That formula has exactly one term an architect can cut without touching depth, width, or context length, and it is $n_{kv}$. Multi-query attention sets it to 1. Grouped-query attention sets it to some $g$ between 1 and $h$, using “an intermediate (more than one, less than number of query heads) number of key-value heads” to reach “quality close to multi-head attention with comparable speed to MQA.” Llama 2’s 34B and 70B use it, with 8 key-value heads against 64 query heads.</p>

<p>Query heads stay at $h$ in all three variants. That is why $W_V$ is eight times smaller than $W_Q$ in the table above.</p>

<p>Sharing keys and values does not collapse the heads. Eight query heads over two key-value heads still produce eight distinct attention patterns, because $W_Q$ differs per head even where $W_K$ is shared. What grouped-query attention gives up is memory, not the diversity that multi-head exists for.</p>

<h2 id="8-heads-partition-the-model-they-do-not-add-to-it">8. Heads partition the model, they do not add to it</h2>

<p>Multi-head attention does not widen the layer.</p>

<p>The original model uses $h = 8$ with $d_k = d_v = d_{model}/h = 64$ and $d_{model} = 512$. Eight heads is 512 divided eight ways, not eight copies of 512. The paper is explicit that “due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.”</p>

<p>At fixed $d_{model}$, adding heads is a trade rather than an upgrade. You get more simultaneous lookups, each in a narrower subspace.</p>

<p>What the trade buys is stated in one sentence: multi-head attention “allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.” The operative word is averaging. One softmax produces one distribution per position, and a position usually needs several unrelated things at once, such as its syntactic parent, its antecedent, the previous token, and the matching bracket. One distribution cannot peak in four places without smearing.</p>

<p>Whether all those heads earn their place is a separate question, and the evidence has a boundary I have to mark. Voita et al. pruned 38 of 48 encoder heads on an English to Russian WMT model for a drop of 0.15 BLEU, and found that “the most important and confident heads play consistent and often linguistically-interpretable roles” and prune last. Michel et al. found many heads removable at test time, with some layers reduced to a single head.</p>

<p>Both studies used 2019-era encoder-decoder NMT models and BERT. Neither says anything direct about a modern decoder-only LLM at scale. “Most heads in GPT-class models are redundant” gets repeated constantly and does not follow from these papers. I am not making that claim.</p>

<h2 id="9-what-an-attention-map-cannot-tell-you">9. What an attention map cannot tell you</h2>

<p>The tempting move with all of this is to screenshot a heatmap and point at the bright cell.</p>

<p>The mechanical reason not to comes straight out of the two circuits. An attention map is a QK object. It records where a head looked. It never contains V or $W_O$, so it cannot record what the head wrote. The contribution of a source token is $\alpha_{ij} W_O W_V x_j$, and if that lands near zero, or in directions no downstream layer reads, a large $\alpha_{ij}$ moves nothing. Per head that map has rank at most 128 out of 8192 dimensions, which leaves room to write nothing at all.</p>

<p>The empirical literature agrees and remains unresolved. Jain and Wallace found attention weights “frequently uncorrelated with gradient-based measures of feature importance”, with very different attention distributions producing equivalent predictions. Wiegreffe and Pinter replied that the conclusion depends on the definition of explanation, and proposed four concrete tests. Cite both or neither.</p>

<p>There is also the blunt fact of attention sinks. Models assign strong attention to initial tokens “even if they are not semantically important.” A head putting 0.6 of its mass on token 0 is usually reporting nothing.</p>

<p>The position I would defend is neither that attention maps explain the model nor that they are meaningless. They are QK evidence. They constrain where a head looked, and any claim about what it did needs the other circuit.</p>

<h2 id="what-i-check-now">What I check now</h2>

<table>
  <thead>
    <tr>
      <th>Matrix</th>
      <th>Computed from</th>
      <th>Role</th>
      <th>Cached at decode</th>
      <th>Shrinks under GQA</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>$W_Q$</td>
      <td>$x$</td>
      <td>What this position seeks</td>
      <td>No, used once</td>
      <td>No</td>
    </tr>
    <tr>
      <td>$W_K$</td>
      <td>$x$</td>
      <td>What this position offers</td>
      <td>Yes</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>$W_V$</td>
      <td>$x$</td>
      <td>What it hands over</td>
      <td>Yes</td>
      <td>Yes</td>
    </tr>
    <tr>
      <td>$W_O$</td>
      <td>head output</td>
      <td>Where it writes in the residual stream</td>
      <td>Not applicable</td>
      <td>No</td>
    </tr>
  </tbody>
</table>

<p>The first three take the same input. Different weights give them different jobs, different lifetimes, and different bills.</p>

<p>Reading an attention implementation now, I check four things: which of the four matrices are shared across heads, which of them are cached, what rank each circuit has, and whether a claim being made about a head is QK or OV. My 2022 post said that attention maps a query and a set of key-value pairs to an output. That is still true. The difference is that I can now say what each of those words costs.</p>

<h2 id="references">References</h2>

<ul>
  <li>Vaswani et al., <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em></a>.</li>
  <li>Elhage et al., <a href="https://transformer-circuits.pub/2021/framework/index.html"><em>A Mathematical Framework for Transformer Circuits</em></a>.</li>
  <li>Shazeer, <a href="https://arxiv.org/abs/1911.02150"><em>Fast Transformer Decoding: One Write-Head is All You Need</em></a>.</li>
  <li>Ainslie et al., <a href="https://aclanthology.org/2023.emnlp-main.298/"><em>GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints</em></a>.</li>
  <li>Touvron et al., <a href="https://arxiv.org/abs/2307.09288"><em>Llama 2: Open Foundation and Fine-Tuned Chat Models</em></a>.</li>
  <li>Voita et al., <a href="https://aclanthology.org/P19-1580/"><em>Analyzing Multi-Head Self-Attention: Specialized Heads Do the Heavy Lifting, the Rest Can Be Pruned</em></a>.</li>
  <li>Michel et al., <a href="https://proceedings.neurips.cc/paper_files/paper/2019/file/2c601ad9d2ff9bc8b282670cdd54f69f-Paper.pdf"><em>Are Sixteen Heads Really Better than One?</em></a>.</li>
  <li>Jain and Wallace, <a href="https://aclanthology.org/N19-1357/"><em>Attention is not Explanation</em></a>.</li>
  <li>Wiegreffe and Pinter, <a href="https://aclanthology.org/D19-1002/"><em>Attention is not not Explanation</em></a>.</li>
  <li>Xiao et al., <a href="https://arxiv.org/abs/2309.17453"><em>Efficient Streaming Language Models with Attention Sinks</em></a>.</li>
  <li>3Blue1Brown, <a href="https://www.3blue1brown.com/lessons/attention/"><em>Attention in transformers, step-by-step</em></a>.</li>
</ul>]]></content><author><name>Huijo</name></author><category term="Machine Learning" /><category term="Engineering" /><summary type="html"><![CDATA[Q, K, V, and the output projection the name leaves out. What each weight does to the same input, and why the differences between them decide what an inference server has to cache.]]></summary></entry><entry><title type="html">What’s inside that token? JWT explained with a boarding pass</title><link href="https://www.huijo.xyz/JWTForMCP/" rel="alternate" type="text/html" title="What’s inside that token? JWT explained with a boarding pass" /><published>2026-07-30T00:00:00+00:00</published><updated>2026-07-30T00:00:00+00:00</updated><id>https://www.huijo.xyz/JWTForMCP</id><content type="html" xml:base="https://www.huijo.xyz/JWTForMCP/"><![CDATA[<p>I recently built an OAuth 2.0 server using <a href="https://www.keycloak.org/">Keycloak</a> so that our MCP (Model Context Protocol) tools can check <em>who</em> is calling them and <em>what</em> that caller is allowed to do. The heart of that system is a small piece of text called a <strong>JWT</strong> (JSON Web Token, pronounced “jot”).</p>

<p>This post explains what a JWT is, what it carries, and how you can put your own information inside it — like which environment (prod or dev), which customer, and which exact permissions a caller has. No security background needed.</p>

<h2 id="the-boarding-pass-analogy">The boarding pass analogy</h2>

<p>A JWT is a boarding pass for software.</p>

<p>When you fly, you first go to the check-in counter, prove who you are with your passport, and receive a boarding pass. From then on, nobody at the gate calls the check-in counter to ask “is this person really allowed on this flight?” They just look at the pass. It says who you are, which flight you may board, which seat class you get, and it has security features so nobody can forge it.</p>

<p>The same flow happens in our system:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> You (or an AI agent)          Keycloak                 MCP server
        |                  (check-in counter)         (boarding gate)
        |                          |                        |
        |--- 1. "Here is my  -----&gt;|                        |
        |     username/password"   |                        |
        |                          |                        |
        |&lt;-- 2. Boarding pass -----|                        |
        |     (the JWT)            |                        |
        |                          |                        |
        |--- 3. "I want to read the database. Here is -----&gt;|
        |        my JWT."                                   |
        |                                                   |
        |&lt;-- 4. Gate checks the pass. Valid? Come in. ------|
</code></pre></div></div>

<p>Keycloak is the check-in counter: it verifies your identity once and hands you a signed pass. The MCP server is the gate: it never needs to see your password. It only reads the pass and checks the security seal.</p>

<h2 id="a-jwt-has-three-parts">A JWT has three parts</h2>

<p>If you look at a raw JWT it seems like gibberish:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>eyJhbGciOi...  .  eyJpc3MiOi...  .  SflKxwRJSM...
   HEADER            PAYLOAD          SIGNATURE
</code></pre></div></div>

<p>Three chunks of text separated by dots. Each has one job:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>+----------------------------------------------------------+
|  HEADER      "What kind of pass is this?"                 |
|              e.g. { "alg": "RS256", "typ": "JWT" }        |
|              (which sealing method was used)              |
+----------------------------------------------------------+
|  PAYLOAD     "The actual facts" (called *claims*)         |
|              who you are, who issued it, what you may do  |
+----------------------------------------------------------+
|  SIGNATURE   "The tamper-proof seal"                      |
|              proves Keycloak wrote it and nobody          |
|              changed a single letter afterwards           |
+----------------------------------------------------------+
</code></pre></div></div>

<p>One thing surprises everyone: <strong>the payload is not encrypted.</strong> Anyone who holds the token can read it, just like anyone who picks up your boarding pass can read your name and seat. What they <em>cannot</em> do is change it — if even one letter of the payload is altered, the signature no longer matches and the gate rejects the pass. So the rule is simple:</p>

<blockquote>
  <p>Put facts in a JWT, never secrets. Names, roles, permissions: yes. Passwords, API keys: never.</p>
</blockquote>

<h2 id="the-facts-inside-claims">The facts inside: claims</h2>

<p>Each fact in the payload is called a <strong>claim</strong>. Some claims are standard — every JWT system in the world understands them:</p>

<table>
  <thead>
    <tr>
      <th>Claim</th>
      <th>Boarding pass equivalent</th>
      <th>What it means</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">iss</code> (issuer)</td>
      <td>The airline that printed the pass</td>
      <td>Which server created this token — e.g. your Keycloak URL. The gate only trusts passes from airlines it knows.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">aud</code> (audience)</td>
      <td>The flight number</td>
      <td>Who this token is <em>for</em> — e.g. <code class="language-plaintext highlighter-rouge">mcp-server</code>. A pass for flight LH123 doesn’t get you onto LH456, and a token issued for one API shouldn’t work on another.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">sub</code> (subject)</td>
      <td>The passenger name</td>
      <td>Who the token is about — the user or service ID.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">exp</code> (expiry)</td>
      <td>The departure time</td>
      <td>When the pass stops working. JWTs are short-lived on purpose: a stolen pass is only useful for minutes, not forever.</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">roles</code></td>
      <td>Economy / Business class</td>
      <td>Broad groups the user belongs to, like <code class="language-plaintext highlighter-rouge">admin</code> or <code class="language-plaintext highlighter-rouge">analyst</code>.</td>
    </tr>
  </tbody>
</table>

<p>A minimal payload from Keycloak looks like this:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"iss"</span><span class="p">:</span><span class="w"> </span><span class="s2">"https://auth.example.com/realms/mcp"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"aud"</span><span class="p">:</span><span class="w"> </span><span class="s2">"mcp-server"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"sub"</span><span class="p">:</span><span class="w"> </span><span class="s2">"user-42"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"exp"</span><span class="p">:</span><span class="w"> </span><span class="mi">1767100000</span><span class="p">,</span><span class="w">
  </span><span class="nl">"realm_access"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"roles"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"analyst"</span><span class="p">]</span><span class="w"> </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<h2 id="adding-your-own-facts-custom-claims">Adding your own facts: custom claims</h2>

<p>Standard claims answer “who are you and who issued this?” But real systems need more context. In our case the MCP server needs to know three extra things before it does anything:</p>

<ol>
  <li><strong>Which environment</strong> is this token for — production or development?</li>
  <li><strong>Which customer’s data</strong> may this caller touch — customer A or B?</li>
  <li><strong>Exactly which actions</strong> are allowed — read the database? read a sheet? write to it?</li>
</ol>

<p>All three fit naturally into the payload as <strong>custom claims</strong>:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"iss"</span><span class="p">:</span><span class="w"> </span><span class="s2">"https://auth.example.com/realms/mcp"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"aud"</span><span class="p">:</span><span class="w"> </span><span class="s2">"mcp-server"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"sub"</span><span class="p">:</span><span class="w"> </span><span class="s2">"user-42"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"exp"</span><span class="p">:</span><span class="w"> </span><span class="mi">1767100000</span><span class="p">,</span><span class="w">
  </span><span class="nl">"realm_access"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"roles"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"analyst"</span><span class="p">]</span><span class="w"> </span><span class="p">},</span><span class="w">

  </span><span class="nl">"env"</span><span class="p">:</span><span class="w"> </span><span class="s2">"prod"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"customer"</span><span class="p">:</span><span class="w"> </span><span class="s2">"A"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"permissions"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"db:read"</span><span class="p">,</span><span class="w"> </span><span class="s2">"sheet:read"</span><span class="p">,</span><span class="w"> </span><span class="s2">"sheet:write"</span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Think of these as extra stamps on the boarding pass: “Lounge access: yes. Priority boarding: no.”</p>

<h3 id="why-the-resourceaction-pattern-is-worth-copying">Why the <code class="language-plaintext highlighter-rouge">resource:action</code> pattern is worth copying</h3>

<p>Notice the shape of the permissions: <code class="language-plaintext highlighter-rouge">db:read</code>, <code class="language-plaintext highlighter-rouge">sheet:write</code>. That’s <em>thing colon verb</em>. It stays readable as the system grows, and the check on the server side becomes one line of logic:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Request: "write row 5 to the sheet"
Check:   does the token's permissions list contain "sheet:write"?
         yes -&gt; do it
         no  -&gt; refuse (403 Forbidden)
</code></pre></div></div>

<p>Roles and permissions work together but answer different questions. A <strong>role</strong> is a job title (“analyst”); a <strong>permission</strong> is a concrete allowance (“may write to sheets”). In Keycloak you define roles, attach permissions to them, and Keycloak expands everything into the token automatically. Users are managed by role; the MCP server only ever checks permissions.</p>

<h3 id="how-to-add-custom-claims-in-keycloak">How to add custom claims in Keycloak</h3>

<p>Keycloak calls this feature <strong>protocol mappers</strong> (in newer versions you’ll find it under <strong>client scopes</strong>). No code required:</p>

<ol>
  <li>Store the fact on the user or client — e.g. a user attribute <code class="language-plaintext highlighter-rouge">customer = A</code> (Users → your user → Attributes).</li>
  <li>Create a mapper that copies the attribute into the token (Clients → your client → Client scopes → Add mapper → <em>User Attribute</em>, set the claim name to <code class="language-plaintext highlighter-rouge">customer</code>).</li>
  <li>That’s it. Every new token for that user now contains <code class="language-plaintext highlighter-rouge">"customer": "A"</code>.</li>
</ol>

<p>The <code class="language-plaintext highlighter-rouge">env</code> claim is often simplest to handle differently: run one Keycloak realm (or client) per environment, and hard-code the claim with a <em>hardcoded claim</em> mapper — <code class="language-plaintext highlighter-rouge">env: prod</code> in the prod realm, <code class="language-plaintext highlighter-rouge">env: dev</code> in the dev realm. Then a dev token can <em>never</em> claim to be a prod token, because the prod issuer never signed it.</p>

<h2 id="the-full-journey-of-one-request">The full journey of one request</h2>

<p>Here is everything together — what happens when an AI agent asks our MCP server to write to a spreadsheet:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> AI agent                                        MCP server
    |                                                |
    |  "Append this row to the sheet."               |
    |  + JWT                                         |
    |-----------------------------------------------&gt;|
    |                                                |
    |                     The gatekeeper checklist:  |
    |                                                |
    |          1. Signature valid?  (not forged)     |
    |          2. iss = our Keycloak?  (right issuer)|
    |          3. aud = mcp-server?  (meant for us)  |
    |          4. exp in the future?  (not expired)  |
    |          5. env = prod?  (right environment)   |
    |          6. customer = A?  (right data scope)  |
    |          7. "sheet:write" in permissions?      |
    |                                                |
    |     ALL seven pass -&gt; row is written           |
    |     ANY one fails  -&gt; request refused          |
    |&lt;-----------------------------------------------|
</code></pre></div></div>

<p>Steps 1–4 are the standard checks every JWT system does. Steps 5–7 are ours — and they only exist because we put <code class="language-plaintext highlighter-rouge">env</code>, <code class="language-plaintext highlighter-rouge">customer</code>, and <code class="language-plaintext highlighter-rouge">permissions</code> into the token as custom claims.</p>

<p>The elegant part: the MCP server made all seven decisions <strong>without contacting Keycloak</strong> and <strong>without storing any user data</strong>. Everything it needed was on the pass. That’s why JWTs are the default choice for connecting many small services — each gate can verify passes on its own, as long as it knows the issuer’s public key.</p>

<h2 id="takeaways">Takeaways</h2>

<ul>
  <li>A <strong>JWT</strong> is a signed, readable, short-lived boarding pass: header (seal type), payload (facts), signature (the seal).</li>
  <li><strong>Readable ≠ forgeable.</strong> Anyone can read it; nobody can change it. So: facts in, secrets out.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">iss</code></strong> says who printed the pass, <strong><code class="language-plaintext highlighter-rouge">aud</code></strong> says which gate it’s for, <strong><code class="language-plaintext highlighter-rouge">exp</code></strong> says when it dies. Check all three, always.</li>
  <li><strong>Custom claims</strong> let you carry your own facts — <code class="language-plaintext highlighter-rouge">env</code>, <code class="language-plaintext highlighter-rouge">customer</code>, <code class="language-plaintext highlighter-rouge">permissions</code> — and Keycloak adds them with mappers, no code.</li>
  <li>The <strong><code class="language-plaintext highlighter-rouge">resource:action</code></strong> permission format (<code class="language-plaintext highlighter-rouge">db:read</code>, <code class="language-plaintext highlighter-rouge">sheet:write</code>) keeps authorization checks one line long, forever.</li>
</ul>]]></content><author><name>Huijo</name></author><category term="Engineering" /><category term="Agents" /><summary type="html"><![CDATA[I built an OAuth 2.0 server with Keycloak for our MCP setup. Here is what a JWT actually carries — issuer, audience, roles — and how we pack our own facts into it: environment, customer, and fine-grained permissions.]]></summary></entry></feed>