forge
Explore
Log in

Don't you dare go Hollow

πŸ›‘οΈ let a locally-proven push skip the runner suite

Browse files at this commit

4c9d9bbe3f7f42fdb6f150b1c6105732ace1d0f3Ahmet Kaan GümüşParent: 0877e45
  • ci
    • πŸ›‘οΈ let a locally-proven push skip the runner suite
Show full message
ci: πŸ›‘οΈ let a locally-proven push skip the runner suite

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/<tree>.ok and prints a `Local-Gate: <tree>
            (<n> passed, <t>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 (<tree>.<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-pushadded+156 -0
@@ -0,0 +1,156 @@
1+#!/usr/bin/env bash
2+# Refuse a FORGED or STALE local-verification trailer.
3+#
4+# Opt in per clone (one command, no config file to forget):
5+#
6+# git config core.hooksPath .githooks
7+#
8+# The default path is: push and let GitHub run the suite, build, pack and (on a
9+# manual dispatch) deploy. An untested push is legitimate, so this hook does NOT
10+# require a stamp. Its single job is to keep the opt-in fast lane honest.
11+#
12+# The fast lane is a commit carrying
13+#
14+# Local-Gate: <tree-sha> (<n> passed, <t>s)
15+#
16+# which makes the workflow's "Decide test gate" step skip the runner suite
17+# (that suite currently hangs on the runner β€” see scripts/gate-local.sh). The
18+# trailer is a claim about verification that happened HERE, so this hook checks
19+# it before the bytes leave:
20+#
21+# * the trailer's tree must be the tree being pushed (a stale trailer is a
22+# lie about lineage, and CI would silently fall back to running the suite
23+# anyway β€” so say it here, once, instead of an hour later);
24+# * there must be a matching stamp in .git/local-gate/, written by
25+# scripts/gate-local.sh, and it must be a FULL-suite stamp (a scoped run
26+# never produces a trailer);
27+# * the stamp's counts and duration must match the trailer, so a hand-typed
28+# line cannot pass.
29+#
30+# To push without the trailer, delete the line (the default path). Two
31+# deliberate escapes, both loud:
32+#
33+# SKIP_LOCAL_GATE=1 git push ... skip this check entirely
34+# GATE_ALLOW_SCOPED=1 git push ... accept a scoped stamp and say what
35+# was NOT run
36+#
37+# (SKIP_LOCAL_GATE skips only THIS hook's trailer check; the commit's trailer,
38+# if any, still decides whether GitHub runs the suite.)
39+
40+set -uo pipefail
41+
42+zero=0000000000000000000000000000000000000000
43+
44+if [ "${SKIP_LOCAL_GATE:-}" = 1 ]; then
45+ cat <<'EOF'
46+SKIP_LOCAL_GATE=1: NOT checking Local-Gate trailers.
47+ skipped: that the trailer's tree matches the tree being pushed;
48+ skipped: that a matching full-suite stamp exists in .git/local-gate/;
49+ skipped: that the trailer's counts/duration match that stamp.
50+Any trailer on these commits still decides whether GitHub runs its own suite.
51+EOF
52+ exit 0
53+fi
54+
55+gitdir=$(git rev-parse --git-dir)
56+stamp_dir=$gitdir/local-gate
57+refused=0
58+
59+while read -r local_ref local_sha remote_ref remote_sha; do
60+ [ -n "${local_sha:-}" ] || continue
61+ [ "$local_sha" != "$zero" ] || continue # branch deletion: nothing to verify
62+ tree=$(git rev-parse --verify -q "$local_sha^{tree}") || continue
63+ short=$(git rev-parse --short "$local_sha")
64+
65+ trailer=$(git log -1 --format=%B "$local_sha" |
66+ grep -E '^Local-Gate: [0-9a-f]{40} \([0-9]+ passed, [0-9]+s\)$' | tail -1 || true)
67+ # No trailer: the default path. GitHub runs the suite; nothing to check.
68+ [ -n "$trailer" ] || continue
69+
70+ claim_tree=$(printf '%s\n' "$trailer" | sed -n 's/^Local-Gate: \([0-9a-f]\{40\}\) .*/\1/p')
71+ claim_passed=$(printf '%s\n' "$trailer" | sed -n 's/^Local-Gate: [0-9a-f]\{40\} (\([0-9]*\) passed.*/\1/p')
72+ claim_seconds=$(printf '%s\n' "$trailer" | sed -n 's/^Local-Gate: [0-9a-f]\{40\} (.*, \([0-9]*\)s)$/\1/p')
73+
74+ if [ "$claim_tree" != "$tree" ]; then
75+ cat >&2 <<EOF
76+REFUSING the push: $short carries a stale Local-Gate trailer.
77+
78+ trailer claims tree : $claim_tree
79+ tree being pushed : $tree
80+
81+A trailer naming another tree is a stale or copy-pasted claim; GitHub would
82+silently run the suite anyway, so the fast lane would just be a lie. Either
83+re-prove the tree you are pushing:
84+
85+ scripts/gate-local.sh # prints the correct trailer
86+ scripts/gate-local.sh --amend # ...and appends it to HEAD
87+
88+or drop the trailer line from the commit message and let GitHub run the suite
89+(the default path). To bypass this check: SKIP_LOCAL_GATE=1 git push ...
90+EOF
91+ refused=1
92+ continue
93+ fi
94+
95+ stamp=$stamp_dir/$tree.ok
96+ if [ ! -f "$stamp" ]; then
97+ cat >&2 <<EOF
98+REFUSING the push: $short claims a full-suite pass for tree $tree, but there
99+is no stamp for it on this machine (looked for $stamp).
100+
101+The trailer is a claim that the suite ran HERE. Without the stamp it cannot be
102+told apart from a hand-typed line. Reproduce a real stamp with:
103+
104+ scripts/gate-local.sh
105+
106+or drop the trailer and let GitHub run the suite. To bypass:
107+SKIP_LOCAL_GATE=1 git push ...
108+EOF
109+ refused=1
110+ continue
111+ fi
112+
113+ stamp_scope=$(sed -n 's/^scope: //p' "$stamp" | tail -1)
114+ stamp_passed=$(sed -n 's/^passed: //p' "$stamp" | tail -1)
115+ stamp_seconds=$(sed -n 's/^duration_seconds: //p' "$stamp" | tail -1)
116+ stamp_time=$(sed -n 's/^time: //p' "$stamp" | tail -1)
117+
118+ if [ "$stamp_scope" != full ]; then
119+ if [ "${GATE_ALLOW_SCOPED:-}" = 1 ]; then
120+ cat <<EOF
121+GATE_ALLOW_SCOPED=1: accepting a SCOPED stamp for tree $tree.
122+ NOT run by that stamp: every test outside scope "$stamp_scope" ($stamp_time).
123+ GitHub will skip its own suite on the strength of a partial run.
124+EOF
125+ continue
126+ fi
127+ cat >&2 <<EOF
128+REFUSING the push: the trailer for tree $tree claims the full suite, but the
129+stamp on disk is a scoped run (scope: $stamp_scope, $stamp_time).
130+
131+A scoped run is quick iteration, not a claim about the suite. Run the whole
132+thing β€” scripts/gate-local.sh β€” or drop the trailer. To accept the partial run
133+on purpose: GATE_ALLOW_SCOPED=1 git push ...
134+EOF
135+ refused=1
136+ continue
137+ fi
138+
139+ if [ "$stamp_passed" != "$claim_passed" ] || [ "$stamp_seconds" != "$claim_seconds" ]; then
140+ cat >&2 <<EOF
141+REFUSING the push: the trailer for tree $tree does not match its stamp.
142+
143+ trailer says : $claim_passed passed, ${claim_seconds}s
144+ stamp says : $stamp_passed passed, ${stamp_seconds}s ($stamp_time)
145+
146+One of the two was edited by hand. Re-run scripts/gate-local.sh and use the
147+line it prints.
148+EOF
149+ refused=1
150+ continue
151+ fi
152+
153+ echo "pre-push: tree $tree verified locally ($stamp_passed passed, ${stamp_seconds}s, $stamp_time) β€” GitHub will skip its own suite."
154+done
155+
156+exit $refused
.github/workflows/main.ymlmodified+119 -3
@@ -24,6 +24,24 @@
24 # GPU'suz makinede rerank 95,9 s sürer: ürün kapısı O-05 p50 <= 6 s GEÇİLMEZ24 # GPU'suz makinede rerank 95,9 s sürer: ürün kapısı O-05 p50 <= 6 s GEÇİLMEZ
25 # β€” o yapΔ±landΔ±rma iΓ§in eşiği sunucuya elle yΓΌkseltmek gerekir.25 # β€” o yapΔ±landΔ±rma iΓ§in eşiği sunucuya elle yΓΌkseltmek gerekir.
26 #26 #
27+# TWO TEST PATHS β€” the default is the full one (same shape as hezarfen_backend):
28+#
29+# DEFAULT Push it and let GitHub do everything: suite, image, bundle,
30+# artifact. This is also the recovery path when the local machine
31+# is unavailable.
32+# SPECIAL Prove the suite on your own machine first (scripts/gate-local.sh
33+# β€” ~32 s here). The suite currently HANGS on the runner: run
34+# 35297989416 sat at 7% for 73 minutes until it was cancelled by
35+# hand, so this lane is the fast one. The script prints (or, with
36+# --amend, appends) a `Local-Gate: <tree> (<n> passed, <t>s)`
37+# trailer; the "Decide test gate" step verifies it against
38+# HEAD^{tree} and only then skips the runner suite β€” CI still
39+# builds the image, proves it API-only, stages and uploads.
40+# A stale or copy-pasted trailer silently falls back to running
41+# the suite, so the fallback costs time, never verification.
42+# Opt the pre-push hook in per clone:
43+# git config core.hooksPath .githooks
44+#
27 # Bir seferlik ân koşullar (workflow'un erişimi dışında):45 # Bir seferlik ân koşullar (workflow'un erişimi dışında):
28 # * repo secret'larΔ± SSH_PRIVATE_KEY / SSH_HOST / SSH_USER;46 # * repo secret'larΔ± SSH_PRIVATE_KEY / SSH_HOST / SSH_USER;
29 # * sunucuda `loginctl enable-linger <user>`;47 # * sunucuda `loginctl enable-linger <user>`;
@@ -39,7 +57,19 @@ on:
39 branches:57 branches:
40 - main58 - main
41 # Deploy'un TEK kapΔ±sΔ± β€” yukarΔ±daki başlΔ±k yorumuna bakΔ±n.59 # Deploy'un TEK kapΔ±sΔ± β€” yukarΔ±daki başlΔ±k yorumuna bakΔ±n.
60+ # `tests` is the escape hatch of the manual door: auto/skip redeploy the
61+ # newest green artifact (the suite is not paid again), force builds and
62+ # tests the dispatched ref first and deploys that fresh artifact.
42 workflow_dispatch:63 workflow_dispatch:
64+ inputs:
65+ tests:
66+ description: "Run the test suite on this run? auto/skip redeploy the newest green artifact; force builds and tests the dispatched ref first."
67+ type: choice
68+ options:
69+ - auto
70+ - skip
71+ - force
72+ default: auto
43 73
44 # Deploy serileştirmesi işin kendisinde: yeni bir push, uçuştaki VPS değişimine74 # Deploy serileştirmesi işin kendisinde: yeni bir push, uçuştaki VPS değişimine
45 # dokunmadan bayat Validate/Build'i iptal edebilmeli.75 # dokunmadan bayat Validate/Build'i iptal edebilmeli.
@@ -83,7 +113,10 @@ jobs:
83 113
84 build:114 build:
85 name: Build and test115 name: Build and test
86- if: github.event_name == 'push'116+ # Pushes always build (and, by default, test). A manual redeploy reuses the
117+ # newest green artifact instead of paying the suite again, unless the
118+ # dispatch asks for `tests: force`, which builds and tests this ref.
119+ if: github.event_name == 'push' || github.event.inputs.tests == 'force'
87 runs-on: ubuntu-24.04120 runs-on: ubuntu-24.04
88 concurrency:121 concurrency:
89 group: ci-${{ github.workflow }}-${{ github.ref }}-build122 group: ci-${{ github.workflow }}-${{ github.ref }}-build
@@ -95,11 +128,53 @@ jobs:
95 uses: actions/setup-python@v5128 uses: actions/setup-python@v5
96 with:129 with:
97 python-version: "3.11"130 python-version: "3.11"
131+ # ── Which test path this run takes ──────────────────────────────────
132+ # SPECIAL: a commit carrying a self-consistent `Local-Gate:` trailer was
133+ # already through the suite on the developer's machine
134+ # (scripts/gate-local.sh prints it; --amend appends it), so this run
135+ # only builds, packs and uploads.
136+ # Verified, never trusted: the trailer's tree must equal HEAD^{tree}, so
137+ # a stale or copy-pasted trailer silently falls back to running the
138+ # suite. The log always says which branch was taken, and why.
139+ # Trailer shape: `Local-Gate: <40-hex tree> (<n> passed, <t>s)`.
140+ - name: Decide test gate
141+ id: gate
142+ run: |
143+ set -euo pipefail
144+ # Only reaches here on a push, or a dispatch with tests=force (the
145+ # job-level `if` skips the other dispatch modes) β€” and force means
146+ # the caller explicitly asked for the suite.
147+ mode='${{ github.event.inputs.tests }}'
148+ tree=$(git rev-parse HEAD^{tree})
149+ if [ "$mode" = force ]; then
150+ echo "workflow_dispatch tests=force β‡’ running the suite on this ref"
151+ echo "skip=false" >> "$GITHUB_OUTPUT"
152+ exit 0
153+ fi
154+ claim=$(git log -1 --format=%B \
155+ | sed -n 's/^Local-Gate: \([0-9a-f]\{40\}\) (\(.*\))$/\1|\2/p' \
156+ | tail -1)
157+ if [ -z "$claim" ]; then
158+ echo "no Local-Gate trailer on $(git rev-parse --short HEAD) β‡’ running the suite (the default path)"
159+ echo "skip=false" >> "$GITHUB_OUTPUT"
160+ elif [ "${claim%%|*}" != "$tree" ]; then
161+ echo "local gate claims tree ${claim%%|*}; actual tree $tree β‡’ running tests anyway"
162+ echo "skip=false" >> "$GITHUB_OUTPUT"
163+ else
164+ echo "local gate trailer matches tree $tree β‡’ skipping the suite (${claim#*|})"
165+ echo "skip=true" >> "$GITHUB_OUTPUT"
166+ fi
167+
98 # CPU tekerleği: CI'da GPU yok ve GPU imajı ~2,5 GB daha büyük.168 # CPU tekerleği: CI'da GPU yok ve GPU imajı ~2,5 GB daha büyük.
99 # Testler ΓœΓ‡ listeyi de ister: servis yolu (requirements.txt), yerel model169 # Testler ΓœΓ‡ listeyi de ister: servis yolu (requirements.txt), yerel model
100 # yığınΔ± (requirements-local.txt) ve eval (requirements-eval.txt β€” yalnΔ±z170 # yığınΔ± (requirements-local.txt) ve eval (requirements-eval.txt β€” yalnΔ±z
101 # CI/geliştirme; imaja girmez).171 # CI/geliştirme; imaja girmez).
172+ # The runner's pip environment exists ONLY to run the suite: the image
173+ # builds its dependencies inside the Containerfile, and the API-only
174+ # proof runs them inside the image. Skipped when the local gate already
175+ # proved the suite.
102 - name: Install dependencies (CPU torch)176 - name: Install dependencies (CPU torch)
177+ if: steps.gate.outputs.skip != 'true'
103 run: |178 run: |
104 set -euo pipefail179 set -euo pipefail
105 pip install --no-cache-dir "torch>=2.6" --index-url https://download.pytorch.org/whl/cpu180 pip install --no-cache-dir "torch>=2.6" --index-url https://download.pytorch.org/whl/cpu
@@ -112,11 +187,39 @@ jobs:
112 # model indirmesi) KENDİLERİ atlar ve nedenini yazar; ağır187 # model indirmesi) KENDİLERİ atlar ve nedenini yazar; ağır
113 # integration/e2e koşumlarΔ± model indirdiği iΓ§in CI kapΔ±sΔ± DEĞİLDΔ°R β€”188 # integration/e2e koşumlarΔ± model indirdiği iΓ§in CI kapΔ±sΔ± DEĞİLDΔ°R β€”
114 # bkz. README "CI deploy".189 # bkz. README "CI deploy".
190+ # `timeout --foreground 600` (10 min) bounds the step at the shell level,
191+ # unbuffered and unpiped: what pytest printed up to the kill survives.
192+ # 600 s is measured, not guessed β€” every green run's Test step took 41 s
193+ # (35248848296, 35246056805, 35235114053, `pip install pytest` included),
194+ # so this is ~15x the worst green, and it turns a stall from the hours it
195+ # has actually burned (73 min stuck at 7% on 35297989416, 3 h 20 min on
196+ # 35283445041) into ten minutes. `-u` is what keeps the progress line
197+ # flowing into the log while the suite runs.
198+ # faulthandler is the layer that NAMES the hang: after 120 s inside a
199+ # single test (4x this machine's whole-suite 32 s, 3x the whole green CI
200+ # step) it dumps every thread's traceback and exits 1. Core pytest, so no
201+ # extra install and no plugin that could change the suite's semantics.
115 - name: Test202 - name: Test
203+ if: steps.gate.outputs.skip != 'true'
116 run: |204 run: |
117 set -euo pipefail205 set -euo pipefail
118 pip install --no-cache-dir pytest206 pip install --no-cache-dir pytest
119- python -m pytest tests/unit -q207+ timeout --foreground 600 \
208+ python -u -m pytest tests/unit -q \
209+ -o faulthandler_timeout=120 -o faulthandler_exit_on_timeout=True
210+
211+ # Always *within the test path*, including when the step above was
212+ # killed: the discriminator. Disk or memory starvation shows here; a
213+ # pytest process still standing after `timeout` returns is the signature
214+ # of a kill the kernel could not deliver.
215+ - name: Stall diagnostics
216+ if: always() && steps.gate.outputs.skip != 'true'
217+ run: |
218+ echo '=== df -h / ==='; df -h / || true
219+ echo '=== free -m ==='; free -m || true
220+ echo '=== nproc ==='; nproc || true
221+ echo '=== surviving pytest processes ==='
222+ ps -eo pid,etimes,stat,cmd | grep '[p]ytest' || echo none
120 223
121 # Laptop ve CI aynı Containerfile'ı kullanır: ENV bloğu ne diyorsa o224 # Laptop ve CI aynı Containerfile'ı kullanır: ENV bloğu ne diyorsa o
122 # gΓΆnderilir, ayrΔ± bir CI ikizi yok.225 # gΓΆnderilir, ayrΔ± bir CI ikizi yok.
@@ -186,8 +289,12 @@ jobs:
186 (needs.build.result == 'skipped' || needs.build.result == 'success')289 (needs.build.result == 'skipped' || needs.build.result == 'success')
187 runs-on: ubuntu-24.04290 runs-on: ubuntu-24.04
188 steps:291 steps:
189- # Elle deploy, BUILD işi yeşil olan en yeni koşuyu alΔ±r.292+ # Elle deploy, BUILD işi yeşil olan en yeni koşuyu alΔ±r β€” ama yalnΔ±z bu
293+ # koşuda build YOKSA: `tests: force` ile dispatch edildiğinde bu koşunun
294+ # kendi taze artefaktı kullanılır (aşağıdaki adım), yoksa build edilen
295+ # imaj hiΓ§bir yere gitmezdi.
190 - name: Find the newest green build296 - name: Find the newest green build
297+ if: needs.build.result == 'skipped'
191 env:298 env:
192 GH_TOKEN: ${{ github.token }}299 GH_TOKEN: ${{ github.token }}
193 run: |300 run: |
@@ -207,6 +314,7 @@ jobs:
207 echo "run_id=$run_id" >> "$GITHUB_ENV"314 echo "run_id=$run_id" >> "$GITHUB_ENV"
208 315
209 - name: Fetch the green release316 - name: Fetch the green release
317+ if: needs.build.result == 'skipped'
210 uses: actions/download-artifact@v4318 uses: actions/download-artifact@v4
211 with:319 with:
212 name: release320 name: release
@@ -214,6 +322,14 @@ jobs:
214 run-id: ${{ env.run_id }}322 run-id: ${{ env.run_id }}
215 github-token: ${{ github.token }}323 github-token: ${{ github.token }}
216 324
325+ # tests=force: the artifact this very run built and gated.
326+ - name: Fetch this run's release
327+ if: needs.build.result == 'success'
328+ uses: actions/download-artifact@v4
329+ with:
330+ name: release
331+ path: stage
332+
217 - name: Check the release is complete333 - name: Check the release is complete
218 run: |334 run: |
219 set -euo pipefail335 set -euo pipefail
scripts/gate-local.shadded+341 -0
@@ -0,0 +1,341 @@
1+#!/usr/bin/env bash
2+# The LOCAL full gate: the "special path" where this machine proves the
3+# suite instead of a GitHub runner.
4+#
5+# Why it exists: the same suite is ~30s here and HANGS on a 2-core runner
6+# (measured: run 35297989416 sat at 7% for 73 minutes until it was cancelled
7+# by hand, and every push since 2026-09-17 17:54 burned 1h-3h20m the same
8+# way). When you have run this script, commit the `Local-Gate:` trailer it
9+# prints (`--amend` writes it for you) and the push carries proof: the
10+# workflow's "Decide test gate" step verifies the trailer against HEAD^{tree}
11+# and then skips the runner suite, so CI only builds, packs and uploads.
12+#
13+# Default path (nothing here): push without a trailer and GitHub runs
14+# everything, suite included. Nothing is mandatory; this is the fast lane.
15+#
16+# What it runs β€” exactly the command CI's gate runs:
17+#
18+# python -u -m pytest tests/unit -q \
19+# -o faulthandler_timeout=120 -o faulthandler_exit_on_timeout=True
20+#
21+# (with --scope F: ... -k F), wrapped in `timeout --foreground 600`. Both
22+# bounds are measured, not guessed: the worst GREEN CI Test step was 41s
23+# (runs 35248848296, 35246056805, 35235114053 β€” all 41s) and this machine
24+# runs the whole suite in 32s, so a single test older than 120s and a step
25+# older than 600s are hangs, not slow tests. faulthandler names the hang
26+# (all-thread traceback, then exit 1); `timeout` is the backstop for a hang
27+# faulthandler's timer thread cannot observe.
28+#
29+# On success it writes .git/local-gate/<tree-sha>.ok (inside .git, so it is
30+# never committed) holding the tree, the timestamp, the scope, the counts
31+# parsed from pytest's summary line and the exact command. Re-running for the
32+# same tree is a no-op that just re-prints the trailer β€” the stamp IS the
33+# proof, so `--force` is the only way to pay for the suite twice.
34+#
35+# The trailer is printed only for a FULL run on a CLEAN tree: a --scope run
36+# is quick iteration, and a dirty tree cannot be described by a tree sha.
37+# Either one still prints the counts; it just makes no claim about a commit.
38+# A scoped run stamps .git/local-gate/<tree-sha>.<scope>.ok β€” its own file, so
39+# it can neither clobber the full-suite stamp nor be read back as one.
40+#
41+# Prerequisites: a virtualenv with CI's dependency set (see the recipe the
42+# script prints when something is missing). Checked first, so a mysterious
43+# failure 90 seconds in is not possible.
44+#
45+# Usage:
46+# scripts/gate-local.sh # full gate (reuses a stamp if it exists)
47+# scripts/gate-local.sh --force # full gate, even if already stamped
48+# scripts/gate-local.sh --scope eval # quick iteration (pytest -k, no trailer)
49+# scripts/gate-local.sh --amend # full gate, then append the
50+# # trailer to the HEAD commit
51+#
52+# Environment:
53+# GATE_PYTHON interpreter to use (default: .venv/bin/python)
54+# GATE_STEP_TIMEOUT shell bound for the suite, seconds (default: 600)
55+# GATE_TEST_TIMEOUT faulthandler per-test bound, seconds (default: 120)
56+set -euo pipefail
57+
58+here=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
59+cd "$here"
60+
61+scope=""
62+amend=0
63+force=0
64+while [ $# -gt 0 ]; do
65+ case "$1" in
66+ --scope)
67+ [ $# -ge 2 ] || { echo "--scope needs a pytest -k filter (e.g. --scope eval)" >&2; exit 2; }
68+ scope=$2
69+ shift 2
70+ ;;
71+ --amend)
72+ amend=1
73+ shift
74+ ;;
75+ --force)
76+ force=1
77+ shift
78+ ;;
79+ -h|--help)
80+ sed -n '/^# Usage:/,/^# Environment:/p' "$0" | sed 's/^# \{0,1\}//'
81+ exit 0
82+ ;;
83+ *)
84+ echo "unknown argument: $1 (see --help)" >&2
85+ exit 2
86+ ;;
87+ esac
88+done
89+
90+py=${GATE_PYTHON:-$here/.venv/bin/python}
91+step_timeout=${GATE_STEP_TIMEOUT:-600}
92+test_timeout=${GATE_TEST_TIMEOUT:-120}
93+
94+# ── Record what this run is ─────────────────────────────────────────────────
95+tree=$(git rev-parse HEAD^{tree})
96+head=$(git rev-parse --short HEAD)
97+stamp_dir=$(git rev-parse --git-dir)/local-gate
98+mkdir -p "$stamp_dir"
99+
100+if [ -n "$scope" ]; then
101+ scope_label=$scope
102+else
103+ scope_label=full
104+fi
105+
106+# Stamps are keyed by tree AND scope. A scoped run gets its own file so it can
107+# never overwrite the full-suite stamp (the trailer is a claim about the whole
108+# suite, and the pre-push hook checks `scope: full`) β€” and never be mistaken
109+# for it on the next run.
110+if [ -n "$scope" ]; then
111+ safe_scope=${scope//[^A-Za-z0-9._-]/_}
112+ stamp=$stamp_dir/$tree.$safe_scope.ok
113+ log=$stamp_dir/$tree.$safe_scope.log
114+else
115+ stamp=$stamp_dir/$tree.ok
116+ log=$stamp_dir/$tree.log
117+fi
118+
119+dirty=no
120+if [ -n "$(git status --porcelain)" ]; then
121+ dirty=yes
122+ cat <<'EOF'
123+WARNING: the working tree is dirty. The gate will test what is on disk, but a
124+ stamp can only describe a committed tree β€” so NO stamp and no trailer
125+ will be written this run. Commit, then re-run to get one.
126+EOF
127+fi
128+
129+# The tail both paths share: print (and optionally amend in) the trailer.
130+emit_trailer() {
131+ if [ "$scope_label" != full ]; then
132+ cat <<EOF
133+
134+== scoped run ($scope_label): no Local-Gate trailer.
135+ The trailer is a claim about the FULL suite, so only an unscoped run
136+ produces it. Re-run \`scripts/gate-local.sh\` before pushing if you want
137+ GitHub to skip its own suite.
138+EOF
139+ return 0
140+ fi
141+ local trailer="Local-Gate: $tree (${passed:-0} passed, ${seconds:-0}s)"
142+ if [ "$amend" = 1 ]; then
143+ if git branch -r --contains HEAD 2>/dev/null | grep -q .; then
144+ echo "REFUSING --amend: HEAD is already on a remote branch; amend would rewrite published history." >&2
145+ echo "Add the trailer by hand instead:" >&2
146+ echo " $trailer" >&2
147+ exit 1
148+ fi
149+ local message
150+ message=$(git log -1 --format=%B)
151+ if printf '%s\n' "$message" | grep -q '^Local-Gate: '; then
152+ message=$(printf '%s\n' "$message" | sed "s|^Local-Gate: .*|$trailer|")
153+ else
154+ message=$(printf '%s\n' "$message" | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}')
155+ message="$message
156+$trailer"
157+ fi
158+ printf '%s\n' "$message" | git commit --amend -q --no-verify -F -
159+ echo "== appended to $(git rev-parse --short HEAD) (tree unchanged: $(git rev-parse HEAD^{tree}))"
160+ fi
161+ cat <<EOF
162+
163+Add this line to the commit you are about to push:
164+
165+ $trailer
166+
167+(\`scripts/gate-local.sh --amend\` appends it to HEAD for you β€” the tree does
168+not change, so an amend cannot invalidate the stamp.) The push then carries a
169+verified claim: the workflow's "Decide test gate" step compares the trailer's
170+tree with HEAD^{tree} and skips the runner suite only when they match.
171+EOF
172+}
173+
174+# Already proven on this exact tree (and this scope): the stamp IS the
175+# evidence, so re-running the suite would only burn half a minute to arrive at
176+# the same line. A --scope request only ever matches its OWN stamp, so it can
177+# never be answered with (or overwrite) a full-suite proof.
178+if [ "$force" = 0 ] && [ "$dirty" = no ] && [ -f "$stamp" ]; then
179+ scope_label=$(sed -n 's/^scope: //p' "$stamp" | tail -1)
180+ passed=$(sed -n 's/^passed: //p' "$stamp" | tail -1)
181+ seconds=$(sed -n 's/^duration_seconds: //p' "$stamp" | tail -1)
182+ echo "== tree $tree already verified on this machine; reusing $stamp (--force to re-run)"
183+ cat "$stamp"
184+ emit_trailer
185+ exit 0
186+fi
187+
188+# ── Prerequisites ───────────────────────────────────────────────────────────
189+# Each says what is missing and the exact command that fixes it: a mysterious
190+# failure 90 seconds in is worse than not starting.
191+[ -x "$py" ] || {
192+ cat >&2 <<EOF
193+No interpreter at $py β€” the gate runs CI's dependency set in a local venv:
194+
195+ python3 -m venv --system-site-packages .venv
196+ .venv/bin/pip install -q -r requirements.txt -r requirements-eval.txt pytest
197+
198+--system-site-packages reuses the system torch/FlagEmbedding
199+(requirements-local.txt) instead of downloading them. Point GATE_PYTHON at
200+another interpreter that already has everything if you keep the venv elsewhere.
201+EOF
202+ exit 1
203+}
204+
205+missing=$("$py" - <<'PY'
206+import importlib.util, sys
207+
208+mods = ["pytest", "deepeval", "fitz", "pdfplumber", "qdrant_client", "fastapi", "aioquic"]
209+gone = []
210+for name in mods:
211+ try:
212+ found = importlib.util.find_spec(name) is not None
213+ except (ImportError, ValueError):
214+ found = False
215+ if not found:
216+ gone.append(name)
217+print(" ".join(gone))
218+PY
219+)
220+if [ -n "$missing" ]; then
221+ cat >&2 <<EOF
222+$py is missing modules the suite imports: $missing
223+
224+Install CI's dependency set into that interpreter:
225+
226+ .venv/bin/pip install -q -r requirements.txt -r requirements-eval.txt pytest
227+
228+requirements-eval.txt is NOT optional: without deepeval five eval test modules
229+(error on import) break collection, and requirements.txt + pytest are the gate
230+itself. torch comes from --system-site-packages, not from pip.
231+EOF
232+ exit 1
233+fi
234+
235+pytest_opts=(-o "faulthandler_timeout=$test_timeout" -o faulthandler_exit_on_timeout=True)
236+
237+: > "$log"
238+echo "== tree $tree (HEAD $head), scope: $scope_label, log: $log"
239+echo "== interpreter: $py ($("$py" -c 'import sys; print(sys.version.split()[0])'))"
240+
241+# ── The suite ───────────────────────────────────────────────────────────────
242+declare -a commands=()
243+
244+run_step() {
245+ local label=$1
246+ shift
247+ commands+=("$(printf '%q ' "$@")")
248+ echo
249+ echo "=== $label"
250+ echo "+ $(printf '%q ' "$@")"
251+ if "$@" 2>&1 | tee -a "$log"; then
252+ echo "--- $label: OK"
253+ else
254+ local rc=$?
255+ if [ "$rc" = 124 ]; then
256+ echo "--- $label: TIMED OUT after ${step_timeout}s (exit 124) β€” the suite hung; the output above is everything it reached" >&2
257+ else
258+ echo "--- $label: FAILED (exit $rc) β€” nothing was stamped; fix it and re-run" >&2
259+ fi
260+ exit $rc
261+ fi
262+}
263+
264+# The gate itself, byte for byte what CI's Test step runs (only the runner's
265+# bare `python` becomes this venv's interpreter). `timeout --foreground` keeps
266+# the process attached to this terminal and unbuffered: the progress dot line
267+# and the faulthandler dump survive the kill.
268+if [ -n "$scope" ]; then
269+ run_step "pytest (scope: $scope)" \
270+ timeout --foreground "$step_timeout" \
271+ "$py" -u -m pytest tests/unit -q -k "$scope" "${pytest_opts[@]}"
272+else
273+ run_step "pytest (full suite)" \
274+ timeout --foreground "$step_timeout" \
275+ "$py" -u -m pytest tests/unit -q "${pytest_opts[@]}"
276+fi
277+
278+# ── Parse pytest's summary line ─────────────────────────────────────────────
279+# Shape: `1387 passed, 34 skipped, 32 warnings, 542 subtests passed in 32.31s`.
280+# The `(^|, )` anchor is what keeps "542 subtests passed" out of the `passed`
281+# count, and anchoring on the trailing `in Xs` picks the summary line rather
282+# than a test that printed a similar sentence.
283+summary=$(grep -E ' in [0-9][0-9.]*s$' "$log" | tail -1 || true)
284+if [ -z "$summary" ]; then
285+ summary=$(grep -E '^[0-9]+ (passed|failed|error)' "$log" | tail -1 || true)
286+fi
287+if [ -z "$summary" ]; then
288+ echo "no pytest summary line in $log β€” the counts are unknown, so no stamp is written" >&2
289+ exit 1
290+fi
291+
292+# Every parse is `|| true`: "0 failed" simply does not appear in the summary
293+# line, and a bare `grep -oE` with no match exits 1 β€” which, under
294+# `set -e` + pipefail, would abort a run that passed.
295+field() {
296+ printf '%s\n' "$summary" | grep -oE "(^|, )[0-9]+ $1" | grep -oE '[0-9]+' | head -1 || true
297+}
298+passed=$(field passed)
299+skipped=$(field skipped)
300+failed=$(field failed)
301+errors=$(field error)
302+subtests=$(printf '%s\n' "$summary" | grep -oE '[0-9]+ subtests passed' | grep -oE '[0-9]+' | head -1 || true)
303+duration=$(printf '%s\n' "$summary" | grep -oE 'in [0-9][0-9.]*s' | grep -oE '[0-9][0-9.]*' | head -1 || true)
304+if [ -z "$passed" ]; then
305+ echo "could not read the counts out of: $summary" >&2
306+ exit 1
307+fi
308+seconds=${duration%%.*}
309+counts="$passed passed, ${failed:-0} failed, ${skipped:-0} skipped (${subtests:-0} subtests passed)"
310+
311+echo
312+echo "== $summary"
313+echo "== counts: $counts (${seconds}s)"
314+
315+if [ "$dirty" = yes ]; then
316+ echo "== no stamp written (dirty working tree); commit and re-run"
317+ exit 0
318+fi
319+
320+# ── The stamp ───────────────────────────────────────────────────────────────
321+{
322+ echo "tree: $tree"
323+ echo "head: $head"
324+ echo "time: $(date -Is)"
325+ echo "scope: $scope_label"
326+ echo "dirty: $dirty"
327+ echo "counts: $counts"
328+ echo "passed: ${passed:-0}"
329+ echo "skipped: ${skipped:-0}"
330+ echo "failed: ${failed:-0}"
331+ echo "errors: ${errors:-0}"
332+ echo "duration_seconds: ${seconds:-0}"
333+ for command in "${commands[@]}"; do
334+ echo "command: ${command% }"
335+ done
336+} > "$stamp"
337+
338+echo "== stamp: $stamp"
339+cat "$stamp"
340+
341+emit_trailer