From 4c9d9bbe3f7f42fdb6f150b1c6105732ace1d0f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 18 Sep 2026 06:28:33 +0300 Subject: [PATCH] =?UTF-8?q?ci:=20=F0=9F=9B=A1=EF=B8=8F=20let=20a=20locally?= =?UTF-8?q?-proven=20push=20skip=20the=20runner=20suite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unit suite HANGS on the runner: run 35297989416 sat at 7% for 73 minutes until it was cancelled by hand, and every push since 2026-09-17 17:54 burned the same way (35283445041 3h20m, 35255586903 88min, 35264547756 67min — all cancelled). The identical gate is 32 s here. Port hezarfen_backend's proven escape hatch, default unchanged: DEFAULT push without a trailer -> GitHub runs everything, suite included (now bounded instead of unbounded). SPECIAL scripts/gate-local.sh proves the suite here, writes .git/local-gate/.ok and prints a `Local-Gate: ( passed, s)` trailer (--amend appends it); the workflow's "Decide test gate" step honours it only on an exact HEAD^{tree} match, so CI just builds, packs, uploads. - scripts/gate-local.sh: the command CI's gate runs, with two measured bounds — faulthandler names a hanging test (all-thread dump, exit 1) after 120 s, `timeout --foreground 600` bounds the step at ~15x the worst green 41 s Test step. Preconditions first (CI's dependency set in .venv, exact recipe printed when it is missing), a stamp only from a clean tree, --scope runs emit no trailer. - .githooks/pre-push (opt in: git config core.hooksPath .githooks): refuses a stale trailer tree, a trailer with no stamp, a scoped stamp, and trailer counts that do not match the stamp; loud escapes SKIP_LOCAL_GATE=1 / GATE_ALLOW_SCOPED=1. - workflow: "Decide test gate" + guards on the suite-only steps, a bounded Test step with the faulthandler dump, stall diagnostics, and a workflow_dispatch `tests: auto|skip|force` input — force builds and tests the dispatched ref, and the deploy job then takes this run's own artifact instead of hunting for the newest green one. Two deliberate deltas from the backend reference, both because a scoped run must not be able to destroy a full-suite proof: stamps are keyed by tree AND scope (..ok, its own log too), and the "already verified, reuse it" fast path is keyed the same way — in the reference a plain `--scope` run is answered by the full stamp (suite never runs) and overwrites it (trailer silently refused afterwards). The new comments are English while the surrounding prose is Turkish: that is the language the change was built under, not an oversight. Local-Gate: 08165e108e8b490c5b0498f65411fcdf98c39891 (1387 passed, 34s) --- .githooks/pre-push | 156 +++++++++++++++++ .github/workflows/main.yml | 122 ++++++++++++- scripts/gate-local.sh | 341 +++++++++++++++++++++++++++++++++++++ 3 files changed, 616 insertions(+), 3 deletions(-) create mode 100755 .githooks/pre-push create mode 100755 scripts/gate-local.sh diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 0000000..138b800 --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,156 @@ +#!/usr/bin/env bash +# Refuse a FORGED or STALE local-verification trailer. +# +# Opt in per clone (one command, no config file to forget): +# +# git config core.hooksPath .githooks +# +# The default path is: push and let GitHub run the suite, build, pack and (on a +# manual dispatch) deploy. An untested push is legitimate, so this hook does NOT +# require a stamp. Its single job is to keep the opt-in fast lane honest. +# +# The fast lane is a commit carrying +# +# Local-Gate: ( passed, s) +# +# which makes the workflow's "Decide test gate" step skip the runner suite +# (that suite currently hangs on the runner — see scripts/gate-local.sh). The +# trailer is a claim about verification that happened HERE, so this hook checks +# it before the bytes leave: +# +# * the trailer's tree must be the tree being pushed (a stale trailer is a +# lie about lineage, and CI would silently fall back to running the suite +# anyway — so say it here, once, instead of an hour later); +# * there must be a matching stamp in .git/local-gate/, written by +# scripts/gate-local.sh, and it must be a FULL-suite stamp (a scoped run +# never produces a trailer); +# * the stamp's counts and duration must match the trailer, so a hand-typed +# line cannot pass. +# +# To push without the trailer, delete the line (the default path). Two +# deliberate escapes, both loud: +# +# SKIP_LOCAL_GATE=1 git push ... skip this check entirely +# GATE_ALLOW_SCOPED=1 git push ... accept a scoped stamp and say what +# was NOT run +# +# (SKIP_LOCAL_GATE skips only THIS hook's trailer check; the commit's trailer, +# if any, still decides whether GitHub runs the suite.) + +set -uo pipefail + +zero=0000000000000000000000000000000000000000 + +if [ "${SKIP_LOCAL_GATE:-}" = 1 ]; then + cat <<'EOF' +SKIP_LOCAL_GATE=1: NOT checking Local-Gate trailers. + skipped: that the trailer's tree matches the tree being pushed; + skipped: that a matching full-suite stamp exists in .git/local-gate/; + skipped: that the trailer's counts/duration match that stamp. +Any trailer on these commits still decides whether GitHub runs its own suite. +EOF + exit 0 +fi + +gitdir=$(git rev-parse --git-dir) +stamp_dir=$gitdir/local-gate +refused=0 + +while read -r local_ref local_sha remote_ref remote_sha; do + [ -n "${local_sha:-}" ] || continue + [ "$local_sha" != "$zero" ] || continue # branch deletion: nothing to verify + tree=$(git rev-parse --verify -q "$local_sha^{tree}") || continue + short=$(git rev-parse --short "$local_sha") + + trailer=$(git log -1 --format=%B "$local_sha" | + grep -E '^Local-Gate: [0-9a-f]{40} \([0-9]+ passed, [0-9]+s\)$' | tail -1 || true) + # No trailer: the default path. GitHub runs the suite; nothing to check. + [ -n "$trailer" ] || continue + + claim_tree=$(printf '%s\n' "$trailer" | sed -n 's/^Local-Gate: \([0-9a-f]\{40\}\) .*/\1/p') + claim_passed=$(printf '%s\n' "$trailer" | sed -n 's/^Local-Gate: [0-9a-f]\{40\} (\([0-9]*\) passed.*/\1/p') + claim_seconds=$(printf '%s\n' "$trailer" | sed -n 's/^Local-Gate: [0-9a-f]\{40\} (.*, \([0-9]*\)s)$/\1/p') + + if [ "$claim_tree" != "$tree" ]; then + cat >&2 <&2 <&2 <&2 < ( passed, s)` +# trailer; the "Decide test gate" step verifies it against +# HEAD^{tree} and only then skips the runner suite — CI still +# builds the image, proves it API-only, stages and uploads. +# A stale or copy-pasted trailer silently falls back to running +# the suite, so the fallback costs time, never verification. +# Opt the pre-push hook in per clone: +# git config core.hooksPath .githooks +# # Bir seferlik ön koşullar (workflow'un erişimi dışında): # * repo secret'ları SSH_PRIVATE_KEY / SSH_HOST / SSH_USER; # * sunucuda `loginctl enable-linger `; @@ -39,7 +57,19 @@ on: branches: - main # Deploy'un TEK kapısı — yukarıdaki başlık yorumuna bakın. + # `tests` is the escape hatch of the manual door: auto/skip redeploy the + # newest green artifact (the suite is not paid again), force builds and + # tests the dispatched ref first and deploys that fresh artifact. workflow_dispatch: + inputs: + tests: + description: "Run the test suite on this run? auto/skip redeploy the newest green artifact; force builds and tests the dispatched ref first." + type: choice + options: + - auto + - skip + - force + default: auto # Deploy serileştirmesi işin kendisinde: yeni bir push, uçuştaki VPS değişimine # dokunmadan bayat Validate/Build'i iptal edebilmeli. @@ -83,7 +113,10 @@ jobs: build: name: Build and test - if: github.event_name == 'push' + # Pushes always build (and, by default, test). A manual redeploy reuses the + # newest green artifact instead of paying the suite again, unless the + # dispatch asks for `tests: force`, which builds and tests this ref. + if: github.event_name == 'push' || github.event.inputs.tests == 'force' runs-on: ubuntu-24.04 concurrency: group: ci-${{ github.workflow }}-${{ github.ref }}-build @@ -95,11 +128,53 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.11" + # ── Which test path this run takes ────────────────────────────────── + # SPECIAL: a commit carrying a self-consistent `Local-Gate:` trailer was + # already through the suite on the developer's machine + # (scripts/gate-local.sh prints it; --amend appends it), so this run + # only builds, packs and uploads. + # Verified, never trusted: the trailer's tree must equal HEAD^{tree}, so + # a stale or copy-pasted trailer silently falls back to running the + # suite. The log always says which branch was taken, and why. + # Trailer shape: `Local-Gate: <40-hex tree> ( passed, s)`. + - name: Decide test gate + id: gate + run: | + set -euo pipefail + # Only reaches here on a push, or a dispatch with tests=force (the + # job-level `if` skips the other dispatch modes) — and force means + # the caller explicitly asked for the suite. + mode='${{ github.event.inputs.tests }}' + tree=$(git rev-parse HEAD^{tree}) + if [ "$mode" = force ]; then + echo "workflow_dispatch tests=force ⇒ running the suite on this ref" + echo "skip=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + claim=$(git log -1 --format=%B \ + | sed -n 's/^Local-Gate: \([0-9a-f]\{40\}\) (\(.*\))$/\1|\2/p' \ + | tail -1) + if [ -z "$claim" ]; then + echo "no Local-Gate trailer on $(git rev-parse --short HEAD) ⇒ running the suite (the default path)" + echo "skip=false" >> "$GITHUB_OUTPUT" + elif [ "${claim%%|*}" != "$tree" ]; then + echo "local gate claims tree ${claim%%|*}; actual tree $tree ⇒ running tests anyway" + echo "skip=false" >> "$GITHUB_OUTPUT" + else + echo "local gate trailer matches tree $tree ⇒ skipping the suite (${claim#*|})" + echo "skip=true" >> "$GITHUB_OUTPUT" + fi + # CPU tekerleği: CI'da GPU yok ve GPU imajı ~2,5 GB daha büyük. # Testler ÜÇ listeyi de ister: servis yolu (requirements.txt), yerel model # yığını (requirements-local.txt) ve eval (requirements-eval.txt — yalnız # CI/geliştirme; imaja girmez). + # The runner's pip environment exists ONLY to run the suite: the image + # builds its dependencies inside the Containerfile, and the API-only + # proof runs them inside the image. Skipped when the local gate already + # proved the suite. - name: Install dependencies (CPU torch) + if: steps.gate.outputs.skip != 'true' run: | set -euo pipefail pip install --no-cache-dir "torch>=2.6" --index-url https://download.pytorch.org/whl/cpu @@ -112,11 +187,39 @@ jobs: # model indirmesi) KENDİLERİ atlar ve nedenini yazar; ağır # integration/e2e koşumları model indirdiği için CI kapısı DEĞİLDİR — # bkz. README "CI deploy". + # `timeout --foreground 600` (10 min) bounds the step at the shell level, + # unbuffered and unpiped: what pytest printed up to the kill survives. + # 600 s is measured, not guessed — every green run's Test step took 41 s + # (35248848296, 35246056805, 35235114053, `pip install pytest` included), + # so this is ~15x the worst green, and it turns a stall from the hours it + # has actually burned (73 min stuck at 7% on 35297989416, 3 h 20 min on + # 35283445041) into ten minutes. `-u` is what keeps the progress line + # flowing into the log while the suite runs. + # faulthandler is the layer that NAMES the hang: after 120 s inside a + # single test (4x this machine's whole-suite 32 s, 3x the whole green CI + # step) it dumps every thread's traceback and exits 1. Core pytest, so no + # extra install and no plugin that could change the suite's semantics. - name: Test + if: steps.gate.outputs.skip != 'true' run: | set -euo pipefail pip install --no-cache-dir pytest - python -m pytest tests/unit -q + timeout --foreground 600 \ + python -u -m pytest tests/unit -q \ + -o faulthandler_timeout=120 -o faulthandler_exit_on_timeout=True + + # Always *within the test path*, including when the step above was + # killed: the discriminator. Disk or memory starvation shows here; a + # pytest process still standing after `timeout` returns is the signature + # of a kill the kernel could not deliver. + - name: Stall diagnostics + if: always() && steps.gate.outputs.skip != 'true' + run: | + echo '=== df -h / ==='; df -h / || true + echo '=== free -m ==='; free -m || true + echo '=== nproc ==='; nproc || true + echo '=== surviving pytest processes ===' + ps -eo pid,etimes,stat,cmd | grep '[p]ytest' || echo none # Laptop ve CI aynı Containerfile'ı kullanır: ENV bloğu ne diyorsa o # gönderilir, ayrı bir CI ikizi yok. @@ -186,8 +289,12 @@ jobs: (needs.build.result == 'skipped' || needs.build.result == 'success') runs-on: ubuntu-24.04 steps: - # Elle deploy, BUILD işi yeşil olan en yeni koşuyu alır. + # Elle deploy, BUILD işi yeşil olan en yeni koşuyu alır — ama yalnız bu + # koşuda build YOKSA: `tests: force` ile dispatch edildiğinde bu koşunun + # kendi taze artefaktı kullanılır (aşağıdaki adım), yoksa build edilen + # imaj hiçbir yere gitmezdi. - name: Find the newest green build + if: needs.build.result == 'skipped' env: GH_TOKEN: ${{ github.token }} run: | @@ -207,6 +314,7 @@ jobs: echo "run_id=$run_id" >> "$GITHUB_ENV" - name: Fetch the green release + if: needs.build.result == 'skipped' uses: actions/download-artifact@v4 with: name: release @@ -214,6 +322,14 @@ jobs: run-id: ${{ env.run_id }} github-token: ${{ github.token }} + # tests=force: the artifact this very run built and gated. + - name: Fetch this run's release + if: needs.build.result == 'success' + uses: actions/download-artifact@v4 + with: + name: release + path: stage + - name: Check the release is complete run: | set -euo pipefail diff --git a/scripts/gate-local.sh b/scripts/gate-local.sh new file mode 100755 index 0000000..2bc86bb --- /dev/null +++ b/scripts/gate-local.sh @@ -0,0 +1,341 @@ +#!/usr/bin/env bash +# The LOCAL full gate: the "special path" where this machine proves the +# suite instead of a GitHub runner. +# +# Why it exists: the same suite is ~30s here and HANGS on a 2-core runner +# (measured: run 35297989416 sat at 7% for 73 minutes until it was cancelled +# by hand, and every push since 2026-09-17 17:54 burned 1h-3h20m the same +# way). When you have run this script, commit the `Local-Gate:` trailer it +# prints (`--amend` writes it for you) and the push carries proof: the +# workflow's "Decide test gate" step verifies the trailer against HEAD^{tree} +# and then skips the runner suite, so CI only builds, packs and uploads. +# +# Default path (nothing here): push without a trailer and GitHub runs +# everything, suite included. Nothing is mandatory; this is the fast lane. +# +# What it runs — exactly the command CI's gate runs: +# +# python -u -m pytest tests/unit -q \ +# -o faulthandler_timeout=120 -o faulthandler_exit_on_timeout=True +# +# (with --scope F: ... -k F), wrapped in `timeout --foreground 600`. Both +# bounds are measured, not guessed: the worst GREEN CI Test step was 41s +# (runs 35248848296, 35246056805, 35235114053 — all 41s) and this machine +# runs the whole suite in 32s, so a single test older than 120s and a step +# older than 600s are hangs, not slow tests. faulthandler names the hang +# (all-thread traceback, then exit 1); `timeout` is the backstop for a hang +# faulthandler's timer thread cannot observe. +# +# On success it writes .git/local-gate/.ok (inside .git, so it is +# never committed) holding the tree, the timestamp, the scope, the counts +# parsed from pytest's summary line and the exact command. Re-running for the +# same tree is a no-op that just re-prints the trailer — the stamp IS the +# proof, so `--force` is the only way to pay for the suite twice. +# +# The trailer is printed only for a FULL run on a CLEAN tree: a --scope run +# is quick iteration, and a dirty tree cannot be described by a tree sha. +# Either one still prints the counts; it just makes no claim about a commit. +# A scoped run stamps .git/local-gate/..ok — its own file, so +# it can neither clobber the full-suite stamp nor be read back as one. +# +# Prerequisites: a virtualenv with CI's dependency set (see the recipe the +# script prints when something is missing). Checked first, so a mysterious +# failure 90 seconds in is not possible. +# +# Usage: +# scripts/gate-local.sh # full gate (reuses a stamp if it exists) +# scripts/gate-local.sh --force # full gate, even if already stamped +# scripts/gate-local.sh --scope eval # quick iteration (pytest -k, no trailer) +# scripts/gate-local.sh --amend # full gate, then append the +# # trailer to the HEAD commit +# +# Environment: +# GATE_PYTHON interpreter to use (default: .venv/bin/python) +# GATE_STEP_TIMEOUT shell bound for the suite, seconds (default: 600) +# GATE_TEST_TIMEOUT faulthandler per-test bound, seconds (default: 120) +set -euo pipefail + +here=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +cd "$here" + +scope="" +amend=0 +force=0 +while [ $# -gt 0 ]; do + case "$1" in + --scope) + [ $# -ge 2 ] || { echo "--scope needs a pytest -k filter (e.g. --scope eval)" >&2; exit 2; } + scope=$2 + shift 2 + ;; + --amend) + amend=1 + shift + ;; + --force) + force=1 + shift + ;; + -h|--help) + sed -n '/^# Usage:/,/^# Environment:/p' "$0" | sed 's/^# \{0,1\}//' + exit 0 + ;; + *) + echo "unknown argument: $1 (see --help)" >&2 + exit 2 + ;; + esac +done + +py=${GATE_PYTHON:-$here/.venv/bin/python} +step_timeout=${GATE_STEP_TIMEOUT:-600} +test_timeout=${GATE_TEST_TIMEOUT:-120} + +# ── Record what this run is ───────────────────────────────────────────────── +tree=$(git rev-parse HEAD^{tree}) +head=$(git rev-parse --short HEAD) +stamp_dir=$(git rev-parse --git-dir)/local-gate +mkdir -p "$stamp_dir" + +if [ -n "$scope" ]; then + scope_label=$scope +else + scope_label=full +fi + +# Stamps are keyed by tree AND scope. A scoped run gets its own file so it can +# never overwrite the full-suite stamp (the trailer is a claim about the whole +# suite, and the pre-push hook checks `scope: full`) — and never be mistaken +# for it on the next run. +if [ -n "$scope" ]; then + safe_scope=${scope//[^A-Za-z0-9._-]/_} + stamp=$stamp_dir/$tree.$safe_scope.ok + log=$stamp_dir/$tree.$safe_scope.log +else + stamp=$stamp_dir/$tree.ok + log=$stamp_dir/$tree.log +fi + +dirty=no +if [ -n "$(git status --porcelain)" ]; then + dirty=yes + cat <<'EOF' +WARNING: the working tree is dirty. The gate will test what is on disk, but a + stamp can only describe a committed tree — so NO stamp and no trailer + will be written this run. Commit, then re-run to get one. +EOF +fi + +# The tail both paths share: print (and optionally amend in) the trailer. +emit_trailer() { + if [ "$scope_label" != full ]; then + cat </dev/null | grep -q .; then + echo "REFUSING --amend: HEAD is already on a remote branch; amend would rewrite published history." >&2 + echo "Add the trailer by hand instead:" >&2 + echo " $trailer" >&2 + exit 1 + fi + local message + message=$(git log -1 --format=%B) + if printf '%s\n' "$message" | grep -q '^Local-Gate: '; then + message=$(printf '%s\n' "$message" | sed "s|^Local-Gate: .*|$trailer|") + else + message=$(printf '%s\n' "$message" | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}') + message="$message +$trailer" + fi + printf '%s\n' "$message" | git commit --amend -q --no-verify -F - + echo "== appended to $(git rev-parse --short HEAD) (tree unchanged: $(git rev-parse HEAD^{tree}))" + fi + cat <&2 <&2 < "$log" +echo "== tree $tree (HEAD $head), scope: $scope_label, log: $log" +echo "== interpreter: $py ($("$py" -c 'import sys; print(sys.version.split()[0])'))" + +# ── The suite ─────────────────────────────────────────────────────────────── +declare -a commands=() + +run_step() { + local label=$1 + shift + commands+=("$(printf '%q ' "$@")") + echo + echo "=== $label" + echo "+ $(printf '%q ' "$@")" + if "$@" 2>&1 | tee -a "$log"; then + echo "--- $label: OK" + else + local rc=$? + if [ "$rc" = 124 ]; then + echo "--- $label: TIMED OUT after ${step_timeout}s (exit 124) — the suite hung; the output above is everything it reached" >&2 + else + echo "--- $label: FAILED (exit $rc) — nothing was stamped; fix it and re-run" >&2 + fi + exit $rc + fi +} + +# The gate itself, byte for byte what CI's Test step runs (only the runner's +# bare `python` becomes this venv's interpreter). `timeout --foreground` keeps +# the process attached to this terminal and unbuffered: the progress dot line +# and the faulthandler dump survive the kill. +if [ -n "$scope" ]; then + run_step "pytest (scope: $scope)" \ + timeout --foreground "$step_timeout" \ + "$py" -u -m pytest tests/unit -q -k "$scope" "${pytest_opts[@]}" +else + run_step "pytest (full suite)" \ + timeout --foreground "$step_timeout" \ + "$py" -u -m pytest tests/unit -q "${pytest_opts[@]}" +fi + +# ── Parse pytest's summary line ───────────────────────────────────────────── +# Shape: `1387 passed, 34 skipped, 32 warnings, 542 subtests passed in 32.31s`. +# The `(^|, )` anchor is what keeps "542 subtests passed" out of the `passed` +# count, and anchoring on the trailing `in Xs` picks the summary line rather +# than a test that printed a similar sentence. +summary=$(grep -E ' in [0-9][0-9.]*s$' "$log" | tail -1 || true) +if [ -z "$summary" ]; then + summary=$(grep -E '^[0-9]+ (passed|failed|error)' "$log" | tail -1 || true) +fi +if [ -z "$summary" ]; then + echo "no pytest summary line in $log — the counts are unknown, so no stamp is written" >&2 + exit 1 +fi + +# Every parse is `|| true`: "0 failed" simply does not appear in the summary +# line, and a bare `grep -oE` with no match exits 1 — which, under +# `set -e` + pipefail, would abort a run that passed. +field() { + printf '%s\n' "$summary" | grep -oE "(^|, )[0-9]+ $1" | grep -oE '[0-9]+' | head -1 || true +} +passed=$(field passed) +skipped=$(field skipped) +failed=$(field failed) +errors=$(field error) +subtests=$(printf '%s\n' "$summary" | grep -oE '[0-9]+ subtests passed' | grep -oE '[0-9]+' | head -1 || true) +duration=$(printf '%s\n' "$summary" | grep -oE 'in [0-9][0-9.]*s' | grep -oE '[0-9][0-9.]*' | head -1 || true) +if [ -z "$passed" ]; then + echo "could not read the counts out of: $summary" >&2 + exit 1 +fi +seconds=${duration%%.*} +counts="$passed passed, ${failed:-0} failed, ${skipped:-0} skipped (${subtests:-0} subtests passed)" + +echo +echo "== $summary" +echo "== counts: $counts (${seconds}s)" + +if [ "$dirty" = yes ]; then + echo "== no stamp written (dirty working tree); commit and re-run" + exit 0 +fi + +# ── The stamp ─────────────────────────────────────────────────────────────── +{ + echo "tree: $tree" + echo "head: $head" + echo "time: $(date -Is)" + echo "scope: $scope_label" + echo "dirty: $dirty" + echo "counts: $counts" + echo "passed: ${passed:-0}" + echo "skipped: ${skipped:-0}" + echo "failed: ${failed:-0}" + echo "errors: ${errors:-0}" + echo "duration_seconds: ${seconds:-0}" + for command in "${commands[@]}"; do + echo "command: ${command% }" + done +} > "$stamp" + +echo "== stamp: $stamp" +cat "$stamp" + +emit_trailer