GitHub Hour 7: Deep Troubleshooting, Optimization, and Advanced Topics

From “red X, just re-run it” to “pinpoint the root cause in three minutes, know what every minute costs, run runners on your own Kubernetes, and write integrations that won't get rate-limited or banned”
ARC gha-runner-scale-set 0.15.1actions/runner v2.338.2gh v2.104.0act v0.2.98 · actionlint v1.7.12Verified against docs.github.com · 2026-11-15
Overall learning objectives
  • Build a reusable workflow troubleshooting methodology: first classify (not triggered / stuck in queue / run failed / wrong result), then gather evidence (debug logs ACTIONS_STEP_DEBUG / ACTIONS_RUNNER_DEBUG,gh run view --log-failed, download log archives), then use workflow commands (::group::,::error file=…) and job summaries GITHUB_STEP_SUMMARY to make the next troubleshooting session faster.
  • Be able to explain why a workflow “does not trigger”: all the common causes: path/branch filters,[skip ci],GITHUB_TOKEN events produced by the workflow itself do not re-trigger it, the workflow file is missing from the default branch, expression evaluation errors; read 403s, cache misses, artifact conflicts, concurrency cancellations, the 6-hour job timeout, and the 24-hour queue limit.
  • Understand the security model of self-hosted runners (do not use with public repositories), ephemeral / JIT runners, and runner groups, and deploy with Helm on Kubernetes Actions Runner Controller (ARC) runner scale sets, explaining the mechanism “job queued → listener → scale out ephemeral runner pods → pick up job → destroy”, and choose dind / kubernetes / kubernetes-novolume container mode.
  • Use caching, job splitting, matrix, concurrency, and larger runners to speed up CI, and to estimate minute and storage costs using the 2026 price list (hosted runner prices cut by up to 39% from 2026-01-01), and to set budgets and alerts.
  • Use act and actionlint to run and check things locally first, reducing the “change one line, push, repeat” loop; and to write tests for custom actions.
  • Write reliable GitHub API / webhook integrations: understand REST primary/secondary rate limits and x-ratelimit-* headers, GraphQL points, ETag conditional requests, GitHub App installation tokens (valid for 1 hour),X-Hub-Signature-256 signature verification, redeliveries (within 3 days), and idempotent handling.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactiveLab (myapp practice repository)
0Before classSetup: fault-injection repositoryCreate myapp-chaos a practice repository, and install gh / act / actionlint / kind (optional)Self-assessment of 10 troubleshooting skillsgh run list Can see a green baseline run
100–06Troubleshooting Methodology and Debug Logsfour failure categories, the two debug-logging switches, re-running with debugging enabled, downloading logs,--log-failed, workflow commands, job summaries“Four-quadrant” troubleshooting triage tool + debug-logging switch comparisonRe-run with debug logging enabled and write a job summary
206–14Deep Dive into Common workflow Failures7 reasons a workflow does not trigger, expression evaluation, 403 permissions, cache/artifacts, concurrency cancellation, timeouts and queue limits“Why didn't it trigger?” event-matching simulatorReproduce and fix 5 classic failures
314–23Self-Hosted Runners and ARCself-hosted security risks, ephemeral/JIT, runner groups, ARC architecture, Helm installation, scaling, container modeCore animation: ARC scales runners on demandDeploy ARC on kind and run a job
423–30Performance: Caching, Parallelism, and Larger Runnerscache hit rate, splitting jobs, matrix, concurrency, speeding up dependency installs, larger runners, static IPs, GPUsCI critical path (Gantt chart) optimizerBefore/after comparison of the same CI
530–37Cost and Billing OptimizationSKU pricing and its relationship to “multipliers,” rounding, storage (artifacts/caches), Packages, Codespaces, budget alerts, and 2026 billing changesActions monthly cost calculatorExport usage reports and set budgets
637–43Local Debugging and Testingact (v0.2.98) usage and limitations, actionlint, reproducing runners in Codespaces/containers, writing tests for custom actions“Can act run it?” checkerLocal act + actionlint loop
743–52API, Webhooks, and GitHub AppsREST primary/secondary rate limits, GraphQL points, ETag, App vs OAuth vs PAT, installation tokens, signature verification, redeliveries and idempotencyCore animation: secondary rate limits and exponential backoffWrite a small client with backoff and signature verification
852–60Mixed Fault Mystery BoxRandomly inject 8 kinds of faults, diagnose using the methodology, troubleshooting treeIn-browser fault mystery box simulator + interactive troubleshooting treeDiagnose the injected faults one by one in the practice repository
—After classCheat sheet · Comprehensive labFault mystery box challenge + performance/cost optimization report + optional ARC deployment on kindFinal quiz (12 questions)Comprehensive lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commands / configurationLab
Enable and interpret debug logs✓✓·····✓gh run rerun --debug,ACTIONS_STEP_DEBUGM1 lab
Diagnose “workflow did not trigger”✓✓···✓·✓on.paths,[skip ci],gh workflow listM2 lab
Fix permission / expression / cache / artifact errors·✓·✓·✓·✓permissions:,actionlintM2 / M8
Operating self-hosted runners securely··✓·✓··✓./config.sh --ephemeral, JIT configM3 lab
Deploy ARC on Kubernetes and scale on demand··✓✓✓···helm install … gha-runner-scale-setM3 / comprehensive lab
Shorten the CI critical path···✓✓···actions/cache,strategy.matrix,concurrencyM4 lab
Estimate and control Actions costs··✓✓✓···Usage reports, budgets,retention-daysM5 lab
Run and statically check workflows locally·✓···✓·✓act -j,actionlintM6 lab
Call APIs reliably and handle webhooks······✓✓gh api -i,If-None-Match, HMAC-SHA256M7 lab

Topics excluded from this hour (and where to learn them)

TopicWhy it's not covered hereWhere to learn
Troubleshooting Git itself (conflicts, reflog, bisect, large files/LFS)Belongs to Git client and repository internalsGit 8-hour course(Lesson 5: Git in CI/CD)
workflow syntax basics, matrix, and introduction to artifactsAssumed already mastered in this courseHour 2
Reusable workflows, releases, action hardening, and SHA pinningEarlier-stage contentHour 5
GHAS, push protection, audit logs, ruleset governanceBelongs to security and governance topicsHour 6
Kubernetes itself (kind, Helm, Pod scheduling, PVCs)ARC is just one operator on K8sKubernetes 8 + 1-hour course
Operating a self-managed GitHub Enterprise Server instanceThis course follows GitHub.com (including GHEC)GHES official documentation
50 production problems and interview questionsCovered in optional Lesson 8Hour 8

How to use this course material

10 pages per module
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · audio · video. For troubleshooting content, start with the triage tool in “Animation,” then reproduce each item against the “Troubleshooting” page.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (if local storage is disabled, progress is cleared on refresh).
Chinese audio
The “Audio” page reads the script aloud using the browser's built-in Web Speech API (en-US); if no Chinese voice pack is installed, the script can still be read or passed to a TTS tool.
Version and billing notes This hour was verified on 2026-11-15 against docs.github.com and the GitHub Changelog. Latest ARC chart gha-runner-scale-set-0.15.1 (2026-10-23); actions/runner v2.338.2; gh CLI v2.104.0; nektos/act v0.2.98; actionlint v1.7.12; action versions follow this course's uniformly verified values (actions/checkout@v7.0.1,actions/cache@v6.1.0,actions/upload-artifact@v7.0.2,actions/download-artifact@v8.0.2,actions/setup-python@v7.1.0). Billing: since 2026-01-01, GitHub-hosted runner prices were cut by up to 39% (Linux 2-core $0.006/minute); the originally planned $0.002/minute platform fee for self-hosted runners starting 2026-03-01 has been announced as postponed, with no new date. Prices and limits change; check the official pages again before making production decisions.

Module 0 · Setup: fault-injection repository (complete before class)

All troubleshooting exercises in this hour are done in a practice repository “specifically for breaking things”; never inject faults into a production repository
Before class ≈ 10 minGitHub Free is sufficientThe ARC lab requires Docker + kind (optional)
Prerequisites
  • CompletedHour 2(workflow, job, step, matrix, artifacts) andHour 5(reusable workflows, SHA pinning); the Lesson 6's myorg-lab organization (example name) is optional.
  • A personal account has a myapp repository (the Flask + gunicorn + Redis example from the Docker course, including Dockerfile,/healthz,tests/), and .github/workflows/ci.yml is green on its default branch.
  • Tools: gh CLI (verified v2.104.0 for this hour), Git 2.56, Docker Engine 29; optional: act,actionlint,kind,kubectl, Helm (ARC lab).

Connection to the previous lesson

In Lesson 6 we added myapp rulesets, CODEOWNERS, and security scanning. This hour do not break things in that repository—make a copy as a public practice repository myapp-chaos: public repositories use standard GitHub-hosted runners for free, so fault injection won't consume your included quota. Note: public repositories must never register self-hosted runners (Module 3 explains why); for the ARC lab, create a separate private repository myapp-arc.

# 1) Copy the practice repository from myapp (keep history for comparison)
gh repo create myapp-chaos --public --clone
cd myapp-chaos
git remote add upstream https://github.com/$(gh api user -q .login)/myapp.git
git fetch upstream && git reset --hard upstream/main
git push -u origin main --force

# 2) Tag the baseline: all faults are injected relative to it, so you can roll back at any time
git tag baseline && git push origin baseline

# 3) Confirm the baseline run is green
gh run list --limit 3
gh run watch "$(gh run list --limit 1 --json databaseId -q '.[0].databaseId')"
STATUS  TITLE                 WORKFLOW  BRANCH  EVENT  ID           ELAPSED  AGE
✓       Initial import        ci        main    push   19283746501  1m12s    about 1 minute ago
✓ main ci · 19283746501
Triggered via push about 1 minute ago
JOBS
✓ test in 58s (ID 54839201734)

Baseline workflow (starting point for all labs in this hour)

name: ci
on:
  push:
    branches: [main]
  pull_request:
  workflow_dispatch:

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7.0.1        # In production, pin to a SHA instead (see Lesson 5)
      - uses: actions/setup-python@v7.1.0
        with:
          python-version: "3.13"
          cache: pip
      - run: pip install -r requirements.txt -r requirements-dev.txt
      - run: pytest -q --junitxml=report.xml
      - uses: actions/upload-artifact@v7.0.2
        if: always()
        with:
          name: junit-report
          path: report.xml
          retention-days: 7

Fault injection script (used in Module 8 and the comprehensive lab)

Put the script below in the repository root as chaos/inject.sh. Each run picks one of 8 faults, commits and pushes it on a new branch, then does not tell you what was injected—you need to diagnose it using the Module 1 methodology.

#!/usr/bin/env bash
# Usage: ./chaos/inject.sh [1-8]   with no argument, picks randomly
set -euo pipefail
n="${1:-$(( RANDOM % 8 + 1 ))}"
branch="chaos/$(date +%s)"
git switch -c "$branch" baseline
wf=.github/workflows/ci.yml
case "$n" in
  1) sed -i 's/^  pull_request:/  pull_request:\n    branches: [master]/' "$wf" ;;  # Wrong branch filter (PR target is main)
  2) sed -i 's/^  pull_request:/  pull_request:\n    paths: ["docs\/**"]/' "$wf" ;;   # Path filter excludes code changes
  3) sed -i 's/contents: read/contents: read\n  issues: none/' "$wf"
     printf '      - run: gh issue create -t "ci" -b "x"\n        env:\n          GH_TOKEN: ${{ github.token }}\n' >> "$wf" ;;  # Permission 403
  4) sed -i 's/cache: pip/cache: pip\n          cache-dependency-path: requirements-nonexist.txt/' "$wf" ;; # Wrong cache path
  5) printf '      - uses: actions/upload-artifact@v7.0.2\n        with:\n          name: junit-report\n          path: report.xml\n' >> "$wf" ;;  # Artifact name conflict
  6) sed -i 's/timeout-minutes: 15/timeout-minutes: 1/' "$wf"
     echo "import time; time.sleep(90)" > tests/test_slow.py ;;                   # Job timeout
  7) sed -i 's/runs-on: ubuntu-latest/runs-on: ubuntu-lates/' "$wf" ;;             # runner label typo, job stays queued
  8) sed -i 's/timeout-minutes: 15/timeout-minutes: 15\n    if: github.ref == refs\/heads\/main/' "$wf" ;; # Expression syntax error (string not quoted)
esac
git add -A && git commit -m "chore: routine update" -q
git push -u origin "$branch" -q
gh pr create --fill --head "$branch" >/dev/null || true
echo "Injected one fault into branch $branch (the number has been written to .git/chaos-answer)"
echo "$n" > .git/chaos-answer
How to roll back Each fault is on its own branch: after diagnosing, gh pr close --delete-branch just switch back to the baseline; locally git switch main. The answer is in .git/chaos-answer (it is not committed), so look at it when you are done.

Optional: ARC lab environment (Module 3 and comprehensive lab)

# kind v0.33.0 and Helm (versions follow the K8s course)
kind create cluster --name arc
kubectl cluster-info --context kind-arc
helm version --short

For kind and Helm installation steps, see Kubernetes 8 + 1-hour course. The official ARC quickstart assumes Helm 3; the K8s course in this series uses Helm 4, and the OCI chart install commands are the same. If you hit incompatibilities, follow the official ARC documentation.

Self-check list (tick off what you already know)

Module 1 · Troubleshooting Methodology and Debug Logs

00:00 – 06:00 · Classify first, gather evidence, then fix: stop “just re-running it to see”
6 minDebug logs · job summaries GA★★★★★
Learning objectives
  • Place any workflow failure into one of four categories: not triggered / stuck in queue / run failed / run succeeded but wrong result, and know the first diagnostic command for each.
  • Distinguish ACTIONS_STEP_DEBUG (step debug logs) and ACTIONS_RUNNER_DEBUG (runner diagnostic logs), and know how to use “re-run with debug logging enabled” without changing repository settings.
  • Be proficient with gh run view --log-failed,gh run view --log, downloading log archives,gh run rerun --failed --debug.
  • Use workflow commands ::group::,::error file=…,line=…::,::add-mask:: and $GITHUB_STEP_SUMMARY to make logs readable and let the problem “speak for itself.”
Prerequisites: the workflow structure from Lesson 2 and gh run basics. Importance:★★★★★ (used in every later module)

What: what exactly are we troubleshooting in a workflow?

A workflow run goes through: event (push, pull_request…) → matching (GitHub reads the workflow file at the triggering commit and evaluates the on: branch/path filters) → creating the run and jobs (parsing YAML, evaluating job-level if:,needs:) → queueing (waiting for a runner with matching labels) → runner picks up the job (downloads actions, prepares the workspace) → step execution (shell / action; produces logs, annotations, outputs) → upload (artifacts, caches, summaries) → status write-back (check run, commit status). A failure can occur at any stage, and each stage leaves different evidence.

Failure categoryTypical symptomWhere to find evidenceFirst command
A. Not triggeredNothing appears on the Actions page after a push; a required check on the PR stays at “Expected — Waiting for status to be reported”the workflow file itself, event type, commit message, triggering actor identitygh run list --workflow ci.yml --limit 5 + check on:
B. Stuck in queue“Waiting for a runner to pick up this job…”runs-on labels, runner online status, concurrency limits, runner group access policygh api repos/OWNER/REPO/actions/runners
C. Run failedred X, a step showing “Process completed with exit code 1”step logs, annotations, debug logs, runner diagnostic logsgh run view RUN_ID --log-failed
D. Wrong resultgreen check but an old version was deployed, tests were skipped, artifact is emptyif: evaluation of conditions, output variables, which cache key was restored, job summaryEnable ACTIONS_STEP_DEBUG re-run, look at ##[debug]Evaluating condition

Why: why a methodology is needed

“Re-running” only fixes transient failures (network blips, upstream registry timeouts). For deterministic failures, re-running only wastes minutes; for categories A and B, re-running is not even possible (there is no run to re-run). The value of a methodology is: spend 1 minute classifying to save 30 minutes of guessing, and let everyone on the team hand off work using the same steps.

How: two kinds of debug logs

Step debug loggingRunner diagnostic logging
Switchsecret or variable ACTIONS_STEP_DEBUG=truesecret or variable ACTIONS_RUNNER_DEBUG=true
ContentExtra lines appear in the step log: ##[debug] lines for expression evaluation, action inputs,core.debug() / ::debug:: outputs, and cache key matchingrunner process logs (coordination and setup) + worker process logs (job execution)
Where to see itDirectly in the web log (expand the collapsed debug lines)Download the log archive, in the runner-diagnostic-logs folder
Useful for investigating“why was this step skipped,” “why did the cache miss,” “what inputs did the action receive”runner connection, job dispatch, workspace setup, container startup, self-hosted runner anomalies
  • Both can be stored as a repository secret or variable; when both exist, the secret's value takes precedence. Requires write permission on an organization repository (collaborator access for personal repositories).
  • The recommended approach: without changing settings, click “Re-run jobs → Enable debug logging” on the failed run, or gh run rerun RUN_ID --debug. Anyone who can run the workflow can enable both logs for a re-run; it affects only that re-run.
  • In a step you can use the runner.debug context (when debugging is enabled, it is '1') to run diagnostic steps that run “only when debugging.”

How: workflow commands that make logs speak for themselves

CommandPurposeKey points
::group::Title / ::endgroup::Collapses a block of output into an expandable groupCollapse large dependency-install output so the real error is easy to find
::error file=F,line=L,endLine=E,col=C,endColumn=EC,title=T::messageCreates an error annotation shown on the run summary page and on the matching line in the PR's “Files changed”warning,notice takes the same parameters; file Default .github,line default 1
::debug::messageShown only when step debugging is enabledNo noise normally; turn it on when troubleshooting
::add-mask::valueReplaces a dynamically generated sensitive value in logs with ***Run once per job for each value; must be registered before output; a masked value can't be set as a job output
$GITHUB_STEP_SUMMARYWrites a Markdown job summary shown on the run summary pageUp to 1 MiB per step; exceeding it makes the upload fail and produces an error annotation; each job shows up to 20 step summaries; a failed upload does not change the step status
$GITHUB_OUTPUT / $GITHUB_ENVSets step outputs / environment variables for later stepsUse for multi-line values with a name<<EOF … EOF delimiter; the old ::set-output has been replaced by environment files

When: which tool to use when

  • CI is red → gh run view --log-failed (look only at the failed step, fastest).
  • Can't tell why a step was skipped / output is empty → with --debug re-run, search for Evaluating.
  • Job “mysteriously interrupted” on a self-hosted runner → runner diagnostic logs + the _diag/ directory on the runner host.
  • Need to show the conclusion to reviewers or on-call colleagues → job summary table + error annotations, rather than making them scroll through 5000 lines of logs.

Comparison with similar technologies

GitHub ActionsAzure PipelinesGitLab CI
Verbose logging switchACTIONS_STEP_DEBUG / re-run checkboxvariable System.Debug=true / runtime checkboxvariable CI_DEBUG_TRACE=true
Collapsed logs::group::##[group]section_start Escape sequences
Inline comments::error file=…##vso[task.logissue]Code Quality report
Markdown summary$GITHUB_STEP_SUMMARY##vso[task.uploadsummary]No native equivalent (use MR comments)
Common misconceptions① “Debug logs leak secrets”—secrets are still masked, but runner diagnostic logs and debug output are voluminous, and derived values (such as a base64-encoded token) are not masked automatically, so you must use ::add-mask::; after troubleshooting, remember to delete the repository-level debug variables. ② “Re-running uses the latest code”—re-runs use the same commit and the same workflow file as the original run; after fixing the workflow, push a new commit or use workflow_dispatch③ “--log-failed Seeing no logs does not mean there are no logs”—when a job fails before any step starts (such as a runner setup failure), look at the job-level logs or the runner diagnostic logs.

Architecture diagram: the evidence chain of one run

Eventpush / PR / dispatch Match workflowon: branch/path filters Job queuedruns-on label match Runner picks upRunner.Listener Steps runRunner.Worker Status write-backcheck run A Not triggered: no run record at allEvidence = workflow file + event + commit message + actor B Stuck in queuerunner / labels C Run failed / D Wrong resultStep logs · ##[debug] · runner-diagnostic-logs Readability tools: ::group:: collapsing · ::error file=… annotations on code lines · $GITHUB_STEP_SUMMARY summaries · ::add-mask:: masking gh run view --log-failed · gh run view --log · gh run download · gh run rerun --failed --debug
Figure 1-1 Each stage leaves different evidence; categories A and B have no step logs to look at

Flowchart: five standard troubleshooting steps

① ClassifyWhich category: A/B/C/D?gh run list ② Gather evidence--log-failedAnnotations / summary ③ Zoom inrerun --debugDownload log archive ④ Reproduce locallyactionlint / act(Module 6) ⑤ Fix + preventVerify with a new commitAdd annotations / summary / checks Only transient failures (network issues, registry 429s) are suitable for a straight re-run; re-running a deterministic failure just wastes minutes
Figure 1-2 Classify → gather evidence → zoom in → reproduce → fix and prevent

Interactive: triage tool + debug-log switch comparison

Choose the symptom on the left and the triage tool gives the category and the next command. On the right, toggle the two debug switches and watch how the log of the same failing step changes (simulated from the structure described in the official documentation: ##[debug] lines and runner-diagnostic-logs archive structure).

① Symptom you see
Select a symptom to start triage.
② Debug switches (applied to the log on the right)
$ gh run view 19283746612 --log-failed

Core commands and parameters

CommandPurposeKey parameters / notes
gh run listList runs--workflow ci.yml,--branch,--event,--status failure,--json databaseId,conclusion,headSha
gh run view RUN_IDView run summary, jobs, annotations--log-failed show only failed steps; --log all logs; --job JOB_ID; --verbose show steps
gh run watch RUN_IDFollow a run live--exit-status Makes the script return a non-zero exit code based on the result
gh run rerun RUN_IDRe-run--failed re-run only failed jobs; --debug enable debug logs; --job JOB_ID
gh run download RUN_IDDownload artifacts-n NAME,-D DIR (log archive uses the REST /logs endpoint)
gh api …/actions/runs/RUN_ID/logsDownload the full log zipRedirects to a short-lived download URL; includes runner diagnostic logs (if enabled)
gh variable set ACTIONS_STEP_DEBUGPermanently enable debugging at the repository levelAfter troubleshooting, be sure to gh variable delete

1. Fastest path: look only at the failed step

RUN=$(gh run list --workflow ci.yml --status failure --limit 1 --json databaseId -q '.[0].databaseId')
gh run view "$RUN"                 # Summary: which job, which step, annotations
gh run view "$RUN" --log-failed    # Print only the logs of failed steps
X main ci · 19283746612
Triggered via push about 3 minutes ago

JOBS
X test in 41s (ID 54839202001)
  ✓ Set up job
  ✓ Run actions/checkout@v7.0.1
  ✓ Run actions/setup-python@v7.1.0
  X Run pytest -q --junitxml=report.xml

ANNOTATIONS
X Process completed with exit code 1.
test: .github#18

test	Run pytest -q	2026-11-15T08:41:22.1934520Z FAILED tests/test_app.py::test_healthz - AssertionError: assert 500 == 200
test	Run pytest -q	2026-11-15T08:41:22.2011987Z ##[error]Process completed with exit code 1.

How to verify: The last few lines of output are near the root cause. Common errors: While the run is still in progress --log-failed there is no content—wait for the run to finish or use gh run watch. Production use: An on-call bot automatically posts --log-failed the last 50 lines of the failed job log as a PR comment.

2. Re-run with debug logging (without changing repository settings)

gh run rerun "$RUN" --failed --debug
gh run watch "$(gh run list --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')"
gh run view "$RUN" --log | grep -E '##\[debug\](Evaluating%7CResult%7CCache)' | head -20
test	Deploy	##[debug]Evaluating condition for step: 'Deploy'
test	Deploy	##[debug]Evaluating: (success() && (github.ref == 'refs/heads/main'))
test	Deploy	##[debug]Expanded: (true && ('refs/pull/42/merge' == 'refs/heads/main'))
test	Deploy	##[debug]Result: false

The re-run has the same run ID as the original, with the attempt number incremented; in the web UI you can switch to “Attempt #2” in the top right.

3. Download the full log archive (including runner diagnostic logs)

gh api "repos/{owner}/{repo}/actions/runs/$RUN/logs" > run-logs.zip
unzip -l run-logs.zip | head -20
  Length      Date    Time    Name
---------  ---------- -----   ----
     5821  2026-11-15 08:41   test/1_Set up job.txt
     1290  2026-11-15 08:41   test/2_Run actions_checkout@v7.0.1.txt
    40211  2026-11-15 08:41   test/5_Run pytest -q --junitxml=report.xml.txt
   188403  2026-11-15 08:41   runner-diagnostic-logs/Runner_20261115-084020-utc.log
   402117  2026-11-15 08:41   runner-diagnostic-logs/Worker_20261115-084031-utc.log

4. workflow commands and job summaries

      - name: Install deps
        run: |
          echo "::group::pip install"
          pip install -r requirements.txt -r requirements-dev.txt
          echo "::endgroup::"
      - name: Lint (annotate offending lines)
        run: |
          ruff check --output-format=github .   # ruff natively outputs the ::error file=…,line=… format
      - name: Test
        id: test
        run: |
          set +e
          pytest -q --junitxml=report.xml | tee pytest.txt
          rc=${PIPESTATUS[0]}
          echo "::debug::pytest rc=$rc"
          {
            echo "### Test results"
            echo ""
            echo "| Item | Value |"
            echo "|---|---|"
            echo "| Exit code | $rc |"
            echo "| Summary | $(tail -n1 pytest.txt) |"
          } >> "$GITHUB_STEP_SUMMARY"
          if [ "$rc" -ne 0 ]; then
            echo "::error file=tests/test_app.py,line=12,title=healthz regression::/healthz returns 500, check the Redis connection"
          fi
          exit $rc
      - name: Diagnostics only when debugging
        if: runner.debug == '1'
        run: |
          env | sort | grep -v -i token
          df -h; free -m

How to verify: The run summary page shows a “test summary” table; the PR's Files changed shows tests/test_app.py a red annotation on line 12. Common errors: Writing a full log over 1 MiB into the summary will be rejected; ::error The file value must be a path relative to the repository root to map to a PR line.

Lab 1: use debug logs to find a “skipped deploy step” (about 5 minutes)

Goal: reproduce a D-category failure (green check but wrong result), and use step debug logs to see the actual evaluation of the conditional expression. Environment: myapp-chaos public repository, GitHub-hosted runners, cost $0.
Add a step “deploy only on main”, deliberately writing the condition so that it is always false in the PR context:
git switch -c lab/m1-debug
cat >> .github/workflows/ci.yml <<'EOF'
      - name: Deploy (fake)
        if: github.ref == 'refs/heads/main'
        run: echo "deploying ${{ github.sha }}"
EOF
git commit -am "lab: add fake deploy" && git push -u origin lab/m1-debug
gh pr create --fill
Observe: CI on the PR is green, but the Deploy step shows as grey “skipped.”
RUN=$(gh run list --branch lab/m1-debug --limit 1 --json databaseId -q '.[0].databaseId')
gh run view "$RUN" --verbose | grep -i deploy
  - Deploy (fake)
Re-run with debug logging and search for the condition evaluation:
gh run rerun "$RUN" --debug
gh run watch "$RUN" --exit-status
gh run view "$RUN" --log | grep -A3 "Evaluating condition for step: 'Deploy (fake)'"
##[debug]Evaluating condition for step: 'Deploy (fake)'
##[debug]Evaluating: (success() && (github.ref == 'refs/heads/main'))
##[debug]Expanded: (true && ('refs/pull/7/merge' == 'refs/heads/main'))
##[debug]Result: false

Note: step-level if: if it does not contain a status function, it is implicitly wrapped with success() && (…).

Add a job summary: replace in the Test step from the “Commands” page above, and after pushing, open the run summary page to confirm the table appears.
Verify: gh run view "$RUN" --log | grep -c '##\[debug\]' is greater than 0 in the debug re-run; it is 0 in the original attempt #1.
Clean up:
gh pr close lab/m1-debug --delete-branch
gh variable delete ACTIONS_STEP_DEBUG 2>/dev/null || true   # if you enabled it with a repository variable

Case 1: integration test that “randomly fails” once a week

Problem: The integration test fails 1–2 times a week, and the team's habit is to click re-run. Approach: Automatically write the tail of the failed job's log --log-failed into the job summary and tally by error signature; after three weeks it was found that 90% were due to the Redis service container not yet being ready (ConnectionRefusedError). Configuration: Add a options: --health-cmd "redis-cli ping" --health-interval 5s to the service container, and add a wait before tests. Limitation: A truly flaky test still needs to be fixed in code; re-running only masks it.

Case 2: a monorepo's 50,000-line log that nobody reads

Problem: One job outputs 50,000 lines; when it fails, the on-call engineer needs 10 minutes to find the error. Approach: Wrap all install and build output in ::group::, and use lint/type checks with --output-format=github (or the corresponding problem matcher) to generate annotations; write test failures into a job summary table. Result: Average time to locate the error dropped from 10 minutes to under 1 minute. Limitation: There is a cap on the number of annotations (see the official documentation), so focus on the first few most important errors.

Case 3: debug variable left in place, causing log bloat and information exposure

Problem: Someone set an organization-level ACTIONS_RUNNER_DEBUG=true and forgot to delete it after troubleshooting; log volume across all repositories exploded, and diagnostic logs contained internal hostnames and paths. Approach: Switch to only using “re-run with debug logging enabled”; check whether the debug variable exists using a scheduled workflow or an audit log query. Limitation: Enabling debugging itself requires the appropriate permissions; at the organization level, restrict who can create organization-level variables/secrets.

Common errors and fixes

##[error]Process completed with exit code 1. (no other error visible in the log)

Cause: A command in the script exited non-zero, but its stderr was redirected, | tee swallowed, or bash -e in a pipeline only the last command's status is checked.

gh run view RUN_ID --log-failed | tail -50
gh run rerun RUN_ID --failed --debug

Fix: On Linux, run: the default shell is bash -e {0} (when explicitly written as shell: bash it is bash --noprofile --norc -eo pipefail {0}), so it is recommended to set the shell explicitly shell: bash to get pipefail; add set -x before critical commands.

gh run view --log-failed produces no output / failed to get run log: log not found

Cause: the run has not finished; or the job failed before “Set up job” (no runner, job cancelled); or the logs have passed their retention period (logs and artifacts default to 90 days, configurable).

gh run view RUN_ID --json status,conclusion,jobs -q '.jobs[] | {name, status, conclusion}'

Fix: Wait for it to finish; if conclusion the run is cancelled/startup_failure, go to Module 2's section on concurrency and workflow file errors.

ACTIONS_STEP_DEBUG is enabled but there are no ##[debug] lines in the log

Cause: the variable was set in a different repository/environment; the name is misspelled; the value is not true; or you are looking at an old run attempt.

gh variable list | grep ACTIONS_
gh secret list | grep ACTIONS_

Fix: The simplest approach is to gh run rerun RUN_ID --debug re-run with debug logging enabled, and switch to the latest attempt in the web UI.

Unable to process file command 'output' successfully. Invalid format 'xxx'

Cause: Writing a multi-line value to $GITHUB_OUTPUT without delimiter syntax, or with a delimiter that happens to appear in the value.

{
  echo "notes<<EOF_$(uuidgen)"   # a fixed random string also works
  cat notes.md
  echo "EOF_..."                  # same delimiter as above
} >> "$GITHUB_OUTPUT"

Fix: Use name<<DELIM … DELIM format, and make sure the delimiter does not appear on its own line in the value.

$GITHUB_STEP_SUMMARY upload aborted, supports content up to a size of 1024k

Cause: A single step summary exceeds 1 MiB (commonly from writing the full test log into the summary).

Fix: Keep only statistics and the first N failures in the summary; upload the full log as an artifact. A failed upload does not change the step status, but it does produce an error annotation.

Command-line exercises
1. One command: re-run the failed jobs from the most recent failed run, with debug logging enabled.
gh run rerun "$(gh run list --status failure --limit 1 --json databaseId -q '.[0].databaseId')" --failed --debug
2. Write a step: collapse the pip install output in the log, and generate a warning annotation on src/app.py line 3.
- run: |
    echo "::group::pip install"
    pip install -r requirements.txt
    echo "::endgroup::"
    echo "::warning file=src/app.py,line=3,title=Deprecated::FLASK_ENV is deprecated, use --debug instead"
Scenario analysis
A colleague says: “The deploy job worked yesterday; today it's green but nothing was deployed, and I re-ran it three times with the same result.” How would you troubleshoot this step by step?

① Classify: green check but wrong result → category D; re-running is pointless (same commit, same workflow). ② gh run view --verbose Check whether the deploy step/job was skipped. ③ gh run rerun --debug Look at Evaluating/Expanded lines, and confirm which context value differs from expectations (e.g., the event changed from push to workflow_dispatch, a different ref, or the upstream job output is empty). ④ Use git log -p .github/workflows to compare changes since yesterday. ⑤ After the fix, add a summary before the deploy step that records key context (event, ref, output values) to prevent recurrence.

Verified instructional videos

▶
GitHub Actions Tutorial | From Zero to Hero in 90 minutes (Environments, Secrets, Runners, etc) — CoderDave
English · systematic review of workflows, environments, secrets, and runners; for the details of debug logs and job summaries in this module, the official documentation takes precedence
▶
GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker — TechWorld with Nana
English · concept review (events, jobs, runners), good for a quick review of the run lifecycle before learning troubleshooting

No dedicated video was found covering ACTIONS_STEP_DEBUG / job summaries that has been verified; please refer to the official documentation below.

Official documentation

Video storyboard script (about 90 seconds)

This course material cannot directly generate video or MP3; the storyboard and narration script are provided so they can be passed to a video tool.

Shot 1 · 0–20s
Visual: a horizontal pipeline: event → match → queue → pick up → execute → write back, with four red warning signs A, B, C, D each placed at different positions.
Narration: workflow failures fall into four categories: not triggered, stuck in queue, run failed, wrong result. Classify first, then act.
Shot 2 · 20–45s
Visual: in the terminal, type gh run view --log-failed; only a few dozen lines of failed-step logs scroll out.
Narration: when a run fails, the first command is always the log-failed one, which gives you only the failed step's logs.
Shot 3 · 45–70s
Visual: click Re-run jobs, check Enable debug logging; grey debug lines appear in the log: Evaluating, Expanded, Result false.
Narration: Can't tell why it was skipped? Re-run with debug logging. Every step of the condition expression's evaluation is written to the log.
Shot 4 · 70–90s
Visual: the run summary page shows a table and a red annotation, and the same error appears next to the PR code line.
Narration: Finally, with groups, annotations, and job summaries, the next troubleshooting session takes just one minute.
or score ≥ 70% on the “Quiz”

Module 2 · Deep Dive into Common workflow Failures

06:00 – 14:00 · Not triggered, YAML/expressions, 403, cache and artifacts, concurrency cancellation, timeouts and queue limits
8 minLimits verified against the Actions limits pageconcurrency queue: max (new)★★★★★
Learning objectives
  • Name the 8 reasons a workflow does not trigger, especially GITHUB_TOKEN events triggered by the workflow's own actions do not create new workflow runs (workflow_dispatch,repository_dispatch exceptions).
  • Identify YAML and expression evaluation errors (Unrecognized named-value, “always true” if), and learn to catch them early with actionlint .
  • Fix 403 Resource not accessible by integration, cache misses/save conflicts, artifact 409 conflicts, and concurrency cancellations.
  • Remember the hard limits: GitHub-hosted runner jobs 6 hours, self-hosted jobs 5 days, self-hosted queue 24 hours, workflow runs 35 days, matrix 256 jobs.
Prerequisites: The four-category triage from Module 1. Importance:★★★★★

What: the 8 reasons for category A “not triggered”

#ReasonMechanismHow to confirm
1Branch / tag filter mismatchon.push.branches,branches-ignore,tags; pull_request.branches matches the target (base) branch rather than the source branch. If only tags: is specified, a regular branch push will not trigger itCompare git push the ref with the PR's base
2Path filter mismatchpaths / paths-ignore. If the diff exceeds 3,000 files and the matching file is not among the first 3,000, it will not run; pushes with more than 1,000 commits, or diff generation timeouts, will always run. Tag pushes do not evaluate path filters.git diff --name-only base...head
3Commit message contains a skip directive[skip ci],[ci skip],[no ci],[skip actions],[actions skip] or at the end skip-checks: true; only applies to push and pull_request (pull_request_target still runs)git log -1 --format=%B
4Triggered by GITHUB_TOKEN eventsTo prevent recursion, using GITHUB_TOKEN pushes, PR opens, or tag creation made with will not create new runs; the exceptions are workflow_dispatch and repository_dispatch exceptionsCheck whether the actor is github-actions[bot]
5The workflow file is not where it should bepush/PR events read the workflow file at the triggering commit; schedule,workflow_dispatch (UI button), and issue/comment events use only the default branch's file; a file with invalid YAML will not run (it shows a workflow file error)gh workflow list --all, and a red “Invalid workflow file” on the Actions page
6The workflow or Actions is disabledmanually disabled; repository/organization policy forbids Actions; a public repository with 60 days of no activity schedule is automatically disabledgh workflow list --all Check the state
7PR-specific conditionspull_request By default only responds to opened,synchronize,reopened; a PR exists Merge conflicts mean the workflow does not run; first-time contributor fork PRs need maintainer approval;the PR page shows “Approve and run” or a conflict
8Trigger rate limitsEach repository allows at most 1,500 trigger events per 10 seconds; webhook-triggered runs beyond 500 runs / 10 seconds are blocked rather than queuedOnly encountered in large-scale automation or bot scenarios
Required-check pitfall Checks of a workflow skipped by path filters, branch filters, or skip directives remain in Pending. If a ruleset makes it a required check, the PR cannot merge. A common fix: remove the workflow-level paths, and instead use an dorny/paths-filter@v4.0.3 condition inside the job, then have an always-running “gate” job aggregate the results and serve as the only required check.

Why: why GITHUB_TOKEN GITHUB_TOKEN-triggered events do not create new runs

If workflow A uses GITHUB_TOKEN to push a commit, that push would trigger workflow A again, causing an endless loop that burns minutes. So GitHub rules that such events do not create new runs. When you need “a release workflow tags, then triggers the deploy workflow,” the options are: ① in the same workflow, chain them with needs , or call a reusable workflow (Lesson 5); ② use workflow_dispatch / repository_dispatch (gh workflow run deploy.yml); ③ use a GitHub App installation token (actions/create-github-app-token) to push — the token identity is different, so the push triggers runs, but you must prevent loops yourself.

How: the six families of category C “run failed”

FamilyTypical errorRoot cause
YAML / workflow fileInvalid workflow file … (Line: 14, Col: 9): Unexpected value 'step'; conclusion startup_failureindentation, misspelled keys, reusable workflow reference missing or insufficient permissions
Expression evaluationUnrecognized named-value: 'refs'; if always truestring literals must use single quotes; if: "${{ a }} == b" after interpolation it is a non-empty string → always true
PermissionsHTTP 403: Resource not accessible by integration; Permission to o/r.git denied to github-actions[bot]permissions: required scope not granted; fork PR tokens are read-only; the organization default token permission is read-only
CacheCache not found for input keys: …; 409 conflict on save / “Unable to reserve cache”key contains volatile content, branch-scope isolation, concurrent saves with the same key (caches cannot be overwritten)
Artifacts(409) Conflict: an artifact with this name already exists on the workflow run; No files were found with the provided pathfrom v4, artifacts are immutable and names must be unique within a run; wrong path (default if-no-files-found: warn)
Concurrency / timeoutsCanceling since a higher priority waiting request for 'ci-main' exists; The job … has exceeded the maximum execution time of 360 minutes.concurrency group design; timeout-minutes default 360

Hard limits (docs.github.com Actions limits, verified 2026-11)

ItemLimitResult when exceeded
Job execution time (GitHub-hosted)6 hoursjob is terminated and fails
Job execution time (self-hosted)5 daysjob is terminated
Self-hosted job queue time24 hoursautomatically cancelled if no runner starts it within 24 hours
Total workflow run duration35 days (including waiting and approvals)run is cancelled
matrix256 jobs per workflow runworkflow is invalid
Concurrent jobs (standard hosted)Free 20 / Pro 40 / Team 60 / Enterprise 500; macOS 5 / 5 / 5 / 50excess jobs are queued
GITHUB_TOKEN API requests1,000 per repository per hour (GHEC resource 15,000)403/429 rate limiting
GITHUB_TOKEN Validityexpires when the job ends; on self-hosted runners it can be refreshed up to 24 hoursJobs longer than that need another authentication method

When: how to choose the fix direction

  • No run record → rule out items 1–8 in the table above one by one; the most common are 1, 2, and 4.
  • A run shows “This run likely failed because of a workflow file issue” → YAML/expression family; first run actionlint.
  • 403 → first check the actual permissions listed in the “GITHUB_TOKEN Permissions” block at the top of the log.
  • Canceled → check whether a newer run in the same group arrived (concurrency), or a manual cancel, or a timeout.

Comparison with similar technologies

GitHub ActionsAzure PipelinesGitLab CI
Skip CI[skip ci] and 5 others + skip-checks: true[skip ci] / ***NO_CI***[skip ci] / -o ci.skip
Recursion-prevention triggerGITHUB_TOKEN events don't triggerbuild service account pushes trigger by default (you must prevent loops yourself)CI_JOB_TOKEN push restrictions
Hosted job timeout6 hoursMicrosoft-hosted 1 hour (free tier) / 31 hours (paid parallel)Configurable per project, default 1 hour
Common misconceptions① “pull_request.branches: [feature/*] will apply to PRs from feature branches”—it actually matches the PR's target branch. ② “I pushed the fix, so just re-run it”—re-runs use the workflow file from the original commit. ③ “if: ${{ github.ref }} == 'refs/heads/main' works”—${{ }} if only part is wrapped, the result is a string,always true; either put the entire expression inside ${{ }}, or omit ${{ }}. ④ “cancel-in-progress only cancels queued runs”—it cancels in-progress runs in the same group; without it, only waiting runs are replaced.

Decision diagram: the filter gates between event → workflow run

Eventpush / PR … Is the actorGITHUB_TOKEN? Actions/workflowEnabled? Valid YAML?(file at this ref) Branch/tagfilter match? Path filtermatch? Commit message has no[skip ci]? Yes → no run created No → no run No → failed run“workflow file issue” No → no run No → no run* Yes → no run* Create workflow run→ evaluate job if / needs → queue * When skipped by path/branch filters or skip directives,the corresponding required check stays Pending and the PR cannot merge Exception: workflow_dispatch / repository_dispatch run even when initiated by GITHUB_TOKEN
Figure 2-1 Gates between event and run (the order is simplified for teaching; the actual platform logic is internal and more complex)

Sequence diagram: three behaviors of a concurrency group

group: ci-${{ github.ref }} Default (queue: single) Run #1 in progress #2 waiting → replaced by #3 #3 runs after #1 completes cancel-in-progress: true #1 is cancelled #2 starts immediately queue: max (up to 100 waiting) #1 #2 (FIFO) #3 (FIFO) cannot be used together with cancel-in-progress
Figure 2-2 By default each group allows at most 1 waiting run; a newer run replaces the older waiter; queue: max per the docs, up to 100 waiting runs are allowed

Simulator: “Why didn't my workflow trigger?”

Choose a scenario and step through it; the simulator evaluates the gates in the order of Figure 2-1. The log below shows the confirmation commands you should run and how GitHub actually behaves.

Please select a scenario.
$ git push origin main

Core commands and parameters

Command / configurationPurposeNotes
gh workflow list --allList workflows including disabled oneswhere state is disabled_manually / disabled_inactivity
gh workflow enable ci.ymlRe-enableused when a schedule was disabled due to inactivity
gh workflow run deploy.yml -f env=prodTrigger workflow_dispatchrequires the workflow to exist on the default branch and declare workflow_dispatch
actionlintStatically check workflowdetects expression syntax, undefined contexts, and shellcheck issues (Module 6)
permissions:Declare GITHUB_TOKEN permissionsworkflow-level or job-level; scopes not listed after declaring are none
concurrency:Concurrency groupgroup,cancel-in-progress,queue
timeout-minutes:Job/step timeoutjob default 360; recommended to set at 2–3× P95

1. Troubleshoot “not triggered”

git log -1 --format='%H%n%B'                          # check whether the commit message has [skip ci]
git diff --name-only origin/main...HEAD               # whether the changed files match paths
gh workflow list --all                                # whether the workflow is disabled
gh api "repos/{owner}/{repo}/actions/permissions" -q '.enabled'   # whether the repository allows Actions
gh run list --workflow ci.yml --limit 5 --json event,headBranch,conclusion,createdAt
NAME     STATE               ID
ci       active              71234501
nightly  disabled_inactivity 71234502
true

2. Trigger with dispatch instead of GITHUB_TOKEN pushes

permissions:
  contents: write
  actions: write          # required to call workflow_dispatch
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7.0.1
      - run: |
          git tag "v${VERSION}" && git push origin "v${VERSION}"   # this push will not trigger deploy.yml
          gh workflow run deploy.yml -f tag="v${VERSION}"            # but workflow_dispatch will
        env:
          GH_TOKEN: ${{ github.token }}
          VERSION: 1.4.0

3. Correct expression syntax

# ✗ Always true: after interpolation it becomes the non-empty string "refs/heads/dev == 'refs/heads/main'"
if: ${{ github.ref }} == 'refs/heads/main'
# ✗ Syntax error: Unrecognized named-value: 'refs'
if: github.ref == refs/heads/main
# ✓ Two correct forms
if: github.ref == 'refs/heads/main'
if: ${{ github.ref == 'refs/heads/main' && github.event_name == 'push' }}
# ✓ Checking upstream job outputs (outputs are always strings)
if: needs.build.outputs.changed == 'true'

4. Confirming and fixing 403 permission errors

gh run view RUN_ID --log | sed -n '/GITHUB_TOKEN Permissions/,/Secret source/p'
test	Set up job	GITHUB_TOKEN Permissions
test	Set up job	  Contents: read
test	Set up job	  Metadata: read
test	Set up job	Secret source: Actions
permissions:
  contents: read
  issues: write          # gh issue create / comment
  pull-requests: write   # PR comments, labels
  id-token: write        # OIDC (Lessons 3 and 4)

5. Safe way to write caches and artifacts

- uses: actions/cache@v6.1.0
  with:
    path: ~/.cache/pip
    key: pip-${{ runner.os }}-py3.13-${{ hashFiles('requirements*.txt') }}
    restore-keys: |
      pip-${{ runner.os }}-py3.13-
- uses: actions/upload-artifact@v7.0.2
  with:
    name: junit-${{ matrix.python }}-${{ github.run_attempt }}   # name stays unique across matrix/re-runs
    path: report.xml
    if-no-files-found: error      # fail immediately on a wrong path instead of silently warning
    retention-days: 7

6. Concurrency and timeouts

concurrency:
  group: ci-${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}   # cancel old runs for PRs; do not cancel on main
jobs:
  test:
    timeout-minutes: 15

Production use: The concurrency group for the deploy workflow must not enable cancel-in-progress, otherwise a deployment cancelled midway would leave an inconsistent state; use default queuing or queue: max.

Lab 2: reproduce and fix 5 classic failures (about 8 minutes)

Goal and environment: on myapp-chaos , use the injection script to reproduce faults 1 (branch filter), 3 (403), 5 (artifact conflict), 7 (label typo), and 8 (expression), cost $0 (public repository).
Fault 1: PR did not trigger
./chaos/inject.sh 1
gh pr checks "$(git branch --show-current)"
no checks reported on the 'chaos/1763190001' branch

Diagnosis: git diff baseline -- .github/workflows/ci.yml Seeing pull_request.branches: [master], while the PR's base is main. Fix: remove the filter or change it to [main], and check that the run appears after pushing.

Fault 3: 403
./chaos/inject.sh 3
RUN=$(gh run list --branch "$(git branch --show-current)" --limit 1 --json databaseId -q '.[0].databaseId')
gh run watch "$RUN"; gh run view "$RUN" --log-failed | tail -3
test	Run gh issue create	GraphQL: Resource not accessible by integration (createIssue)
test	Run gh issue create	##[error]Process completed with exit code 1.

Fix: add at the job level permissions: { contents: read, issues: write }.

Fault 5: artifact conflict
./chaos/inject.sh 5   # after the run finishes
gh run view "$(gh run list --limit 1 --json databaseId -q '.[0].databaseId')" --log-failed | grep -i conflict
##[error]Failed to CreateArtifact: Received non-retryable error: Failed request: (409) Conflict: an artifact with this name already exists on the workflow run

Fix: remove the duplicate upload or rename it; to merge multiple artifacts, use actions/upload-artifact/merge a helper action.

Fault 7: stuck in queue: the run page shows “Waiting for a runner to pick up this job…”. gh run view RUN_ID --json jobs -q '.jobs[].labels' Check ["ubuntu-lates"], fix the label. Think: if this were a self-hosted label, what would happen after 24 hours? (Answer: the job is automatically cancelled.)
Fault 8: expression: the Actions page shows “Invalid workflow file”; details Unrecognized named-value: 'refs'. Locally actionlint .github/workflows/ci.yml can directly point to the line and column. Fix it to if: github.ref == 'refs/heads/main'.
Verify: after each fix is pushed, gh pr checks everything is green.
Clean up:
for b in $(git branch -r | grep 'origin/chaos/' | sed 's#origin/##'); do gh pr close "$b" --delete-branch || git push origin --delete "$b"; done
git switch main && git branch | grep chaos/ | xargs -r git branch -D

Case 1: deployment did not trigger after release-please merge

Problem: release-please (googleapis/release-please-action@v5.0.0) using the default GITHUB_TOKEN creates a Release and tag, but the deploy workflow listening for release: published the deploy workflow never ran. Approach: Confirm that this is a “GITHUB_TOKEN event does not trigger new runs.” Instead, in the same workflow, use needs: release + if: needs.release.outputs.release_created to chain the deploy job. Limitation: If the organization requires deployment in a separate workflow, create the Release with a GitHub App token and add a loop-prevention condition in the deploy workflow.

Case 2: monorepo required check stuck on Pending forever

Problem: The frontend workflow is configured with paths: [web/**] and is set as a required check, so PRs that change only the backend cannot merge. Approach: Remove the workflow-level path filter, and use dorny/paths-filter@v4.0.3 in the first job to output the changed scope, and each job if: uses an if condition; the last gate job if: always() checks needs.*.result for any failure/cancelled skipped results; only the gate is set as a required check. Limitation: Every PR starts a very short job (a few seconds, but billed rounded up to the minute).

Case 3: concurrency cancellation of a deployment leaves half-built resources

Problem: The deploy workflow reused the CI's cancel-in-progress: true, and two quick merges caused the first Terraform apply to be cancelled midway, leaving the state lock behind. Approach: Change the deploy group to concurrency: { group: deploy-prod } not cancel; at the Terraform level, use -lock-timeout. Limitation: By default only one waiting run is kept, so intermediate deployments are replaced and skipped—this is the desired behavior for “deploy only the latest version”; if you need to deploy each one in turn, consider queue: max.

Common errors and fixes

Invalid workflow file: .github/workflows/ci.yml#L14 — The workflow is not valid. (Line: 14, Col: 9): Unrecognized named-value: 'refs'

Cause: a string literal in the expression is not in single quotes; or a nonexistent context is used.

actionlint .github/workflows/ci.yml

Fix:if: github.ref == 'refs/heads/main'. String literals in expressions must use single quotes; double quotes cause an error.

HTTP 403: Resource not accessible by integration

Cause:GITHUB_TOKEN the corresponding permission is missing; or in a fork PR the token is read-only and cannot access secrets.

gh run view RUN_ID --log | sed -n '/GITHUB_TOKEN Permissions/,/Secret source/p'
gh api "repos/{owner}/{repo}/actions/permissions/workflow"   # the repository's default token permissions

Fix: Declare the required scopes at the job level with least privilege. When a fork PR needs to post comments, use pull_request_target but never check out and execute PR code (from checkout v7 onward, checking out fork PRs is blocked by default for this event; see Lessons 5 and 6).

remote: Permission to owner/repo.git denied to github-actions[bot]. fatal: unable to access … 403

Cause:contents: write not granted; or the branch is protected by a ruleset and the bot is not on the bypass list.

Fix: Add permissions: contents: write; protected branches should be merged via PR, or use a GitHub App that the ruleset allows to bypass.

Cache not found for input keys: pip-Linux-py3.13-8f3a…, pip-Linux-py3.13-

Cause: first run; a cache not accessed for 7 days is deleted; the repository exceeded its cache limit and entries were evicted by last-access time; or on a feature branch, caches from sibling branches other than the default branch cannot be found (scope isolation).

gh cache list --limit 20
gh cache list --key pip-Linux --json key,ref,sizeInBytes,lastAccessedAt

Fix: Make sure runs on the default branch save the cache (so PRs can reuse it); use restore-keys as a prefix fallback.

Failed to save: Unable to reserve cache with key …, another job may be creating this cache. (or 409 Conflict)

Cause: cache entries cannot be overwritten: the same key (same version, same scope) already exists or is being saved concurrently by parallel matrix jobs.

Fix: This is warning-level and does not fail the job; to update content, make the key include a hash of the dependency file; in a matrix, put matrix variable into the key.

Canceling since a higher priority waiting request for 'ci-refs/heads/main' exists

Cause: A new run arrived in the same concurrency group; by default it replaces the waiting run, and with cancel-in-progress enabled, in-progress runs are cancelled too.

Fix: Check whether the group name is too broad (for example, all branches share one group); do not cancel in-progress runs for deploy groups.

The job running on runner GitHub Actions 12 has exceeded the maximum execution time of 360 minutes.

Cause: timeout-minutes is not set timeout-minutes (default 360); the job hangs (waiting for interactive input, deadlocked tests) until the 6-hour cap.

Fix: Set a reasonable timeout for each job; add per-test timeouts in the test framework (such as pytest-timeout); split long tasks or move them to self-hosted runners (5-day limit).

Command-line exercises
1. List all disabled workflows in the repository, and re-enable the one named nightly.
gh workflow list --all | grep disabled
gh workflow enable nightly
2. Write a concurrency configuration that cancels old runs for PRs but does not cancel on the main branch.
concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}
Scenario analysis
The team's “auto-update dependencies” workflow uses GITHUB_TOKEN to push branches and open PRs, but these PRs never get CI checks, so they cannot be merged. How do you fix this? What are the trade-offs of each option?

Cause: GITHUB_TOKEN PRs/pushes it creates do not trigger new runs. Options: ① use a GitHub App installation token (actions/create-github-app-token) to push and open PRs—this triggers CI, permissions can be fine-grained, and the token expires in 1 hour; recommended. ② use a fine-grained PAT—workable, but tied to a personal account, leaves a departure risk and needs rotation; ③ after opening the PR, use gh workflow run ci.yml --ref branch to trigger it—this requires CI to declare workflow_dispatch, and the check name is associated with the PR differently, so the required checks may not match; ④ switch to Dependabot (Lesson 6), whose PRs do trigger CI (note: runs triggered by Dependabot have restricted secrets).

Verified instructional videos

▶
Github Actions CI/CD - Everything you need to know to get started — DevOps Journey
English · introductory explanation of triggers, filters, and job dependencies; for this module's limits and non-trigger rules, the official documentation takes precedence
▶
5 Ways to DevOps-ify your App - Github Actions Tutorial — Fireship
English · short video for a quick review of common workflow usage

Official documentation

Video storyboard script (about 90 seconds)

This course material cannot directly generate video or MP3; the storyboard and narration script are provided.

Shot 1 · 0–25s
Visual: an event ball moves along a conveyor belt, passing six gates in turn: token, enabled, YAML, branch, path, skip directive.
Narration: a push has to become a run by passing through several gates. If any one of them fails, nothing happens.
Shot 2 · 25–50s
Visual: the github-actions bot icon pushes a tag; an arrow points to the deploy workflow, blocked by a red X; beside it, a workflow_dispatch arrow passes through in green.
Narration: events produced with GITHUB_TOKEN do not trigger new runs; this design prevents infinite loops. When you need to chain them, use dispatch or a GitHub App token.
Shot 3 · 50–75s
Visual: the if-expression string “refs/heads/dev == 'refs/heads/main'” is highlighted as “non-empty string = true”.
Narration: if the double curly braces wrap only half, the result is a string that is always true. The whole expression must be wrapped entirely, or not at all.
Shot 4 · 75–90s
Visual: a timer shows three limits: 6 hours, 24 hours, 35 days.
Narration: finally, remember three numbers: hosted jobs six hours, self-hosted queue twenty-four hours, the whole run thirty-five days.
or score ≥ 70% on the “Quiz”

Module 3 · Self-Hosted Runners and ARC (Kubernetes)

14:00 – 23:00 · Put runners inside your own network and cluster: security boundaries, ephemeral runners, on-demand scaling
9 minARC gha-runner-scale-set 0.15.1 (2026-10-23)Self-hosted runners disabled for public repositories★★★★☆
Learning objectives
  • Explain the risks of self-hosted runners: any fork PR on a public repository may execute code on your machine; state left behind on persistent runners and credential leakage.
  • Be able to register ephemeral runners (--ephemeral) and JIT runners (REST generate-jitconfig), and use runner groups to restrict which repositories/workflows can use which runners.
  • Install ARC with Helm: gha-runner-scale-set-controller + gha-runner-scale-set (OCI chart), and understand how the controller, listener, EphemeralRunnerSet, and EphemeralRunner work together.
  • Choose a container mode based on requirements dind / kubernetes / kubernetes-novolume, and configure minRunners/maxRunners and GitHub App authentication.
Prerequisites:K8s courseon Pods, ServiceAccounts, and Helm. Importance:★★★★☆ (essential for platform teams)

What: what are self-hosted runners and ARC

A self-hosted runner is a program you run on your own VM, physical machine, or container actions/runner (latest verified in this hour: v2.338.2). It connects to GitHub via outbound HTTPS long polling and needs no inbound ports open. It can be registered at the repository, organization, or enterprise level. Actions Runner Controller (ARC) is a Kubernetes operator maintained by GitHub that creates ephemeral runner Pods on demand in the cluster, in the form of “runner scale sets.”

Why: why (and when not) to use self-hosted runners

ReasonDetailsAlternative
Access private networksDeploy to internal databases and private Kubernetes APIslarger runners with Azure private networking / static IPs (Module 4), OIDC + private endpoints
Special hardware / OSARM servers, GPUs, specific kernels, macOS signing machinesGitHub-hosted arm64 / GPU larger runners
CostYour own compute is cheaper at high minute volumes; currently GitHub does not charge per-minute fees for self-hosted runners (the platform fee originally planned for 2026-03 has been postponed)Decide after doing the optimizations in Modules 4 and 5
ComplianceBuilds must run in a specified region/data centerGHEC data residency (per official documentation)
Security red line Official recommendation Use self-hosted runners only in private repositories. In a public repository, anyone can fork and submit a PR that causes malicious code to run on your runner (cryptomining, lateral movement, stealing credentials cached on the runner). Even in private repositories, a persistent (non-ephemeral) runner keeps files, Docker images, and environment variables from the previous job, causing cross-job contamination.

How: three runner lifecycles

Persistent runnerEphemeral runnerJIT runner
Registration method./config.sh --url … --token …Same as above, plus --ephemeralREST POST …/actions/runners/generate-jitconfig returns encoded_jit_config,./run.sh --jitconfig …
JobsunlimitedAutomatically deregisters after running only 1 job1 job; no registration token needed; one-time configuration
Suitable forlabs, solo projectsVM autoscaling group + rebuild each timecustom schedulers; ARC uses JIT internally
Risksstate left behind, credentials persistrequires an external mechanism to supply new runnersSame as left; a leaked JIT config means the runner can be impersonated, so protect it

Runner groups: at the organization/enterprise level, group runners (or ARC scale sets) and configure which repositories can use them, whether public repositories are allowed, and optionally restrict to specific workflows. The default group is “Default.” Plan requirements for creating additional runner groups are per the official documentation.

How: how ARC works (runner scale set mode)

  1. Helm install the controller (controller manager Pod, namespace such as arc-systems).
  2. Install a runner scale set: the AutoscalingRunnerSet controller gets the runner group ID from GitHub, creates or fetches the scale set in the Actions service, and then creates listener resources.
  3. listener Pod After authenticating, it keeps an HTTPS long-poll connection with the Actions service; while idle it does nothing, until it receives Job Available a message.
  4. When a job in the workflow with runs-on: arc-runner-set is assigned to the scale set; if the listener can scale to the desired count, it acknowledges the message.
  5. The listener uses the Kubernetes API via a ServiceAccount + Role to patch the desired replica count of the EphemeralRunnerSet.
  6. EphemeralRunnerSet creates EphemeralRunners; the EphemeralRunner controller, for each runner, requests a JIT configuration and creates a runner Pod (retried up to 5 times if the Pod fails).
  7. The runner registers with the JIT token, starts its own long polling, receives job details and executes them, and streams logs and status back in real time.
  8. After the job ends, the controller confirms with the service that the runner can be deleted, then deletes the EphemeralRunner and Pod, and the replica count drops back to minRunners. If no runner picks up the job within 24 hours, the service cancels the assignment.

Container mode comparison

containerMode.typeMechanismRequirementsSuitable for
(not set)the runner container runs steps directly; cannot use container:/services:/Docker container actionsNonepure script / language toolchain builds
dindeach runner Pod carries a Docker daemon (K8s v1.29+ as a sidecar)the dind container requires privilegedRequired docker build / docker compose jobs; clusters with lower security requirements
kubernetesrunner container hooks handle container jobs, services, and container actions by creating separate Podsrequires PVs and dynamic provisioning (StorageClass); jobs without a container fail by default (ACTIONS_RUNNER_REQUIRE_JOB_CONTAINER)multi-tenant clusters that disallow privileged
kubernetes-novolumeUses container lifecycle hooks to move the job's filesystem between Pods; no PV neededSame as above; no shared storage neededClusters without dynamic volume provisioning

When: selection guidance

  • Teams < 20 people with no internal network needs → keep using GitHub-hosted runners.
  • Need internal network access, already have a K8s platform → ARC + kubernetes mode + GitHub App authentication + dedicated node pool.
  • For Docker builds → prefer remote BuildKit builds / Kaniko as an alternative to dind, or isolate dind runners on a dedicated node pool.
  • Enterprise-level runners (enterprise scope) require classic PAT authentication in ARC (per official documentation).

Comparison with similar technologies

ARC (scale set)Legacy ARC (community, summerwind)GitLab Runner K8s executorAzure Pipelines self-hosted / Managed DevOps Pools
MaintainerGitHubCommunity (legacy pattern, not recommended for new deployments)GitLabMicrosoft
Scaling triggerlistener long-polls the Actions servicewebhook / polling API (prone to rate limiting)runner polls for jobsplatform-managed pool
runner lifecycleone-time JITpersistentper-job Podconfigurable
Common misconceptions① “The runner is on the internal network, so inbound ports must be opened”—runners only initiate outbound HTTPS. ② “ARC scales based on CPU utilization”—it scales based on the number of jobs assigned to the scale set, not HPA. ③ “Ephemeral means it's safe”—ephemeral fixes state leftovers, but it cannot stop a malicious PR from accessing the cluster network or ServiceAccount during a job; you still need NetworkPolicy, least privilege, and private repositories only. ④ “runs-on Multiple labels can match ARC”—an ARC scale set uses the install name (runnerScaleSetName) as its runs-on value.

Architecture diagram: ARC components and their connections to GitHub

GitHub workflow runruns-on: arc-runner-set Actions servicerunner scale set(belongs to a runner group) REST APIJIT config / runner group Kubernetes cluster (kind / AKS / EKS) namespace arc-systems controllermanager listener PodHTTPS long polling namespace arc-runners AutoscalingRunnerSet (helm release) EphemeralRunnerSet (replicas = desired count) runner Pod runner Pod added on demand each Pod = 1 EphemeralRunner (JIT, runs 1 job) dind: Pod includes a docker sidecar; kubernetes: a separate job Pod Outbound 443:Job Available message patch runner registers with JIT → picks up job → streams logs back
Figure 3-1 All connections are outbound HTTPS initiated by the cluster; scaling is based on the number of jobs assigned to the scale set

Trust boundary: why self-hosted runners cannot be used with public repositories

Stranger forksmodifies ci.yml / tests PR to the public repository(approval may be bypassed or clicked by mistake) Your self-hosted runnerexecutes arbitrary code internal lateral movement / cloud metadata endpoint leftover credentials, Docker socket, cache persistent backdoor (non-ephemeral runner) Mitigations: private repositories only + runner groups restricting repositories + ephemeral/JIT + dedicated network segment + do not mount the host Docker socket
Figure 3-2 Attack surface of self-hosted runners

Core animation: ARC scales runners on demand

Click “Enqueue job” to simulate a workflow producing jobs, then play or step through. Each step corresponds to the real actions described in the ARC documentation: the listener receives Job Available a message → patches EphemeralRunnerSet → the controller requests a JIT config and creates a Pod → the runner registers and picks up the job → Pod is deleted after completion.

minRunners 0 maxRunners 3
GitHub job queue
listener / EphemeralRunnerSet
runner Pods (arc-runners)
Created (requesting JIT)Pending / registeringRunning jobCompleted → deleted

Core commands and parameters

CommandPurposeKey parameters
./config.shRegister a self-hosted runner--url,--token,--ephemeral,--labels,--runnergroup,--unattended,--name
sudo ./svc.sh install|start|statusrun as a systemd serviceLinux/macOS
gh api …/actions/runners/registration-tokenGet a registration token (valid for 1 hour)POST; repository- or organization-level
gh api …/actions/runners/generate-jitconfigGenerate JIT configurationname,runner_group_id,labels[]
helm install arc … gha-runner-scale-set-controllerInstall ARC controller--namespace arc-systems --create-namespace,--version
helm install NAME … gha-runner-scale-setInstall a runner scale setgithubConfigUrl,githubConfigSecret,minRunners,maxRunners,runnerGroup,containerMode.type
kubectl get autoscalingrunnersets,ephemeralrunnersets,ephemeralrunners -AView ARC custom resourcesPreferred for troubleshooting

1. Register an ephemeral runner on a VM (private repository)

mkdir actions-runner && cd actions-runner
VER=2.338.2
curl -fsSLo runner.tgz "https://github.com/actions/runner/releases/download/v${VER}/actions-runner-linux-x64-${VER}.tar.gz"
tar xzf runner.tgz
TOKEN=$(gh api -X POST repos/OWNER/myapp-arc/actions/runners/registration-token -q .token)
./config.sh --url https://github.com/OWNER/myapp-arc --token "$TOKEN" \
  --name vm-eph-01 --labels linux,x64,lab --ephemeral --unattended
./run.sh        # automatically deregisters and exits after running one job
√ Connected to GitHub
√ Runner successfully added
√ Settings Saved.
√ Connected to GitHub
2026-11-15 09:02:11Z: Listening for Jobs
2026-11-15 09:03:40Z: Running job: test
2026-11-15 09:04:31Z: Job test completed with result: Succeeded

In production, verify the tar package's SHA-256 (provided on the release page). The registration token is valid for 1 hour; do not bake it into an image.

2. JIT runner (no registration token needed; one-time configuration)

JIT=$(gh api -X POST repos/OWNER/myapp-arc/actions/runners/generate-jitconfig \
  -f name="jit-$(date +%s)" -F runner_group_id=1 -f 'labels[]=self-hosted' -f 'labels[]=lab' \
  -q .encoded_jit_config)
./run.sh --jitconfig "$JIT"

3. Install ARC with Helm (official quickstart syntax + GitHub App authentication)

# controller
helm install arc \
  --namespace arc-systems --create-namespace \
  --version 0.15.1 \
  oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set-controller

# Authentication: GitHub App recommended for production (the Secret must be in the same namespace as the scale set)
kubectl create namespace arc-runners
kubectl create secret generic gh-app -n arc-runners \
  --from-literal=github_app_id=123456 \
  --from-literal=github_app_installation_id=7890123 \
  --from-file=github_app_private_key=./arc-app.private-key.pem

# runner scale set: the install name is the value of runs-on
helm install arc-runner-set \
  --namespace arc-runners \
  --version 0.15.1 \
  --set githubConfigUrl="https://github.com/OWNER/myapp-arc" \
  --set githubConfigSecret=gh-app \
  --set minRunners=0 --set maxRunners=5 \
  --set containerMode.type=kubernetes-novolume \
  oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set

kubectl get pods -n arc-systems
NAME                                     READY   STATUS    RESTARTS   AGE
arc-gha-rs-controller-6d9f8b7c5d-x2lqp   1/1     Running   0          60s
arc-runner-set-754b578d-listener         1/1     Running   0          20s

How to verify: The repository's Settings → Actions → Runners shows a scale set named arc-runner-set . Common errors: The Secret is placed in arc-systems rather than the scale set's namespace; an App ID written unquoted into values.yaml is parsed as a number (the official guidance is to quote IDs as strings). Production use: Manage the two releases with Argo CD/Flux, with values files stored in Git.

4. Use the scale set in a workflow

name: arc-demo
on: workflow_dispatch
jobs:
  build:
    runs-on: arc-runner-set            # = Helm install name / runnerScaleSetName
    container: python:3.13-slim        # jobs need a container in kubernetes(-novolume) mode
    steps:
      - uses: actions/checkout@v7.0.1
      - run: python -c "import platform; print(platform.node())"
gh workflow run arc-demo.yml -R OWNER/myapp-arc
kubectl get pods -n arc-runners -w
NAME                                READY   STATUS              AGE
arc-runner-set-hbq4k-runner-7x2mz   0/1     ContainerCreating   2s
arc-runner-set-hbq4k-runner-7x2mz   1/1     Running             6s
arc-runner-set-hbq4k-runner-7x2mz-workflow   0/1   Pending      9s
arc-runner-set-hbq4k-runner-7x2mz-workflow   1/1   Running      14s
arc-runner-set-hbq4k-runner-7x2mz   0/1     Completed           41s
arc-runner-set-hbq4k-runner-7x2mz   0/1     Terminating         42s

5. Upgrade and uninstall (Helm cannot upgrade CRDs)

# Official upgrade process: first uninstall all scale sets, wait for cleanup, then uninstall the controller, delete the actions.github.com CRDs if necessary, then reinstall
helm uninstall arc-runner-set -n arc-runners
kubectl get ephemeralrunners -n arc-runners        # wait until empty
helm uninstall arc -n arc-systems
kubectl get crd | grep actions.github.com

Lab 3: deploy ARC on kind and observe scaling (about 10 minutes, optional)

Goal and environment: a kind cluster on a local machine or lab VM arc (created in Module 0), private repository OWNER/myapp-arc. Cost: $0 locally; billed per VM on cloud VMs. Permissions: repository admin (to create App / PAT). Risk: Use private repositories only; for the lab PAT, set a 7-day expiration and delete it during cleanup.
Create a private repository and add the workflow:
gh repo create myapp-arc --private --clone && cd myapp-arc
mkdir -p .github/workflows
# write arc-demo.yml from section 4 of the “Commands” page
git add . && git commit -m "arc demo" && git push -u origin main
Install the controller and scale set: for the lab, a fine-grained PAT (repository Administration: read and write) or classic PAT (repo); use a Secret reference rather than plaintext on the command line:
kubectl create namespace arc-runners
kubectl create secret generic gh-pat -n arc-runners --from-literal=github_token="$ARC_PAT"
helm install arc -n arc-systems --create-namespace --version 0.15.1 \
  oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set-controller
helm install arc-runner-set -n arc-runners --version 0.15.1 \
  --set githubConfigUrl="https://github.com/$(gh api user -q .login)/myapp-arc" \
  --set githubConfigSecret=gh-pat --set maxRunners=3 \
  --set containerMode.type=kubernetes-novolume \
  oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set
kubectl get pods -n arc-systems
Trigger 3 jobs and observe scaling:
for i in 1 2 3; do gh workflow run arc-demo.yml; done
kubectl get ephemeralrunnerset -n arc-runners -w
NAME                   DESIREDREPLICAS   CURRENTREPLICAS   PENDING RUNNERS   RUNNING RUNNERS
arc-runner-set-hbq4k   0                 0
arc-runner-set-hbq4k   3                 0
arc-runner-set-hbq4k   3                 3                 3
arc-runner-set-hbq4k   3                 3                 0                 3
arc-runner-set-hbq4k   0                 0
Check the scaling decisions in the listener logs:
kubectl logs -n arc-systems -l app.kubernetes.io/component=runner-scale-set-listener --tail=20
"Processing message" messageType="RunnerScaleSetJobMessages"
"Job available message received" jobId=93125
"Calculated target runner count" assigned job=3 decision=3 min=0 max=3 currentRunnerCount=0
"Scaling ephemeral runner set" desiredReplicas=3
Verify: all three runs succeed; after the jobs end, kubectl get pods -n arc-runners only an empty list remains (minRunners=0). Change maxRunners to 1, then trigger 3 jobs again, and observe the jobs queued and executed one after another.
Clean up:
helm uninstall arc-runner-set -n arc-runners && helm uninstall arc -n arc-systems
kind delete cluster --name arc
gh repo delete myapp-arc --yes        # requires the delete_repo scope
# delete the lab PAT / App in GitHub settings

Case 1: migrating from persistent VM runners to ARC

Problem: 10 persistent VM runners sit idle at night and queue during the day; in one build, credentials left in /tmp were read by the next job. Approach: Deploy ARC,minRunners: 2 (raise it during work hours with a CronJob and set it to 0 at night—ARC does not support scheduled limits, so the official guidance is to change it with an external scheduling tool),maxRunners: 40; enable cluster autoscaling for the runner node pool. Configuration:kubernetes mode + dedicated StorageClass; GitHub App authentication. Limitation: Cold starts add 20–60 seconds (pulling images, scheduling); this can be mitigated with an image-pre-pulling DaemonSet or minRunners.

Case 2: cluster security audit issue caused by dind

Problem: The security team prohibits privileged Pods, but the team needs docker build. Approach: Switch to kubernetes-novolume mode, using BuildKit rootless or a remote BuildKit service for build steps; the few repositories that still need dind are placed in a separate scale set on an isolated node pool, and a runner group limits access to only those repositories. Limitation: Some actions that depend on the Docker socket are incompatible and need reworking.

Case 3: public open-source project misuses a self-hosted runner

Problem: An open-source project attached a self-hosted runner to a public repository for GPU tests, and a cryptomining script was planted via a fork PR. Approach: Immediately remove the runner, rotate all credentials on that machine, and reinstall the OS; switch to a GitHub-hosted GPU larger runner (billed per minute, public repositories are also charged) or run GPU tests only in a maintainer-approved workflow_dispatch environment with access to a private image registry. Limitation: larger runners require a Team or Enterprise Cloud organization.

Common errors and fixes

The listener Pod does not appear / controller log: failed to get runner group ID / 401 Bad credentials

Cause: the Secret is not in the scale set namespace, the PAT has expired or lacks scope, the App is not installed on the target repository/organization,githubConfigUrl wrong (with an extra .git or using the API URL).

kubectl logs -n arc-systems deploy/arc-gha-rs-controller --tail=50
kubectl get secret -n arc-runners
kubectl get autoscalingrunnerset -n arc-runners -o yaml | grep -A3 githubConfig

Fix: After correcting the Secret/URL, helm upgrade reinstall the scale set; enterprise-level runners require a classic PAT.

The job stays at “Waiting for a runner to pick up this job…” but ARC does not scale up

Cause:runs-on does not match the install name; the runner group containing the scale set has not authorized the repository; maxRunners has reached its limit; the listener has crashed.

kubectl get pods -n arc-systems
kubectl get ephemeralrunnerset -n arc-runners
gh api orgs/ORG/actions/runner-groups -q '.runner_groups[] | {name, visibility}'

Fix: Align the names; allow the repository in the runner group; increase maxRunners or node capacity.

Jobs without a job container are forbidden on this runner, please add a 'container:' to your job or contact your self-hosted runner administrator.

Cause:kubernetes/kubernetes-novolume kubernetes mode by default requires jobs to declare container:.

Fix: Add container:; or set on the runner container ACTIONS_RUNNER_REQUIRE_JOB_CONTAINER=false (the official note says this may give the runner Pod higher K8s API permissions; use with caution).

runner Pod stuck in Pending: 0/3 nodes are available: pod has unbound immediate PersistentVolumeClaims

Cause:kubernetes mode needs dynamic PVs, but the cluster has no default StorageClass, or the StorageClass name in values is wrong.

kubectl get sc
kubectl describe pod -n arc-runners POD | tail -20

Fix: Configure the correct StorageClass, or switch to kubernetes-novolume.

dind container CrashLoopBackOff: failed to start daemon: Error initializing network controller … operation not permitted

Cause: dind requires privileged; it is rejected or downgraded by Pod Security Admission (restricted/baseline) or a policy engine.

Fix: Relax the policy for that namespace separately and isolate the node pool, or switch to kubernetes mode + rootless build tools.

After upgrading the chart, helm upgrade reports CRD-related errors / new fields do not take effect

Cause: Helm neither upgrades nor deletes CRDs; versions such as 0.12.0 include CRD changes.

Fix: Follow the official process: uninstall all scale sets → uninstall the controller → delete the changed actions.github.com CRDs → reinstall. Rehearse first on a staging cluster.

Command-line exercises
1. View all ARC custom resources and find the currently desired runner count.
kubectl get autoscalingrunnersets,ephemeralrunnersets,ephemeralrunners -A
kubectl get ephemeralrunnerset -n arc-runners -o jsonpath='{.items[0].spec.replicas}'
2. Write the command that changes maxRunners of the installed scale set to 10 (keeping other values).
helm upgrade arc-runner-set -n arc-runners --reuse-values --set maxRunners=10 \
  oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set --version 0.15.1
Scenario analysis
The company requires all builds to be completed on the internal network, and the security team prohibits privileged containers; some repositories are public open-source components. Design a runner plan.

① Public repositories should not use self-hosted runners; keep using GitHub-hosted runners (standard specs are free); if internal network access is required, run only after merge, on push the protected branch, or workflow_dispatch , and use a separate runner group to restrict use to specified workflows only. ② Private repositories use ARC: kubernetes or kubernetes-novolume mode (no privileged needed), with image builds switched to rootless BuildKit/Kaniko. ③ GitHub App authentication, Secret stored in the scale set namespace; add a NetworkPolicy to the runner namespace that allows traffic only to GitHub and required internal services; ServiceAccount with least privilege. ④ One scale set + runner group per sensitivity level. ⑤ Centralize controller/listener/runner logs and monitor queue time.

Verified instructional videos

▶
GitHub Actions Self Hosted Runner (Autoscaling with Kubernetes) — Anton Putra
English · hands-on guide to autoscaling self-hosted runners on Kubernetes. Note: this video was recorded earlier and uses the older (community summerwind) ARC chart; for new deployments, follow gha-runner-scale-set 0.15.1 in this hour and the official documentation
▶
GitHub Actions Tutorial | From Zero to Hero in 90 minutes (Environments, Secrets, Runners, etc) — CoderDave
English · includes the self-hosted runner registration section

Official documentation

Video storyboard script (about 100 seconds)

This course material cannot directly generate video or MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: GitHub cloud on the left, Kubernetes cluster on the right; the cluster has only two Pods, controller and listener, with a dashed line from listener to GitHub.
Narration: when ARC is idle it has only two Pods: the controller and the listener. The listener keeps a long poll open to GitHub and needs no inbound ports.
Shot 2 · 20–45s
Visual: three job cards fly into the GitHub queue; the listener flashes, showing Job Available; the EphemeralRunnerSet replicas change from 0 to 3.
Narration: jobs arrive, the listener receives the Job Available message, and after acknowledging it changes the desired replica count through the Kubernetes API.
Shot 3 · 45–75s
Visual: three runner Pods turn from blue to yellow to green in turn; above each Pod appears a one-time JIT key.
Narration: the controller requests a one-time JIT configuration for each runner; after the Pod starts, it registers, picks up the job, and streams back logs.
Shot 4 · 75–100s
Visual: jobs complete, the Pod turns red and disappears, replicas return to 0; a warning sign “private repositories only” appears in a corner of the screen.
Narration: jobs end, the runner is deleted, and the cluster returns to idle. Remember: self-hosted runners are for private repositories only.
or score ≥ 70% on the “Quiz”

Module 4 · Performance: Caching, Parallelism, and Larger Runners

23:00 – 30:00 · Shorten the critical path instead of blindly adding machines, and know that “faster” can mean “more expensive”
7 minactions/cache v6.1.0larger runners: Team / GHEC★★★★☆
Learning objectives
  • Measure CI: total wall-clock time, critical path, per-job duration, cache hit rate (cache-hit output).
  • Master five speed-up techniques: caching (dependencies / build layers), splitting jobs for parallel execution, matrix and test sharding,concurrency cancelling duplicate runs, and speeding up dependency installation.
  • Understand larger runner specs (up to 96 vCPU / 384 GB / 2040 GB SSD; arm64; GPU: 4 vCPU + 1× Tesla T4 with 16 GB VRAM), static IPs (GHEC only, up to 10 pools), and Azure private networking.
  • Understand the relationship between parallelization and billing: each job is individually rounded up to the whole minute, so the more you split, the more billed minutes you may incur.
Prerequisites: Lesson 2 on matrix and caching basics. Importance:★★★★☆

What: where CI time is spent

The wall-clock time of one CI run = queue time + the sum of job durations along the critical path. Each job consists of fixed overhead (allocating a runner, Set up job, checkout, setup-*) + dependency installation + the actual work (lint/test/build) + uploads. Before optimizing, look at the data: the job timeline on the run summary page, and gh run view --json jobs the start/end time of each step in the

Why: fast CI is productivity and also cost

Cutting PR feedback from 20 minutes to 5 means developers stop context-switching; and since hosted runners bill by the minute, caching and cancelling duplicate runs save both time and money. However,parallelization and larger runners trade “more minutes / higher unit price” for “shorter wall-clock time” and need to be weighed (calculated in Module 5).

How: five techniques

TechniqueMechanismTypical benefitNotes
Dependency cacheactions/cache@v6.1.0 or setup-python/node cache input cache:; exact key match → restore-keys prefix fallbackinstallation drops from minutes to secondscache entries cannot be overwritten; deleted after 7 days without access; repositories default to 10 GB (can be increased; overage is billed); scope: current branch + default branch (PRs can also read the base branch)
Build-layer cacheDocker BuildKit cache-to: type=gha (via the Actions cache service) or registry cacheimage build 4 minutes → 1 minutesubject to the same 10 GB and 7-day rules; uploads limited to 200 per minute per repository
Split jobs for parallelismlint, test, and build run in parallel when they have no dependencies; use needs to express only real dependencieswall clock ≈ longest jobeach job repeats fixed overhead; billing is rounded per job
matrix / shardingstrategy.matrix multiple versions; tests sharded by file/time (such as pytest --splits plugin, Jest --shard)tests 8 minutes → 4×2 minutesup to 256 jobs; fail-fast default true; max-parallel limit concurrency
Cancel duplicate runsconcurrency + cancel-in-progress (PRs)when pushing repeatedly, only the last run executesdo not cancel for deploy groups
Speed up dependency installationlock files + binary wheels; npm ci; uv; pre-built runner images (custom larger runner images / self-built ARC images)saves a further 30–70%custom image storage is billed separately
Shallow cloneactions/checkout@v7.0.1 default fetch-depth: 1saves tens of seconds on large repositoriesdeepen only when history is needed (version numbers, diffs)

larger runners at a glance (docs.github.com, verified 2026-11)

TypeSpec rangeNotes
Linux / Windows x64up to 96 vCPU, 384 GB RAM, 2040 GB SSDnames and labels are defined by the admin when creating them; supports autoscaling maximums and runner groups
arm642–32 vCPU tiers, plus 64 vCPU arm64 (208 GB RAM)good for native arm64 image builds
GPU4 vCPU, 1× Tesla T4, 28 GB RAM, 16 GB VRAM, 176 GB SSDUbuntu or Windows; concurrency limit of 100 GPU jobs
macOSLarge: Intel 12 CPU / 30 GB (macos-15-large,macos-26-large…); XLarge: M2 5 CPU / 14 GB (macos-15-xlarge,macos-26-xlarge…)use labels directly; no admin creation needed
Static IPall runners in a pool share one static IP range; up to 10 pools with static IPsGitHub Enterprise Cloud only; no extra charge; IPs are released after 90 days of non-use
Azure private networkingrunners connect to your Azure VNetmacOS larger runners are not yet supported

larger runners are available only to Team and Enterprise Cloud organizations/enterprises, requiring a valid payment method and an Actions spending limit > 0; they are also billed in public repositories. Concurrency limit: 1,000 larger runner jobs combined for Team/Enterprise.

When: optimization order

  1. First remove waste: concurrency cancel duplicates, path filtering (inside jobs), skip irrelevant jobs.
  2. Then add caching: dependency cache → build-layer cache, target hit rate > 80%.
  3. Then parallelize: split jobs with no dependencies, shard tests.
  4. Add hardware last: larger runners (CPU-intensive compilation/testing), or your own ARC compute.

Comparison with similar technologies

GitHub ActionsAzure PipelinesGitLab CI
Dependency cacheactions/cache (10 GB per repository by default)Cache@2 Taskcache: keyword (runner-side storage)
Test shardingmatrix + third-party sharding toolstest slicing (distributionBatchType)parallel: N + CI_NODE_INDEX
Large hosted machineslarger runnersManaged DevOps Pools / self-hostedlarge-spec runners in SaaS
Common misconceptions① “Caching node_modules is always fastest”—crossing Node versions/OSes is error-prone; official examples cache the package manager's download cache (~/.npm) and then npm ci. ② “Splitting into 10 parallel jobs always saves money”—every job pays fixed overhead and rounds up to whole minutes, so it can actually cost more. ③ “A cache hit always makes the build faster”—if the cache is huge, downloading and extracting it can itself take a long time; evaluate caches larger than a few GB. ④ “Doubling larger runner cores halves the time”—only work that can use multiple cores in parallel (compilation,pytest -n auto) benefits.

Gantt chart: critical path before and after optimization

Before: single job, serial ≈ 16.7 minutes (billed 17 minutes) install 3.0 lint 1 test 8.0 docker build 4.0 After: caching + split + 4 test shards ≈ 3.4 minutes wall clock lint job test shard 1/4 test shard 2/4 … (4 in total) build (gha layer cache) gate job (needs: all) wall clock ↓ about 80% but jobs go from 1 → 7, each rounded up to the minute individually: billed minutes 17 → about 21 (caching only, without splitting: 17 → 12) Legend: grey = allocation/checkout, blue = setup, yellow = install, red = test, green = build
Figure 4-1 Wall-clock time is determined by the critical path; billing is determined by “the sum of per-job rounded-up minutes × unit price”

Cache key matching flow

Exact key match?pip-Linux-…-8f3a Hit cache-hit=trueno save at job end restore-keys prefixtake the most recently created matching entry Partial hit cache-hit=falseinstall the increment → save new key at end No matchfull install → save Lookup scope: current branch → default branch(PRs can also read the base branch)caches from sibling branches are not visible
Figure 4-2 Cache restore and save; the default branch must run regularly for PRs to have a usable cache

Interactive: CI critical path and billed-minute optimizer

Check optimization techniques and observe changes in wall-clock time and billed minutes (each job rounded up individually). Unit prices use the 2026 current price list: Linux 2-core $0.006/minute, Linux 4-core larger runner $0.012/minute. Durations are illustrative teaching values.

Wall-clock time
Billed per run
Cost per PR

Core commands and parameters

Command / configurationPurposeNotes
gh run view RUN --json jobsget start/end times of each job/stepcombined with jq to compute durations
gh cache list / gh cache deleteList/delete caches--sort size_in_bytes,--key,--ref,--all
gh api repos/{owner}/{repo}/actions/cache/usagerepository cache usageactive_caches_size_in_bytes,active_caches_count
steps.<id>.outputs.cache-hitwhether there was an exact hita partial hit (restore-keys) is false
strategy.matrix / fail-fast / max-parallelparallel matrixup to 256 jobs

1. Find the slowest jobs and steps

gh run view "$RUN" --json jobs -q '.jobs[] | {name, secs: ((.completedAt|fromdateiso8601) - (.startedAt|fromdateiso8601))}'
gh run view "$RUN" --json jobs -q '.jobs[0].steps[] | [.name, .startedAt, .completedAt] | @tsv'
{"name":"test","secs":1002}
Set up job	2026-11-15T09:10:02Z	2026-11-15T09:10:04Z
Run actions/setup-python@v7.1.0	2026-11-15T09:10:05Z	2026-11-15T09:10:33Z
Run pip install …	2026-11-15T09:10:33Z	2026-11-15T09:13:31Z
Run pytest -q	2026-11-15T09:13:31Z	2026-11-15T09:21:40Z

2. Optimized CI (caching + splitting + sharding + gate)

name: ci
on:
  pull_request:
  push:
    branches: [main]
  workflow_dispatch:
permissions:
  contents: read
concurrency:
  group: ci-${{ github.head_ref || github.run_id }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
  lint:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v7.0.1
      - uses: actions/setup-python@v7.1.0
        with: { python-version: "3.13", cache: pip }
      - run: pip install ruff && ruff check --output-format=github .
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v7.0.1
      - uses: actions/setup-python@v7.1.0
        id: py
        with: { python-version: "3.13", cache: pip, cache-dependency-path: "requirements*.txt" }
      - run: echo "pip cache hit = ${{ steps.py.outputs.cache-hit }}" >> "$GITHUB_STEP_SUMMARY"
      - run: pip install -r requirements.txt -r requirements-dev.txt
      - run: |
          # simple sharding by file hash; for production, use a plugin that shards by historical duration
          files=$(ls tests/test_*.py | awk -v n=4 -v i=${{ matrix.shard }} 'NR%n==i-1')
          pytest -q -n auto $files --junitxml=report-${{ matrix.shard }}.xml
      - uses: actions/upload-artifact@v7.0.2
        if: always()
        with: { name: junit-${{ matrix.shard }}, path: "report-*.xml", retention-days: 7 }
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7.0.1
      - uses: docker/setup-buildx-action@v4.4.1    # latest release found in 2026-11; pin to a SHA in production
      - uses: docker/build-push-action@v7.4.0
        with:
          context: .
          push: false
          cache-from: type=gha
          cache-to: type=gha,mode=max
  gate:
    if: always()
    needs: [lint, test, build]
    runs-on: ubuntu-latest
    steps:
      - run: |
          echo '${{ toJSON(needs) }}' | grep -Eq '"result": "(failure|cancelled)"' && exit 1 || exit 0

pytest -n auto Requires pytest-xdist (placed in requirements-dev.txt). docker/setup-buildx-action v4.4.1 (2026-09-16) and docker/build-push-action v7.4.0 (2026-09-15) are the latest releases found for this hour via GitHub Releases; for more image build details, see the Docker course.

3. Cache management

gh api "repos/{owner}/{repo}/actions/cache/usage"
gh cache list --sort size_in_bytes --order desc --limit 10
gh cache delete --all --ref refs/pull/42/merge     # clean up caches for merged PRs
{"full_name":"OWNER/myapp-chaos","active_caches_size_in_bytes":3221225472,"active_caches_count":41}

4. Use a larger runner (the organization admin has created a runner named ubuntu-4core)

jobs:
  test:
    runs-on: ubuntu-4core            # the name is defined by the admin in organization settings
  gpu-smoke:
    runs-on:
      group: gpu-runners             # can also be selected by runner group + label
      labels: gpu-t4
    steps:
      - run: nvidia-smi

Lab 4: before/after comparison of the same CI (about 8 minutes)

Goal and environment: on myapp-chaos , measure the baseline CI, then apply caching, splitting, sharding, and concurrency, and output a comparison table. Standard runners in public repositories are free; the larger runner part is read-only (requires Team/GHEC).
Collect a baseline (3 consecutive runs, take the median):
git switch main
for i in 1 2 3; do gh workflow run ci.yml; sleep 5; done
gh run list --workflow ci.yml --limit 3 --json databaseId -q '.[].databaseId' > baseline.txt
Write a measurement script:
#!/usr/bin/env bash
# Output: run_id  wall-clock seconds  job count  billed minutes (sum of per-job rounded-up values)
for id in $(cat "$1"); do
  gh run view "$id" --json jobs,createdAt,updatedAt -q '
    [ (.jobs | map(((.completedAt|fromdateiso8601) - (.startedAt|fromdateiso8601))) ) ] as [$d]
    | [ '"$id"',
        ((.updatedAt|fromdateiso8601) - (.createdAt|fromdateiso8601)),
        ($d|length),
        ($d | map((. / 60) | ceil) | add) ] | @tsv'
done
chmod +x measure.sh && ./measure.sh baseline.txt
19283750001	1031	1	17
19283750002	1018	1	17
19283750004	1044	1	18
Apply optimizations: replace with section 2 of the “Commands” page ci.yml (add to requirements-dev.txt pytest-xdist), push to main, run once to “warm up” the cache, then run 3 more times consecutively and measure:
git commit -am "ci: cache + split + shard" && git push
gh run watch "$(gh run list --limit 1 --json databaseId -q '.[0].databaseId')"
for i in 1 2 3; do gh workflow run ci.yml; sleep 5; done
gh run list --workflow ci.yml --limit 3 --json databaseId -q '.[].databaseId' > optimized.txt
./measure.sh optimized.txt
19283751101	231	7	21
19283751102	226	7	21
19283751105	240	7	22
Write up in the report (used in the comprehensive lab): wall clock 1031s → 231s (−78%); billed minutes 17 → 21 (+24%): the minutes saved by caching are offset by 7 jobs each rounding up and repeating fixed overhead. Control experiment: with caching only and no splitting, 1 job gives about 12 billed minutes and about 700 seconds of wall clock. State your trade-off in the report (PR feedback speed vs cost); you can refer to the calculations on the Module 4 animation page.
Verify: in the run summary pip cache hit = true; the gh cache list step should appear in setup-python-… the build log with buildkit-related entries.
Clean up:
gh cache delete --all     # optional: clear lab caches
rm -f baseline.txt optimized.txt

Case 1: cache hit rate is only 20%

Problem: the key includes ${{ github.sha }}, so every commit creates a new key; restore can only use prefixes, save keeps writing new entries, and the 10 GB quickly fills up, causing eviction by last access. Approach: Change the key to hashFiles('**/package-lock.json'); run the default branch on a daily schedule to keep caches “fresh” (avoiding 7-day eviction); clean up PR caches. Result: Hit rate rose to 90%; install time dropped from 4 minutes to 25 seconds.

Case 2: after splitting jobs, the bill went up instead of down

Problem: Splitting one 12-minute job into 15 jobs of 1–2 minutes each cut wall clock to 3 minutes, but per-job rounding plus fixed overhead raised billed minutes from 12 to 28. Approach: Merge jobs that are too fine-grained (combine lint-type jobs into one), size test shards so each shard is ≥ 3 minutes; for PRs, run only the affected modules. Limitation: Wall clock and cost must be balanced according to team priorities.

Case 3: larger runner + static IP to reach a customer's firewall

Problem: Integration tests need to reach a customer API that is open only to an IP allowlist. Approach: In a GHEC organization, create a larger runner pool with a static IP, give the IP range to the customer, and only the integration test job uses this pool. Limitation: Static IPs are GHEC-only; up to 10 pools; IPs are reclaimed after 90 days of non-use; larger runners are billed per minute (public repositories are billed too).

Common errors and fixes

Cache restored from key: pip-Linux-… but installation is still slow

Cause: the cache holds download caches,pip install resolution and installation are still needed; or the hit was an old restore-keys prefix, requiring a large increment download.

Fix: Check cache-hit whether it is true; consider caching the virtual environment (the key must include the Python version and OS) or using uv; pin dependency versions.

Warning: Cache save failed. / Failed to save: Our services aren't available right now

Cause: the cache service is briefly unavailable or upload rate limits are triggered (200 per minute per repository).

Fix: A cache failure should not fail the job (actions/cache does this by default); in a matrix, avoid each job saving the same content (only one shard saves, using actions/cache/save + if:).

The job was not acquired by Runner of type hosted even after multiple attempts / large numbers of jobs queued for a long time

Cause: the account concurrency limit was reached (Free 20 / Pro 40 / Team 60 / Enterprise 500; macOS is lower) or the autoscaling limit for larger runners; it could also be a platform failure.

gh run list --status queued --limit 50 --json databaseId,workflowName | jq length

Fix: Reduce matrix concurrency (max-parallel), cancel duplicate runs, raise the maximum concurrency of larger runners; check githubstatus.com.

docker buildx: failed to solve: … error writing layer blob: … 429 Too Many Requests (cache-to type=gha)

Cause: BuildKit's gha cache backend wrote a large number of layers in a short time, triggering rate limiting on the cache service.

Fix: Switch to mode=min, or configure a larger timeout/retry for the BuildKit gha backend; when there are too many image layers, consider registry cache (type=registry).

No runner matching the specified labels was found: ubuntu-4core

Cause: the larger runner name is misspelled, the runner group is not open to this repository, or the organization is not Team/GHEC.

Fix: In organization settings → Actions → Runners, confirm the name and the repository access policy of the runner group.

Command-line exercises
1. List the 5 largest caches in the repository, and delete all caches for a given PR ref.
gh cache list --sort size_in_bytes --order desc --limit 5
gh cache delete --all --ref refs/pull/42/merge
2. Write a combination of steps in which only the first matrix shard saves the cache and the other shards only restore it.
- uses: actions/cache/restore@v6.1.0
  id: c
  with: { path: ~/.cache/pip, key: "pip-${{ hashFiles('requirements*.txt') }}" }
- run: pip install -r requirements.txt
- uses: actions/cache/save@v6.1.0
  if: matrix.shard == 1 && steps.c.outputs.cache-hit != 'true'
  with: { path: ~/.cache/pip, key: "pip-${{ hashFiles('requirements*.txt') }}" }
Scenario analysis
Management requires “reduce CI from 25 minutes to 8 minutes, but monthly cost must not rise.” Provide a phased plan and a measurement method.

Measurement: use the measurement script to collect the weekly medians of wall clock, critical path, billed minutes, and cache hit rate. Phase 1 (saves money and speeds up): cancel duplicates with concurrency, path filtering inside jobs, dependency and layer caching; this usually cuts 30–50% and billed minutes drop in step. Phase 2 (faster, cost-neutral): split only the truly long jobs, shard tests by duration so each shard is ≥ 3 minutes, and use the minutes saved in Phase 1 to offset rounding overhead. Phase 3 (still not on target): use 4-core larger runners only for CPU-intensive jobs (2× unit price, but cost is flat if the duration drops to under half), or evaluate ARC's own compute. Re-measure at the end of each phase, and verify cost with the Module 5 calculator.

Verified instructional videos

▶
GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker — TechWorld with Nana
English · basic approach to Docker build pipelines; can serve as a “baseline” reference before optimization
▶
GitHub Actions CI/CD pipeline | Step by Step guide — Ali Bouali
English · step-by-step pipeline setup; for details on caching, sharding, and larger runners, this hour and the official documentation take precedence

No verified video specifically covering larger runners / test sharding was found.

Official documentation

Video storyboard script (about 80 seconds)

This course material cannot directly generate video or MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a 17-minute Gantt bar; the install and test segments are especially long.
Narration: measure before optimizing. Wall-clock time is determined by the critical path, so first find the longest segment.
Shot 2 · 20–45s
Visual: the install segment is shortened to one-fifth of its original length; the label reads cache hit true.
Narration: caching is usually the biggest win. Use a hash of the lock file in the key, and the default branch must run regularly for PRs to have a usable cache.
Shot 3 · 45–65s
Visual: the long bar splits into four short parallel bars; the billing counter on the right drops only slightly.
Narration: splitting and sharding shorten wall-clock time, but each job is rounded up to the whole minute individually, so billed minutes don't necessarily drop proportionally.
Shot 4 · 65–80s
Visual: a larger server icon labeled “4 cores, 2× unit price.”
Narration: consider a larger runner last; it's only worth it for work that can fully use multiple cores.
or score ≥ 70% on the “Quiz”

Module 5 · Cost and Billing Optimization

30:00 – 37:00 · Understanding the bill: per-minute SKU prices, rounding, storage, Packages and Codespaces, and 2026 billing changes
7 minHosted runner prices cut by up to 39% on 2026-01-01Self-hosted platform fee: postponed★★★★☆
Learning objectives
  • Calculate Actions costs with current unit prices: Linux 2-core $0.006/minute, Windows 2-core $0.010, macOS $0.062; each job rounded up to the whole minute.
  • Understand that “included allowances” are now expressed as dollar amounts (Free $12 / Pro $18 / Team $18 / GHEC $300 per month), and how the old “minute multiplier” concept maps to per-SKU pricing.
  • Calculate storage costs: artifacts and Packages share a storage pool (cumulative GB-hours); caches are free up to 10 GB per repository, and overage is billed after raising the limit.
  • Set budgets (75% / 90% / 100% alerts, optionally blocking usage) and use usage reports to find the most expensive repositories and workflows.
  • Accurately describe the 2026 billing changes: the hosted runner price cuts are in effect; the self-hosted runner $0.002/minute platform fee originally scheduled for 2026-03-01 has been announced as postponed, with no new date yet.
Prerequisites: Timing measurement from Module 4. Importance:★★★★☆ (essential for platform/FinOps roles)

What: what makes up the Actions bill

Billing itemMeteringFree allowanceOverage price (official page, 2026-11)
Hosted runner computeper-job rounded-up minutes × SKU unit pricestandard runners in public repositories are free; private repositories consume the included allowancesee table below
larger runnerssame, with higher unit priceNot free (public repositories are also charged); can be deducted from the Team/GHEC included allowancee.g., Linux 4-core $0.012, GPU Linux 4-core $0.052
Self-hosted runners—currently free; do not consume the included allowancethe originally planned platform fee has been postponed
Artifact + Packages storagecumulative GB-hours per hour → converted to GB-monthsFree 500 MB / Pro 1 GB / Team 2 GB / GHEC 50 GB (shared pool)$0.25 / GB-month
Cache storagehourly peak10 GB per repositoryonly when the limit is raised above 10 GB, overage is $0.07 / GB-month

Standard hosted runner unit prices (per minute, from 2026-01-01)

SKUUnit priceRelative to Linux 2-coreNotes
Linux 1-core (x64)$0.0020.33×lightweight jobs (e.g., labeling, notifications)
Linux 2-core (x64)$0.0061×ubuntu-latest standard runner, etc.
Windows 2-core (x64)$0.010≈1.7×In the old billing model, Windows was a 2× “minute multiplier”
macOS 3/4-core$0.062≈10×In the old billing model, macOS was a 10× “minute multiplier”
Linux 4-core larger$0.0122×Windows 4-core $0.022; macOS 12-core $0.077; macOS 5-core M2 Pro $0.102
GPU 4-core (T4)Linux $0.052 / Windows $0.102≈8.7× / 17×Team / GHEC only

About “multipliers”: Older documentation used “minute multipliers” (Windows 2×, macOS 10×) to convert each OS into Linux minutes. Current documentation expresses the included allowance as dollar amounts, with each runner type deducted directly at its own unit price, and no longer called a multiplier. For reference: $12 ≈ 2,000 Linux 2-core minutes, $300 ≈ 50,000 Linux 2-core minutes (official examples).

Included allowance (resets monthly)

PlanIncluded compute allowance≈ Linux 2-core minutesArtifact/Packages storagePackages data transfer/month
Free (personal and organization)$122,000500 MB1 GB
Pro$183,0001 GB (the Packages page says 2 GB; the billing page is authoritative)10 GB
Team$183,0002 GB10 GB
Enterprise Cloud$30050,00050 GB100 GB

Why: where the money actually goes (common “leaks”)

  • macOS jobs: 1 minute of macOS ≈ 10 minutes of Linux. Use only when necessary (iOS builds/signing).
  • Rounding: a 10-second job is billed as 1 minute; large numbers of tiny jobs (lightweight checks in a matrix) add up quickly.
  • Duplicate runs: every push runs in full; without concurrency cancellation.
  • Default timeout 360 minutes: a stuck job can burn through 6 hours in one go.
  • Artifact retention 90 days (default): large build outputs uploaded on each run accumulate in the shared storage pool.
  • Codespaces: 2-core $0.18/hour + storage $0.07/GB-month; organization plans have no free Codespaces allowance; forgotten codespaces that are not stopped or deleted keep generating storage charges.

How: controls

ControlApproach
BudgetsSet budgets for Actions or other products or SKUs by account/organization/repository/cost center (enterprise); 75%, 90%, 100% alerts; for metered products like Actions, you can choose block usage when the limit is reached; budgets only cover usage after creation
Included-allowance alertsEmails are sent when the included allowance reaches 90% and 100%
No payment methodusage is blocked after the included allowance runs out (a “hard cap” suited to personal/lab accounts)
Usage reportsDownload usage reports (CSV) from Billing → Usage, sorted by repository/workflow/SKU; enterprises can aggregate them with cost centers
Retention periodsretention-days (artifacts), repository/organization-level default retention; regularly gh cache delete
Engineering optimizationModule 4's caching, cancelling duplicates, in-job path filtering, sensible timeout-minutes

When: 2026 billing change timeline (always defer to the official source)

DateEventStatus (verified 2026-11-15)
2025-12-16GitHub Changelog announces Actions pricing changesoriginal announcement
2026-01-01GitHub-hosted runner prices cut by up to 39% (depending on machine type); free allowances unchangedIn effect (Linux 2-core $0.006)
2026-03-01 (originally planned)Added a $0.002/minute “Actions cloud platform fee” for jobs using self-hosted runners in private repositoriesAnnounced as postponed, GitHub said it needs time to reassess,no new date given
—public repository runner usage, GHES pricing structureannouncement says it stays free / unchanged
Note Many online articles from December 2025 still present “charging self-hosted runners from 2026-03-01” as settled fact; this is outdated. When budgeting, use the original GitHub Changelog post (including its update notes) and Actions runner pricing as the source of truth.

Comparison with similar technologies

GitHub ActionsAzure PipelinesGitLab.com
Pricing unitper-SKU per-minute price, rounded per jobby concurrent jobs (fixed monthly fee)compute minutes × machine-type factor
Public/open sourcestandard runners freefree concurrency for public projects (by application)open-source plan
Hard capbudget blocks usage / no payment methodconcurrency is the cappurchase when allowance runs out
Common misconceptions① “Self-hosted runners have been charged since March 2026”—it has been postponed, with no new date as of the verification date. ② “Everything is free in public repositories”—larger runners are also charged in public repositories; storage overage is also billed. ③ “Deleting artifacts gets you a refund”—deletion only stops further accumulation; GB-hours already accrued in this billing cycle still appear on the bill. ④ “Pushing container images to GHCR is billed as Packages”—the official note currently says that storage and bandwidth for the Container registry are temporarily free, and any changes will be announced at least one month in advance.

Billing structure diagram

Job A: 3 min 10 sRounded up → 4 min × $0.006 Job B (macOS): 2 min2 min × $0.062 Artifacts 1.2 GB × 90 dayscumulative GB-hours metered usageCompute $0.024 + $0.124Storage GB-month × $0.25Cache >10 GB portion × $0.07(standard runners in public repositories = 0) ① First deduct the included allowanceFree $12 · Pro/Team $18 · GHEC $300 ② Overage: budget check75/90/100% alerts · can block usage ③ No payment method → blockPayment method on file → pay per unit price
Figure 5-1 Each job is rounded individually; the included allowance is deducted by amount

The same 1,000 minutes, priced on different SKUs

(unit: US dollars, computed at 2026-11 official unit prices; bar lengths proportional) Linux 1-core$2 Linux 2-core$6 Windows 2-core$10 Linux 4-core larger$12 GPU Linux 4-core$52 macOS 3/4-core$62
Figure 5-2 macOS and GPU unit prices are about 9–10× that of Linux 2-core

Interactive: Actions monthly cost calculator

Enter your team's CI profile; the calculator computes the monthly cost using 2026-11 official unit prices, per-job rounding, and included-allowance amounts. For estimates only; GitHub billing and the official pricing calculator are authoritative.

Compute (after rounding)
Storage
Payable after deducting the included allowance

Core commands and parameters

Command / locationPurposeNotes
Settings → Billing and licensing → UsageView usage, download usage reportsFilter by product/SKU/repository
Billing → Budgets and alertsCreate a budgetcan optionally block Actions usage when 100% is reached
gh api /organizations/ORG/settings/billing/usageUsage API of the enhanced billing platformendpoints and fields per the official REST documentation
gh api repos/{owner}/{repo}/actions/artifactsList artifacts and sizessize_in_bytes,expires_at
gh api -X DELETE …/actions/artifacts/IDDelete artifactsstops further storage accumulation
gh codespace list / gh codespace deleteClean up codespaces--days N Delete those unused for N days

1. Find the artifacts using the most storage

gh api --paginate "repos/{owner}/{repo}/actions/artifacts?per_page=100" \
  -q '.artifacts[] | [.name, (.size_in_bytes/1048576|floor), .created_at, .expired] | @tsv' \
  | sort -t$'\t' -k2 -nr | head -10
docker-image-tar	1874	2026-10-02T10:11:09Z	false
coverage-html	96	2026-11-14T08:01:22Z	false
junit-report	1	2026-11-15T08:41:30Z	false

2. Bulk-delete artifacts older than 30 days

cutoff=$(date -u -d '30 days ago' +%s)
gh api --paginate "repos/{owner}/{repo}/actions/artifacts?per_page=100" \
  -q ".artifacts[] | select((.created_at|fromdateiso8601) < $cutoff) | .id" \
| while read -r id; do gh api -X DELETE "repos/{owner}/{repo}/actions/artifacts/$id"; done

3. Reduce retention and storage in the workflow

- uses: actions/upload-artifact@v7.0.2
  with:
    name: coverage-html
    path: htmlcov/
    retention-days: 3          # PR artifacts do not need 90 days
    compression-level: 9       # compression pays off well for text artifacts
# Do not upload images as tar artifacts → push to GHCR (container image storage and bandwidth are currently free)

4. Tally “who spends the most” (approximation based on run duration)

gh run list --limit 200 --json workflowName,databaseId -q '.[] | [.workflowName, .databaseId] | @tsv' |
while IFS=$'\t' read -r wf id; do
  m=$(gh run view "$id" --json jobs -q '[.jobs[] | select(.completedAt != null) | (((.completedAt|fromdateiso8601) - (.startedAt|fromdateiso8601)) / 60 | ceil)] | add // 0')
  echo -e "$wf\t$m"
done | awk -F'\t' '{s[$1]+=$2} END {for (k in s) printf "%-20s %6d min\n", k, s[k]}' | sort -k2 -nr
ci                     1840 min
nightly-e2e             920 min
release                  64 min

The approximation does not distinguish runner SKUs; for exact figures, use the billing usage report.

Lab 5: export usage, set a budget, compress storage (about 6 minutes)

Goal and environment: the billing page of a personal account or lab organization; requires account owner or billing manager permissions. Cost: $0 (read-only and settings).
View usage: Settings → Billing and licensing → Usage, filter the product “Actions,” group by repository; download the usage report CSV. Use a spreadsheet to summarize minutes and amounts by SKU.
Create a budget: Budgets and alerts → New budget → choose type Actions, scope organization or repository, amount (e.g., $5), check the option to block usage when the limit is reached (recommended for lab accounts), and add alert recipients. Verify: the budget appears in the budget list with a progress bar at 0% (budgets only count usage after creation).
Compress artifact storage: run sections 1 and 2 of the “Commands” page to list and delete artifacts older than 30 days; change the retention-days to 3–7 days in the workflow.
Convert the Module 4 optimizations into dollars: in the calculator on the “Animation” page, enter the profiles before optimization (1 job × 1030 seconds) and after (7 jobs × average 170 seconds, 21 minutes total after rounding), with 60 runs per day, a private repository, and the Team plan; record both monthly costs and write them into the comprehensive lab report.
Clean up: the lab budget can be kept as a safeguard; to delete it, remove it on the Budgets page.

Case 1: iOS team burns the annual budget in one month

Problem: All jobs (including lint and unit tests) run on macos-latest . Approach: Move platform-independent lint, unit tests, and static analysis to Linux (about 1/10 of the unit price); macOS handles only compilation and signing; add concurrency cancellation and strict timeout-minutes timeout limits. Result: macOS minutes reduced by 70%. Limitation: Some Swift toolchains are only available on macOS.

Case 2: storage overage from Docker image tar artifacts

Problem: Each CI run uploads a 1.8 GB image tar as an artifact for downstream jobs, with the default 90-day retention, and the shared storage pool far exceeds GHEC's 50 GB. Approach: Switch to pushing to GHCR (tagged by SHA), with downstream jobs pulling by tag; change artifact retention to 1 day; clean up historical artifacts. Limitation: Deletion only stops further accumulation; the portion already accrued this month is still billed.

Case 3: self-hosted migration decision influenced by billing messages

Problem: After the 2025-12 announcement, management asked to assess the impact of “self-hosted runners at $0.002 per minute in the future.”Approach: Model two scenarios (platform fee takes effect / does not take effect), and note “postponed as of 2026-11, no new date”; the decision is driven mainly by security and network requirements, with cost as a secondary factor. Limitation: Policy may change again; review the official page every quarter.

Common errors and fixes

The job was not started because your account is locked due to a billing issue.

Cause: payment failed, or the included allowance is used up with no payment method / the budget is set to block usage.

Fix: Update the payment method or adjust the budget on the billing page; standard runners in public repositories are not affected by the included allowance.

You are running out of storage / Artifact storage quota has been hit. Unable to upload any new artifacts.

Cause: artifact + Packages shared storage exceeds the included amount and cannot be billed (no payment method or budget blocking).

gh api --paginate "repos/{owner}/{repo}/actions/artifacts?per_page=100" -q '[.artifacts[].size_in_bytes] | add / 1073741824'

Fix: Delete old artifacts, shorten retention-days; storage usage statistics may lag by several hours.

larger runner charges appear on the bill for a public repository

Cause: larger runners do not get the public-repository free tier.

Fix: For public repositories, switch to standard ubuntu-latest; use runner groups to restrict larger runners to specific repositories.

Budget is set to block, but spending still exceeded the budget this month

Cause: budgets only count usage after creation; the first billing cycle may overrun; usage reporting has a delay.

Fix: Leave headroom (e.g., set it at 80% of the desired cap), and combine with 75%/90% alerts for manual intervention.

Calculation problems (in place of command-line exercises)
1. Private repository, Team plan, one workflow with 3 Linux 2-core jobs taking 50 seconds, 2 min 05 s, and exactly 4 minutes. Runs 40 times a day, 22 workdays. What is the compute cost for the month? What is payable after deducting the included allowance?

Per run: 1 + 3 + 4 = 8 minutes (rounded up) → 8 × $0.006 = $0.048. Per month: 0.048 × 40 × 22 = $42.24. Deducting the Team included $18 → payable about $24.24 (storage not included).

2. Write a command that computes the total size of all of the repository's current artifacts (GB).
gh api --paginate "repos/{owner}/{repo}/actions/artifacts?per_page=100" -q '.artifacts[].size_in_bytes' | awk '{s+=$1} END {printf "%.2f GB\n", s/1073741824}'
Scenario analysis
Finance asks: “I heard GitHub has been charging for self-hosted runners since 2026, and 80% of our jobs run on self-hosted. Should we move back to hosted runners right away?” How would you answer?

First correct the facts: what took effect on 2026-01-01 is the hosted runner price cut (up to 39%); the self-hosted runner $0.002/minute platform fee originally scheduled for 2026-03-01 has been announced as postponed, with no new date as of 2026-11. Then model it: assume a future $0.002/minute charge, compute the upper-bound impact from current self-hosted minutes, and compare with the cost of moving back to hosted runners (Linux 2-core $0.006) plus savings from owned infrastructure. Finally, emphasize the decision factors: internal network access, compliance, security (self-hosted cannot be used with public repositories), and operations staffing; recommend reviewing the official changelog quarterly rather than migrating immediately based on outdated news.

Verified instructional videos

No video explaining the new 2026 Actions billing rules and verified via oEmbed was found (billing rules change quickly, so videos go out of date easily). Please read the official documentation below directly.

Official documentation

Video storyboard script (about 80 seconds)

This course material cannot directly generate video or MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a 50-second job is “rounded up” into a 1-minute block.
Narration: Actions bills per job; each job is individually rounded up to the whole minute.
Shot 2 · 20–40s
Visual: price tags appear in turn: Linux 0.006, Windows 0.010, macOS 0.062.
Narration: different runners have different unit prices. macOS is roughly ten times Linux, so don't run on macOS any job that can run on Linux.
Shot 3 · 40–60s
Visual: a wallet icon holds $18, deducted step by step per job; the progress bar rings bells at 75%, 90%, and 100%.
Narration: the included allowance is now expressed in dollars; once it runs out, the budget decides whether to continue, with alerts at 75, 90, and 100 percent.
Shot 4 · 60–80s
Visual: on the calendar, January 1, 2026 is checked off as “price cut in effect,” and March 1 is crossed out as “self-hosted charges postponed.”
Narration: in 2026, hosted runners have had their prices cut; the platform fee originally planned for self-hosted runners has been postponed. Please refer to the official announcement.
or score ≥ 70% on the “Quiz”

Module 6 · Local Debugging and Testing (act, etc.)

37:00 – 43:00 · Check and run locally first, then push: say goodbye to a commit history of “fix ci” × 20
6 minact v0.2.98 · actionlint v1.7.12act is a community project, not official★★★★☆
Learning objectives
  • Use actionlint to statically check workflows (syntax, expression types, contexts, embedded shellcheck), and wire it into pre-commit and CI.
  • Use nektos/act to run workflows in Docker: choose events, choose jobs, pass secrets/variables/inputs, map runner images, and be clear about what it cannot simulate.
  • Approximate the runner environment in Codespaces or a local container, and know where to look up the software inventory of GitHub-hosted images.
  • Write tests for custom actions (composite / JavaScript / Docker): unit tests + an integration test matrix in workflows.
Prerequisites: Docker course; Lesson 5 custom actions. Importance:★★★★☆

What: three layers of local validation

LayerToolIssues foundTime
① Static checkingactionlint (rhysd/actionlint, v1.7.12)YAML structure, unknown keys, expression syntax and types, undefined needs/steps references,runs-on labels,run: shell issues in run blocks (calls shellcheck), and input names of known actionsmilliseconds
② Local executionact (nektos/act, v0.2.98)script logic, dependency installation, test failures, output/environment passing between stepsminutes (the first image pull takes longer)
③ Environment reproductionCodespaces / devcontainer / runner-images inventoryenvironment differences behind “fails only on CI”: tool versions, locale, time zone, permissions, CPU architectureas needed

Why: why run locally first

A loop of “push → wait for queue → wait for run → read logs → change one line → push again” takes at least 2–5 minutes, and it pollutes commit history and consumes minutes. actionlint can catch half of the errors from Module 2 as soon as you save the file; act can reproduce most script issues within seconds to a minute.

How: how act works

  • act reads .github/workflows/, and based on the event you specify (default push), calculates the jobs to run, starts a Docker container for each job, and maps runs-on labels to images (-P ubuntu-latest=…).
  • On the first run it asks for a default image size: Micro (Node base image, very small but missing tools), Medium (community-maintained catthehacker/ubuntu:act-*, a few hundred MB, commonly used), Large (close to GitHub's images, tens of GB). The choice is saved in ~/.config/act/actrc (or ~/.actrc, depending on the installed version).
  • Remote actions are cloned into a local cache; JavaScript actions run with Node inside the container, and Docker actions build/pull images.
  • act has a built-in artifact server (requires --artifact-server-path) and a cache server, to simulate upload-artifact and actions/cache; compatibility with the latest official actions is per the act documentation and issues.

Main limitations of act (be sure to know them)

CapabilitySituation in act
Windows / macOS runnercontainers must be Linux; can use -P macos-latest=-self-hosted run directly on the host (no isolation), not equivalent to GitHub images
GITHUB_TOKENis not provided automatically; requires -s GITHUB_TOKEN="$(gh auth token)" (note: this is your personal token, with far greater permissions than the token in CI)
OIDC (id-token: write)does not support exchanging for cloud credentials; cloud deployment steps must be skipped or use local credentials
concurrency, environment protection rules, approvals, required checksplatform features that act does not simulate
Software preinstalled on hosted runnersThe Medium image contains only common tools; install whatever is missing yourself or switch to the Large image
Event payloadthe default is a minimal simulated payload; PR-related expressions need -e event.json to provide it
Job summaries, annotationsare written to files but not rendered in the GitHub UI

How: test pyramid for custom actions

Action typeUnit testsIntegration tests
JavaScript / TypeScriptJest/Vitest, mock @actions/core (getInput,setOutput,setFailed); inputs come at runtime from INPUT_<NAME> environment variablesan in-repo workflow uses uses: ./ on a matrix (ubuntu/windows/macos) and asserts outputs; you can also use the GitHub-provided @github/local-action to run locally (per its README)
CompositeExtract the script to scripts/*.sh tested with batsuses: ./ + assertions steps.x.outputs.y
Dockerunit tests for entry scripts inside containers; docker run -e INPUT_NAME=…uses: ./ (only Linux runners support Docker actions)

When: which layer to use when

  • Every time you save a workflow → actionlint (editor plugin or pre-commit).
  • Changed a script or dependency → act -j test.
  • CI fails while local/act both work → layer 3: compare the runner-images software inventory, reproduce in Codespaces with the same versions, or temporarily add a diagnostic step in CI (if: runner.debug == '1').

Comparison with similar technologies

act (GitHub Actions)gitlab-ci-local (GitLab)Azure Pipelines
MaintainerCommunity (nektos)CommunityNo official local executor (can be tested with a self-hosted agent)
Execution methodDocker containerDocker / shell—
Static checkingactionlintCI Lint APIYAML preview API
Common misconceptions① “If act passes, CI will definitely pass”—images, token permissions, OIDC, and platform features all differ; act only shortens the feedback loop. ② “act is a GitHub official tool”—it's a community project; its behavior follows its documentation. ③ “Passing the gh auth token to act is fine”—that's your full-permission personal token, and any third-party action in the workflow can access it; only use it with trusted workflows, preferably with a short-lived fine-grained PAT. ④ “actionlint only checks YAML syntax”—it also performs expression type checks and calls shellcheck to check run: scripts.

Local feedback loop vs remote feedback loop

Edit ci.ymlor script actionlint≈ 0.1 s act -j test≈ 30–120 s (Docker) git push+ queue GitHub-hosted runner≈ 2–15 min · billed Platform-only: OIDC, environment approvals,concurrency, required checks, real images Local inner loop: pass here first
Figure 6-1 The local inner loop covers most script and syntax issues; platform-only features can only be verified on GitHub

act internals: one act -j test

Parse workflowevent=push · job=test -P maps imagesubuntu-latest → act-latest docker run job containerMount the repository into the workspace Clone remote actionsnode / docker execution Output ✅ / ❌Local artifact/cache server secrets come from -s / --secret-file; variables come from --var / --var-file; event payload comes from -e event.json
Figure 6-2 act approximates the runner with Docker; the images are not the same as GitHub-hosted images

Checker: “Can this workflow run in act?”

Check the features your workflow uses; the checker gives each item's status in act and alternatives (based on the capabilities described in the act documentation and the limitations table in this section; for some items, the installed version prevails).

Select features, then click “Check.”
$ act -l

Core commands and parameters

CommandPurposeKey parameters
actionlintCheck .github/workflows/*.yml-shellcheck= (disable or specify a path),-format '{{json .}}',-ignore 'regex'
act -llist jobs and events-W path specify the workflow file
act [event] -j jobrun a specified jobpull_request,workflow_dispatch --input k=v,-e event.json
act -P label=imagemap runs-on to an image-P ubuntu-latest=catthehacker/ubuntu:act-latest
act -s / --secret-fileprovide secrets.secrets in dotenv format; be sure to add .gitignore
act --var / --var-fileprovide vars contextdotenv format
act --matrix k:vrun only a specific matrix combinatione.g., --matrix python:3.13
act --artifact-server-path DIRenable the local artifact serverupload/download-artifact requires
act -n / --dryrunplan only, don't executecheck job dependencies and selection
gh extension install nektos/gh-actas gh act usedsame function as act

1. Install (Linux)

# actionlint: official download script (downloads the latest version to the current directory)
bash <(curl -fsSL https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash)
sudo mv actionlint /usr/local/bin/ && actionlint -version

# act: download v0.2.98 from GitHub Releases (a package manager or gh extension also works)
curl -fsSL -o act.tgz https://github.com/nektos/act/releases/download/v0.2.98/act_Linux_x86_64.tar.gz
tar xzf act.tgz act && sudo mv act /usr/local/bin/ && act --version
1.7.12
installed by downloading from release page
built with go1.2x.x compiler for linux/amd64
act version 0.2.98

Release asset file names follow the release page. You can also run actionlint with its Docker image: docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:1.7.12 -color.

2. actionlint finds the Module 2 errors

actionlint
.github/workflows/ci.yml:14:9: got unexpected character '/' while lexing expression, expecting 'a'..'z', 'A'..'Z', '_', '0'..'9', ''', '}', '(', ')', '[', ']', '.', '!', '<', '>', '=', '&', '|', '*', ',', ' ' [expression]
.github/workflows/ci.yml:22:15: label "ubuntu-lates" is unknown. available labels are "ubuntu-latest", "ubuntu-24.04", … [runner-label]
.github/workflows/ci.yml:31:9: shellcheck reported issue in this script: SC2086:info:1:6: Double quote to prevent globbing and word splitting [shellcheck]

3. Run the test job with act

act -l
act push -j test -P ubuntu-latest=catthehacker/ubuntu:act-latest
act pull_request -j test -e .github/act/pr-event.json
act workflow_dispatch -W .github/workflows/deploy.yml --input env=staging -n
Stage  Job ID  Job name  Workflow name  Workflow file  Events
0      lint    lint      ci             ci.yml         pull_request,push,workflow_dispatch
0      test    test      ci             ci.yml         pull_request,push,workflow_dispatch
0      build   build     ci             ci.yml         pull_request,push,workflow_dispatch
1      gate    gate      ci             ci.yml         pull_request,push,workflow_dispatch
[ci/test-1] 🚀  Start image=catthehacker/ubuntu:act-latest
[ci/test-1]   ✅  Success - Main actions/checkout@v7.0.1
[ci/test-1]   ✅  Success - Main pip install -r requirements.txt -r requirements-dev.txt
[ci/test-1]   ❌  Failure - Main pytest -q
[ci/test-1] 🏁  Job failed
{
  "pull_request": { "number": 7, "head": { "ref": "feature/x" }, "base": { "ref": "main" } }
}

4. Project-level .actrc and secrets

-P ubuntu-latest=catthehacker/ubuntu:act-latest
--secret-file .secrets
--var-file .vars
--artifact-server-path /tmp/act-artifacts
printf 'GITHUB_TOKEN=%s\n' "$(gh auth token)" > .secrets    # use only with trusted workflows
echo ".secrets" >> .gitignore
act -j test

5. Write an integration test for a composite action

name: test-action
on: [push, pull_request]
jobs:
  test:
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v7.0.1
      - id: ver
        uses: ./                       # tests the action.yml in the repository root
        with:
          file: tests/fixtures/pyproject.toml
      - name: Assert output
        shell: bash
        run: |
          test "${{ steps.ver.outputs.version }}" = "1.4.0" || { echo "::error::expected 1.4.0, got ${{ steps.ver.outputs.version }}"; exit 1; }

6. Run actionlint in CI

name: lint-workflows
on:
  pull_request:
    paths: [".github/workflows/**"]
permissions:
  contents: read
jobs:
  actionlint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7.0.1
      - run: |
          bash <(curl -fsSL https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash) 1.7.12
          ./actionlint -color

The download script accepts a version argument to pin the version. Note that this workflow itself uses a path filter—if you make it a required check, refer to the gate pattern in Module 2.

Lab 6: actionlint + act local loop (about 6 minutes)

Goal and environment: local machine with Docker Engine 29,myapp-chaos repository, act v0.2.98, actionlint v1.7.12. Cost $0 (does not consume Actions minutes). The first pull of the Medium image takes a few minutes and about 1 GB of disk.
Inject two faults without pushing:
git switch -c lab/m6 baseline
sed -i 's/runs-on: ubuntu-latest/runs-on: ubuntu-lates/' .github/workflows/ci.yml
sed -i 's/timeout-minutes: 15/timeout-minutes: 15\n    if: github.ref == refs\/heads\/main/' .github/workflows/ci.yml
actionlint

Expected: actionlint reports an unknown label and an expression lexical error (see section 2 of the “Commands” page).

After fixing, run the tests with act:
git checkout -- .github/workflows/ci.yml
act -j test -P ubuntu-latest=catthehacker/ubuntu:act-latest
Create a failure that appears only in act/CI: assert the time zone in a test assert time.tzname[0] == "CST", which fails in act while your machine may pass—experience the “environment difference.” Run act -j test , observe ❌, then delete the assertion.
Verify: actionlint no output and exit code 0; act -j test the final output shows 🏁 Job succeeded.
Clean up:
git switch main && git branch -D lab/m6
docker image ls | grep catthehacker     # docker image rm to free space when needed
rm -f .secrets

Case 1: the platform team's workflow repository

Problem: The organization's shared reusable-workflow repository frequently breaks 200 downstream repositories with small changes. Approach: Enforce actionlint on PRs (gate job), prepare a caller test workflow for each reusable workflow to run in a sandbox repository, and publish with semantic version tags. Limitation: act's support for remote reusable workflows is limited; final validation of reusable workflows still has to be done on GitHub.

Case 2: missing tools in act cause “false failures”

Problem: A developer ran act with the Micro image,python3/docker was missing, and wrongly concluded the workflow was broken. Approach: Commit .actrc to the repository; standardize on the Medium image, and document act's known differences in the README. Limitation: The Large image is close to GitHub's images but very large; use it only in a few debugging scenarios.

Case 3: regression in a custom JavaScript action

Problem: After upgrading dependencies, the action's path handling broke on a Windows runner. Approach: Unit tests cover path separators; the integration test workflow uses uses: ./ to run on three OSes; before release, npm run package and verify dist/ matches the source (in CI, git diff --exit-code dist/). Limitation: macOS jobs have a high unit price, so run the full matrix only on release branches.

Common errors and fixes

Error: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Cause: act depends on Docker; the daemon is not running or the current user lacks permissions.

docker info >/dev/null && echo ok
`sudo usermod -aG docker "$USER"   # takes effect after logging in again`
[ci/test] ❌ Failure - Main actions/checkout … / Unable to resolve action … authentication required

Cause: no token was provided, so cloning a private action or calling the API failed; or unauthenticated GitHub rate limiting was triggered (60 per IP per hour).

Fix:act -s GITHUB_TOKEN="$(gh auth token)", or provide it in .secrets .

/var/run/act/workflow/2: line 1: python: command not found

Cause: the Micro image was used or the image lacks that tool, while GitHub-hosted images have it preinstalled.

Fix: Explicitly install it in the workflow using actions/setup-python@v7.1.0 (a good habit for CI as well), or switch to the Medium/Large image.

Error: Unable to get the ACTIONS_RUNTIME_TOKEN env variable (upload-artifact / cache)

Cause: act's artifact server is not enabled, or a newer official action version is incompatible with act's simulated services.

Fix: Add --artifact-server-path /tmp/act-artifacts; if it still fails, skip the step in act: if: ${{ !env.ACT }} (act sets the ACT=true environment variable).

actionlint: property "foo" is not defined in object type {…} [expression]

Cause: references a non-existent output/context property (misspelled or wrong step id).

Fix: Compare against the steps.<id>.outputs.<name> id and name of the step; for dynamic outputs you can use -ignore to ignore specific rules.

Command-line exercises
1. Use act to run only the python 3.13 combination of the test job in ci.yml, simulating a pull_request event and using the .secrets file.
act pull_request -W .github/workflows/ci.yml -j test --matrix python:3.13 --secret-file .secrets
2. Write a step that is skipped in act but runs normally on GitHub.
- name: Deploy
  if: ${{ !env.ACT }}
  run: ./deploy.sh
Scenario analysis
A test passes in both act and locally but consistently fails on a GitHub-hosted runner with “locale.Error: unsupported locale setting.” How do you troubleshoot it?

① Confirm it is an environment difference (layer 3). ② In CI, add a diagnostic step that runs only in debug mode: locale -a,echo $LANG $LC_ALL,cat /etc/os-release. ③ Compare the software inventory and locale settings of that image in the actions/runner-images repository. ④ Fix: do not depend on the system locale in tests, or explicitly install/set it in the workflow (sudo locale-gen zh_CN.UTF-8 and set LANG). ⑤ Also write that setting into the devcontainer so the Codespaces environment matches CI.

Verified instructional videos

▶
Run GitHub Actions locally - act LIVE DEMO — Dev Leonardo
English · live demo of act (installation, choosing images, running jobs); the video is older, so parameters follow the act v0.2.98 documentation

No verified video dedicated to actionlint was found.

Official / project documentation

Video storyboard script (about 75 seconds)

This course material cannot directly generate video or MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a long string of “fix ci” in the commit history.
Narration: every push has to queue, wait, and be billed. Let's move the feedback loop to local first.
Shot 2 · 20–40s
Visual: the editor saves the file, and actionlint immediately draws a red line on line 14.
Narration: actionlint checks syntax, expression types, and shell scripts in a tenth of a second.
Shot 3 · 40–60s
Visual: the terminal runs act -j test, a Docker container starts, and the steps are checked off one by one.
Narration: act uses a Docker container to approximate the runner, reproducing most script issues within tens of seconds.
Shot 4 · 60–75s
Visual: OIDC, approval, and concurrency icons are placed into a box labeled “can only be verified on GitHub.”
Narration: but OIDC, environment approvals, and concurrency control can only be verified on GitHub; passing in act does not mean CI will definitely pass.
or score ≥ 70% on the “Quiz”

Module 7 · API, Webhooks, and GitHub Apps: Rate Limits and Reliability

43:00 – 52:00 · Write an integration that won't get rate-limited or banned, misses no events, and doesn't process duplicates
9 minREST / GraphQL limits verified against the official pagesInstallation tokens 1 hour · webhook redelivery 3 days★★★★★
Learning objectives
  • Distinguish REST's primary rate limits (hourly quota,x-ratelimit-* headers) and secondary rate limits (concurrency 100, points per minute, CPU time, content creation rate), and handle 403/429 per the official rules: retry-after → x-ratelimit-reset → wait at least 1 minute → exponential backoff.
  • Calculate GraphQL query points (5,000 points per hour; node limit 500,000; first/last 1–100), using rateLimit { cost remaining resetAt } to self-check.
  • Use ETag conditional requests (304 responses do not count toward the primary limit) and webhooks instead of polling.
  • Choose among GitHub App, OAuth App, PAT,GITHUB_TOKEN and be able to use a JWT to exchange for an installation token valid for 1 hour.
  • Verify X-Hub-Signature-256 (HMAC-SHA256, constant-time comparison), respond with 2XX within 10 seconds, and use X-GitHub-Delivery for idempotency, and use the API to redeliver failed deliveries from within 3 days.
Prerequisites: HTTP basics, and Lesson 5's GitHub App tokens. Importance:★★★★★ (unavoidable for all automation and platform tooling)

What: REST primary rate limits (per hour)

IdentityLimitNotes
Unauthenticated60per originating IP
User (PAT, App acting on behalf of a user)5,000GitHub App owned by a GHEC organization / approved OAuth App: 15,000
GitHub App installation tokenat least 5,000non-GHEC: after more than 20 repositories, +50 per repository; after more than 20 organization users, +50 per user, capped at 12,500; GHEC: 15,000
OAuth App (client ID + secret, public data only)5,000owned by a GHEC organization: 15,000
The Actions GITHUB_TOKEN1,000 per repositoryGHEC resource 15,000

Response headers: x-ratelimit-limit (limit),x-ratelimit-remaining (remaining),x-ratelimit-used (used),x-ratelimit-reset (window reset time, UTC epoch seconds),x-ratelimit-resource (the resource category counted, such as core,search,graphql). Official note: requests are handled across multiple regions, so values in different responses may differ,the response headers are authoritative rather than GET /rate_limit.

What: secondary rate limits (anti-abuse; remaining quota cannot be queried)

DimensionLimit
Concurrent requestsup to 100 (shared between REST and GraphQL)
Points per endpoint per minuteREST 900 points / GraphQL 2,000 points; most REST GET/HEAD/OPTIONS requests are 1 point, most POST/PATCH/PUT/DELETE are 5 points (points for some endpoints are not published)
CPU timeno more than 90 seconds of CPU time per 60 seconds of real time, of which GraphQL is no more than 60 seconds
Content creationgenerally about 80 content-generating requests per minute and 500 per hour (some endpoints are lower; web actions also count)
OAuth access token requestsGitHub App and OAuth App: 2,000 per hour

Handling order defined by the official docs

  1. Primary limit exhausted: 403 or 429,x-ratelimit-remaining: 0 → do not retry before x-ratelimit-reset .
  2. Secondary limit: 403 or 429, error message indicating a secondary rate limit: if the retry-after header is present → wait that many seconds; otherwise, if x-ratelimit-remaining is 0 → wait until reset; otherwise wait at least 1 minute.
  3. If it still fails → exponential backoff, and stop with an error once the maximum number of retries is reached.
  4. Official warning: continuing to send requests while rate limited may result in the integration being banned.

Prevention: serialize requests (queue) rather than sending concurrently; space out bulk write operations by at least 1 second; use webhooks instead of polling (when polling is necessary, respect x-poll-interval); use Link header pagination instead of building page numbers by hand; use conditional requests.

What: GraphQL limits

  • The primary limit is based on points: users get 5,000 points per hour (GitHub App owned by a GHEC organization: 10,000); installation tokens start at 5,000, with the same rules as REST (up to 12,500; GHEC 10,000); GITHUB_TOKEN 1,000 per repository.
  • Point calculation: assume each connection fetches the maximum first/last, add up the number of requests needed, divide by 100, round, minimum 1 point. For example, a query requiring 5,101 requests costs 51 points.
  • Every connection must specify first or last (1–100); a single call must not exceed 500,000 total nodes.
  • Processing longer than 10 seconds is terminated and returns 502/504, and additional points are deducted from the next hour.
  • Add rateLimit { limit cost remaining resetAt } to a query to get this query's cost.

Why: conditional requests and webhooks

Save the response's etag (or last-modified), and on the next request send If-None-Match (or If-Modified-Since). If the resource has not changed, GitHub returns 304 Not Modified, as long as the request carries Authorization header,a 304 does not count toward the primary limit. Write operations (POST/PUT/PATCH/DELETE) generally do not support conditional requests. A better approach is to subscribe to webhooks: GitHub pushes changes to you, with zero polling.

How: choosing an identity

GitHub App (installation token)OAuth AppFine-grained PATclassic PATGITHUB_TOKEN
Acts asthe App itself (can also act on behalf of a user)useruseruserthe current repository's workflow
Permission granularityfine-grained permissions + selected repositoriescoarse scopesfine-grained + selected repositoriescoarse scopespermissions:
Validity1 hour (re-exchanged with a JWT)does not expire by default, until the user revokes itexpiration must be setmay not expireexpires when the job ends
Limitgrows with installation size, up to 12,500 (GHEC 15,000)5,000 (user)5,0005,0001,000/repository
webhookbuilt-in, centrally configuredmust be configured per repository/organization———
Departure riskNone (not tied to a person)tied to the authorizing usertied to a persontied to a personNone
Recommended use casesorganization automation, bots, platform integrations (preferred)“Login with GitHub”; enterprise-level resources (Apps do not yet support enterprise-level permissions)personal scripts, one-off taskslegacy; phase out where possibleCI operations within the same repository

Installation token flow:① Sign a JWT with the App's private key using RS256 (iat recommended to backdate by 60 seconds,exp no more than 10 minutes,iss with iss set to the client ID or app ID) → ② request an installation token with POST /app/installations/{installation_id}/access_tokens, can use repositories/repository_ids (up to 500) and permissions to narrow further → ③ get an installation token valid for 1 hour ghs_… (cannot exceed the permissions the App has been granted). In Actions, you can use actions/create-github-app-token (latest as of 2026-11: v3.3.0).

How: a reliable webhook receiver

  • Verify the signature: GitHub computes an HMAC-SHA256 of the raw request body using the webhook secret, and places it in X-Hub-Signature-256: sha256=<hex>; the receiver computes it the same way and compares using a constant-time comparison (Python hmac.compare_digest, Node crypto.timingSafeEqual), never ==. Official test vector: secret It's a Secret to Everybody, payload Hello, World! → 757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17.
  • Return 2XX within 10 seconds, otherwise GitHub disconnects and records a failure; after receiving, enqueue and process asynchronously.
  • Idempotency: X-GitHub-Delivery is a unique GUID for each delivery,and keeps the same value on redelivery— use it as the deduplication key (e.g., Redis SET NX with an expiry)
  • Check the event: first look at X-GitHub-Event and the top-level fields of the payload action before processing; subscribe only to the events you need.
  • Redelivery: GitHub does not automatically redeliver failed deliveries; you can redeliver them in the UI or via the REST API from the past 3 days. The official recommendation is a scheduled script: list deliveries since the last run → find status those that are not OK → call the redelivery API.

When: design checklist

  • Need thousands of reads per minute? → switch to webhooks + local cache, or consolidate queries with GraphQL.
  • Bulk-creating issues/comments? → serial queue + at least 1 second between requests + secondary rate limit backoff.
  • Cross-organization bot? → GitHub App; exchange a token per installation and cache it for about 50 minutes.

Comparison with similar technologies

GitHubGitLab.comAzure DevOps
Rate limit headersx-ratelimit-*RateLimit-*X-RateLimit-* + Retry-After
webhook signatureHMAC-SHA256 X-Hub-Signature-256plaintext X-Gitlab-Token (or signed token, per official documentation)Basic auth / custom header
application identityGitHub App (short-lived installation token)Group/Project access tokenService principal / managed identity
Common misconceptions① “With 4,000 quota left, I can fire 200 concurrent requests”—exceeding 100 concurrent requests triggers secondary limits, unrelated to the primary quota. ② “On a 403, retry immediately 3 times”—continuing to send requests while rate limited can lead to a ban; you must follow retry-after/ reset / wait at least 1 minute. ③ “Signature is computed over json.dumps(request.json) the re-parsed JSON”—you must use the raw bytes, since re-serializing changes the bytes and breaks verification. ④ “GitHub automatically retries failed webhooks”—it doesn't; you must redeliver yourself. ⑤ “Installation tokens can be cached for a whole day”—they expire after 1 hour.

Rate limit decision path for requests

Client requestwith Authorization If-None-MatchResource unchanged? 304 Not Modifieddoes not count toward primary limit Secondary limitsconcurrency/points/CPU/content 403/429 secondaryretry-after? → waitotherwise ≥ 1 minute + backoff Primary limitremaining > 0? 403/429remaining: 0wait until x-ratelimit-reset 200 / 201record x-ratelimit-remaining Prevention: serial queue (small concurrency) · ≥ 1 second between writes · webhooks instead of polling · Link header pagination · consolidated GraphQL queries Continuing to request while rate limited → official warning: may get the integration banned
Figure 7-1 The decision order is a teaching illustration; the platform's internal implementation is not public, but handling rules follow the official documentation

GitHub App token and webhook delivery sequence

Your serviceGitHub APIGitHub event ① JWT (RS256, exp ≤ 10 minutes) POST /app/installations/ID/access_tokens ② ghs_… installation token (valid 1 hour) ③ API call Authorization: Bearer ghs_… ④ POST webhook: X-GitHub-Event · X-GitHub-Delivery · X-Hub-Signature-256 ⑤ Verify signature → enqueue → 202 within 10 seconds ⑥ Scheduled job: GET …/hooks/deliveries (within 3 days) ⑦ POST …/deliveries/ID/attempts to redeliver failed items (same delivery GUID) Consumers deduplicate by X-GitHub-Delivery, so redeliveries are not processed twice
Figure 7-2 Token acquisition, webhook delivery, failed redelivery, and idempotency

Core animation: triggering secondary rate limits and exponential backoff retries

Scenario: a script must create one issue in each of 120 repositories (content-creation requests, simulated using the official secondary limit of “about 80 per minute”). Choose a client strategy and play; observe the distribution of 201 (green) and 403 secondary (red), total time, and the “violating request count.” Time compression: 1 cell = 5 seconds.

0 sTime
Created
403 secondary
Elapsed
Choose a strategy, then play.

Core commands and parameters

CommandPurposeNotes
gh api -i PATHShow response headersView x-ratelimit-*,etag,link
gh api rate_limitView quotas per resourceitself does not count toward the primary limit; the actual response headers are authoritative
gh api -H 'If-None-Match: "…"'Conditional requeston 304, gh returns a non-zero exit code; handle this in scripts
gh api --paginateAutomatically follow Link header paginationcombined with per_page=100
gh api graphql -f query=…GraphQLplus rateLimit{cost remaining resetAt}
gh api …/hooks/HOOK_ID/deliveriesList webhook deliveriesendpoints exist at repository, organization, and App levels
gh api -X POST …/deliveries/ID/attemptsRedeliver a deliveryonly within the past 3 days

1. Check rate limit headers

gh api -i repos/{owner}/{repo} 2>&1 | grep -iE '^(x-ratelimit|etag|retry-after)'
Etag: W/"4c1d2a9f0b8e7d6c5b4a3f2e1d0c9b8a"
X-Ratelimit-Limit: 5000
X-Ratelimit-Remaining: 4987
X-Ratelimit-Reset: 1763200800
X-Ratelimit-Resource: core
X-Ratelimit-Used: 13

2. Conditional request: 304 does not count toward the primary limit

ETAG=$(gh api -i repos/{owner}/{repo} | awk -F': ' 'tolower($1)=="etag"{print $2}' | tr -d '\r')
gh api -i -H "If-None-Match: $ETAG" repos/{owner}/{repo} 2>&1 | grep -E '^HTTP|X-Ratelimit-Remaining'
HTTP/2.0 304 Not Modified
X-Ratelimit-Remaining: 4987

3. GraphQL point self-check

gh api graphql -f query='
query {
  repository(owner: "OWNER", name: "myapp-chaos") {
    pullRequests(last: 50, states: OPEN) { nodes { number title } }
  }
  rateLimit { limit cost remaining resetAt }
}' -q .data.rateLimit
{"cost":1,"limit":5000,"remaining":4999,"resetAt":"2026-11-15T10:00:00Z"}

4. Client with backoff (Python, following the official handling order)

import random, time, requests

API = "https://api.github.com"

def gh_request(method, path, token, max_retries=6, **kw):
    headers = {"Authorization": f"Bearer {token}",
               "Accept": "application/vnd.github+json",
               "X-GitHub-Api-Version": "2022-11-28"}
    delay = 60                                   # secondary limit with no retry-after: at least 1 minute
    for attempt in range(max_retries + 1):
        r = requests.request(method, API + path, headers=headers, timeout=30, **kw)
        if r.status_code not in (403, 429):
            return r
        remaining = r.headers.get("x-ratelimit-remaining")
        if "retry-after" in r.headers:           # ① if retry-after is present, obey it strictly
            wait = int(r.headers["retry-after"])
        elif remaining == "0":                   # ② primary limit exhausted: wait until reset
            wait = max(0, int(r.headers["x-ratelimit-reset"]) - int(time.time())) + 1
        elif "rate limit" in r.text.lower():     # ③ secondary limit: ≥ 60 seconds, then exponential growth + jitter
            wait = delay + random.uniform(0, delay * 0.2)
            delay = min(delay * 2, 900)
        else:
            return r                             # genuine permission 403; do not retry
        print(f"[{attempt}] {r.status_code} rate limited, sleeping {wait:.0f}s")
        time.sleep(wait)
    raise RuntimeError(f"gave up after {max_retries} retries: {method} {path}")

def create_issues(token, repos):
    for full in repos:                           # serial, not concurrent
        gh_request("POST", f"/repos/{full}/issues", token,
                   json={"title": "Quarterly dependency review"})
        time.sleep(1)                            # at least 1 second between write operations

For Node.js, you can directly use Octokit's @octokit/plugin-throttling (latest as of 2026-11: v11.0.5) and @octokit/plugin-retry, which implement similar logic.

5. Get a GitHub App installation token in Actions

- uses: actions/create-github-app-token@v3.3.0     # pin to a SHA in production
  id: app
  with:
    client-id: ${{ vars.BOT_CLIENT_ID }}           # the app-id input is deprecated; use client-id instead (verified in action.yml, 2026-11)
    permission-pull-requests: write                # further narrow token permissions
    permission-contents: write
    private-key: ${{ secrets.BOT_PRIVATE_KEY }}
    owner: ${{ github.repository_owner }}
    repositories: myapp-chaos
- run: gh pr create --fill
  env:
    GH_TOKEN: ${{ steps.app.outputs.token }}       # PRs created by the App trigger CI (unlike GITHUB_TOKEN)

6. Webhook receiver (Flask, signature + idempotency + async)

import hashlib, hmac, os
from flask import Flask, request, abort
import redis

app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"].encode()
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"))

def verify(body: bytes, sig: str | None) -> bool:
    if not sig:
        return False
    expected = "sha256=" + hmac.new(SECRET, msg=body, digestmod=hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, sig)      # constant-time comparison

@app.post("/github/webhook")
def hook():
    body = request.get_data()                      # raw bytes; don't parse JSON and then re-serialize
    if not verify(body, request.headers.get("X-Hub-Signature-256")):
        abort(401)
    delivery = request.headers["X-GitHub-Delivery"]
    if not r.set(f"gh:delivery:{delivery}", 1, nx=True, ex=7 * 24 * 3600):
        return "", 200                             # redelivery / duplicate: already processed
    r.rpush("gh:events", body)                     # enqueue; a background worker processes it
    return "", 202                                 # respond within 10 seconds
# self-check the signature function with the official test vector
python3 - <<'EOF'
import hmac, hashlib
print(hmac.new(b"It's a Secret to Everybody", b"Hello, World!", hashlib.sha256).hexdigest())
EOF
757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17

7. Find and redeliver failed deliveries (repository webhook)

HOOK=$(gh api repos/{owner}/{repo}/hooks -q '.[0].id')
gh api --paginate "repos/{owner}/{repo}/hooks/$HOOK/deliveries?per_page=100" \
  -q '.[] | select(.status != "OK") | [.id, .guid, .event, .status_code, .delivered_at] | @tsv'
# redeliver one delivery (must be from the past 3 days)
gh api -X POST "repos/{owner}/{repo}/hooks/$HOOK/deliveries/DELIVERY_ID/attempts"
51234567890	0f1e2d3c-…-9a8b	push	502	2026-11-15T07:12:09Z
51234567911	7a6b5c4d-…-1e2f	pull_request	0	2026-11-15T07:40:51Z

Lab 7: rate limit headers, conditional requests, signature verification, and redelivery (about 8 minutes)

Goal and environment: local machine with Python 3.12+ and gh CLI logged in; myapp-chaos repository; optionally run Redis with Docker. Cost $0. Risk: Do not bulk-create issues in a real repository; use a random value for the test webhook's secret, and delete the webhook after the lab.
Observe primary limit consumption:
gh api rate_limit -q '.resources.core'
for i in $(seq 1 5); do gh api repos/{owner}/{repo} >/dev/null; done
gh api rate_limit -q '.resources.core'

Expected: used increases by 5,remaining decreases by 5 (rate_limit the call itself does not count).

Conditional request: run section 2 of the “Commands” page, and confirm the second request returns 304 and X-Ratelimit-Remaining is unchanged.
Signature verification: save section 6 as webhook.py, first verify the HMAC with the test vector, then start it locally and simulate one delivery:
docker run -d --name redis -p 6379:6379 redis:7
pip install flask redis requests
WEBHOOK_SECRET='lab-secret' REDIS_HOST=localhost flask --app webhook run -p 8080 &
body='{"zen":"Keep it logically awesome."}'
sig="sha256=$(printf '%s' "$body" | openssl dgst -sha256 -hmac 'lab-secret' | awk '{print $2}')"
curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:8080/github/webhook \
  -H "X-Hub-Signature-256: $sig" -H "X-GitHub-Delivery: test-1" -H "X-GitHub-Event: ping" -d "$body"
curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:8080/github/webhook \
  -H "X-Hub-Signature-256: $sig" -H "X-GitHub-Delivery: test-1" -H "X-GitHub-Event: ping" -d "$body"
curl -s -o /dev/null -w '%{http_code}\n' -X POST localhost:8080/github/webhook \
  -H "X-Hub-Signature-256: sha256=deadbeef" -H "X-GitHub-Delivery: test-2" -d "$body"
202
200
401

The first call is enqueued (202); the same Delivery GUID sent again is deduplicated (200); an invalid signature is rejected (401).

(Optional) real webhook and redelivery: use a tunneling tool to expose 8080 over HTTPS; add it in the repository's Settings → Webhooks (enter the secret as lab-secret), first stop Flask to create failed deliveries, then use the section 7 commands to find the failed items and redeliver them, and confirm the redelivery's X-GitHub-Delivery matches the original delivery and is handled correctly by the deduplication logic.
Backoff client (read-only demo): replace the gh_client.py in create_issues with a loop over GET /repos/{owner}/{repo} that prints each x-ratelimit-remaining, to understand how the client throttles based on headers (do not actually trigger secondary limits).
Clean up:
kill %1 2>/dev/null; docker rm -f redis
gh api -X DELETE "repos/{owner}/{repo}/hooks/HOOK_ID"   # if you created a real webhook

Case 1: migration script interrupted by secondary limits and nearly banned

Problem: A migration tool used 50 threads to set branch rules for 3,000 repositories concurrently; within minutes a large number of 403s “You have exceeded a secondary rate limit” appeared, and the script retried immediately, causing continued throttling. Approach: Switch to a single-threaded queue, 1 second between write operations, implement the official handling order (retry-after → reset → 60 seconds → exponential backoff), and persist progress so the job can resume from checkpoints. Result: Total duration about 1.5 hours, zero violations. Limitation: Secondary limits cannot be queried; only conservative rates and backoff can be used.

Case 2: dashboard polling exhausts the 5,000 quota

Problem: An internal dashboard polled the PR status of 200 repositories every 30 seconds using a single service-account PAT, making 24,000 requests per hour. Approach: Switch to a GitHub App + organization-level webhooks (pull_request,check_suite) to push updates, with local caching; for fallback polling, use ETag conditional requests (304 does not count toward the primary limit) and batched GraphQL queries. Result: API usage dropped by 98%.

Case 3: webhook processed twice, causing a duplicate deployment

Problem: The receiver took longer than 10 seconds to process, so GitHub recorded a failure; the on-call engineer manually redelivered, and the same push was deployed twice. Approach: The receiver only verifies signatures, enqueues, and immediately returns 202; the worker deduplicates by X-GitHub-Delivery , and the deployment task itself is idempotent by commit SHA. Limitation: Redelivery only covers deliveries from the past 3 days; longer outages require active reconciliation via the API (e.g., listing recent commits/PRs).

Common errors and fixes

403 {"message":"API rate limit exceeded for user ID 1234567.","documentation_url":"…"} x-ratelimit-remaining: 0

Cause: the primary limit is exhausted.

gh api rate_limit -q '.resources.core | "\(.remaining)/\(.limit) reset=\(.reset|todate)"'

Fix: Wait until reset; long-term options: GitHub App (higher limits that grow with scale), conditional requests, webhooks, consolidated GraphQL queries.

403 You have exceeded a secondary rate limit. Please wait a few minutes before you try again.

Cause: concurrency is too high, too many writes in a short time, or points/CPU limits exceeded; unrelated to how much primary quota remains.

Fix: Obey retry-after, otherwise wait at least 1 minute before exponential backoff; switch to serial requests and space writes by ≥ 1 second. Do not retry immediately.

401 {"message":"'Expiration time' claim ('exp') is too far in the future"} / A JSON web token could not be decoded

Cause: The JWT's exp exceeds 10 minutes, server clock drift, not using RS256, or a mismatched private key.

Fix:iat = now - 60,exp = now + 540; sync NTP; confirm you are using the App's currently valid private key.

401 Bad credentials (starts appearing after about 1 hour of running)

Cause: the installation token expires after 1 hour.

Fix: Cache the token and its expires_at, refresh 5–10 minutes early; use Octokit's App auth strategy to renew automatically.

Webhook receiver returns 401: signature mismatch (the locally computed sha256 differs from X-Hub-Signature-256)

Cause: computing HMAC over re-serialized parsed JSON; the framework rewrote the request body (encoding, line endings); the secret differs between sides; reading the X-Hub-Signature (the legacy SHA-1 header).

Fix: Use the raw bytes; first verify the function with the official test vector; confirm the secret; use X-Hub-Signature-256.

Recent Deliveries shows “We couldn't deliver this payload: timed out”

Cause: the receiver did not respond within 10 seconds.

Fix: The synchronous path only verifies and enqueues; after the fix, use the redelivery API to resend failed deliveries from the past 3 days; consumers deduplicate by Delivery GUID.

Command-line exercises
1. One command that shows the remaining core resource quota and a human-readable reset time.
gh api rate_limit -q '.resources.core | "\(.remaining)/\(.limit) reset=\(.reset|todate)"'
2. List the delivery IDs of recent failed deliveries for a repository's webhook.
gh api --paginate "repos/{owner}/{repo}/hooks/HOOK_ID/deliveries?per_page=100" -q '.[] | select(.status != "OK") | .id'
Scenario analysis
You are building a bot: across the organization's 400 repositories, whenever a PR gets the needs-review label, it automatically assigns reviewers and comments. Design the identity, event intake, rate limiting, and reliability plan.

Identity: GitHub App with Pull requests: write and Metadata: read permissions, installed on the organization with selected repositories; don't use a personal PAT. Events: subscribe to pull_request (labeled action) App webhooks; the receiver verifies signatures (X-Hub-Signature-256, constant-time comparison) → deduplicates by X-GitHub-Delivery → enqueues → returns 202 within 10 seconds. Processing: the worker caches installation tokens per installation (1-hour expiry, refreshed early); writes are serial with ≥ 1 second spacing; implement retry-after / reset / 60 seconds / exponential backoff; comments carry an idempotency marker (check whether already commented first). Reliability: a scheduled job every 10 minutes uses the deliveries API to redeliver failed deliveries from the past 3 days; for outages longer than 3 days, reconcile using search/list APIs; monitor the 403/429 ratio and queue length.

Verified instructional videos

No verified video found (checked via oEmbed) that specifically explains GitHub API secondary rate limits, GitHub App installation tokens, or webhook signature verification. Please refer to the official documentation below, and use the storyboard script to produce your own.

Official documentation

Video storyboard script (about 100 seconds)

This course material cannot directly generate video or MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: two gauges: on the left, a large tank labeled “5000 per hour”; on the right, a small faucet labeled “per minute.”
Narration: GitHub has two kinds of rate limits. The primary limit is the total hourly quota; secondary limits govern concurrency and speed.
Shot 2 · 20–50s
Visual: 50 arrows fire at the API simultaneously, and red 403 secondary bounce back; the client immediately fires again, and a “ban warning” appears on screen.
Narration: bursting concurrent requests triggers secondary limits. Retrying immediately only makes it worse, and the official warning says you may even be banned.
Shot 3 · 50–75s
Visual: waiting blocks on a timeline: retry-after, 60 seconds, 120 seconds, 240 seconds, with arrows beside them turning green one by one.
Narration: the right approach: if retry-after is present, follow it; if not, wait at least one minute, then back off exponentially, and switch to serial requests with a one-second gap between each write.
Shot 4 · 75–100s
Visual: a webhook envelope is stamped with an HMAC seal and a unique number; a duplicate envelope is blocked by a deduplication filter.
Narration: when receiving a webhook, first verify the signature, reply within ten seconds, then deduplicate using the delivery ID. Failed deliveries can be redelivered within three days.
or score ≥ 70% on the “Quiz”

Module 8 · Mixed Fault Mystery Box

52:00 – 60:00 · 8 randomly injected faults; you get only the symptoms, and diagnose each one with the Module 1 methodology
8 minIn-browser simulator + real repository injection script★★★★★
Learning objectives
  • In without knowing what was injected, diagnose workflow failures using the five steps “classify → gather evidence → zoom in → reproduce → fix.”
  • Locate the root cause with the fewest diagnostic commands (the simulator counts how many commands you used and how much time you spent).
  • Be proficient with the interactive troubleshooting tree (the “Troubleshooting” page of this module), and be able to write a short incident postmortem.
Prerequisites: Modules 1–7. Importance:★★★★★ (tests whether you have learned this hour)

What: what's in the mystery box

The chaos/inject.sh injection script from Module 0 and this page's simulator use the same set of 8 faults, covering three of the four categories (A not triggered, B stuck in queue, C run failed). You can only see the “symptoms” and must choose diagnostic commands yourself to gather evidence.

CategoryPossible symptomsRelated module
A Not triggeredNo checks on the PR; no new runs on the Actions page; or “Invalid workflow file” appearsModule 2
B Stuck in queueThe job stays at “Waiting for a runner to pick up this job…”Modules 2, 3
C Run failedA step shows a red X: 403, cache path, artifact conflict, timeoutModules 1, 2, 4

Why: why practice with “mystery boxes”

In real incidents, nobody tells you the answer. The mystery box forces you to classify first and gather evidence, rather than guessing from memory. Timing and command counting show your troubleshooting efficiency: skilled practitioners usually pinpoint the issue in 2–3 commands.

How: rules

  1. Click “Draw a mystery box” and read the symptom description.
  2. Choose diagnostic commands from the toolbox (each command counts as 1), and read the evidence returned.
  3. When you think you've found the root cause, submit a diagnosis from the 8 options; a correct answer shows the fix and prevention measures.
  4. Scoring: correct with ≤ 3 commands earns ★★★; ≤ 5 earns ★★; otherwise ★. A wrong answer loses points but you can continue gathering evidence.

When: when is it “done”?

Each of the 8 faults must be answered correctly at least once, with an average of ≤ 4 commands. The real-repository version (the “Lab” page) requires completing at least 3 random mystery boxes.

Differences from real incidents

Mystery boxReal incident
Number of faultsone at a timemay stack (e.g., permissions + cache)
Evidencefixed, typical outputlots of noise, and platform incidents are possible (check githubstatus.com first)
PressureNonesomeone is waiting to merge/release—methodology matters even more
Common misconceptions① “Change the code first, look later”—changes without evidence introduce a second fault. ② “Re-run once and see”—all 8 faults in the mystery box are deterministic, so re-running won't turn it green. ③ “Seeing a 403, add permissions: write-all”—add only the scopes needed, following least privilege.

Diagnostic matrix: symptom × most effective first command

Symptom First command What to look at PR has no checks git diff baseline -- .github/workflows on: branches / paths; the PR's base; changed files Invalid workflow file actionlint line/column numbers, expression lexical/type errors Waiting for a runner gh run view --json jobs (labels) runs-on label spelling; runner group; online runners Step red X gh run view --log-failed 403 / 409 Conflict / No file matched / exceeded time Green check but wrong result gh run rerun --debug ##[debug]Evaluating / Expanded / Result Each of the 8 mystery box faults can get decisive evidence in 1–2 commands using one of these 5 rows
Figure 8-1 Mapping from symptom to first command (print it and tape it next to your monitor)

Incident postmortem template (5 lines)

① Symptomwho, when, what was seen ② ClassificationA/B/C/D ③ Decisive evidencecommand + verbatim output ④ Root cause + fixcommit SHA ⑤ Preventionactionlint / checks /summaries / alerts
Figure 8-2 Write a 5-line postmortem after diagnosing each mystery box; compile them into the comprehensive lab report

In-browser fault mystery box simulator

Evidence text is typical output compiled from official documentation and common real-world errors (IDs and times are example values).

Not started yet
Symptom
Click “Draw a mystery box.”
Toolbox (each counts as 1)
$ # evidence will be displayed here
Submit diagnosis

Diagnostic toolbox

CommandQuestion answered
gh pr checksDoes this PR have any checks? What is their status?
gh run list --branch B --limit 3Was there a run? What's the conclusion?
gh run view RUN --log-failedWhich step failed? What is the verbatim error?
gh run view RUN --json jobsjob status, labels, step durations
git diff baseline -- .github/workflowsWhat did the workflow change?
actionlintDoes the workflow have syntax/expression errors?
git log -1 --format=%BDoes the commit message contain a skip directive?
gh run rerun RUN --debugHow were the condition and cache key evaluated?

One-click evidence script (collects key evidence into a Markdown file)

#!/usr/bin/env bash
# Usage: ./chaos/diagnose.sh [branch name]   defaults to the current branch; outputs diag-<branch>.md
set -uo pipefail
b="${1:-$(git branch --show-current)}"
out="diag-${b//\//_}.md"
{
  echo "# Diagnostic report: $b  ($(date -u +%FT%TZ))"
  echo "## 1. Commit message"; echo '```'; git log -1 --format=%B "origin/$b" 2>/dev/null || git log -1 --format=%B; echo '```'
  echo "## 2. workflow changes relative to baseline"; echo '```diff'; git diff baseline "origin/$b" -- .github/workflows 2>/dev/null; echo '```'
  echo "## 3. actionlint"; echo '```'; actionlint 2>&1 || true; echo '```'
  echo "## 4. PR checks"; echo '```'; gh pr checks "$b" 2>&1 || true; echo '```'
  run=$(gh run list --branch "$b" --limit 1 --json databaseId -q '.[0].databaseId')
  if [ -n "$run" ]; then
    echo "## 5. Latest run $run"; echo '```'
    gh run view "$run" --json status,conclusion,jobs -q '{status, conclusion, jobs: [.jobs[] | {name, status, conclusion, labels}]}'
    echo '```'
    echo "## 6. Failure log (last 40 lines)"; echo '```'; gh run view "$run" --log-failed 2>&1 | tail -40; echo '```'
  else
    echo "## 5. No runs at all → category A: check sections 1 and 2 (branch/path filters, skip directives, YAML)"
  fi
} > "$out"
echo "Generated $out"
chmod +x chaos/diagnose.sh
./chaos/inject.sh          # random injection
./chaos/diagnose.sh        # collect evidence
less diag-chaos_*.md
# Diagnostic report: chaos/1763190507  (2026-11-15T09:48:27Z)
## 5. Latest run 19283760112
{"conclusion":"","jobs":[{"conclusion":"","labels":["ubuntu-lates"],"name":"test","status":"queued"}],"status":"queued"}
## 6. Failure log (last 40 lines)
failed to get run log: run 19283760112 is still in progress; logs will be available when it is complete

How to verify: The report has at least one section with decisive evidence; if every section looks “normal,” go to gh run rerun --debug the troubleshooting tree on the “Troubleshooting” page.

Lab 8: real-repository fault mystery box (about 10 minutes, at least 3 rounds)

Goal and environment: myapp-chaos public repository (standard runners free); the inject.sh from Module 0 and the above diagnose.sh. Fault 6 (timeout) runs the job until it times out; fault 7 (label typo) stays queued indefinitely—after diagnosing, cancel the run immediately to avoid occupying concurrency.
Round 1:
./chaos/inject.sh
start=$(date +%s)
./chaos/diagnose.sh
Read the report, and write down the category and the root cause you think it is.
Zoom in on evidence when needed:
RUN=$(gh run list --branch "$(git branch --show-current)" --limit 1 --json databaseId -q '.[0].databaseId')
gh run rerun "$RUN" --failed --debug    # effective for category C
gh run cancel "$RUN"                    # for category B (queued) or timeout faults, cancel after diagnosing
Check the answer and record the time:
echo "Time taken $(( $(date +%s) - start )) seconds; answer: $(cat .git/chaos-answer)"
Reference numbers: 1 branch filter · 2 path filter · 3 permission 403 · 4 cache path · 5 artifact conflict · 6 timeout · 7 label typo · 8 expression syntax.
Fix and verify: commit the fix on the same branch,gh pr checks --watch and make sure everything is green. Write a 5-line postmortem per Figure 8-2.
Repeat for 2 or more rounds (you may specify a number to ./chaos/inject.sh 4 practice weak areas).
Clean up:
gh run list --status queued --json databaseId -q '.[].databaseId' | xargs -r -n1 gh run cancel
for b in $(gh pr list --search 'head:chaos/' --json headRefName -q '.[].headRefName'); do gh pr close "$b" --delete-branch; done
git switch main; git branch --list 'chaos/*' | xargs -r git branch -D; rm -f diag-*.md

Case 1: release day “CI is completely down”

Symptom: CI on all PRs has been failing since 10 a.m. Diagnosis: classified as C; --log-failed shows setup-python download failed; githubstatus.com shows no incidents; comparison revealed that a shared reusable workflow had just changed the python-version to a version not yet published to the tool cache. Fix: roll back the reusable workflow's tag; Prevention: add actionlint and caller tests to the reusable-workflow repository (Module 6), and publish with semantic version tags.

Case 2: stacked faults

Symptom: After fixing the 403, an artifact 409 appeared. Diagnosis: The same PR changed both the permissions and the upload step (a copy-paste caused a duplicate upload). Lesson: Fix one problem at a time and re-classify after each fix; record the “second fault” in the postmortem.

Case 3: turning on-call knowledge into a runbook

Approach: Put the Figure 8-1 diagnostic matrix,diagnose.sh and this module's troubleshooting tree into the on-call runbook; new hires practice with the mystery box for 30 minutes. Result: Mean time to recovery (MTTR) for CI incidents dropped significantly. Limitation: The mystery box only covers the workflow layer; for platform incidents (GitHub outages), subscribe separately to githubstatus notifications.

Interactive troubleshooting tree: workflow failures

Start from the symptom and answer step by step; leaf nodes give the diagnostic commands and fixes. Covers the main faults from Modules 1–7 of this hour.

Additional: issues with the mystery box itself

./chaos/inject.sh: sed: -e expression #1, char N: unterminated `s' command (macOS)

Cause: macOS ships with BSD sed,-i whose semantics differ from \n .

Fix:brew install gnu-sed install GNU sed and use gsed, or run it on Linux / Codespaces.

fatal: 'baseline' is not a commit and a branch 'chaos/…' cannot be created from it

Cause: there is no local baseline tag (e.g., the repository was cloned again).

Fix:git fetch --tags; or go back to Module 0 and recreate the tag.

pull request create failed: GraphQL: No commits between main and chaos/…

Cause: sed matched nothing (the baseline ci.yml had already been modified), so the fault was not actually injected.

Fix:git diff baseline -- .github/workflows Confirm; restore main's ci.yml to the Module 0 baseline version.

Command-line exercises
1. Cancel all queued runs in the current repository.
gh run list --status queued --json databaseId -q '.[].databaseId' | xargs -r -n1 gh run cancel
2. One command that shows each job's name, status, and runs-on label for the most recent run.
gh run view "$(gh run list --limit 1 --json databaseId -q '.[0].databaseId')" --json jobs -q '.jobs[] | [.name, .status, (.labels|join(","))] | @tsv'
Scenario analysis
Mystery box symptom: “the required check on the PR test shows Expected — Waiting for status to be reported, and the Actions page has no run for this branch.” List your first three commands and the cause each one rules out.

① git diff baseline -- .github/workflows: rules out / confirms pull_request.branches,paths filter and YAML changes (faults 1, 2, 8). ② actionlint: confirm whether the workflow file is invalid (fault 8; when invalid, the Actions page usually shows a failed run, and if there is no run, a filter is more likely). ③ git log -1 --format=%B + git diff --name-only origin/main...HEAD: rule out skip directives, and check whether the changed files match paths. If all three are normal, next check whether the PR has merge conflicts and whether the workflow is disabled (gh workflow list --all), and whether it was triggered by GITHUB_TOKEN a push.

Verified instructional videos

▶
GitHub Actions Tutorial | From Zero to Hero in 90 minutes (Environments, Secrets, Runners, etc) — CoderDave
English · as a comprehensive review; the diagnostic methods in the mystery box follow this hour

No verified GitHub Actions video on the topic of “fault injection / troubleshooting drills” was found.

Official documentation

Video storyboard script (about 90 seconds)

This course material cannot directly generate video or MP3; the storyboard and narration script are provided.

Shot 1 · 0–20s
Visual: a gift box opens, and a card floats out: “No checks on the PR.”
Narration: the fault mystery box only tells you the symptom. The first step is always classification.
Shot 2 · 20–50s
Visual: the toolbox holds 8 tools; the player picks up only git diff, and the screen highlights branches: [master].
Narration: no run? Look at what changed in the workflow. One command, clear evidence: the branch filter is wrong.
Shot 3 · 50–75s
Visual: second box: “job keeps waiting for a runner”; the player checks the job label and finds ubuntu-lates.
Narration: stuck in queue? Check the label first. Typos are more common than you'd think.
Shot 4 · 75–90s
Visual: the scoreboard shows three stars, with the five-line postmortem template below.
Narration: find the root cause in three commands or fewer, then write a five-line postmortem. This is production-grade troubleshooting practice.
or score ≥ 70% on the “Quiz”

Command cheat sheet

Troubleshooting, ARC, performance, cost, local debugging, API reliability—all on one page
Verified 2026-11-15

Troubleshooting evidence

gh run list --workflow ci.yml --status failure --limit 5
gh run view RUN --log-failed
gh run view RUN --log | grep '##\[debug\]'
gh run rerun RUN --failed --debug
gh api "repos/{owner}/{repo}/actions/runs/RUN/logs" > logs.zip
gh run view RUN --json jobs -q '.jobs[] | {name,status,conclusion,labels}'

Not triggered / disabled / triggered

git log -1 --format=%B            # [skip ci], etc.
git diff --name-only origin/main...HEAD
gh workflow list --all             # disabled_*
gh workflow enable nightly
gh workflow run deploy.yml -f env=staging
actionlint

Workflow commands

echo "::group::Title";  …;  echo "::endgroup::"
echo "::error file=src/app.py,line=12,title=T::message"
echo "::warning::message"; echo "::notice::message"
echo "::debug::shown only in debug mode"
echo "::add-mask::$DERIVED_SECRET"
echo "### Summary" >> "$GITHUB_STEP_SUMMARY"   # ≤ 1 MiB per step
echo "k=v" >> "$GITHUB_OUTPUT"

Self-hosted and ARC

./config.sh --url URL --token T --ephemeral --labels lab --unattended
gh api -X POST repos/O/R/actions/runners/generate-jitconfig -f name=jit1 -F runner_group_id=1 -f 'labels[]=lab'
helm install arc -n arc-systems --create-namespace --version 0.15.1 \
  oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set-controller
helm install arc-runner-set -n arc-runners --create-namespace --version 0.15.1 \
  --set githubConfigUrl=URL --set githubConfigSecret=SECRET \
  oci://ghcr.io/actions/actions-runner-controller-charts/gha-runner-scale-set
kubectl get autoscalingrunnersets,ephemeralrunnersets,ephemeralrunners -A

Performance and caching

gh cache list --sort size_in_bytes --order desc
gh cache delete --all --ref refs/pull/42/merge
gh api "repos/{owner}/{repo}/actions/cache/usage"
gh run view RUN --json jobs -q '.jobs[] | {name, s:((.completedAt|fromdateiso8601)-(.startedAt|fromdateiso8601))}'

Cost

# Unit prices (per minute): Linux 2-core 0.006 · Win 2-core 0.010 · macOS 0.062
# Linux 4-core 0.012 · GPU Linux 0.052 · rounded up per job
gh api --paginate "repos/{owner}/{repo}/actions/artifacts?per_page=100" -q '.artifacts[] | [.name,.size_in_bytes] | @tsv'
gh api -X DELETE "repos/{owner}/{repo}/actions/artifacts/ID"
gh codespace list; gh codespace delete --days 7

Local debugging

actionlint -color
act -l
act pull_request -j test -e event.json --secret-file .secrets
act -P ubuntu-latest=catthehacker/ubuntu:act-latest --matrix python:3.13
act --artifact-server-path /tmp/act-artifacts
# in a step: if: ${{ !env.ACT }}

API and webhooks

gh api -i repos/{owner}/{repo} | grep -i x-ratelimit
gh api rate_limit -q .resources.core
gh api -H 'If-None-Match: "ETAG"' repos/{owner}/{repo}   # 304 does not count
gh api graphql -f query='{ rateLimit { cost remaining resetAt } }'
gh api "repos/{owner}/{repo}/hooks/HOOK/deliveries" -q '.[] | select(.status!="OK") | .id'
gh api -X POST "repos/{owner}/{repo}/hooks/HOOK/deliveries/ID/attempts"

Quick troubleshooting table

Symptom / errorMost likely causeFirst step
No run after pushbranch/path filters,[skip ci],GITHUB_TOKEN triggered by an event from GITHUB_TOKEN, workflow disabledgit diff workflow,gh workflow list --all
Invalid workflow file / Unrecognized named-valueYAML or expression errorsactionlint
Waiting for a runner…label mismatch, runner group, concurrency limit, ARC listener errorsCheck the job's labels,kubectl get pods -n arc-systems
Resource not accessible by integrationpermissions: insufficient permissions / fork PRlog “GITHUB_TOKEN Permissions” block
(409) Conflict: an artifact with this name already existsartifact name collision within the same run (immutable from v4 onward)add matrix/attempt to the name
Cache not found for input keysfirst run / 7-day eviction / branch scopegh cache list
Canceling since a higher priority waiting request…concurrency groupCheck the group name and cancel-in-progress
exceeded the maximum execution time of 360 minutesnot set timeout-minutes, jobs hangset timeouts, add test timeouts
You have exceeded a secondary rate limitconcurrency / writes too fastretry-after → ≥ 60 s → exponential backoff; serialize
webhook 401 signature mismatchnot using raw body / secret mismatchverify the HMAC function with the official test vector

Recommended configuration snippet

permissions:
  contents: read                                   # least privilege; add per job
concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 15                            # never rely on the 31-hour default
    steps:
      - uses: actions/checkout@v7.0.1              # pin to a SHA in production
      - uses: actions/setup-python@v7.1.0
        with: { python-version: "3.13", cache: pip }
      - run: |
          echo "::group::install"; pip install -r requirements.txt; echo "::endgroup::"
      - if: runner.debug == '1'
        run: env | sort | grep -vi token
      - uses: actions/upload-artifact@v7.0.2
        if: always()
        with: { name: "report-${{ github.run_attempt }}", path: report.xml, if-no-files-found: error, retention-days: 7 }

Comprehensive lab + final quiz

Fault mystery box challenge + performance/cost optimization report + optional ARC deployment on kind
After class ≈ 60–90 minPublic repository: $0 costARC portion optional

Scenario

You have just taken over your team's myapp CI: it often fails for no clear reason, PR feedback takes 17 minutes, finance is complaining about the Actions bill, and the platform team wants to move jobs that need internal network access to the company's Kubernetes. Complete the following tasks in the practice repository myapp-chaos (public) and myapp-arc (private, optional) and submit a “CI Health Report.”

Fault mystery box challenge: use ./chaos/inject.sh to randomly inject faults 5 times (covering at least 4 different numbers). Each time, use diagnose.sh the Module 1 five-step method to diagnose, recording time, command count, and a 5-line postmortem. Target: ≤ 4 commands on average and ≤ 5 minutes.
Baseline measurement: run the baseline CI 3 times in a row on main, and use the Module 4 measure.sh to record wall clock, job count, and billed minutes (median).
Performance optimization: apply caching (dependencies + Docker layers), split lint/test/build, shard tests into 4 shards,concurrency, and sensible timeout-minutes, and add a gate job as the only required check. Warm up, then measure 3 more times.
Cost conversion: enter the before and after profiles into the Module 5 calculator (private repository, Team, 60 runs per day, 22 workdays) to get a monthly cost comparison; then list the current artifact storage status and cleanup plan (retention-days).
Observability: add job summaries (test statistics, cache hits, durations) and lint annotations to CI; deliberately cause one test failure, and take screenshots of the annotations and summary on the PR.
Local closed loop: add lint-workflows.yml (actionlint) and .actrc, showing that act -j test can reproduce a failure locally.
(Optional) deploy ARC on kind: following the Module 3 lab, deploy gha-runner-scale-set 0.15.1, and in a private repository myapp-arc trigger 3 jobs, and record the EphemeralRunnerSet desired replica count changing from 0 → 3 → 0 and the listener logs. For kind and Helm basics, see Kubernetes 8 + 1-hour course.
(Optional) API mini tool: using the gh_client.py from Module 7 to write a read-only script that lists the latest CI conclusion for every repository in the organization (using conditional requests and backoff), and writes the output to a job summary.

“CI Health Report” template

## 1. Mystery box challenge
| Round | Symptom | Category | Commands | Time | Root cause | Prevention |
|---|---|---|---|---|---|---|
## 2. Performance comparison (median of 3 runs)
| Metric | Before | After | Change |
|---|---|---|---|
| Wall clock (seconds) | 1031 | 231 | -78% |
| Jobs | 1 | 7 | |
| Billed minutes/run | 17 | 21 | +24% (caching only: 12) |
| Cache hit rate | — | 100% | |
## 3. Cost (monthly, private repository assumed)
| Item | Before | After |
|---|---|---|
| Compute | $ | $ |
| Storage | $ | $ |
## 4. Risks and next steps (self-hosted/ARC, larger runners, budget alerts)

Acceptance checklist

Open-ended self-test

1. Explain in your own words why “re-running” does not work for categories A and B, and is largely ineffective for category D.

Category A has no run to re-run; category B is a runner/label problem, so a re-run is still queued; category D re-runs use the same commit and the same workflow file, so the condition evaluation does not change. Only transient failures (network, upstream rate limiting) are suitable for re-running.

2. A release workflow uses GITHUB_TOKEN to push a tag, and the deploy workflow does not run. Give three ways to fix it and compare them.

Within the same workflow, use needs to chain jobs (simplest and safest); use workflow_dispatch/repository_dispatch an explicit trigger (requires actions: write, decoupled); push with a GitHub App token (this triggers runs, but you must guard against loops and manage the App).

3. Explain the full ARC chain from “job queued” to “runner Pod deleted,” and identify two places where it can get stuck.

The job is assigned to the scale set → the listener's long poll receives Job Available → it acknowledges and patches the EphemeralRunnerSet replica count → the controller requests a JIT config and creates a Pod → the runner registers, picks up the job, and streams logs back → after completion, the controller confirms and deletes it. Stuck points: authentication/Secret errors mean the listener never exists; Pods stay Pending due to PVC/privileged/insufficient resources; the runner group has not authorized the repository; maxRunners is full.

4. After splitting jobs, wall clock dropped 70%, but the bill went up. What could cause this, and how do you balance both?

Each job is rounded up individually, plus repeated fixed overhead (runner allocation, checkout, setup, dependency installation). To balance both: first add caching to reduce per-job overhead; merge overly fine-grained jobs; size shards so each is ≥ 3 minutes; for PRs, run only the affected parts.

5. What changed in GitHub Actions billing in 2026? Which claims are now outdated?

On 2026-01-01, hosted runner prices were cut by up to 39% (Linux 2-core $0.006/minute); included allowances are now expressed as dollar amounts (Free $12, Pro/Team $18, GHEC $300; the free allowances are unchanged). The plan to charge a $0.002/minute platform fee for self-hosted runners in private repositories starting 2026-03-01 has been announced as postponed, with no new date—the claim that “self-hosted runners are already being charged” is outdated.

6. Design a rate-limiting strategy for a script that bulk-changes settings across 1,000 repositories.

Use a GitHub App installation token (higher limits, not tied to a person); a single-threaded queue with ≥ 1 second between writes; use conditional requests for reads; when handling 403/429, follow retry-after → x-ratelimit-reset → at least 60 seconds → exponential backoff + jitter, with a maximum number of retries; persist progress so runs can resume from checkpoints; refresh the token before its 1-hour expiry; and log the x-ratelimit-remaining of each response so the script can slow down adaptively.

Sources and version notes

All limits, prices, and versions were verified against official pages on 2026-11-15
Prices and limits change; the official sources take precedence

Sources table

TopicVerified findingSource (accessed 2026-11-15)
Debug logsACTIONS_STEP_DEBUG/ACTIONS_RUNNER_DEBUG Can be a secret or variable, with secret taking precedence; re-runs can enable debugging; diagnostic logs are in the runner-diagnostic-logs folder (two files: runner and worker); runner.debug contextEnabling debug logging
workflow commands and summaries::error parameters file/line/endLine/col/endColumn/title; job summaries are 1 MiB per step, with up to 20 displayed per job; ::add-mask:: RulesWorkflow commands
Actions limitshosted jobs 6 hours, self-hosted jobs 5 days, self-hosted queue 24 hours, runs 35 days, matrix 256, concurrency 20/40/60/500 (macOS 5/5/5/50), larger runners 1,000 concurrent (GPU 100),GITHUB_TOKEN 1,000 requests/hour/repository, 1,500 trigger events/10 seconds/repositoryActions limits
Skipping runs5 keywords + skip-checks: true; only push/pull_request; skipped required checks stay PendingSkipping workflow runs
GITHUB_TOKENevents it produces do not create new runs (workflow_dispatch/repository_dispatch exceptions); on self-hosted runners, refresh up to 24 hoursGITHUB_TOKEN
Path filtering and concurrencydiff limit of 3,000 files; >1,000 commits always run; queue: single default,queue: max up to 100 waiting, and cannot be used with cancel-in-progressWorkflow syntax
Dependency cachedeleted after 7 days without access; default 10 GB/repository, can be increased (overage billed); scope: current branch + default branch (PRs include base); uploads 200/minute, downloads 1,500/minuteDependency caching
ARCLatest gha-runner-scale-set-0.15.1 (2026-10-23); OCI chart address; listener long polling, patch EphemeralRunnerSet, JIT, Pod retry 5 times on failure, assignment cancelled if not picked up within 24 hours; container modes dind / kubernetes / kubernetes-novolume; Helm does not upgrade CRDs; enterprise-level runners require a classic PATARC releases · ARC concepts · Quickstart · Deploy runner scale sets
actions/runnerlatest v2.338.2 (2026-10-26)actions/runner releases
larger runnersup to 96 vCPU/384 GB/2040 GB; arm64; GPU 4 vCPU + T4 16 GB VRAM + 28 GB RAM; static IPs GHEC only, up to 10 pools, reclaimed after 90 days unused; macOS does not support Azure private networkingLarger runners reference
runner unit pricesLinux 1-core $0.002, 2-core $0.006, Windows 2-core $0.010, macOS $0.062, Linux 4-core $0.012, GPU Linux $0.052 / Windows $0.102; jobs rounded up; static IPs carry no extra chargeActions runner pricing
Actions billingIncluded allowance Free $12 / Pro $18 / Team $18 / GHEC $300; storage GB-hours; artifacts and Packages share storage, overage $0.25/GB-month; cache >10 GB portion $0.07/GB-month; standard runners in public repositories and self-hosted runners are freeGitHub Actions billing
2026 billing changes2026-01-01 hosted runner price cut of up to 39%; the self-hosted $0.002/minute platform fee originally scheduled for 2026-03-01 has been postponed, no new dateGitHub Changelog 2025-12-16 (including updates)
Budgets75/90/100% alerts; metered products can block usage; budgets only cover usage after creationBudgets and alerts
Packages / CodespacesGHCR container image storage and bandwidth currently free; Codespaces 2-core $0.18/hour, storage $0.07/GB-month, personal Free 120 core-hours + 15 GB-monthPackages billing · Codespaces billing
REST rate limits60 / 5,000 / 15,000 (GHEC); installation tokens start at 5,000, up to 12,500; secondary: concurrency 100, 900 points/minute, CPU 90 s/60 s, content creation 80/minute 500/hour; handling order retry-after → reset → ≥1 minute → exponential backoffREST rate limits · REST best practices
GraphQL limitsusers 5,000 points/hour, GHEC App 10,000; node limit 500,000; first/last 1–100; 10-second timeoutGraphQL limits
GitHub App tokensinstallation tokens expire after 1 hour; can be limited to up to 500 repositories and permissions; JWT RS256, exp ≤ 10 minutes, iss is client ID or app ID; actions/create-github-app-token v3.3.0,app-id deprecated, changed to client-idInstallation token · JWT · create-github-app-token
WebhookX-Hub-Signature-256 HMAC-SHA256, constant-time comparison, official test vector (this hour re-computed with Node/Python and results matched); 2XX within 10 seconds; X-GitHub-Delivery redeliveries keep the same value; no automatic redelivery; can redeliver within the past 3 daysValidating deliveries · Best practices · Redelivering
Tool versionsgh v2.104.0 (2026-11-12); nektos/act v0.2.98 (2026-11); actionlint v1.7.12 (2026-03-30); docker/build-push-action v7.4.0; docker/setup-buildx-action v4.4.1; @octokit/plugin-throttling v11.0.5cli/cli · nektos/act · actionlint
Other action versionscheckout v7.0.1, setup-python v7.1.0, cache v6.1.0, upload-artifact v7.0.2, download-artifact v8.0.2, dorny/paths-filter v4.0.3, release-please-action v5.0.0This course's unified verified values (see the course specification)

Video verification notes

The following videos were all checked via the YouTube oEmbed interface (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-15 for title and channel:

No verified dedicated videos were found for Module 5 (2026 billing) or Module 7 (API rate limits / GitHub Apps / webhooks), so storyboard scripts are provided instead. Video content may predate this hour's verification date; for version details, this hour and the official documentation take precedence.

Audio narration notes

The “Audio” page uses the browser's built-in Web Speech API (speechSynthesis), preferring a zh-CN voice and reading English terms with an en-US voice. Numbers in the narration scripts are written out in Chinese reading form for TTS. This course material cannot directly generate MP3 or video; the narration scripts and storyboards can be passed to external TTS / video tools.

Known limitations

  • In the expected output, run IDs, job IDs, timestamps, ETags, IPs, and Pod name suffixes are all example values; ARC listener log field names may change between versions.
  • The commands in this course material were not actually executed when written; work in a practice repository and treat actual output as authoritative.
  • Prices, included allowances, limits, and 2026 billing policies may change after the verification date; in particular, for the postponed self-hosted runner platform fee, check the GitHub Changelog before budgeting.
  • The Pro plan's artifact/Packages storage is stated inconsistently (1 GB on the Actions billing page and 2 GB on the Packages billing page); this hour follows the billing page and notes it in the table.
  • act is a community project; its compatibility with the latest official actions (such as upload-artifact v7 and cache v6) is governed by the act documentation and issues; this hour has not verified each one.
  • Larger runners, static IPs, and GPU runners require Team / Enterprise Cloud and a payment method; personal Free accounts can only read the relevant sections.
  • The fault injection script depends on GNU sed; on macOS, use gsed or run it on Linux/Codespaces.
  • The simulators on the “Animation” pages (ARC scaling, rate-limit backoff, cost calculation, mystery box) are teaching models with compressed time and quantities; they do not represent internal platform implementation details.