<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Umut Güngör]]></title><description><![CDATA[Umut Güngör]]></description><link>https://umutgungorrhashnodedev.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 26 Nov 2026 11:52:46 GMT</lastBuildDate><atom:link href="https://umutgungorrhashnodedev.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[RAG Evaluation Guide: Separate Retrieval Quality from Answer Quality (Runnable Node.js Example)]]></title><description><![CDATA[Original guide + downloadable runnable script: Read on umutgungorr.com · Download rag-evaluation.mjs A runnable Node.js example covering recall, precision…]]></description><link>https://umutgungorrhashnodedev.hashnode.dev/rag-evaluation-guide-separate-retrieval-quality-from-answer-quality-runnable-node-js-example</link><guid isPermaLink="true">https://umutgungorrhashnodedev.hashnode.dev/rag-evaluation-guide-separate-retrieval-quality-from-answer-quality-runnable-node-js-example</guid><category><![CDATA[AI]]></category><category><![CDATA[RAG ]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Testing]]></category><category><![CDATA[llm]]></category><dc:creator><![CDATA[Umut Güngör]]></dc:creator><pubDate>Wed, 25 Nov 2026 20:44:24 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><strong>Original guide + downloadable runnable script:</strong> <a href="https://umutgungorr.com/blog/rag-evaluation-traces?lang=en">Read on umutgungorr.com</a> · <a href="https://umutgungorr.com/examples/rag-evaluation.mjs">Download rag-evaluation.mjs</a></p>
</blockquote>
<p>A runnable Node.js example covering recall, precision, answer omissions and out-of-corpus questions. Synthetic data, actual test output and limitations.</p>
<h2>What are we measuring?</h2>
<p>RAG evaluation asks two separate questions: did retrieval find the necessary evidence, and did the answer convey the necessary information? Fluent answers can hide missing evidence; complete evidence does not guarantee a complete answer.</p>
<p>The example was prepared and run locally on Node.js v24.19.0. It uses three synthetic documents, two questions and keyword matching, without embeddings, a vector database or an LLM. It is a small evaluation fixture, not a full RAG system or a production benchmark.</p>
<h2>Dataset and expected evidence</h2>
<p>The release question needs two documents: build covers test/build and secrets covers the secret check. The media question needs only images. Expected document IDs and answer facts are stored in the evaluation fixtures, not read by the retrieval function.</p>
<p>Recall is relevant evidence retrieved divided by relevant evidence expected. Precision is relevant evidence retrieved divided by all evidence retrieved. factCoverage checks only whether expected strings appear in the answer; it cannot establish semantic correctness or hallucination rates. It can miss valid paraphrases or accept a phrase inside a negation.</p>
<h2>Run the example</h2>
<p>Save <code>rag-evaluation.mjs</code> from the source links and run <code>node rag-evaluation.mjs</code> using Node.js 24. No package, account, API key or network access is needed. A failed assertion terminates the command with an error.</p>
<pre><code class="language-javascript">// Synthetic documents; no LLM, API key, embedding model or external request.
import assert from 'node:assert/strict';
const corpus = [
  { id: 'build', text: 'Yayın öncesi test ve build çalıştırılır.' },
  { id: 'secrets', text: 'Yayın öncesi gizli anahtar kontrolü yapılır.' },
  { id: 'images', text: 'Blog görselleri WebP biçiminde saklanır.' },
];
const cases = [
  { id: 'release', query: 'yayın test build gizli anahtar', expected: ['build', 'secrets'], facts: ['test ve build', 'gizli anahtar'] },
  { id: 'media', query: 'blog görselleri', expected: ['images'], facts: ['WebP'] },
];
const tokens = text =&gt; new Set(text.toLocaleLowerCase('tr-TR').match(/[\p{L}\p{N}]+/gu) || []);
function retrieve(query, k) {
  const terms = tokens(query);
  return corpus.map(doc =&gt; ({ ...doc, score: [...tokens(doc.text)].filter(t =&gt; terms.has(t)).length }))
    .filter(doc =&gt; doc.score &gt; 0).sort((a, b) =&gt; b.score - a.score || a.id.localeCompare(a.id)).slice(0, k);
}
function evaluate(item, docs, answer) {
  const hits = docs.filter(doc =&gt; item.expected.includes(doc.id)).length;
  return { recall: hits / item.expected.length, precision: docs.length ? hits / docs.length : 0,
    factCoverage: item.facts.filter(fact =&gt; answer.includes(fact)).length / item.facts.length };
}
for (const item of cases) {
  for (const k of [1, 2]) {
    const docs = retrieve(item.query, k);
    // This is evidence concatenation, NOT an LLM-generated answer.
    const result = evaluate(item, docs, docs.map(doc =&gt; doc.text).join(' '));
    if (item.id === 'release') assert.equal(result.recall, k === 1 ? 0.5 : 1);
    else assert.equal(result.recall, 1);
    assert.equal(result.precision, 1);
    console.log(JSON.stringify({ case: item.id, k, retrieved: docs.map(d =&gt; d.id), ...result }));
  }
}
const release = cases[0];
const fullEvidence = retrieve(release.query, 2);
const incompleteAnswer = fullEvidence[0].text;
const incomplete = evaluate(release, fullEvidence, incompleteAnswer);
assert.equal(incomplete.recall, 1);
assert.equal(incomplete.factCoverage, 0.5);
console.log(JSON.stringify({ case: 'answer-omission', ...incomplete }));
assert.equal(retrieve('pasaport yenileme', 2).length, 0);
console.log('PASS: retrieval, answer omission and out-of-corpus checks');
</code></pre>
<h2>Observed results</h2>
<p>For the release question, k=1 retrieved only build: recall 0.5, precision 1 and factCoverage 0.5. k=2 retrieved build and secrets, giving 1 for all three ratios. Both k values returned only images for the media question. These are fixture results, not overall accuracy claims.</p>
<p>The answer-omission case intentionally uses only the first retrieved document despite complete evidence. Recall remains 1 while factCoverage drops to 0.5, reproducing the distinction between retrieval and answer completeness. An out-of-corpus query returns no evidence; a real product still needs a separate abstention policy.</p>
<pre><code class="language-json">{"case":"release","k":1,"retrieved":["build"],"recall":0.5,"precision":1,"factCoverage":0.5}
{"case":"release","k":2,"retrieved":["build","secrets"],"recall":1,"precision":1,"factCoverage":1}
{"case":"answer-omission","recall":1,"precision":1,"factCoverage":0.5}
</code></pre>
<h2>Moving to a real system</h2>
<p>Two questions cannot establish that larger k is always better. Real evaluations need varied questions, irrelevant documents, missing evidence and contradictions, alongside cost, latency and context-noise measurements. Review evidence labels and avoid tuning on the same cases used to claim success.</p>
<p>Do not accept real LLM answers using substring matching alone. Review grounding, abstention and domain risk separately. Traces can retain document IDs and versions, but private text and credentials must not enter public logs.</p>
<h2>Your first evaluation record</h2>
<p>Record question ID, corpus version, expected and retrieved evidence IDs, ranks, k, answer and separate evaluation results together. Identify the failing layer, change that layer and rerun the same cases. The linked debugging guide complements this with one hypothesis per change.</p>
<hr />
<p><strong>Related engineering guides on umutgungorr.com:</strong> <a href="https://umutgungorr.com/blog/rag-evaluation-traces?lang=en">Original RAG Evaluation Guide</a> | <a href="https://umutgungorr.com/blog/debugging-with-hypotheses?lang=en">Debugging Shared-State Bugs with Hypotheses</a> | <a href="https://umutgungorr.com/blog/interfaces-for-uncertainty?lang=en">Interfaces for Uncertain Systems</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Catch Missing .env Variables and .env.example Drift Before Production Deploy]]></title><description><![CDATA[Updated guide + full FAQ & EnvDoctor case study: Read on umutgungorr.com · Explore EnvDoctor architecture How to stop silent .env vs .env.example…]]></description><link>https://umutgungorrhashnodedev.hashnode.dev/how-to-catch-missing-env-variables-and-env-example-drift-before-production-deploy</link><guid isPermaLink="true">https://umutgungorrhashnodedev.hashnode.dev/how-to-catch-missing-env-variables-and-env-example-drift-before-production-deploy</guid><category><![CDATA[Python]]></category><category><![CDATA[Devops]]></category><category><![CDATA[ci-cd]]></category><category><![CDATA[cli]]></category><category><![CDATA[GitHub Actions]]></category><dc:creator><![CDATA[Umut Güngör]]></dc:creator><pubDate>Wed, 25 Nov 2026 20:41:50 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><strong>Updated guide + full FAQ &amp; EnvDoctor case study:</strong> <a href="https://umutgungorr.com/blog/env-contract-drift-envdoctor?lang=en">Read on umutgungorr.com</a> · <a href="https://umutgungorr.com/projects/envdoctor?lang=en">Explore EnvDoctor architecture</a></p>
</blockquote>
<p>How to stop silent <code>.env</code> vs <code>.env.example</code> configuration drift and undocumented <code>os.getenv</code> calls in CI/CD before a missing environment variable breaks production.</p>
<h2>Why code that passes locally crashes on deploy</h2>
<p>Adding a new webhook secret, cache URL, or feature flag to your local <code>.env</code> file takes seconds. Forgetting to mirror that key into <code>.env.example</code> and your production runtime config rarely shows up in code review because local tests read your machine's <code>.env</code> or mocked fixtures.</p>
<p>Once that silent drift ships to production, one of two failures occurs: the service crashes with a <code>KeyError</code> / <code>undefined</code> error the first time real traffic hits that branch, or worse, a fallback like <code>os.getenv("STRIPE_WEBHOOK_KEY", "")</code> silently runs with an empty string and breaks signature verification or auth behavior.</p>
<p>Missing keys are only half the cost. Over months, orphaned variables accumulate in <code>.env.example</code>, new engineers cannot tell which keys are mandatory versus retired, and local onboarding slows to guesswork.</p>
<h2>Step 1: Enforce the .env ↔ .env.example contract in strict mode</h2>
<p>Treating <code>.env.example</code> as an enforced build contract instead of passive documentation eliminates drift at the source. The zero-dependency Python tool <code>envdoctor-cli</code> compares <code>.env</code> against <code>.env.example</code> strictly by <strong>key names</strong>—never printing or transmitting secret values.</p>
<p><code>envdoctor check --strict</code> flags both missing keys and undocumented extras with exit code <code>1</code>. Instead of copying lines manually—and risking accidentally pasting a real secret into <code>.env.example</code>—running <code>envdoctor sync</code> appends missing keys with safe empty or masked placeholders.</p>
<pre><code class="language-bash">pip install envdoctor-cli

# 1) Strictly verify missing or extra keys between .env and .env.example
envdoctor check --strict

# Sample output:
# [OK]      DATABASE_URL        present in both contracts
# [OK]      REDIS_PORT          present in both contracts
# [MISSING] STRIPE_WEBHOOK_KEY  missing from .env.example
# exit code 1

# 2) Sync missing keys to .env.example without leaking secret values
envdoctor sync
</code></pre>
<h2>Step 2: Surface undocumented env vars in source code with Python AST</h2>
<p>Comparing <code>.env</code> and <code>.env.example</code> alone leaves a major blind spot: an engineer can add <code>os.getenv("NEW_WEBHOOK_SECRET")</code> or <code>os.environ["BILLING_SIGNING_KEY"]</code> in Python code without updating either file. Both env files still match, yet production has no idea that variable exists.</p>
<p>Naive <code>grep</code> or regex scans misfire on comments, docstrings, and unrelated strings. <code>envdoctor audit</code> parses Python files via the standard library <code>ast</code> module to locate real <code>os.getenv(...)</code>, <code>os.environ.get(...)</code>, and <code>os.environ[...]</code> calls, reporting both undocumented code lookups and orphan keys that no module reads anymore.</p>
<pre><code class="language-bash"># Audit os.getenv / os.environ usage via Python AST and emit JSON for CI
envdoctor audit --format json

# Sample JSON output:
# {
#   "status": "drift_detected",
#   "undocumented_in_code": [{"key": "STRIPE_WEBHOOK_KEY", "file": "src/billing/hooks.py", "line": 18}],
#   "orphan_in_example": ["LEGACY_API_FLAG"]
# }
</code></pre>
<h2>Step 3: Add a Pull Request Gate in GitHub Actions (and Multi-Env Setups)</h2>
<p>CI runners do not—and should not—contain production <code>.env</code> files. On pull requests, run <code>envdoctor audit</code> so every environment variable referenced in code is guaranteed to exist in <code>.env.example</code>. Locally or in pre-commit hooks, run <code>envdoctor check --strict</code> to verify your local <code>.env</code> matches the template.</p>
<p>In monorepos with multiple services (<code>services/api</code>, <code>services/worker</code>), audit each service against its own <code>.env.example</code> so each workload documents only the minimum secrets it requires.</p>
<pre><code class="language-yaml">name: Env Contract Audit
on:
  pull_request:
    paths:
      - "**/*.py"
      - ".env.example"

permissions:
  contents: read

jobs:
  envdoctor:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Audit undocumented env vars via AST
        run: |
          pip install envdoctor-cli
          envdoctor audit
</code></pre>
<h2>Frequently Asked Questions</h2>
<h3>Will envdoctor sync ever leak my real secret values into .env.example?</h3>
<p>No. <code>envdoctor sync</code> reads only key names that are missing from <code>.env.example</code> and writes empty or masked placeholders—real secret values are never copied to the template.</p>
<h3>How does envdoctor work in GitHub Actions where no .env file exists?</h3>
<p>CI does not need a <code>.env</code> file. <code>envdoctor audit</code> scans Python source code with AST for <code>os.getenv</code> and <code>os.environ</code> calls and validates them directly against the committed <code>.env.example</code> file.</p>
<h3>Can AST analysis detect dynamically constructed env var names like f-strings?</h3>
<p>Static AST parsing resolves string-literal keys deterministically. Dynamic expressions like <code>os.getenv(f"{prefix}_KEY")</code> cannot be statically resolved, so centralizing configuration reads as explicit literal constants in one config module is recommended.</p>
<hr />
<p><strong>Try EnvDoctor &amp; see the architecture notes:</strong> <a href="https://umutgungorr.com/projects/envdoctor?lang=en">EnvDoctor Project Page</a> | <a href="https://umutgungorr.com/blog/env-contract-drift-envdoctor?lang=en">Original Guide on umutgungorr.com</a> | <a href="https://github.com/umutgungorr/envdoctor">GitHub</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Remove Leaked API Keys and .env Files from Git History (git filter-repo Guide)]]></title><description><![CDATA[Updated guide + full FAQ & TokenGuard case study: Read on umutgungorr.com · Explore TokenGuard architecture Deleting a leaked .env file in a new commit…]]></description><link>https://umutgungorrhashnodedev.hashnode.dev/how-to-remove-leaked-api-keys-and-env-files-from-git-history-git-filter-repo-guide</link><guid isPermaLink="true">https://umutgungorrhashnodedev.hashnode.dev/how-to-remove-leaked-api-keys-and-env-files-from-git-history-git-filter-repo-guide</guid><category><![CDATA[GitHub]]></category><category><![CDATA[Git]]></category><category><![CDATA[Security]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Umut Güngör]]></dc:creator><pubDate>Wed, 25 Nov 2026 19:55:55 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><strong>Updated guide + full FAQ &amp; TokenGuard case study:</strong> <a href="https://umutgungorr.com/blog/git-filter-repo-clean-leaked-secrets?lang=en">Read on umutgungorr.com</a> · <a href="https://umutgungorr.com/projects/tokenguard?lang=en">Explore TokenGuard architecture</a></p>
</blockquote>
<p>Deleting a leaked <code>.env</code> file in a new commit leaves the secret readable in Git history. Follow the complete recovery sequence: key rotation, <code>git filter-repo</code> scrubbing across all refs, team sync, and TokenGuard pre-commit prevention.</p>
<h2>Step 1: Revoke &amp; Rotate the Exposed Key Before Scrubbing History</h2>
<p>The moment a <code>.env</code> file, AWS access key, Stripe <code>sk_live_</code> token, or private signing key is pushed to a public GitHub repository, automated credential scrapers can harvest it within seconds. Running <code>git rm .env</code> in a follow-up commit does not erase earlier Git objects—anyone inspecting <code>git log -p</code> or the raw commit SHA URL can still read the secret.</p>
<p>Therefore, your first action is never rewriting Git history—it is immediately revoking and rotating the compromised credential at the provider (AWS IAM, GitHub, Stripe, Supabase, OpenAI, etc.). Rewriting history without revoking an active key only hides the leak while leaving the credential valid. Check provider audit logs between the push timestamp and revocation timestamp to confirm no unauthorized requests occurred.</p>
<h2>Step 2: Scrub the File or Secret String on a Fresh Mirror Clone with git filter-repo</h2>
<p>The Git project officially recommends <code>git-filter-repo</code> over legacy <code>git filter-branch</code> and BFG for accuracy and speed. Always perform history rewrites on a fresh <code>--mirror</code> clone rather than your working tree so every branch and tag ref is rewritten consistently without risking uncommitted local work.</p>
<p>There are two common recovery patterns: if an entire <code>.env</code> file was committed by mistake, <code>--path .env --invert-paths</code> purges every <code>.env</code> blob from history. If a secret was hardcoded inside a real source file (<code>src/config.py</code>), use <code>--replace-text secrets.txt</code> so the source file stays intact while every occurrence of the secret string becomes <code>***REMOVED***</code>. Note that <code>git-filter-repo</code> removes the <code>origin</code> remote by design to prevent accidental pushes—verify locally before re-adding the remote.</p>
<pre><code class="language-bash"># 1) Install git-filter-repo and create a fresh mirror clone
pip install git-filter-repo
git clone --mirror https://github.com/OWNER/REPO.git repo-clean.git
cd repo-clean.git

# 2a) Permanently remove a committed .env file across all history
git filter-repo --path .env --invert-paths

# 2b) Or redact a specific secret string inside source files
# secrets.txt line format: sk_live_EXAMPLE_KEY==&gt;***REMOVED***
git filter-repo --replace-text ../secrets.txt

# 3) Local verification: must return 0 matches
git log --all --full-history -- .env

# 4) Re-add origin and force-push all rewritten branches and tags
git remote add origin https://github.com/OWNER/REPO.git
git push --force --all
git push --force --tags
</code></pre>
<h2>Step 3: GitHub Commit Caches, PR Refs &amp; Safe Team Recovery</h2>
<p>Running <code>git push --force --all</code> updates branch and tag heads, but GitHub can retain dangling commit objects referenced by pull requests (<code>refs/pull/*/head</code>) or cached views. For sensitive leaks, contact GitHub Support to request a cached-commit purge, and make sure <code>.env</code> is added to <code>.gitignore</code> immediately.</p>
<p>After a force-push rewrite, teammates running a normal <code>git pull</code> can accidentally merge the old tainted history back into <code>main</code>. Every collaborator must either re-clone or run a hard reset to the rewritten upstream branch.</p>
<pre><code class="language-bash"># Reset collaborator clones to rewritten history without merging old commits
git fetch origin
git checkout main
git reset --hard origin/main
git reflog expire --expire=now --all
git gc --prune=now --aggressive
</code></pre>
<h2>Step 4: Block Future Leaks Before Commit with TokenGuard Pre-Commit</h2>
<p>Scrubbing Git history is incident remediation; the durable defense is blocking credentials before <code>git commit</code> succeeds. My zero-dependency Python CLI TokenGuard (<code>tokenguard-cli</code>) inspects staged diffs offline using both provider token signatures (AWS, GitHub, Stripe, JWT, PEM private keys) and Shannon entropy checks.</p>
<p>When TokenGuard detects a secret, it masks the value in terminal output (<code>AKIA************</code>), aborts the commit with exit code <code>1</code>, and supports <code>--format sarif</code> in GitHub Actions for defense-in-depth across the team.</p>
<pre><code class="language-bash">pip install tokenguard-cli

# Scan staged files offline before commit
tokenguard scan --staged

# Install automatic Git pre-commit hook
tokenguard install-hook
</code></pre>
<h2>Frequently Asked Questions</h2>
<h3>Does running git rm --cached .env remove the secret from Git history?</h3>
<p>No. <code>git rm --cached .env</code> only untracks the file for future commits while leaving earlier commit blobs intact. You must revoke the credential first and then rewrite history with <code>git filter-repo</code>.</p>
<h3>Why does git filter-repo remove the origin remote automatically?</h3>
<p>As a safety mechanism to prevent accidentally force-pushing rewritten history before verifying the cleanup locally. After confirming <code>git log --all -- .env</code> returns empty, re-add <code>origin</code> and force-push.</p>
<h3>Do I still need git filter-repo if I never pushed the commit?</h3>
<p>If the leak is only in the latest unpushed commit, <code>git reset --soft HEAD~1</code>, unstaging <code>.env</code>, and recommitting is enough. If it sits several commits back or across multiple local branches, <code>git filter-repo</code> is cleaner and safer.</p>
<h3>What should teammates do after I force-push rewritten history?</h3>
<p>They must not run a normal <code>git pull</code>, which merges the old tainted commits back in. Everyone should run <code>git fetch origin &amp;&amp; git reset --hard origin/main</code> or take a fresh clone.</p>
<hr />
<p><strong>Prevent future leaks with TokenGuard:</strong> <a href="https://umutgungorr.com/projects/tokenguard?lang=en">TokenGuard Project Page</a> | <a href="https://umutgungorr.com/blog/git-secret-leak-prevention-tokenguard?lang=en">TokenGuard Pre-Commit Guide</a> | <a href="https://umutgungorr.com/blog/git-filter-repo-clean-leaked-secrets?lang=en">Original Guide on umutgungorr.com</a></p>
]]></content:encoded></item><item><title><![CDATA[How to Catch Broken Markdown Links and Dead Anchors in GitHub Actions]]></title><description><![CDATA[Interactive case study & benchmarks: DeadLinkFinder on umutgungorr.com Renamed files, moved headings, and missing images silently break developer docs. A…]]></description><link>https://umutgungorrhashnodedev.hashnode.dev/how-to-catch-broken-markdown-links-and-dead-anchors-in-github-actions</link><guid isPermaLink="true">https://umutgungorrhashnodedev.hashnode.dev/how-to-catch-broken-markdown-links-and-dead-anchors-in-github-actions</guid><category><![CDATA[Python]]></category><category><![CDATA[Devops]]></category><category><![CDATA[GitHub Actions]]></category><category><![CDATA[markdown]]></category><category><![CDATA[ci-cd]]></category><dc:creator><![CDATA[Umut Güngör]]></dc:creator><pubDate>Tue, 24 Nov 2026 19:05:44 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><strong>Interactive case study &amp; benchmarks:</strong> <a href="https://umutgungorr.com/projects/deadlinkfinder?lang=en">DeadLinkFinder on umutgungorr.com</a></p>
</blockquote>
<p>Renamed files, moved headings, and missing images silently break developer docs. A complete guide to checking relative Markdown links, GFM #anchors, and SARIF pull-request annotations in GitHub Actions.</p>
<h2>Why Markdown links break silently across pull requests</h2>
<p>When an engineer renames <code>docs/setup.md</code> to <code>docs/quickstart.md</code>, moves a diagram asset, or edits a heading from <code>## Authentication</code> to <code>## Token Setup</code>, unit tests, linters, and TypeScript builds still pass green. Standard CI gates never notice that <code>#authentication</code> in your README now points nowhere.</p>
<p>Traditional HTTP link crawlers introduce two chronic failures in pull requests. First, crawling only external URLs misses local relative file paths (<code>../guides/deploy.md</code>) and GitHub Flavored Markdown (GFM) heading anchors inside an unmerged PR. Second, external <code>429</code> rate limits and <code>403</code> anti-bot responses make CI flaky, causing engineers to ignore or disable the check.</p>
<p>The sustainable architecture splits link verification into two lanes: a <strong>zero-network offline check</strong> that gates every pull request deterministically, and a <strong>scheduled external HTTP sweep</strong> that runs weekly without blocking merges.</p>
<h2>Step 1: Verify relative files, images, and GFM #anchors offline</h2>
<p>GitHub's GFM heading slugification is subtler than naive lowercasing: punctuation is stripped, spaces become hyphens, Unicode letters are preserved, and duplicate headings such as a second <code>## Setup</code> automatically receive <code>-1</code>, <code>-2</code> suffixes. Simple regex scripts either trigger false positives or miss broken duplicate anchors.</p>
<p>Built purely on the Python standard library (<code>re</code>, <code>pathlib</code>, <code>difflib</code>, <code>urllib</code>), <code>deadlinkfinder</code> scans an entire repository in milliseconds with zero network calls. It verifies relative Markdown paths, image assets, and exact GFM heading maps—and when a target breaks, <code>difflib</code> prints an actionable 'did you mean' suggestion pointing to the renamed file or heading.</p>
<pre><code class="language-bash">pip install deadlinkfinder

# 1) Scan local Markdown links, images, and #heading anchors offline
deadlinkfinder check .

# Sample output:
# FAIL README.md:42 -&gt; docs/auth.md#authentication (broken anchor)
#      Hint: Did you mean #token-setup?
# Scanned 48 targets offline in 19ms · exit code 1

# 2) Machine-readable JSON or scheduled external URL sweep
deadlinkfinder check docs/ --format json
deadlinkfinder check docs/ --external --timeout 8
</code></pre>
<h2>Step 2: Gate Pull Requests in GitHub Actions with SARIF v2.1.0 Annotations</h2>
<p>Console-only failures force reviewers to dig through workflow logs. Exporting <code>deadlinkfinder check . --format sarif</code> into <code>github/codeql-action/upload-sarif@v3</code> renders broken links directly inline on the Pull Request diff and inside GitHub Security → Code Scanning with stable line fingerprints.</p>
<p>The workflow below triggers only when Markdown or docs change (<code>paths</code> filter), requests least-privilege permissions (<code>contents: read</code> and <code>security-events: write</code>), uploads SARIF annotations even on failure (<code>if: always()</code>), and blocks broken merges with exit code <code>1</code>.</p>
<pre><code class="language-yaml">name: Markdown Link Check
on:
  pull_request:
    paths:
      - "**/*.md"
      - "docs/**"

permissions:
  contents: read
  security-events: write

jobs:
  offline-links:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Install DeadLinkFinder
        run: pip install deadlinkfinder
      - name: Generate SARIF report
        id: scan
        continue-on-error: true
        run: deadlinkfinder check . --format sarif &gt; links.sarif
      - name: Upload SARIF to GitHub Code Scanning
        if: always()
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: links.sarif
      - name: Enforce PR gate
        if: steps.scan.outcome == 'failure'
        run: deadlinkfinder check .
</code></pre>
<h2>Step 3: Isolate External HTTP Checks into a Weekly Scheduled Workflow</h2>
<p>Monitoring external references (such as third-party API docs returning 404) is still valuable, but belongs in a weekly <code>schedule</code> workflow rather than a blocking PR check. Temporary third-party outages never stall deployments, while genuine external link rot surfaces cleanly once a week.</p>
<p>Excluding fenced code-block placeholders (<code>http://localhost:3000</code>, <code>https://example.com</code>) keeps noise at zero so every non-zero exit represents a real documentation defect.</p>
<pre><code class="language-yaml"># Separate weekly scheduled workflow for external URL checks
on:
  schedule:
    - cron: "0 7 * * 1" # Every Monday at 07:00 UTC
  workflow_dispatch:
</code></pre>
<h2>Frequently Asked Questions</h2>
<h3>Why shouldn't I run external HTTP link checks on every pull request?</h3>
<p>External hosts frequently return transient 429 rate limits, 503 outages, or 403 anti-bot responses, making PR checks flaky. Run offline local file, image, and <code>#anchor</code> checks on every PR, and move external HTTP sweeps to a weekly scheduled job.</p>
<h3>Which GitHub Actions permissions are required to upload SARIF results?</h3>
<p>Your workflow needs <code>contents: read</code> and <code>security-events: write</code> under <code>permissions</code>. GitHub Code Scanning is free for public repositories and requires GitHub Advanced Security on private repositories.</p>
<h3>How are Unicode headings and duplicate Markdown headings handled?</h3>
<p>Following GitHub Flavored Markdown rules, Unicode letters are preserved, punctuation is stripped, and duplicate headings receive <code>-1</code>, <code>-2</code> suffixes. <code>deadlinkfinder</code> implements exact GFM slugification and suggests close matches via <code>difflib</code>.</p>
<hr />
<p><em>Originally published at <a href="https://umutgungorr.com/blog/github-actions-broken-links-deadlinkfinder?lang=en">umutgungorr.com</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Shrink Noisy CI/CD Logs Without Losing Stack Traces]]></title><description><![CDATA[When GitHub Actions, Docker builds, or verbose test suites emit thousands of repetitive lines, real errors get buried. Learn how to shrink piped log…]]></description><link>https://umutgungorrhashnodedev.hashnode.dev/shrink-noisy-ci-cd-logs-without-losing-stack-traces</link><guid isPermaLink="true">https://umutgungorrhashnodedev.hashnode.dev/shrink-noisy-ci-cd-logs-without-losing-stack-traces</guid><category><![CDATA[Devops]]></category><category><![CDATA[cli]]></category><category><![CDATA[Python]]></category><category><![CDATA[debugging]]></category><category><![CDATA[GitHub Actions]]></category><dc:creator><![CDATA[Umut Güngör]]></dc:creator><pubDate>Sun, 22 Nov 2026 10:05:22 GMT</pubDate><content:encoded><![CDATA[<p>When GitHub Actions, Docker builds, or verbose test suites emit thousands of repetitive lines, real errors get buried. Learn how to shrink piped log streams by 70–90% in constant memory while preserving stack traces and non-zero exit codes.</p>
<h2>Why huge CI logs bury the one traceback you actually need</h2>
<p>When an integration suite (<code>pytest -vv</code>), Docker BuildKit layer pull, or native wheel compile emits tens of thousands of repeated status lines, ANSI progress-bar redraws (<code>\r</code>, <code>\x1b[K</code>), or <code>ConnectionResetError</code> retry loops, the single traceback you need disappears under megabytes of scrollback. GitHub Actions truncates oversized logs in the browser, and pasting raw output into an issue or debugging session overflows context limits.</p>
<p>Quick workarounds like <code>grep -v</code> or <code>tail -n 200</code> introduce two dangerous bugs. First, naive line slicing drops surrounding diagnostic context right above the failure. Second, in standard POSIX shells, a pipe like <code>docker build . | grep -v ...</code> returns the exit code of the rightmost filter rather than the failing build—silently turning a broken CI run <strong>green</strong> unless <code>pipefail</code> is enforced.</p>
<h2>Step 1: Deduplicate stdout/stderr in constant memory and preserve exit codes with pipefail</h2>
<p>A trustworthy log compactor follows three strict invariants: process <code>stdin</code> line-by-line in constant $O(1)$ memory without buffering full files, strip transient ANSI redraw noise while collapsing consecutive duplicates into a single count, and let every <code>Traceback</code>, <code>AssertionError</code>, <code>panic:</code>, or <code>FATAL</code> block bypass suppression verbatim.</p>
<p>Built purely on the Python standard library with zero third-party dependencies, <code>logshrink</code> shrinks verbose CI and build output by <strong>70–90%</strong> while leaving stack traces untouched. Combining it with <code>set -o pipefail</code> (enabled by default in GitHub Actions <code>bash</code> steps) guarantees the upstream non-zero exit code is never masked.</p>
<pre><code class="language-bash">pip install logshrink

# 1) Shrink noisy pytest output without losing tracebacks
set -o pipefail &amp;&amp; pytest -vv 2&gt;&amp;1 | logshrink

# 2) Compress Docker build logs while preserving exit code 1
set -o pipefail &amp;&amp; docker build . 2&gt;&amp;1 | logshrink

# Sample compressed output:
# [stream] Fetching Python wheels &amp; compiling native extensions...
#   ↳ collapsed 14,820 noisy progress/polling lines (-88%)
# WARN retry #2 -&gt; upstream/proxy
# Traceback (most recent call last):
#   File "api/webhooks.py", line 84, in verify
# AssertionError: missing HMAC signature header
</code></pre>
<h2>Step 2: Triage multi-megabyte production log dumps before opening an editor</h2>
<p>When an incident hands you a 200 MB container or reverse-proxy log dump, streaming it through <code>logshrink</code> into <code>less -R</code> or a triage summary file before opening an editor cuts initial diagnosis from minutes to seconds.</p>
<p>Once repetitive healthchecks (<code>GET /health 200</code>) and retry storms collapse into counts, the chronological fault transition—first upstream timeout, retry cascade, and final crash—stands out immediately.</p>
<pre><code class="language-bash"># Compress a downloaded CI log file in constant memory
cat build-failure.log | logshrink | less -R

# Usage inside a critical GitHub Actions test step:
# - name: Run integration suite
#   shell: bash
#   run: set -o pipefail &amp;&amp; pytest -vv 2&gt;&amp;1 | logshrink
</code></pre>
<h2>When should you still preserve raw logs?</h2>
<p>Log compaction optimizes human triage and CI console readability, not forensic compliance storage. Whenever you need full per-line timestamps or audit trails, split the stream with <code>tee raw.log | logshrink</code>—archive <code>raw.log</code> as a CI artifact on failure while keeping the live console output concise and readable.</p>
<pre><code class="language-bash"># Archive raw logs while viewing the compressed summary in CI
set -o pipefail &amp;&amp; pytest -vv 2&gt;&amp;1 | tee raw-test.log | logshrink
</code></pre>
<h2>Frequently Asked Questions</h2>
<h3>If I pipe my build into logshrink, could a failing CI step falsely pass green?</h3>
<p>Without <code>set -o pipefail</code>, POSIX shells return the exit status of the rightmost command in a pipe. GitHub Actions enables <code>pipefail</code> in default <code>bash</code> steps, and prefixing <code>set -o pipefail &amp;&amp;</code> makes exit-code preservation explicit across every shell.</p>
<h3>Does LogShrink consume high RAM on very large (e.g., 1 GB) log files?</h3>
<p>No. It operates as a streaming line-by-line pass in constant memory rather than loading the entire file into RAM, so memory usage stays flat even on multi-hundred-megabyte dumps.</p>
<h3>Can stack traces or panic blocks get collapsed by accident?</h3>
<p>No. Stack traces, runtime exceptions, and failure blocks bypass deduplication and pass through verbatim; only repetitive progress and polling noise gets collapsed.</p>
<hr />
<p><em>Originally published at</em> <a href="https://umutgungorr.com/blog/debug-production-logs-logshrink?lang=en"><em>umutgungorr.com</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[How to Fix EADDRINUSE: Address Already in Use on Windows, Linux, macOS & Docker]]></title><description><![CDATA[A practical OS-by-OS command playbook to diagnose and cleanly resolve EADDRINUSE port conflicts across Windows, Linux, macOS, WSL2, and Docker containers…]]></description><link>https://umutgungorrhashnodedev.hashnode.dev/how-to-fix-eaddrinuse-address-already-in-use-on-windows-linux-macos-docker</link><guid isPermaLink="true">https://umutgungorrhashnodedev.hashnode.dev/how-to-fix-eaddrinuse-address-already-in-use-on-windows-linux-macos-docker</guid><category><![CDATA[debugging]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Linux]]></category><category><![CDATA[devtools]]></category><dc:creator><![CDATA[Umut Güngör]]></dc:creator><pubDate>Fri, 20 Nov 2026 16:06:51 GMT</pubDate><content:encoded><![CDATA[<p>A practical OS-by-OS command playbook to diagnose and cleanly resolve EADDRINUSE port conflicts across Windows, Linux, macOS, WSL2, and Docker containers.</p>
<h2>Why EADDRINUSE Happens (and Why Blind kill -9 Often Fails)</h2>
<p>When starting a Node.js, Python (Uvicorn/Flask), Go, or Vite dev server throws <code>Error: listen EADDRINUSE: address already in use :::3000</code> (or Python's <code>OSError: [Errno 98] Address already in use</code>), the OS kernel is rejecting the <code>bind()</code> syscall because another socket already owns that local IP and TCP port.</p>
<p>The most common reflex is locating a single PID and immediately running <code>kill -9 &lt;PID&gt;</code> or <code>taskkill /F /PID &lt;PID&gt;</code>. That blind kill fails in three common scenarios: a supervisor (nodemon, PM2, Vite watcher, systemd, or an IDE debugger) immediately respawns the child process; the port is actually forwarded by <code>docker-proxy</code> for a running container; or the process is a shared local service such as PostgreSQL or Redis that you should not terminate abruptly.</p>
<p>The reliable triage sequence is always the same: inspect the exact bound address (<code>127.0.0.1</code>, <code>0.0.0.0</code>, or <code>::1</code>) and PID, read the parent process (<code>PPID</code>) and full command line (<code>CommandLine</code>), and then stop the right owner gracefully (<code>SIGTERM</code>) instead of killing a symptom.</p>
<pre><code class="language-bash">Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1904:16)
    at listenInCluster (node:net:1961:12)

# Python / Uvicorn equivalent:
OSError: [Errno 98] Address already in use
</code></pre>
<h2>Finding the Port Owner and Parent Process on Windows, Linux &amp; macOS</h2>
<p>Every major operating system includes built-in socket inspection tools. Rather than stopping at the raw PID, always inspect the process command line and parent PID so you know which terminal tab, repo, or background daemon owns the port.</p>
<p>On Windows, <code>netstat -ano | findstr :3000</code> only shows a numeric PID. Pairing PowerShell's <code>Get-NetTCPConnection</code> with <code>Get-CimInstance Win32_Process</code> exposes both <code>ParentProcessId</code> and the exact <code>CommandLine</code>. On modern Linux distributions, <code>ss -tulpn</code> queries kernel netlink tables directly and is faster than legacy <code>netstat</code>. On macOS, <code>lsof -nP -iTCP:3000 -sTCP:LISTEN</code> disables DNS and port-name lookups (<code>-nP</code>) for instant output.</p>
<p>One Windows-specific trap: Hyper-V and WSL2 reserve dynamic excluded TCP port ranges at boot. Even when no process is listening on port 3000 or 5000, binding can fail if the port falls inside a reserved range—verify with <code>netsh interface ipv4 show excludedportrange protocol=tcp</code>.</p>
<pre><code class="language-bash"># Linux (fastest check + parent process)
ss -tulpn | grep :3000
ps -o pid,ppid,cmd -p &lt;PID&gt;

# macOS (fast list without DNS lookup)
lsof -nP -iTCP:3000 -sTCP:LISTEN
ps -o pid,ppid,command -p &lt;PID&gt;

# Windows PowerShell (port 3000 + command line + parent PID)
$conn = Get-NetTCPConnection -LocalPort 3000 -State Listen -ErrorAction SilentlyContinue
$conn | ForEach-Object {
  Get-CimInstance Win32_Process -Filter "ProcessId = $($_.OwningProcess)" |
    Select-Object ProcessId, ParentProcessId, Name, CommandLine
}

# Windows Hyper-V / WSL2 excluded port range check
netsh interface ipv4 show excludedportrange protocol=tcp
</code></pre>
<h2>Masked Ports in Docker, WSL2 &amp; Automated CI Pipelines</h2>
<p>When a container publishes a port to the host (<code>-p 3000:3000</code>), host-level <code>lsof</code> or <code>ss</code> only attributes the socket to <code>docker-proxy</code> or <code>com.docker.backend</code>. Force-killing the proxy daemon can corrupt container networking; instead, identify the exact publishing container and stop it cleanly with <code>docker stop</code>.</p>
<p>On WSL2, a dev server started inside Ubuntu is automatically forwarded to Windows <code>localhost:3000</code>. Checking Windows <code>netstat</code> only shows <code>wslrelay.exe</code>; you must inspect <code>ss -tulpn</code> inside the WSL distro to find and stop the actual Linux process.</p>
<p>In CI/CD pipelines running parallel integration suites, binding to port <code>0</code> (<code>server.listen(0)</code>) lets the kernel assign a guaranteed free ephemeral port. When a fixed port is unavoidable (such as OAuth callback tests), add a pre-flight assertion step before launching the server.</p>
<pre><code class="language-bash"># Check which Docker container publishes port 3000 or 5432
docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Ports}}" | grep -E "3000|5432"

# Stop only the conflicting container cleanly
docker stop &lt;CONTAINER_ID&gt;

# Graceful SIGTERM on Linux/macOS before force-killing
kill -15 &lt;PID&gt;
# Clean shutdown in Windows PowerShell
Stop-Process -Id &lt;PID&gt;
</code></pre>
<h2>IPv4 vs IPv6 (127.0.0.1 vs ::1) Traps and Graceful Shutdown in Code</h2>
<p>In Node.js 18+ and modern browsers, <code>localhost</code> often resolves to IPv6 <code>::1</code> first. If one server binds <code>127.0.0.1:3000</code> and another tries to bind wildcard <code>:::3000</code>, you can hit confusing <code>EADDRINUSE</code> errors or split traffic between two servers. Pinning <code>--host 127.0.0.1</code> explicitly in dev configs removes dual-stack ambiguity.</p>
<p>Finally, ensure dev servers and API workers handle <code>SIGINT</code> and <code>SIGTERM</code> by calling <code>server.close()</code> cleanly. Without graceful shutdown, open HTTP keep-alive sockets linger briefly in kernel state and trigger <code>EADDRINUSE</code> during fast restarts.</p>
<pre><code class="language-typescript">// Graceful shutdown in Node.js (prevents lingering sockets)
const server = app.listen(3000, "127.0.0.1");

for (const signal of ["SIGINT", "SIGTERM"]) {
  process.on(signal, () =&gt; {
    server.close(() =&gt; process.exit(0));
  });
}
</code></pre>
<h2>Inspect &amp; Clean the Full Process Tree in One Command with PortTree</h2>
<p>Instead of memorizing OS-specific <code>ss</code>, <code>lsof</code>, <code>netstat</code>, and PowerShell CIM flags, my zero-dependency Python CLI PortTree maps listening sockets to their full parent process tree across Linux, macOS, and Windows under one interface.</p>
<p>If you want to dive deeper into how kernel socket tables, supervisor inheritance, and Docker network namespaces work under the hood, read the companion PortTree architecture guide linked below.</p>
<pre><code class="language-bash"># Inspect the full process tree and working directory holding port 3000
python -m porttree --port 3000

# CI preflight check: exit 0 if free, exit 1 + JSON if occupied
python -m porttree --assert-free 3000 --json

# Safe two-stage cleanup (SIGTERM -&gt; timeout -&gt; SIGKILL)
python -m porttree --kill 3000
</code></pre>
<h2>Frequently Asked Questions</h2>
<h3>Why does EADDRINUSE come back two seconds after I kill the PID?</h3>
<p>Because you terminated a child worker whose parent supervisor (nodemon, PM2, Docker, or an IDE watcher) immediately respawned it. Inspect the parent PID (<code>PPID</code>) and stop the supervisor or container instead.</p>
<h3>Why does Windows block port 3000 even when netstat shows no listening process?</h3>
<p>Hyper-V and WSL2 reserve dynamic TCP port ranges at boot. Run <code>netsh interface ipv4 show excludedportrange protocol=tcp</code> to verify whether your port falls inside an excluded block, then either pick an unreserved port or restart the <code>winnat</code> service.</p>
<h3>Is it safe to kill -9 docker-proxy when a container holds the port?</h3>
<p>No. Killing <code>docker-proxy</code> directly can leave container networking in an inconsistent state. Locate the publishing container with <code>docker ps</code> and stop it cleanly via <code>docker stop &lt;id&gt;</code>.</p>
<h3>How do I permanently prevent EADDRINUSE in CI test suites?</h3>
<p>Bind test servers to port <code>0</code> (<code>listen(0)</code>) so the kernel assigns an unused ephemeral port, and always close the server in teardown. If a fixed port is required, add a pre-flight check such as <code>porttree --assert-free &lt;port&gt;</code> before starting the server.</p>
<hr />
<p><em>Originally published at <a href="https://umutgungorr.com/blog/eaddrinuse-port-conflict-fix?lang=en">umutgungorr.com</a>.</em></p>
]]></content:encoded></item></channel></rss>