forge
Explore
Log in

Don't you dare go Hollow

hezarfen_rag

Clone
★ 0

0 watching0 forksPython2.4 MiB184b84dAhmet Kaan Gümüş2 months ago189 commits

gate-local.sh341 lines, 13.1 KiBHistoryRawDownload
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, uploads and deploys this run's artifact.
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)
56set -euo pipefail
57
58here=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
59cd "$here"
60
61scope=""
62amend=0
63force=0
64while [ $# -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
88done
89
90py=${GATE_PYTHON:-$here/.venv/bin/python}
91step_timeout=${GATE_STEP_TIMEOUT:-600}
92test_timeout=${GATE_TEST_TIMEOUT:-120}
93
94# ── Record what this run is ─────────────────────────────────────────────────
95tree=$(git rev-parse HEAD^{tree})
96head=$(git rev-parse --short HEAD)
97stamp_dir=$(git rev-parse --git-dir)/local-gate
98mkdir -p "$stamp_dir"
99
100if [ -n "$scope" ]; then
101 scope_label=$scope
102else
103 scope_label=full
104fi
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.
110if [ -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
114else
115 stamp=$stamp_dir/$tree.ok
116 log=$stamp_dir/$tree.log
117fi
118
119dirty=no
120if [ -n "$(git status --porcelain)" ]; then
121 dirty=yes
122 cat <<'EOF'
123WARNING: 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.
126EOF
127fi
128
129# The tail both paths share: print (and optionally amend in) the trailer.
130emit_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.
138EOF
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
163Add 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
168not change, so an amend cannot invalidate the stamp.) The push then carries a
169verified claim: the workflow's "Decide test gate" step compares the trailer's
170tree with HEAD^{tree} and skips the runner suite only when they match.
171EOF
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.
178if [ "$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
186fi
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
193No 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
200another interpreter that already has everything if you keep the venv elsewhere.
201EOF
202 exit 1
203}
204
205missing=$("$py" - <<'PY'
206import importlib.util, sys
207
208mods = ["pytest", "deepeval", "fitz", "pdfplumber", "qdrant_client", "fastapi", "aioquic"]
209gone = []
210for 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)
217print(" ".join(gone))
218PY
219)
220if [ -n "$missing" ]; then
221 cat >&2 <<EOF
222$py is missing modules the suite imports: $missing
223
224Install CI's dependency set into that interpreter:
225
226 .venv/bin/pip install -q -r requirements.txt -r requirements-eval.txt pytest
227
228requirements-eval.txt is NOT optional: without deepeval five eval test modules
229(error on import) break collection, and requirements.txt + pytest are the gate
230itself. torch comes from --system-site-packages, not from pip.
231EOF
232 exit 1
233fi
234
235pytest_opts=(-o "faulthandler_timeout=$test_timeout" -o faulthandler_exit_on_timeout=True)
236
237: > "$log"
238echo "== tree $tree (HEAD $head), scope: $scope_label, log: $log"
239echo "== interpreter: $py ($("$py" -c 'import sys; print(sys.version.split()[0])'))"
240
241# ── The suite ───────────────────────────────────────────────────────────────
242declare -a commands=()
243
244run_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.
268if [ -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[@]}"
272else
273 run_step "pytest (full suite)" \
274 timeout --foreground "$step_timeout" \
275 "$py" -u -m pytest tests/unit -q "${pytest_opts[@]}"
276fi
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.
283summary=$(grep -E ' in [0-9][0-9.]*s$' "$log" | tail -1 || true)
284if [ -z "$summary" ]; then
285 summary=$(grep -E '^[0-9]+ (passed|failed|error)' "$log" | tail -1 || true)
286fi
287if [ -z "$summary" ]; then
288 echo "no pytest summary line in $log — the counts are unknown, so no stamp is written" >&2
289 exit 1
290fi
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.
295field() {
296 printf '%s\n' "$summary" | grep -oE "(^|, )[0-9]+ $1" | grep -oE '[0-9]+' | head -1 || true
297}
298passed=$(field passed)
299skipped=$(field skipped)
300failed=$(field failed)
301errors=$(field error)
302subtests=$(printf '%s\n' "$summary" | grep -oE '[0-9]+ subtests passed' | grep -oE '[0-9]+' | head -1 || true)
303duration=$(printf '%s\n' "$summary" | grep -oE 'in [0-9][0-9.]*s' | grep -oE '[0-9][0-9.]*' | head -1 || true)
304if [ -z "$passed" ]; then
305 echo "could not read the counts out of: $summary" >&2
306 exit 1
307fi
308seconds=${duration%%.*}
309counts="$passed passed, ${failed:-0} failed, ${skipped:-0} skipped (${subtests:-0} subtests passed)"
310
311echo
312echo "== $summary"
313echo "== counts: $counts (${seconds}s)"
314
315if [ "$dirty" = yes ]; then
316 echo "== no stamp written (dirty working tree); commit and re-run"
317 exit 0
318fi
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
338echo "== stamp: $stamp"
339cat "$stamp"
340
341emit_trailer