oficina / equipo Public

Merge branch 'hosted-ci' into main

Merge hosted-ci: Equipo CI on amadan hosted CI, in a box, 24 shards

Every step runs in a privileged container on a hosted arm64 machine with
the pinned bubblewrap 0.11.0, codex and claude for its architecture.
arm64 pins sit beside the certified amd64 ones. Cold run 216 s, warm
rerun 100 s; nothing runs on docs-t1. See
docs/superpowers/plans/HOSTED-CI-PROGRESS.md.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 4462596fa5879bfa7096ee472e418142b0dc94b4 parent 85404a0parent cdc159e
40 files changed, +1,301 −77
  • .amadan/ci +5 −1
  • .amadan/ci.d/00-prepare +5 −0
  • .amadan/ci.d/05-build +0 −2
  • .amadan/ci.d/10-compile +4 −0
  • .amadan/ci.d/10-vet +0 −2
  • .amadan/ci.d/15-budget +0 −2
  • .amadan/ci.d/20-check@24 +10 −0
  • .amadan/ci.d/20-fmt +0 −2
  • .amadan/ci.d/25-staticcheck +0 −2
  • .amadan/ci.d/26-govulncheck +0 −2
  • .amadan/ci.d/27-gitleaks +0 −2
  • .amadan/ci.d/30-test@7 +0 −4
  • .amadan/ci.d/31-test-quarantine +0 −4
  • .amadan/ci.d/34-runner-dead-references +0 −3
  • .amadan/ci.d/35-runner-adapter-test +0 −2
  • .amadan/ci.d/36-runner-namespaces +0 −2
  • .amadan/ci.d/40-migration-check +0 −2
  • .amadan/ci.d/50-perf +2 −1
  • .amadan/ci.d/90-cache +3 −0
  • Makefile +24 −5
  • docs/superpowers/plans/HOSTED-CI-PROGRESS.md +162 −0
  • internal/equipotest/foundation_test.go +35 −7
  • internal/runner/mac/gate_test.go +11 −0
  • internal/runner/provider/claude/pins.go +23 −0
  • internal/runner/provider/claude/pins_test.go +19 −0
  • internal/runner/provider/claude/runtime_replay_test.go +9 −2
  • internal/runner/provider/codex/pins.go +26 −0
  • internal/runner/provider/codex/pins_test.go +34 −0
  • internal/runner/provider/codex/runtime_replay_test.go +9 −2
  • internal/runner/provider/providertest/release.go +7 −0
  • internal/runner/setup/install_test.go +23 −1
  • internal/testci/absent_test.go +37 −0
  • internal/testci/box_test.go +63 −0
  • internal/testci/budget_test.go +11 −0
  • internal/testci/testci.go +16 −0
  • scripts/ci-box-enter.sh +58 −0
  • scripts/ci-box.json +110 −0
  • scripts/ci-box.py +476 −0
  • scripts/ci-test.py +111 −25
  • scripts/runner-prerequisites.py +8 −2

CI passed — run details

landed from hosted-ci

diff --git a/.amadan/ci b/.amadan/ci
index 8c547eee..beeef7ea 100755
--- a/.amadan/ci
+++ b/.amadan/ci
@@ -2,5 +2,9 @@
# amadan CI entry (single-script fallback for runners without step
# support). The steps in ci.d/ are the same targets, reported one by
# one. Must stay executable: a non-executable script resolves "skipped".
+#
+# "$(dirname "$0")/../scripts/ci-box.py" puts the command in the CI box on a hosted CI machine
+# and runs it directly on a runner host.
set -e
-exec make ci
+"$(dirname "$0")/../scripts/ci-box.py" prepare
+exec "$(dirname "$0")/../scripts/ci-box.py" run make ci
diff --git a/.amadan/ci.d/00-prepare b/.amadan/ci.d/00-prepare
new file mode 100755
index 00000000..c5e9b09c
--- /dev/null
+++ b/.amadan/ci.d/00-prepare
@@ -0,0 +1,5 @@
+#!/bin/sh
+# Get the CI box ready on a hosted CI machine: the pinned bubblewrap,
+# Codex and Claude programs, the image, the full clone and file times
+# that let cached test results hold. Nothing to do on a runner host.
+exec "$(dirname "$0")/../../scripts/ci-box.py" prepare
diff --git a/.amadan/ci.d/05-build b/.amadan/ci.d/05-build
deleted file mode 100755
index 9fc4060b..00000000
--- a/.amadan/ci.d/05-build
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make build
diff --git a/.amadan/ci.d/10-compile b/.amadan/ci.d/10-compile
new file mode 100755
index 00000000..afa597e6
--- /dev/null
+++ b/.amadan/ci.d/10-compile
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Compile every package once, so the shards of the next
+# step do not each compile them. A few seconds when the cache is warm.
+exec "$(dirname "$0")/../../scripts/ci-box.py" run make ci-compile
diff --git a/.amadan/ci.d/10-vet b/.amadan/ci.d/10-vet
deleted file mode 100755
index 139a2a25..00000000
--- a/.amadan/ci.d/10-vet
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make vet
diff --git a/.amadan/ci.d/15-budget b/.amadan/ci.d/15-budget
deleted file mode 100755
index b9dabd50..00000000
--- a/.amadan/ci.d/15-budget
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make budget
diff --git a/.amadan/ci.d/20-check@24 b/.amadan/ci.d/20-check@24
new file mode 100755
index 00000000..6857abbc
--- /dev/null
+++ b/.amadan/ci.d/20-check@24
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Everything but perf, as 24 shards side by side; AMADAN_SHARD picks one
+# (scripts/ci-test.py: LANES, then EXTRA_SHARDS). Eighteen test lanes of
+# about a minute each. Then the quarantine: known flaky tests
+# (scripts/ci-quarantine.txt), each retried once on failure, a pass on the
+# retry reported as a flake. Then runner-host: the exact bubblewrap build,
+# the pinned programs, real namespaces and the cgroup move, uncached. Then
+# the static checks: build, vet, format, budgets, references and the
+# migration check; staticcheck; govulncheck; gitleaks.
+exec "$(dirname "$0")/../../scripts/ci-box.py" run make ci-shard
diff --git a/.amadan/ci.d/20-fmt b/.amadan/ci.d/20-fmt
deleted file mode 100755
index 5884a7b5..00000000
--- a/.amadan/ci.d/20-fmt
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make fmt-check
diff --git a/.amadan/ci.d/25-staticcheck b/.amadan/ci.d/25-staticcheck
deleted file mode 100755
index 751a4e61..00000000
--- a/.amadan/ci.d/25-staticcheck
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make staticcheck
diff --git a/.amadan/ci.d/26-govulncheck b/.amadan/ci.d/26-govulncheck
deleted file mode 100755
index 6873a71b..00000000
--- a/.amadan/ci.d/26-govulncheck
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make govulncheck
diff --git a/.amadan/ci.d/27-gitleaks b/.amadan/ci.d/27-gitleaks
deleted file mode 100755
index faeccf6e..00000000
--- a/.amadan/ci.d/27-gitleaks
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make gitleaks
diff --git a/.amadan/ci.d/30-test@7 b/.amadan/ci.d/30-test@7
deleted file mode 100755
index ecb26e42..00000000
--- a/.amadan/ci.d/30-test@7
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-# Seven shards, one per test lane (scripts/ci-test.py LANES), run side by
-# side: AMADAN_SHARD picks the lane.
-exec make test-shard
diff --git a/.amadan/ci.d/31-test-quarantine b/.amadan/ci.d/31-test-quarantine
deleted file mode 100755
index dcfd05ca..00000000
--- a/.amadan/ci.d/31-test-quarantine
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-# Known flaky tests (scripts/ci-quarantine.txt), each retried once on
-# failure; a pass on the retry is reported as a flake.
-exec make test-quarantine
diff --git a/.amadan/ci.d/34-runner-dead-references b/.amadan/ci.d/34-runner-dead-references
deleted file mode 100755
index fb3d202a..00000000
--- a/.amadan/ci.d/34-runner-dead-references
+++ /dev/null
@@ -1,3 +0,0 @@
-#!/bin/sh
-set -eu
-exec make runner-dead-references
diff --git a/.amadan/ci.d/35-runner-adapter-test b/.amadan/ci.d/35-runner-adapter-test
deleted file mode 100755
index 7bef3886..00000000
--- a/.amadan/ci.d/35-runner-adapter-test
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make runner-adapter-test
diff --git a/.amadan/ci.d/36-runner-namespaces b/.amadan/ci.d/36-runner-namespaces
deleted file mode 100755
index 88d7bf45..00000000
--- a/.amadan/ci.d/36-runner-namespaces
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make runner-namespace-test
diff --git a/.amadan/ci.d/40-migration-check b/.amadan/ci.d/40-migration-check
deleted file mode 100755
index 81db0932..00000000
--- a/.amadan/ci.d/40-migration-check
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/sh
-exec make migration-check
diff --git a/.amadan/ci.d/50-perf b/.amadan/ci.d/50-perf
index 0c6a01a7..93ad2cd1 100755
--- a/.amadan/ci.d/50-perf
+++ b/.amadan/ci.d/50-perf
@@ -1,2 +1,3 @@
#!/bin/sh
-exec make perf
+# Alone, after everything else: it measures time.
+exec "$(dirname "$0")/../../scripts/ci-box.py" run make perf
diff --git a/.amadan/ci.d/90-cache b/.amadan/ci.d/90-cache
new file mode 100755
index 00000000..130445b0
--- /dev/null
+++ b/.amadan/ci.d/90-cache
@@ -0,0 +1,3 @@
+#!/bin/sh
+# Report the Go caches and keep them under what hosted CI will save.
+exec "$(dirname "$0")/../../scripts/ci-box.py" cache
diff --git a/Makefile b/Makefile
index b86a9f84..d61a8bd4 100644
--- a/Makefile
+++ b/Makefile
@@ -27,7 +27,7 @@ RUNNER_RELEASE_DIR = releases/equipo-runner-linux-amd64-$(RELEASE_VERSION)
# and a suite running beside it would be measured too.
.NOTPARALLEL:
-.PHONY: build release test test-lane test-shard test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-dead-references ci
+.PHONY: build release test test-lane ci-shard ci-compile test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-host runner-dead-references ci
RASTRILLO := go run amadan.net/rastrillo/rastrillo/cmd/rastrillo
@@ -83,8 +83,10 @@ budget:
# lists the packages that must run every time (UNCACHED).
#
# test runs every package at once. CI runs the same packages as lanes,
-# the shards of .amadan/ci.d/30-test@7: the slow packages each in a lane
-# of their own, side by side (make test-lane LANE=headless runs one).
+# shards of .amadan/ci.d/20-check@N side by side: the slow packages split
+# by test name into lanes of about a minute (make test-lane
+# LANE=headless-work runs one; scripts/ci-test.py lanes lists them), with
+# test-quarantine, runner-host and the static checks as further shards.
# Known flaky tests are quarantined (scripts/ci-quarantine.txt): skipped
# here, run by test-quarantine with one retry, and reported as flakes.
test:
@@ -93,9 +95,19 @@ test:
test-lane:
RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py lane $(LANE)
-test-shard:
+ci-shard:
RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py shard
+# ci-compile compiles every package once, before the shards of 20-check
+# start. Go does not share a compile between processes that start
+# together: 23 shards on an empty cache each compiled the same packages,
+# and every one of them took as long as the whole job used to. After this
+# the shards find their packages in the cache. Nothing is linked, so with
+# a warm cache it takes a few seconds.
+ci-compile:
+ go build ./...
+ python3 scripts/ci-test.py compile
+
test-quarantine:
python3 scripts/ci-test.py quarantine
@@ -189,6 +201,13 @@ runner-adapter-test: runner-prerequisites
runner-dead-references:
python3 scripts/runner-dead-references.py
+# runner-host checks the machine the tests run on, not only the code: the
+# exact bubblewrap build, the pinned Codex program, real namespaces, and a
+# process moved between two delegated cgroups. Uncached, every time. On
+# hosted CI the machine is the CI box (scripts/ci-box.py), which is made
+# to pass for a runner host.
+runner-host: runner-adapter-test runner-namespace-test
+
# ci is the one gate: what a runner executes and what you run before
# pushing are the same definition. amadan's runner falls back to this
# target when .amadan/ci is absent; ci.d/ carries the same targets,
@@ -196,7 +215,7 @@ runner-dead-references:
# fails the build the moment models.go and migrations/ disagree,
# instead of at boot on whatever machine notices next. If the app
# declares manifest resources, also add: rastrillo generate --check
-ci: runner-dead-references build vet fmt-check staticcheck govulncheck gitleaks budget test test-quarantine runner-adapter-test runner-namespace-test migration-check perf
+ci: runner-dead-references build vet fmt-check staticcheck govulncheck gitleaks budget test test-quarantine runner-host migration-check perf
.PHONY: copy-release-check direct-release-check release-runner runner-prerequisites
copy-release-check:
diff --git a/docs/superpowers/plans/HOSTED-CI-PROGRESS.md b/docs/superpowers/plans/HOSTED-CI-PROGRESS.md
new file mode 100644
index 00000000..cd193534
--- /dev/null
+++ b/docs/superpowers/plans/HOSTED-CI-PROGRESS.md
@@ -0,0 +1,162 @@
+# Hosted CI (branch hosted-ci)
+
+Goal: Equipo's CI on amadan's hosted CI, fast, with nothing on docs-t1.
+Paul's ruling (2026-11-10): no CI on docs-t1 at all, not even a small
+host step. Locally, run only targeted tests.
+
+## What hosted CI is
+
+Each job gets its own single-use arm64 machine (Amazon Linux 2023, up to
+32 vCPU), with Go, Docker, git, make and python3 3.9. No bubblewrap, no
+systemd user session, no isolation around steps. The clone is one commit
+deep. GOCACHE and GOMODCACHE are restored from S3 before the job and
+saved after a passing one (limits: 2 GiB compressed, 6 GiB unpacked;
+over either, the save is dropped whole). Steps run one after another; a
+step's `@N` shards run side by side on the one machine. Only the `ci`
+pipeline gives the commit its verdict.
+
+## What Equipo needs that the machine lacks
+
+Most of the suite, not only the old steps 35 and 36, starts real
+containment through production code that requires `bubblewrap 0.11.0`
+exactly, runs the pinned Codex program, and one test moves a process
+between two delegated cgroups. So:
+
+- **The CI box** (`scripts/ci-box.py`, `scripts/ci-box-enter.sh`,
+ `scripts/ci-box.json`). Every step runs in one privileged container,
+ the official Go 1.26.10 image on Debian 13 (the runner host's own
+ system, pinned by digest, pulled, never built), as an ordinary user.
+ The pinned programs are fetched by URL and checked by SHA-256 for the
+ machine's architecture, then mounted where a runner host has them:
+ Debian's bubblewrap 0.11.0-2+deb13u1 at `/usr/bin/bwrap`, codex
+ 0.165.0 on PATH, and codex, its code mode host and claude 2.1.312 in
+ `~/.local/share/equipo/try/bin`. The entry script gives `/etc` its own
+ filesystem (containment overlays `/etc`, and the kernel refuses an
+ overlay over the container's overlay root), a machine id, a git
+ identity, and a cgroup v2 subtree the user may write, at the path a
+ systemd user session has. socat (Claude's own sandbox needs it) is
+ fetched and pinned like the rest.
+- **On a runner host the box is skipped.** `ci-box.py run` runs the
+ command directly where `/usr/bin/bwrap` is already 0.11.0 and codex is
+ on PATH. `EQUIPO_CI_BOX=on|off` forces it.
+- **arm64 pins beside the certified ones** (`codex/pins.go`,
+ `claude/pins.go`). The certified amd64 constants are untouched and are
+ still the only pins a launcher or a release trusts. The replay tests
+ pick the pin for `runtime.GOARCH`. Digests come from the official
+ releases:
+
+ | program | arm64 SHA-256 | source |
+ |---|---|---|
+ | codex 0.165.0 | b32ece31...c543f | openai/codex rust-v0.165.0, aarch64-unknown-linux-musl |
+ | codex code mode host | fd7a4a1f...aa14 | same release |
+ | claude 2.1.312 | dc4af289...61f5 | the release manifest at downloads.claude.ai |
+ | bubblewrap 0.11.0 | ef2316fc...3b59 | Debian 0.11.0-2+deb13u1 arm64, snapshot.debian.org |
+
+ The same sources reproduce the amd64 pins already in the tree (codex
+ c06a67fd, host 522935d4, claude 4f4178ce, bwrap 0dfa36b9), which is the
+ check that they are the right sources.
+- **A missing pinned program fails on CI** instead of skipping
+ (`testci.Absent`, `EQUIPO_TEST_TOOLS_REQUIRED=1` set by the box).
+
+## Caches across fresh machines
+
+- Fixed paths in the box (`/work/equipo`, `/cache/go-build`,
+ `/cache/go-mod`): Go keys a compiled package on its directory.
+- `ci-box.py prepare` sets every tracked file's modification time from
+ its git blob and every directory's to one fixed time, so go test's
+ cached results (keyed on size and time of each file a test opened)
+ hold on the next machine. A changed file gets a new time. Measured: a
+ rerun on a fresh machine replayed every test package from the cache.
+- `ci-box.py prepare` also deepens the clone (hosted clones one commit;
+ gitleaks, the mixed-version test and a release test read history). It
+ runs on the machine, outside the box, where the job's git credential
+ is.
+- `ci-box.py cache` (last step) reports the cache sizes and, past 4 GiB,
+ drops build cache entries the job did not read. A restore stamps every
+ entry "now", so Go's own trim never fires on hosted. One full run
+ leaves 1.96 GiB of build cache and 0.79 GiB of modules, under the
+ 6 GiB limit.
+
+## Steps
+
+| step | what |
+|---|---|
+| `00-prepare` | fetch and verify the pinned programs, pull the image, deepen the clone, set file times |
+| `10-compile` | compile every package once, link nothing |
+| `20-check@24` | 18 test lanes, the quarantine, `runner-host` (bubblewrap build, pinned codex, namespaces, cgroup move, uncached), and the static checks in four groups |
+| `50-perf` | alone, it measures time |
+| `90-cache` | report and trim the caches |
+
+Hosted runs steps one after another and only a step's shards side by
+side, so everything that can run together is one step.
+
+## What made it fast, in the order found
+
+1. **/tmp in memory.** With /tmp on the machine's disk every lane took
+ twice as long (thintest 35 to 78 s, directlive 88 to 168 s): the tests
+ sync small files and databases thousands of times. The installer
+ tests, which need user extended attributes a tmpfs refuses before
+ Linux 6.6, put their home under the user's home instead.
+2. **Compile once, then fan out.** 23 shards on an empty cache each
+ compiled the same packages (Go shares no compile between processes
+ that start together): every shard took 150 to 370 s and two
+ timing-sensitive tests failed under the load.
+3. **Lanes split by test name** (`scripts/ci-test.py` LANES), from
+ measured times: headless six lanes, runner three, equipotest four. A
+ lane that names no tests runs whatever its package's other lanes do
+ not, so a new test always lands somewhere. directlive stays whole:
+ two of its lanes side by side both failed with
+ `provider_account_containment`.
+4. **Static checks beside the tests**, not before them.
+
+To rebalance: each shard's log ends with its time and its five slowest
+tests; move names between lanes of a package, keep `20-check@N` equal to
+the lanes plus the extra shards (a test checks the count).
+
+## Before (docs-t1)
+
+Main c6319a5 on docs-t1 (load 26 to 44): failed after 512 s; the
+headless lane ran 470 s and failed, thintest failed at 102 s. Best warm
+docs-t1 run (ci-speed 5258905, nothing changed): 217 s.
+
+## Runs on hosted (32 CPUs, arm64)
+
+Proved in the scratch repository `oficina/equipo-hostedci` (hosted is
+per repository, and main's old steps cannot pass there). Times are the
+sum of steps; push to verdict adds the machine's boot and the cache
+restore, about 110 s, which is amadan's side.
+
+| run | what | steps | slowest shard |
+|---|---|---|---|
+| 0d5e136 | first full run, cold, 9 shards, old layout | 351 s, red | headless 265 s |
+| d4ea8db | /tmp on disk | 397 s, red | headless 312 s |
+| dd9e43c | 23 shards, no compile step | 384 s, red | equipotest 373 s |
+| dd7960c | compile step, /tmp in memory | 249 s, red | equipotest 196 s |
+| 42e4278 | rebalanced, 24 shards, cold | **202 s, green** | directlive 121 s |
+| 42e4278 rerun | nothing changed, fresh machine, warm cache | **100 s, green** | runner-host 26 s |
+| 10ae706 | main 85404a0 merged in (app code changed), warm cache | **168 s, green** | directlive 92 s |
+
+In the cold green run: prepare 10 s, compile 42 s, checks 121 s, perf
+28 s. In the warm rerun: prepare 11 s, compile 38 s (it still linked
+every test binary; it no longer does), checks 26 s, perf 24 s.
+In the merge run: prepare 11 s, compile 39 s (core packages changed),
+checks 92 s, perf 25 s; the runner lanes it did not touch replayed from
+the cache.
+
+## Open
+
+- Timing budgets are reported, not enforced (`EQUIPO_CI_DEDICATED` is
+ unset). The machine is the job's own, but 24 shards share it; set the
+ variable once a week of hosted times says the budgets hold.
+- `provider_account_containment` in directlive when two of its lanes run
+ side by side: cause unknown, worked around by keeping it one lane.
+- TestGateVerifyByMarkerAlone (runner/mac) failed twice on cold, loaded
+ runs: the test started a marked process and Verify looked before the
+ kernel showed the new environment, so it settled with the process
+ alive. The test now waits for the marker. The same window exists for a
+ real marked process caught in the middle of its exec; not changed here.
+- TestCoordinatorRecoveryCallRefusalKeepsServing (runner) failed once
+ under the load of the uncompiled 23 shard run and not since.
+- The image is pinned by digest and pulled from the public ECR mirror of
+ Docker Hub each job (8 s). The pinned programs come from GitHub,
+ downloads.claude.ai and snapshot.debian.org each job (4 s).
diff --git a/internal/equipotest/foundation_test.go b/internal/equipotest/foundation_test.go
index a3f7f0a2..04975a1b 100644
--- a/internal/equipotest/foundation_test.go
+++ b/internal/equipotest/foundation_test.go
@@ -11,7 +11,9 @@ import (
"os/exec"
"path/filepath"
"reflect"
+ "regexp"
"sort"
+ "strconv"
"strings"
"testing"
@@ -167,12 +169,16 @@ func TestFoundationMigratesTwice(t *testing.T) {
// Mutation check: remove build from ci and a wrapper, one at a time;
// each must fail. Executing with a fake make also checks shell behavior.
+//
+// The steps run through scripts/ci-box.py, which on a hosted CI machine
+// puts the command in the CI box. EQUIPO_CI_BOX=off runs it directly, as
+// on a runner host, so the fake make sees what each step asks for.
func TestCIGateSteps(t *testing.T) {
root := filepath.Join("..", "..")
- want := []string{"build", "vet", "fmt-check", "staticcheck", "govulncheck", "gitleaks", "budget", "test", "test-quarantine", "runner-adapter-test", "runner-namespace-test", "runner-dead-references", "migration-check", "perf"}
+ want := []string{"build", "vet", "fmt-check", "staticcheck", "govulncheck", "gitleaks", "budget", "test", "test-quarantine", "runner-host", "runner-dead-references", "migration-check", "perf"}
sort.Strings(want)
// The step scripts run outside this process; their bytes are inputs.
- testci.Files(t, filepath.Join(root, ".amadan"), filepath.Join(root, "scripts", "ci-test.py"))
+ testci.Files(t, filepath.Join(root, ".amadan"), filepath.Join(root, "scripts", "ci-test.py"), filepath.Join(root, "scripts", "ci-box.py"))
contents, err := os.ReadFile(filepath.Join(root, "Makefile"))
if err != nil {
t.Fatal(err)
@@ -187,6 +193,19 @@ func TestCIGateSteps(t *testing.T) {
if !reflect.DeepEqual(targets, want) {
t.Errorf("make ci targets = %v, want %v", targets, want)
}
+ // The shards after the lanes, as ci-test.py lists them: one line of
+ // make targets each.
+ script, err := os.ReadFile(filepath.Join(root, "scripts", "ci-test.py"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ extra := regexp.MustCompile(`(?s)\nEXTRA_SHARDS = \[\n(.*?)\n\]\n`).FindSubmatch(script)
+ if extra == nil {
+ t.Fatal("scripts/ci-test.py has no EXTRA_SHARDS list")
+ }
+ extraLines := strings.Split(string(extra[1]), "\n")
+ extraTargets := strings.Fields(strings.NewReplacer(`"`, "", ",", " ", "[", "", "]", "").Replace(string(extra[1])))
+ lanes := strings.Count(string(script), "\n (\"")
bin := t.TempDir()
if err := os.WriteFile(filepath.Join(bin, "make"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0755); err != nil {
t.Fatal(err)
@@ -201,7 +220,7 @@ func TestCIGateSteps(t *testing.T) {
t.Errorf("%s is not executable", path)
}
cmd := exec.Command(path)
- cmd.Env = append(os.Environ(), "PATH="+bin+":"+os.Getenv("PATH"))
+ cmd.Env = append(os.Environ(), "PATH="+bin+":"+os.Getenv("PATH"), "EQUIPO_CI_BOX=off")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("%s: %v: %s", path, err, out)
@@ -217,12 +236,21 @@ func TestCIGateSteps(t *testing.T) {
}
var steps []string
for _, path := range paths {
+ _, shards, _ := strings.Cut(filepath.Base(path), "@")
for _, target := range run(path) {
- // CI runs make test as its lanes, the shards of one step.
- if target == "test-shard" {
- target = "test"
+ if target == "ci-compile" {
+ continue // fills the build cache for the shards; checks nothing itself
+ }
+ if target != "ci-shard" {
+ steps = append(steps, target)
+ continue
+ }
+ // CI runs make test as its lanes, then the extra shards.
+ if want := strconv.Itoa(lanes + len(extraLines)); shards != want {
+ t.Errorf("%s: %d lanes and %d extra shards need @%s", path, lanes, len(extraLines), want)
}
- steps = append(steps, target)
+ steps = append(steps, "test")
+ steps = append(steps, extraTargets...)
}
}
sort.Strings(steps)
diff --git a/internal/runner/mac/gate_test.go b/internal/runner/mac/gate_test.go
index e5fac5c9..e37a68fe 100644
--- a/internal/runner/mac/gate_test.go
+++ b/internal/runner/mac/gate_test.go
@@ -313,6 +313,17 @@ func TestGateVerifyByMarkerAlone(t *testing.T) {
}
waited := make(chan error, 1)
go func() { waited <- c.Wait() }()
+ // Start returns once the child has begun its exec, and the kernel shows
+ // the new environment a moment later. On a loaded machine Verify could
+ // look in between, see no marked process and settle: wait for the marker.
+ for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(5 * time.Millisecond) {
+ if marked, _ := Marked("checks-i-1"); len(marked) != 0 {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("the marked process never showed its marker")
+ }
+ }
if !g.Verify(RecordID(0, "checks-i-1")) {
t.Fatal("marker-only record not settled")
}
diff --git a/internal/runner/provider/claude/pins.go b/internal/runner/provider/claude/pins.go
new file mode 100644
index 00000000..a2db6154
--- /dev/null
+++ b/internal/runner/provider/claude/pins.go
@@ -0,0 +1,23 @@
+package claude
+
+// The arm64 build of the pinned release, for tests only. The certified
+// runner target is linux/amd64: ExecutableSHA256 is the only pin a
+// launcher or a release trusts, and no release ships with the one below.
+// It is the official 2.1.312 linux-arm64 binary, as its release manifest
+// lists it, so a test that runs the real program can run on an arm64 CI
+// machine.
+const ExecutableSHA256Arm64 = "dc4af28917455e009d26704b82a438353a06149e825b6cdf782908b2d28661f5"
+
+// ReleasePin returns the digest of the official 2.1.312 binary built for
+// goarch: the certified pin on amd64, the arm64 build's on arm64. A test
+// hands it runtime.GOARCH to check the binary on the machine it runs on.
+// ok is false where there is no pinned build.
+func ReleasePin(goarch string) (pin string, ok bool) {
+ switch goarch {
+ case "amd64":
+ return ExecutableSHA256, true
+ case "arm64":
+ return ExecutableSHA256Arm64, true
+ }
+ return "", false
+}
diff --git a/internal/runner/provider/claude/pins_test.go b/internal/runner/provider/claude/pins_test.go
new file mode 100644
index 00000000..94eb21a3
--- /dev/null
+++ b/internal/runner/provider/claude/pins_test.go
@@ -0,0 +1,19 @@
+package claude
+
+import "testing"
+
+// The amd64 pin is the certified one and must not move with the arm64 one
+// beside it. The arm64 digest is the official 2.1.312 linux-arm64 binary.
+func TestReleasePinByArchitecture(t *testing.T) {
+ pin, ok := ReleasePin("amd64")
+ if !ok || pin != ExecutableSHA256 {
+ t.Fatalf("amd64 must be the certified pin, got %q %v", pin, ok)
+ }
+ pin, ok = ReleasePin("arm64")
+ if !ok || pin != "dc4af28917455e009d26704b82a438353a06149e825b6cdf782908b2d28661f5" {
+ t.Fatalf("arm64 pin changed: %q %v", pin, ok)
+ }
+ if pin, ok = ReleasePin("riscv64"); ok || pin != "" {
+ t.Fatal("an architecture with no pinned build has a pin")
+ }
+}
diff --git a/internal/runner/provider/claude/runtime_replay_test.go b/internal/runner/provider/claude/runtime_replay_test.go
index 6c9d17f9..d2c32eca 100644
--- a/internal/runner/provider/claude/runtime_replay_test.go
+++ b/internal/runner/provider/claude/runtime_replay_test.go
@@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strings"
"testing"
"time"
@@ -125,7 +126,7 @@ func TestClaudeEmptyHomeReplay(t *testing.T) {
binary := filepath.Join(home, ".local/share/equipo/try/bin/claude")
file, err := os.Open(binary)
if os.IsNotExist(err) {
- t.Skip("pinned Claude 2.1.312 binary absent; empty-home replay requires the local pinned installation")
+ testci.Absent(t, "pinned Claude 2.1.312 binary absent; empty-home replay requires the local pinned installation")
}
if err != nil {
t.Fatal(err)
@@ -133,7 +134,12 @@ func TestClaudeEmptyHomeReplay(t *testing.T) {
sum := sha256.New()
_, err = io.Copy(sum, file)
file.Close()
- if err != nil || hex.EncodeToString(sum.Sum(nil)) != ExecutableSHA256 {
+ // The official build for this machine: the certified pin on amd64.
+ pin, ok := ReleasePin(runtime.GOARCH)
+ if !ok {
+ t.Fatalf("no pinned Claude 2.1.312 build for %s", runtime.GOARCH)
+ }
+ if err != nil || hex.EncodeToString(sum.Sum(nil)) != pin {
t.Fatal("pinned Claude digest differs")
}
for _, role := range []string{"Engineering", "Coordinator"} {
@@ -181,6 +187,7 @@ func TestClaudeEmptyHomeReplay(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ launcher.digest = pin
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
_, err = launcher.Open(ctx, f.launch)
diff --git a/internal/runner/provider/codex/pins.go b/internal/runner/provider/codex/pins.go
new file mode 100644
index 00000000..75bc33d8
--- /dev/null
+++ b/internal/runner/provider/codex/pins.go
@@ -0,0 +1,26 @@
+package codex
+
+// The arm64 builds of the pinned release, for tests only. The certified
+// runner target is linux/amd64: ExecutableSHA256 and CodeModeHostSHA256
+// are the only pins a launcher or a release trusts, and no release ships
+// with the ones below. These are the same official release's
+// aarch64-unknown-linux-musl binaries (rust-v0.165.0), so a test that
+// runs the real program can run on an arm64 CI machine.
+const (
+ ExecutableSHA256Arm64 = "b32ece31af06440da980b733fb8fefdd1f193439595fda84096f1caaceec543f"
+ CodeModeHostSHA256Arm64 = "fd7a4a1f29871fb0015c19ad2f885ef6a878244643260703e17663418695aa14"
+)
+
+// ReleasePins returns the digests of the official 0.165.0 binaries built
+// for goarch: the certified pins on amd64, the arm64 build's on arm64. A
+// test hands it runtime.GOARCH to check the binaries on the machine it
+// runs on. ok is false where there is no pinned build.
+func ReleasePins(goarch string) (executable, codeModeHost string, ok bool) {
+ switch goarch {
+ case "amd64":
+ return ExecutableSHA256, CodeModeHostSHA256, true
+ case "arm64":
+ return ExecutableSHA256Arm64, CodeModeHostSHA256Arm64, true
+ }
+ return "", "", false
+}
diff --git a/internal/runner/provider/codex/pins_test.go b/internal/runner/provider/codex/pins_test.go
new file mode 100644
index 00000000..6d9ad081
--- /dev/null
+++ b/internal/runner/provider/codex/pins_test.go
@@ -0,0 +1,34 @@
+package codex
+
+import "testing"
+
+// The amd64 pins are the certified ones and must not move with the arm64
+// ones beside them. The arm64 digests are the official rust-v0.165.0
+// aarch64-unknown-linux-musl binaries.
+func TestReleasePinsByArchitecture(t *testing.T) {
+ executable, host, ok := ReleasePins("amd64")
+ if !ok || executable != ExecutableSHA256 || host != CodeModeHostSHA256 {
+ t.Fatalf("amd64 must be the certified pins, got %q %q %v", executable, host, ok)
+ }
+ executable, host, ok = ReleasePins("arm64")
+ if !ok || executable != "b32ece31af06440da980b733fb8fefdd1f193439595fda84096f1caaceec543f" || host != "fd7a4a1f29871fb0015c19ad2f885ef6a878244643260703e17663418695aa14" {
+ t.Fatalf("arm64 pins changed: %q %q %v", executable, host, ok)
+ }
+ if executable == ExecutableSHA256 || host == CodeModeHostSHA256 {
+ t.Fatal("arm64 pins equal the certified amd64 pins")
+ }
+ if executable, host, ok = ReleasePins("riscv64"); ok || executable != "" || host != "" {
+ t.Fatal("an architecture with no official build has pins")
+ }
+}
+
+// A launcher trusts only the certified pins, whatever machine builds it.
+func TestLauncherKeepsCertifiedPins(t *testing.T) {
+ l, err := New(offlineCodexHost{t}, fakeCapture{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if l.digest != ExecutableSHA256 || l.hostDigest != CodeModeHostSHA256 {
+ t.Fatal("launcher pins are not the certified ones")
+ }
+}
diff --git a/internal/runner/provider/codex/runtime_replay_test.go b/internal/runner/provider/codex/runtime_replay_test.go
index b23c2f48..ea29e1fe 100644
--- a/internal/runner/provider/codex/runtime_replay_test.go
+++ b/internal/runner/provider/codex/runtime_replay_test.go
@@ -10,6 +10,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"strings"
"testing"
"time"
@@ -78,10 +79,15 @@ func TestCodexEmptyHomeReplay(t *testing.T) {
t.Fatal(err)
}
bin := filepath.Join(home, ".local/share/equipo/try/bin")
- for name, want := range map[string]string{"codex": ExecutableSHA256, "codex-code-mode-host": CodeModeHostSHA256} {
+ // The official build for this machine: the certified pins on amd64.
+ executable, codeModeHost, ok := ReleasePins(runtime.GOARCH)
+ if !ok {
+ t.Fatalf("no pinned Codex 0.165.0 build for %s", runtime.GOARCH)
+ }
+ for name, want := range map[string]string{"codex": executable, "codex-code-mode-host": codeModeHost} {
f, err := os.Open(filepath.Join(bin, name))
if os.IsNotExist(err) {
- t.Skip("pinned Codex 0.165.0 binaries absent; empty-home replay requires the local pinned installation")
+ testci.Absent(t, "pinned Codex 0.165.0 binaries absent; empty-home replay requires the local pinned installation")
}
if err != nil {
t.Fatal(err)
@@ -126,6 +132,7 @@ func TestCodexEmptyHomeReplay(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ f.l.digest, f.l.hostDigest = executable, codeModeHost
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err = f.l.Open(ctx, f.launch)
diff --git a/internal/runner/provider/providertest/release.go b/internal/runner/provider/providertest/release.go
index cdc523f6..3c03ed8a 100644
--- a/internal/runner/provider/providertest/release.go
+++ b/internal/runner/provider/providertest/release.go
@@ -9,6 +9,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "regexp"
"strings"
"testing"
)
@@ -50,6 +51,12 @@ func installCertificationFixture(t *testing.T, root string, m *release.Manifest,
}
releaseMust(t, os.WriteFile(path, []byte(strings.Join(lines, "\n")), 0600))
}
+ // On an arm64 machine the prerequisites check reads the arm64 pin.
+ path := filepath.Join(root, "internal/runner/provider/codex/pins.go")
+ data, err := os.ReadFile(path)
+ releaseMust(t, err)
+ arm := regexp.MustCompile(`(ExecutableSHA256Arm64\s+= )"[a-f0-9]{64}"`)
+ releaseMust(t, os.WriteFile(path, arm.ReplaceAll(data, []byte(`${1}"`+binaryHashes["codex"]+`"`)), 0600))
}
for i, c := range m.DirectPolicies {
dir := filepath.Join(root, "internal/release/evidence", c.Provider)
diff --git a/internal/runner/setup/install_test.go b/internal/runner/setup/install_test.go
index 4d4e042e..0553dfd0 100644
--- a/internal/runner/setup/install_test.go
+++ b/internal/runner/setup/install_test.go
@@ -12,11 +12,33 @@ import (
"amadan.net/oficina/equipo/internal/release"
"amadan.net/oficina/equipo/internal/runner/provider"
+ "golang.org/x/sys/unix"
)
-func installFixture(t *testing.T) (InstallOptions, installHost, *int) {
+// installHome is a home directory on a filesystem that keeps user
+// extended attributes: the installer marks what it wrote with one. A
+// tmpfs refuses them before Linux 6.6, so where the test's temporary
+// directory is one, the home goes under the user's own home instead.
+func installHome(t *testing.T) string {
t.Helper()
home := t.TempDir()
+ if unix.Setxattr(home, "user.equipo.test", []byte("1"), 0) == nil {
+ return home
+ }
+ base, err := os.UserHomeDir()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if home, err = os.MkdirTemp(base, "equipo-install-test-"); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(home) })
+ return home
+}
+
+func installFixture(t *testing.T) (InstallOptions, installHost, *int) {
+ t.Helper()
+ home := installHome(t)
binary := []byte("fixture runner bytes")
m := release.InstallManifest{Version: "fixture-16", Target: "linux/amd64", RunnerSHA256: fmt.Sprintf("%x", sha256.Sum256(binary)), NamespaceArgs: provider.NamespaceArguments(), Release: release.BuildManifest()}
m.Release.Binaries = []release.BinaryDigest{{Name: "equipo-tool-proxy", Version: m.Release.LauncherVersion, SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("fixture tool proxy")))}}
diff --git a/internal/testci/absent_test.go b/internal/testci/absent_test.go
new file mode 100644
index 00000000..65de61b4
--- /dev/null
+++ b/internal/testci/absent_test.go
@@ -0,0 +1,37 @@
+package testci
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+)
+
+// recorder stands in for a test, so Absent's verdict can be read.
+type recorder struct {
+ testing.TB
+ skipped, failed string
+}
+
+func (r *recorder) Helper() {}
+func (r *recorder) Skip(args ...any) { r.skipped = fmt.Sprint(args...) }
+func (r *recorder) Fatalf(f string, a ...any) { r.failed = fmt.Sprintf(f, a...) }
+
+func TestAbsentSkipsOnADeveloperMachine(t *testing.T) {
+ t.Setenv(ToolsRequired, "")
+ r := &recorder{TB: t}
+ Absent(r, "pinned program absent")
+ if r.skipped != "pinned program absent" || r.failed != "" {
+ t.Fatalf("want a skip, got skip %q fail %q", r.skipped, r.failed)
+ }
+}
+
+// Where CI installs the pinned programs, a missing one is a failure: a
+// skip there would be a green run that tested nothing.
+func TestAbsentFailsWhereToolsAreRequired(t *testing.T) {
+ t.Setenv(ToolsRequired, "1")
+ r := &recorder{TB: t}
+ Absent(r, "pinned program absent")
+ if r.skipped != "" || !strings.Contains(r.failed, "pinned program absent") || !strings.Contains(r.failed, ToolsRequired) {
+ t.Fatalf("want a failure naming the program and the variable, got skip %q fail %q", r.skipped, r.failed)
+ }
+}
diff --git a/internal/testci/box_test.go b/internal/testci/box_test.go
new file mode 100644
index 00000000..fd8de184
--- /dev/null
+++ b/internal/testci/box_test.go
@@ -0,0 +1,63 @@
+package testci_test
+
+import (
+ "encoding/json"
+ "os"
+ "regexp"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/provider/claude"
+ "amadan.net/oficina/equipo/internal/runner/provider/codex"
+)
+
+// The CI box fetches the pinned programs by the digests in
+// scripts/ci-box.json. They must be the ones the tests check: the
+// certified pins on amd64 and the arm64 pins beside them.
+func TestBoxPinsMatchTheCode(t *testing.T) {
+ raw, err := os.ReadFile("../../scripts/ci-box.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var box struct {
+ Image string
+ Tools map[string]map[string]json.RawMessage
+ }
+ if err = json.Unmarshal(raw, &box); err != nil {
+ t.Fatal(err)
+ }
+ if !regexp.MustCompile(`@sha256:[a-f0-9]{64}$`).MatchString(box.Image) {
+ t.Errorf("the box image %q is not pinned by digest", box.Image)
+ }
+ digest := regexp.MustCompile(`^[a-f0-9]{64}$`)
+ for _, arch := range []string{"amd64", "arm64"} {
+ executable, host, ok := codex.ReleasePins(arch)
+ pin, okClaude := claude.ReleasePin(arch)
+ if !ok || !okClaude {
+ t.Fatalf("no pins for %s", arch)
+ }
+ want := map[string]string{"codex": executable, "codex-code-mode-host": host, "claude": pin, "bwrap": ""}
+ for name, sum := range want {
+ var entry struct{ URL, SHA256 string }
+ if err = json.Unmarshal(box.Tools[name][arch], &entry); err != nil {
+ t.Errorf("%s %s: %v", name, arch, err)
+ continue
+ }
+ if !strings.HasPrefix(entry.URL, "https://") || !digest.MatchString(entry.SHA256) {
+ t.Errorf("%s %s: want an https URL and a SHA-256, got %q %q", name, arch, entry.URL, entry.SHA256)
+ }
+ if sum != "" && entry.SHA256 != sum {
+ t.Errorf("%s %s: the box fetches %s, the code pins %s", name, arch, entry.SHA256, sum)
+ }
+ }
+ }
+ // Every other program the box fetches is pinned for both architectures too.
+ for name, tool := range box.Tools {
+ for _, arch := range []string{"amd64", "arm64"} {
+ var entry struct{ URL, SHA256 string }
+ if err = json.Unmarshal(tool[arch], &entry); err != nil || !strings.HasPrefix(entry.URL, "https://") || !digest.MatchString(entry.SHA256) {
+ t.Errorf("%s %s: want an https URL and a SHA-256, got %q %q (%v)", name, arch, entry.URL, entry.SHA256, err)
+ }
+ }
+ }
+}
diff --git a/internal/testci/budget_test.go b/internal/testci/budget_test.go
new file mode 100644
index 00000000..d04718e5
--- /dev/null
+++ b/internal/testci/budget_test.go
@@ -0,0 +1,11 @@
+package testci
+
+import (
+ "os"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/budget"
+)
+
+// TestMain prints this package's time for rastrillo budget test (make test).
+func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
diff --git a/internal/testci/testci.go b/internal/testci/testci.go
index 568a785a..2485149e 100644
--- a/internal/testci/testci.go
+++ b/internal/testci/testci.go
@@ -283,3 +283,19 @@ func quarantineListed(test string) (bool, error) {
}
return false, s.Err()
}
+
+// ToolsRequired is the environment variable CI sets to 1 on a machine it
+// has given every pinned program the tests run (make ci-box does).
+const ToolsRequired = "EQUIPO_TEST_TOOLS_REQUIRED"
+
+// Absent reports that a pinned program the test runs is not installed.
+// On a developer's machine that skips the test. Where ToolsRequired is 1
+// it fails it: a skip there would be a green run that tested nothing.
+func Absent(t testing.TB, what string) {
+ t.Helper()
+ if os.Getenv(ToolsRequired) == "1" {
+ t.Fatalf("%s, and %s=1 says this machine has it", what, ToolsRequired)
+ return
+ }
+ t.Skip(what)
+}
diff --git a/scripts/ci-box-enter.sh b/scripts/ci-box-enter.sh
new file mode 100755
index 00000000..79ddb356
--- /dev/null
+++ b/scripts/ci-box-enter.sh
@@ -0,0 +1,58 @@
+#!/bin/sh
+# The first program in Equipo's CI box (scripts/ci-box.py run). It starts
+# as root, makes the box look like a runner host, and runs the command as
+# the job's own user:
+#
+# - /etc on a filesystem of its own. Containment lays an overlay over
+# /etc, and the kernel refuses one whose lower layer is the
+# container's own overlay root;
+# - a machine id, which a real host has and the image does not;
+# - a home directory, with the pinned programs where tests look for them,
+# and a git identity, without which git refuses to commit;
+# - a cgroup v2 subtree the user may write, at the path systemd gives a
+# user session. The cgroup move test moves a contained process between
+# two cgroups there, as a person on a runner host can.
+#
+# Tests never run as root: bubblewrap and file permissions behave
+# differently for root, and no runner runs as root. The one exception is a
+# rootless engine on a developer's machine, whose root is the caller.
+set -eu
+
+uid=${EQUIPO_BOX_UID:-0}
+gid=${EQUIPO_BOX_GID:-0}
+home=/home/ci
+
+if [ "$(id -u)" != 0 ]; then
+ exec "$@"
+fi
+
+mkdir -p /run/equipo-etc
+mount -t tmpfs -o mode=0755 tmpfs /run/equipo-etc
+cp -a /etc/. /run/equipo-etc/
+mount --bind /run/equipo-etc /etc
+[ -s /etc/machine-id ] || echo 0ec1b0c1e9015c1b0c5e9015c1b0c1e9 >/etc/machine-id
+
+grep -q '^ci:' /etc/passwd || [ "$uid" = 0 ] || echo "ci:x:$uid:$gid:Equipo CI:$home:/bin/sh" >>/etc/passwd
+grep -q '^ci:' /etc/group || [ "$gid" = 0 ] || echo "ci:x:$gid:" >>/etc/group
+mkdir -p "$home/.local/share/equipo/try"
+chown "$uid:$gid" "$home" "$home/.local" "$home/.local/share" "$home/.local/share/equipo" "$home/.local/share/equipo/try"
+
+base=/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service
+if mkdir -p "$base/ci.scope" 2>/dev/null && echo $$ >"$base/ci.scope/cgroup.procs" 2>/dev/null; then
+ for file in "$base" "$base/cgroup.procs" "$base/cgroup.threads" "$base/cgroup.subtree_control" \
+ "$base/ci.scope" "$base/ci.scope/cgroup.procs" "$base/ci.scope/cgroup.threads" "$base/ci.scope/cgroup.subtree_control"; do
+ chown "$uid:$gid" "$file"
+ done
+else
+ echo "ci-box: no writable cgroup v2 tree here; the cgroup move test will fail" >&2
+fi
+
+printf '[user]\n\tname = Equipo CI\n\temail = ci@equipo.invalid\n' >"$home/.gitconfig"
+[ "$uid" != 0 ] || printf '[safe]\n\tdirectory = *\n' >>"$home/.gitconfig"
+chown "$uid:$gid" "$home/.gitconfig"
+export HOME="$home"
+if [ "$uid" = 0 ]; then
+ exec "$@"
+fi
+export USER=ci LOGNAME=ci
+exec setpriv --reuid "$uid" --regid "$gid" --clear-groups -- "$@"
diff --git a/scripts/ci-box.json b/scripts/ci-box.json
new file mode 100644
index 00000000..097a38e9
--- /dev/null
+++ b/scripts/ci-box.json
@@ -0,0 +1,110 @@
+{
+ "image": "public.ecr.aws/docker/library/golang:1.26.10-trixie@sha256:fd9a91f0ece5664556f4851d06dce5e5b505a71166dffd385a03ba9d200b6983",
+ "tools": {
+ "bwrap": {
+ "version": "bubblewrap 0.11.0",
+ "amd64": {
+ "url": "https://snapshot.debian.org/file/817a2e6186906394f63696c2b289f0f19e45b8d3",
+ "archive_sha256": "7a541ad9d12b23db7082ed3bf1f6d5253f23439cdfa7c28b4e022d0a602a19d6",
+ "format": "deb",
+ "member": "./usr/bin/bwrap",
+ "sha256": "0dfa36b98ada69568aaaa741fe210d2150a1441433bd13c428137d6a972a959c"
+ },
+ "arm64": {
+ "url": "https://snapshot.debian.org/file/ef2d83d8c40c740e00a7dde0ffffff41e5f855ee",
+ "archive_sha256": "c838daebddb7fe169ebb461612e90b1fcb981de838f81bfbecf26d45ab5a71ee",
+ "format": "deb",
+ "member": "./usr/bin/bwrap",
+ "sha256": "ef2316fc741885e6d7b422661ea60c20cbe07ec7eb592a4c2370cbcb90843b59"
+ },
+ "box": "/usr/bin/bwrap"
+ },
+ "codex": {
+ "version": "codex-cli 0.165.0",
+ "amd64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.165.0/codex-x86_64-unknown-linux-musl.tar.gz",
+ "archive_sha256": "be635d3486a5bd060d0fff582ae6d30160280c31344dd85719707fa920e187f0",
+ "format": "tar.gz",
+ "member": "codex-x86_64-unknown-linux-musl",
+ "sha256": "c06a67fd8ac76508dc78bd99ce20c9f317b8d568beda59485f3f4134df9962d5"
+ },
+ "arm64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.165.0/codex-aarch64-unknown-linux-musl.tar.gz",
+ "archive_sha256": "6522e056d0be7f531da915c9a81ae05bc70811b782542499cc0a9776d3abf5d3",
+ "format": "tar.gz",
+ "member": "codex-aarch64-unknown-linux-musl",
+ "sha256": "b32ece31af06440da980b733fb8fefdd1f193439595fda84096f1caaceec543f"
+ },
+ "box": "/usr/local/bin/codex",
+ "try_bin": true
+ },
+ "codex-code-mode-host": {
+ "amd64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.165.0/codex-code-mode-host-x86_64-unknown-linux-musl.tar.gz",
+ "archive_sha256": "9577b09b2a546eeb3da8a09807de6d58fbaa207755256390113772ea4f05235e",
+ "format": "tar.gz",
+ "member": "codex-code-mode-host-x86_64-unknown-linux-musl",
+ "sha256": "522935d4392ec9674fab60b239b5495992c6a93e4deb65113a216b6f5451ccd4"
+ },
+ "arm64": {
+ "url": "https://github.com/openai/codex/releases/download/rust-v0.165.0/codex-code-mode-host-aarch64-unknown-linux-musl.tar.gz",
+ "archive_sha256": "400956c325a2118768029f235958b7d2fd2ea4e59c5466d336fb4fb7f0e94b61",
+ "format": "tar.gz",
+ "member": "codex-code-mode-host-aarch64-unknown-linux-musl",
+ "sha256": "fd7a4a1f29871fb0015c19ad2f885ef6a878244643260703e17663418695aa14"
+ },
+ "try_bin": true
+ },
+ "claude": {
+ "version": "2.1.312 (Claude Code)",
+ "amd64": {
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.312/linux-x64/claude",
+ "format": "raw",
+ "sha256": "4f4178ce41d83e23341ebfbaecdbcf8ea6bf7baea0690025abe49eeec3a5d01d"
+ },
+ "arm64": {
+ "url": "https://downloads.claude.ai/claude-code-releases/2.1.312/linux-arm64/claude",
+ "format": "raw",
+ "sha256": "dc4af28917455e009d26704b82a438353a06149e825b6cdf782908b2d28661f5"
+ },
+ "try_bin": true
+ },
+ "socat": {
+ "version": "socat 1.8.0.3",
+ "box": "/usr/bin/socat",
+ "amd64": {
+ "url": "https://snapshot.debian.org/file/37c6de3f1d589800dcaf20979c2e209ab65975ef",
+ "archive_sha256": "6ad18d699071c1e0e3b1e9acd020368544369d339607e80b7eca97bcf4f97017",
+ "format": "deb",
+ "member": "./usr/bin/socat1",
+ "sha256": "7053ab3b63bb5f1bde806e8b32c13607fc65a6c76efa9cd440b7427ada51300a"
+ },
+ "arm64": {
+ "url": "https://snapshot.debian.org/file/493b336ad97e9592797bd9cdd3aa5365ec5c5ab6",
+ "archive_sha256": "935b5ea942807ed82507bf585ae4e666937ebf5c910c5bbe6887ea2b22f19a44",
+ "format": "deb",
+ "member": "./usr/bin/socat1",
+ "sha256": "0b8d4c71219df55dfdcfd96de153ec1452cffe0c756f8b9fc87d66a6931a7e02"
+ }
+ },
+ "libwrap": {
+ "version": "libwrap0 7.6.q-36",
+ "amd64": {
+ "url": "https://snapshot.debian.org/file/f68950b258f62f06af58295d7ae6c141a9a0e47d",
+ "archive_sha256": "cde12afa15d6b1556c5e0564d22edf3b99e6b8fa94c59ccd8b8eebbb62dc19ec",
+ "format": "deb",
+ "member": "./usr/lib/x86_64-linux-gnu/libwrap.so.0.7.6",
+ "sha256": "a1679facc8b1b3e16b1d910b7557c1e33461f981add05d3fcb71d2b1aa2df894",
+ "box": "/usr/lib/x86_64-linux-gnu/libwrap.so.0"
+ },
+ "arm64": {
+ "url": "https://snapshot.debian.org/file/2147a199f0eb525d8f88e6dfe925e10f7a627849",
+ "archive_sha256": "fd2e54582a07fba9c8a6f78c68dcc6d3c8cf1c70632a68124394bde4dccf52ea",
+ "format": "deb",
+ "member": "./usr/lib/aarch64-linux-gnu/libwrap.so.0.7.6",
+ "sha256": "961f48b0d807ffdbdf8971b7e13f04409a4bc639cff3ea42defbd850b6ca739d",
+ "box": "/usr/lib/aarch64-linux-gnu/libwrap.so.0"
+ }
+ }
+ }
+}
diff --git a/scripts/ci-box.py b/scripts/ci-box.py
new file mode 100755
index 00000000..ecd93397
--- /dev/null
+++ b/scripts/ci-box.py
@@ -0,0 +1,476 @@
+#!/usr/bin/env python3
+"""Run Equipo's CI in its box: one container that looks like a runner host.
+
+ scripts/ci-box.py prepare fetch the pinned tools and the image; on CI
+ also deepen the clone and set file times
+ scripts/ci-box.py run CMD... run CMD in the box, from the repository root
+ scripts/ci-box.py cache report the Go caches and trim them to fit
+ scripts/ci-box.py facts print what this machine is
+
+amadan's hosted CI gives each job a fresh arm64 machine with Docker and no
+bubblewrap. Equipo's tests start real containment: they need bubblewrap
+0.11.0 exactly, the pinned Codex and Claude programs, user namespaces and
+a delegated cgroup. The box supplies those. It is the official Go image
+on Debian 13 (the runner host's own system), run privileged, with the
+pinned programs mounted where a runner host has them:
+
+ /usr/bin/bwrap Debian's 0.11.0-2+deb13u1 build
+ /usr/local/bin/codex codex 0.165.0
+ ~/.local/share/equipo/try/bin codex, its code mode host, claude
+ /usr/bin/socat Claude's own sandbox needs it
+
+Every pinned program is fetched by URL and checked against the SHA-256 in
+scripts/ci-box.json, for this machine's architecture. The job's checkout
+and Go caches are mounted at fixed paths, so Go's build and test caches
+hold from one fresh machine to the next. Inside, the command runs as an
+ordinary user (scripts/ci-box-enter.sh), never as root.
+
+This file also runs on the CI machine itself, outside the box, where
+python3 is 3.9: keep it to that.
+"""
+import hashlib
+import io
+import json
+import lzma
+import os
+import platform
+import shutil
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import urllib.request
+from concurrent.futures import ThreadPoolExecutor
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+PINS = os.path.join(ROOT, "scripts", "ci-box.json")
+
+# Where things sit inside the box. Fixed, whatever the job's own paths
+# are: Go keys a compiled package on its source directory, so a checkout
+# that moved would recompile everything.
+WORK = "/work/equipo"
+GOCACHE = "/cache/go-build"
+GOMODCACHE = "/cache/go-mod"
+HOME = "/home/ci"
+TRY_BIN = HOME + "/.local/share/equipo/try/bin"
+
+# Fetched programs get this modification time (2026-01-01), and tracked
+# files get one made from their content: make test fingerprints programs
+# by size and time, and go test keys a cached result on the size and time
+# of each file the test opened. A fresh clone would stamp everything
+# "now" and no result would ever be reused.
+TOOL_TIME = 1767225600
+FILE_TIME_BASE = 1577836800 # 2020-01-01
+FILE_TIME_SPAN = 5 * 365 * 86400
+
+# The hosted cache holds 6 GiB unpacked and 2 GiB compressed, and a save
+# over either is dropped whole. Trim well under it.
+CACHE_LIMIT = 4 * 1024 ** 3
+
+# Environment a step may see inside the box, besides what run() sets.
+# Not GOPRIVATE or GOAUTH: the job's git credential stays outside the
+# box, and every module Equipo uses is on the public proxy.
+PASS_PREFIXES = ("AMADAN_", "EQUIPO_")
+PASS_NAMES = ("CI", "GOFLAGS", "GOPROXY", "TERM")
+
+
+def say(text):
+ print("ci-box: " + text, flush=True)
+
+
+def arch():
+ machine = platform.machine().lower()
+ name = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(machine)
+ if name is None:
+ sys.exit("ci-box: no pinned tools for a %s machine" % machine)
+ return name
+
+
+def pins():
+ with open(PINS) as f:
+ return json.load(f)
+
+
+def box_dir():
+ path = os.environ.get("EQUIPO_CI_BOX_DIR") or os.path.join(os.path.expanduser("~"), ".cache", "equipo-ci-box")
+ os.makedirs(path, exist_ok=True)
+ return path
+
+
+def tools_dir():
+ return os.path.join(box_dir(), "tools", arch())
+
+
+def tool_path(name, tool):
+ """Where a fetched program is kept: the ones tests find in the try
+ directory together in bin, mounted as that directory; the rest in sys."""
+ return os.path.join(tools_dir(), "bin" if tool.get("try_bin") else "sys", name)
+
+
+def boxed():
+ """Whether commands go in the box. EQUIPO_CI_BOX=on or off decides;
+ unset, a machine that already has what the box supplies (the pinned
+ bubblewrap and a codex) is a runner host, and commands run directly."""
+ mode = os.environ.get("EQUIPO_CI_BOX", "")
+ if mode in ("on", "off"):
+ return mode == "on"
+ if mode:
+ sys.exit("ci-box: EQUIPO_CI_BOX is %r; use on or off" % mode)
+ try:
+ version = subprocess.check_output(["/usr/bin/bwrap", "--version"], stderr=subprocess.DEVNULL, text=True).strip()
+ except (OSError, subprocess.CalledProcessError):
+ version = ""
+ return version != pins()["tools"]["bwrap"]["version"] or shutil.which("codex") is None
+
+
+# Pinned tools.
+
+def sha256_file(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for block in iter(lambda: f.read(1 << 20), b""):
+ h.update(block)
+ return h.hexdigest()
+
+
+def download(url, dest):
+ """Fetch url into dest and return its SHA-256; three attempts."""
+ last = None
+ for attempt in range(3):
+ try:
+ h = hashlib.sha256()
+ request = urllib.request.Request(url, headers={"User-Agent": "equipo-ci-box"})
+ with urllib.request.urlopen(request, timeout=120) as response, open(dest, "wb") as out:
+ for block in iter(lambda: response.read(1 << 20), b""):
+ h.update(block)
+ out.write(block)
+ return h.hexdigest()
+ except Exception as e: # a CDN's bad minute is not this change's failure
+ last = e
+ time.sleep(2 * (attempt + 1))
+ raise RuntimeError("fetch %s: %s" % (url, last))
+
+
+def deb_data(path):
+ """The data archive of a .deb: an ar file whose data.tar.* member holds the files."""
+ with open(path, "rb") as f:
+ if f.read(8) != b"!<arch>\n":
+ raise RuntimeError("not a .deb: " + path)
+ while True:
+ header = f.read(60)
+ if len(header) < 60:
+ raise RuntimeError("no data archive in " + path)
+ name = header[:16].decode().strip().rstrip("/")
+ size = int(header[48:58].decode().strip())
+ body = f.read(size + (size & 1))[:size]
+ if name.startswith("data.tar"):
+ if name.endswith(".xz"):
+ body = lzma.decompress(body)
+ elif name != "data.tar":
+ raise RuntimeError("unsupported .deb compression: " + name)
+ return body
+
+
+def extract(archive, fmt, member, dest):
+ if fmt == "raw":
+ shutil.copyfile(archive, dest)
+ return
+ if fmt == "deb":
+ tar = tarfile.open(fileobj=io.BytesIO(deb_data(archive)))
+ elif fmt == "tar.gz":
+ tar = tarfile.open(archive, "r:gz")
+ else:
+ raise RuntimeError("unknown archive format " + fmt)
+ with tar:
+ source = tar.extractfile(member)
+ if source is None:
+ raise RuntimeError("%s is not a file in the archive" % member)
+ with source, open(dest, "wb") as out:
+ shutil.copyfileobj(source, out)
+
+
+def fetch_tool(name, pin, target):
+ if os.path.isfile(target) and sha256_file(target) == pin["sha256"]:
+ return "%s: present" % name
+ started = time.time()
+ os.makedirs(os.path.dirname(target), exist_ok=True)
+ with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch:
+ archive = os.path.join(scratch, "archive")
+ got = download(pin["url"], archive)
+ want = pin.get("archive_sha256", pin["sha256"])
+ if got != want:
+ raise RuntimeError("%s: %s has SHA-256 %s, pinned %s" % (name, pin["url"], got, want))
+ out = os.path.join(scratch, name)
+ extract(archive, pin["format"], pin.get("member"), out)
+ if sha256_file(out) != pin["sha256"]:
+ raise RuntimeError("%s: the program in %s is not the pinned one" % (name, pin["url"]))
+ os.chmod(out, 0o755)
+ os.utime(out, (TOOL_TIME, TOOL_TIME))
+ os.replace(out, target)
+ return "%s: fetched and verified in %.1fs" % (name, time.time() - started)
+
+
+def fetch_tools():
+ os.makedirs(os.path.join(tools_dir(), "bin"), exist_ok=True)
+ machine = arch()
+ jobs = []
+ for name, tool in sorted(pins()["tools"].items()):
+ if machine not in tool:
+ sys.exit("ci-box: %s has no pin for %s" % (name, machine))
+ jobs.append((name, tool[machine], tool_path(name, tool)))
+ with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
+ for line in pool.map(lambda job: fetch_tool(*job), jobs):
+ say(line)
+ return tools_dir()
+
+
+# The container engine and the image.
+
+def engine():
+ name = os.environ.get("EQUIPO_CI_ENGINE")
+ if name:
+ return name
+ for name in ("docker", "podman"):
+ if shutil.which(name):
+ return name
+ sys.exit("ci-box: neither docker nor podman is installed")
+
+
+def pull_image():
+ image = pins()["image"]
+ if subprocess.call([engine(), "image", "inspect", image], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
+ say("image present")
+ return
+ started = time.time()
+ for attempt in range(3):
+ if subprocess.call([engine(), "pull", "-q", image], stdout=subprocess.DEVNULL) == 0:
+ say("image pulled in %.1fs" % (time.time() - started))
+ return
+ time.sleep(3 * (attempt + 1))
+ sys.exit("ci-box: could not pull " + image)
+
+
+# The checkout.
+
+def git(*args):
+ return subprocess.run(["git", "-C", ROOT] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+
+def deepen():
+ """A hosted job clones one commit. gitleaks reads history, and the
+ mixed-version test builds an older release, so fetch the rest."""
+ if git("rev-parse", "--is-shallow-repository").stdout.strip() != b"true":
+ return
+ started = time.time()
+ result = git("fetch", "--quiet", "--unshallow", "origin")
+ if result.returncode != 0:
+ say("WARNING: the clone is one commit deep and could not be deepened: " +
+ result.stderr.decode(errors="replace").strip()[-400:])
+ # Names only, never values: what git has to authenticate with.
+ names = sorted(n for n in os.environ if n.startswith(("GIT_", "GOAUTH", "GOPRIVATE", "NETRC")))
+ keys = sorted(set(line.split("=", 1)[0] for line in git("config", "--list").stdout.decode().splitlines()
+ if "credential" in line or "url." in line or "extraheader" in line.lower()))
+ say("git settings present (names only): env %s; config %s; origin %s" %
+ (names or "none", keys or "none", git("remote", "get-url", "origin").stdout.decode().strip()))
+ return
+ say("clone deepened in %.1fs" % (time.time() - started))
+
+
+def set_file_times():
+ """Give every tracked file a modification time made from its content,
+ and every directory one fixed time. See TOOL_TIME."""
+ listed = git("ls-files", "-s", "-z")
+ if listed.returncode != 0:
+ sys.exit("ci-box: git ls-files: " + listed.stderr.decode(errors="replace"))
+ directories = {ROOT}
+ count = 0
+ for entry in listed.stdout.split(b"\0"):
+ if not entry:
+ continue
+ meta, name = entry.split(b"\t", 1)
+ mode, blob = meta.split()[:2]
+ if mode == b"160000":
+ continue
+ path = os.path.join(ROOT, os.fsdecode(name))
+ stamp = FILE_TIME_BASE + int(blob[:8], 16) % FILE_TIME_SPAN
+ try:
+ os.utime(path, (stamp, stamp), follow_symlinks=False)
+ except FileNotFoundError:
+ continue
+ count += 1
+ parent = os.path.dirname(path)
+ while parent not in directories:
+ directories.add(parent)
+ parent = os.path.dirname(parent)
+ for directory in directories:
+ os.utime(directory, (FILE_TIME_BASE, FILE_TIME_BASE))
+ git("update-index", "-q", "--refresh")
+ say("file times set from content: %d files, %d directories" % (count, len(directories)))
+
+
+# Running a command in the box.
+
+def go_env(name):
+ value = os.environ.get(name)
+ if value:
+ return value
+ return subprocess.check_output(["go", "env", name], text=True).strip()
+
+
+def run(command):
+ if not command:
+ sys.exit("ci-box: run what?")
+ if not boxed():
+ os.chdir(ROOT)
+ os.execvp(command[0], command)
+ machine = arch()
+ tools = pins()["tools"]
+ missing = [name for name, tool in tools.items() if not os.path.isfile(tool_path(name, tool))]
+ if missing:
+ sys.exit("ci-box: %s not fetched; run scripts/ci-box.py prepare first" % ", ".join(sorted(missing)))
+ gocache, gomodcache = go_env("GOCACHE"), go_env("GOMODCACHE")
+ for path in (gocache, gomodcache):
+ os.makedirs(path, exist_ok=True)
+ tool = engine()
+ # /tmp in memory. The tests sync small files and databases thousands
+ # of times; on the machine's disk that doubled every lane's time.
+ args = [tool, "run", "--rm", "--privileged", "--cgroupns=private",
+ "--tmpfs", "/tmp:exec,mode=1777",
+ "-v", ROOT + ":" + WORK, "-w", WORK,
+ "-v", gocache + ":" + GOCACHE, "-v", gomodcache + ":" + GOMODCACHE,
+ "-v", os.path.join(tools_dir(), "bin") + ":" + TRY_BIN + ":ro"]
+ for name, entry in sorted(tools.items()):
+ inside = entry[machine].get("box") or entry.get("box")
+ if inside:
+ args += ["-v", tool_path(name, entry) + ":" + inside + ":ro"]
+ if tool == "docker":
+ args.append("--init") # reaps the orphans the containment tests leave on purpose
+ # A CI runner checks a branch out as a git worktree: .git is a file
+ # that names a directory in the shared clone. Mount that clone where
+ # the file says it is, or git has no repository inside the box.
+ if os.path.isfile(os.path.join(ROOT, ".git")):
+ common = git("rev-parse", "--path-format=absolute", "--git-common-dir").stdout.decode().strip()
+ if common:
+ args += ["-v", common + ":" + common]
+ for mount in filter(None, os.environ.get("EQUIPO_CI_BOX_MOUNTS", "").split(",")):
+ args += ["-v", mount]
+ env = {
+ "GOCACHE": GOCACHE, "GOMODCACHE": GOMODCACHE,
+ "EQUIPO_TEST_TOOLS_REQUIRED": "1",
+ "EQUIPO_BOX_UID": str(os.getuid()), "EQUIPO_BOX_GID": str(os.getgid()),
+ }
+ if tool == "podman" and os.getuid() != 0:
+ # Rootless podman, a developer's machine: its root is the caller, and
+ # any other user inside could not write the checkout. Tests then run
+ # as that root, which is good for a first look and not for a verdict.
+ env["EQUIPO_BOX_UID"] = env["EQUIPO_BOX_GID"] = "0"
+ for name, value in os.environ.items():
+ if name in PASS_NAMES or name.startswith(PASS_PREFIXES):
+ env.setdefault(name, value)
+ for name in sorted(env):
+ args += ["-e", name + "=" + env[name]]
+ args += [pins()["image"], WORK + "/scripts/ci-box-enter.sh"] + command
+ os.execvp(args[0], args)
+
+
+# The Go caches.
+
+def tree_size(path):
+ total = files = 0
+ for directory, _, names in os.walk(path):
+ for name in names:
+ try:
+ total += os.lstat(os.path.join(directory, name)).st_size
+ files += 1
+ except OSError:
+ pass
+ return total, files
+
+
+def cache():
+ """Report the caches and, past CACHE_LIMIT, drop what this job did not
+ read. A restore stamps every entry "now", so Go's own five-day trim
+ never fires on a hosted machine and the cache would grow until its
+ save is refused."""
+ if not boxed():
+ return # a runner host's cache is its own to trim
+ gocache, gomodcache = go_env("GOCACHE"), go_env("GOMODCACHE")
+ for name, path in (("build cache", gocache), ("module cache", gomodcache)):
+ size, files = tree_size(path)
+ say("%s %s: %.2f GiB in %d files" % (name, path, size / 1024 ** 3, files))
+ size, _ = tree_size(gocache)
+ marker = os.path.join(box_dir(), "prepared")
+ if size <= CACHE_LIMIT or not os.path.exists(marker):
+ return
+ since = os.stat(marker).st_mtime
+ dropped = kept = 0
+ for directory, _, names in os.walk(gocache):
+ for name in names:
+ path = os.path.join(directory, name)
+ try:
+ st = os.lstat(path)
+ if max(st.st_atime, st.st_mtime) < since:
+ os.unlink(path)
+ dropped += st.st_size
+ else:
+ kept += st.st_size
+ except OSError:
+ pass
+ say("build cache over %.1f GiB: dropped %.2f GiB this job did not read, kept %.2f GiB" %
+ (CACHE_LIMIT / 1024 ** 3, dropped / 1024 ** 3, kept / 1024 ** 3))
+
+
+def facts():
+ def out(*command):
+ try:
+ return subprocess.check_output(list(command), stderr=subprocess.STDOUT, text=True).strip()
+ except Exception as e:
+ return "unavailable (%s)" % e
+
+ memory = "unknown"
+ try:
+ with open("/proc/meminfo") as f:
+ memory = "%.0f GiB" % (int(f.readline().split()[1]) / 1024 ** 2)
+ except OSError:
+ pass
+ say("machine: %s, %s CPUs, %s memory, kernel %s" % (platform.machine(), os.cpu_count(), memory, platform.release()))
+ say("python %s; %s" % (platform.python_version(), out(engine(), "--version")))
+ say("user namespaces allowed: " + out("cat", "/proc/sys/user/max_user_namespaces"))
+ say("cgroup: " + out("stat", "-fc", "%T", "/sys/fs/cgroup"))
+ for path in (ROOT, box_dir()):
+ say("disk %s: %s" % (path, out("df", "-h", "--output=fstype,size,avail", path).replace("\n", " | ")))
+
+
+def prepare():
+ if not boxed():
+ return # a runner host: nothing to fetch
+ started = time.time()
+ facts()
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ image = pool.submit(pull_image)
+ fetch_tools()
+ image.result()
+ if os.environ.get("AMADAN_CI") == "1":
+ deepen()
+ set_file_times()
+ with open(os.path.join(box_dir(), "prepared"), "w") as f:
+ f.write("%d\n" % time.time())
+ say("ready in %.1fs" % (time.time() - started))
+
+
+def main(argv):
+ if argv == ["prepare"]:
+ return prepare()
+ if argv[:1] == ["run"]:
+ return run(argv[1:])
+ if argv == ["cache"]:
+ return cache()
+ if argv == ["facts"]:
+ return facts()
+ print(__doc__, file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/ci-test.py b/scripts/ci-test.py
index a47bd215..e148a643 100755
--- a/scripts/ci-test.py
+++ b/scripts/ci-test.py
@@ -3,15 +3,18 @@
scripts/ci-test.py all every lane in one go test (make test)
scripts/ci-test.py lane NAME one lane (make test-lane LANE=NAME)
- scripts/ci-test.py shard the lane AMADAN_SHARD names (make test-shard)
+ scripts/ci-test.py shard the shard AMADAN_SHARD names (make ci-shard)
scripts/ci-test.py quarantine the quarantined tests (make test-quarantine)
+ scripts/ci-test.py compile compile every package once (make ci-compile)
scripts/ci-test.py lanes print each lane and its packages
The slow packages each have a lane of their own and "rest" holds every
other package. CI runs the lanes side by side as the shards of one step,
-.amadan/ci.d/30-test@N: amadan runs separate steps one after another, and
+.amadan/ci.d/20-check@N: amadan runs separate steps one after another, and
a step's @N shards are how it runs work in parallel. A lane's packages
-pass or fail in that shard's own log.
+pass or fail in that shard's own log. The quarantine, the runner host
+checks (make runner-host) and the static checks are shards of the same
+step, after the lanes.
Results are cached: go test replays a pass for a package whose test
binary, declared files and environment are unchanged (internal/testci
@@ -35,16 +38,52 @@ MODULE = "amadan.net/oficina/equipo"
TAGS = "testbuild"
TIMEOUT = "15m"
-# Lane order is the shard index: shard 0 runs the first lane. Keep the
-# count in .amadan/ci.d/30-test@N equal to the number of lanes.
+# Lane order is the shard index: shard 0 runs the first lane. After the
+# lanes come EXTRA_SHARDS. Keep the count in .amadan/ci.d/20-check@N equal
+# to the number of lanes plus the extra shards.
+#
+# A lane is (name, packages, tests). With tests, the lane runs only those
+# of its one package: "TestX" is a test, "TestX/name" one of its subtests,
+# and anything starting with ^ is a regular expression over test names.
+# A lane of the same package without tests runs everything the others do
+# not name, so a new test always lands somewhere. Split a package when its
+# lane is the slowest shard, by the times its shard prints; the measured
+# seconds beside each lane are test time on a 32 CPU hosted machine.
+HEADLESS, RUNNER, EQUIPOTEST = "./internal/headless", "./internal/runner", "./internal/equipotest"
LANES = [
- ("headless", ["./internal/headless"]),
- ("thintest", ["./internal/thintest"]),
- ("directlive", ["./internal/directlive"]),
- ("runner-thin", ["./internal/runner/thin"]),
- ("runner", ["./internal/runner"]),
- ("contracts", ["./internal/equipotest", "./internal/plan3test"]),
- ("rest", None), # every package no other lane names
+ ("headless-work", [HEADLESS], ["TestHeadless/4c_rebase", "TestHeadless/4b_ask", "TestHeadless/4c_checks_card", "TestHeadless/4_step_crash"]), # 54
+ ("headless-review", [HEADLESS], ["TestHeadless/4_review", "TestHeadless/2b_access", "TestHeadless/runner_crash", "TestHeadless/2b_first_message", "TestHeadless/4_checks_honest", "TestHeadless/7_stream_resume", "TestHeadless/2b_notebook", "TestHeadless/2b_move_in"]), # 50
+ ("headless-connections", [HEADLESS], ["TestHeadlessConnections"]), # 52 without the quarantined
+ ("headless-mac", [HEADLESS], ["TestMacWorker", "TestHeadlessAttachments", "TestHeadlessPrewarm"]), # 43
+ ("headless-guards", [HEADLESS], ["TestHeadlessCopyRotation", "TestHeadlessPolicyGuards", "TestHeadlessRunnerKillLeavesNoCopies", "TestHeadlessNewHouseRuleStartsFresh"]), # 41
+ ("headless-rest", [HEADLESS], None), # 52 of TestHeadless and the small ones
+ ("thintest", ["./internal/thintest"], None), # 47
+ # directlive stays whole: two lanes of it side by side both failed
+ # with provider_account_containment (run dd7960c).
+ ("directlive", ["./internal/directlive"], None), # 88
+ ("runner-thin", ["./internal/runner/thin"], None), # 38
+ ("runner-bug", [RUNNER], ["TestDirectBugWorkflow", "TestEnrolKeepsTheRole"]), # 65
+ ("runner-plans", [RUNNER], ["TestPlanWorkflowCandidateOrder", "TestPlanWorkflowFeature", "TestCoordinatorRecoveryCallRefusalKeepsServing", "TestCoordinatorRefusalMatrix"]), # 54
+ ("runner-rest", [RUNNER], None), # 36
+ ("equipotest-a", [EQUIPOTEST], ["^Test[A-C]"]), # the whole package: 183
+ ("equipotest-d", [EQUIPOTEST], ["^Test[D-P]"]),
+ ("equipotest-r", [EQUIPOTEST], ["^TestR"]),
+ ("equipotest-rest", [EQUIPOTEST], None),
+ ("plan3test", ["./internal/plan3test"], None), # 35
+ ("rest", None, None), # every package no other lane names
+]
+
+# Shards after the lanes: work that is not a lane of packages but runs
+# beside them, each a list of make targets run in order. The static
+# checks are here too: hosted CI runs steps one after another and only
+# shards side by side, so a lint step of its own would only add its time.
+EXTRA_SHARDS = [
+ ["test-quarantine"],
+ ["runner-host"],
+ ["runner-dead-references", "build", "vet", "fmt-check", "budget", "migration-check"],
+ ["staticcheck"],
+ ["govulncheck"],
+ ["gitleaks"],
]
# Packages whose results must never come from the cache, with the reason.
@@ -73,14 +112,42 @@ def all_packages():
def lane_packages(name):
- for lane, packages in LANES:
+ for lane, packages, _ in LANES:
if lane != name:
continue
if packages is not None:
return packages
- named = {p for _, ps in LANES if ps for p in ps}
+ named = {p for _, ps, _ in LANES if ps for p in ps}
return [p for p in all_packages() if p not in named]
- sys.exit(f"ci-test: unknown lane {name!r}; lanes: {', '.join(l for l, _ in LANES)}")
+ sys.exit(f"ci-test: unknown lane {name!r}; lanes: {', '.join(l for l, _, _ in LANES)}")
+
+
+def test_pattern(tests):
+ """The go test -run or -skip pattern naming exactly tests."""
+ parts = []
+ for t in tests:
+ if t.startswith("^"):
+ parts.append(t)
+ else:
+ parts.append("/".join("^" + re.escape(level) + "$" for level in t.split("/")))
+ return "|".join(parts)
+
+
+def lane_flags(name):
+ """-run for a lane that names tests; -skip, for a lane that does not,
+ of every test the other lanes of its package name."""
+ for lane, packages, tests in LANES:
+ if lane != name:
+ continue
+ if tests:
+ if packages is None or len(packages) != 1:
+ sys.exit(f"ci-test: lane {name} names tests, so it must name one package")
+ return ["-run", test_pattern(tests)]
+ if packages is None:
+ return []
+ taken = [t for other, ps, ts in LANES if other != name and ts and ps[0] in packages for t in ts]
+ return ["-skip", test_pattern(taken)] if taken else []
+ return []
def fingerprint():
@@ -140,7 +207,7 @@ def rastrillo():
"RASTRILLO", "go run amadan.net/rastrillo/rastrillo/cmd/rastrillo"))
-def budget_test(packages, env):
+def budget_test(packages, env, flags=()):
"""One rastrillo budget test over packages; returns its exit status."""
status = 0
cached = [p for p in packages if p not in UNCACHED]
@@ -150,8 +217,8 @@ def budget_test(packages, env):
continue
for p in group if extra else []:
print(f"uncached: {p}: {UNCACHED[p]}", flush=True)
- cmd = rastrillo() + ["budget", "test", "-tags", TAGS, "-timeout", TIMEOUT] + extra + group
- print("+ " + " ".join(cmd), flush=True)
+ cmd = rastrillo() + ["budget", "test", "-tags", TAGS, "-timeout", TIMEOUT] + extra + list(flags) + group
+ print("+ " + " ".join(shlex.quote(c) for c in cmd), flush=True)
status = run_reporting_misses(cmd, env) or status
return status
@@ -181,7 +248,7 @@ def run_reporting_misses(cmd, env):
def run_lane(name):
packages = lane_packages(name)
print(f"test lane {name}: {' '.join(packages)}", flush=True)
- return budget_test(packages, budget_env(environment(False)))
+ return budget_test(packages, budget_env(environment(False)), lane_flags(name))
def run_all():
@@ -194,13 +261,30 @@ def run_all():
return budget_test(all_packages(), env)
+def run_compile():
+ """Compile every package, as the tests build them, and link nothing:
+ what stays is the build cache the shards then share. Each shard still
+ compiles its own test files and links its own binary."""
+ cmd = ["go", "build", "-tags", TAGS, "./..."]
+ print("+ " + " ".join(cmd), flush=True)
+ return subprocess.call(cmd)
+
+
def run_shard():
index = int(os.environ.get("AMADAN_SHARD", "-1"))
count = int(os.environ.get("AMADAN_SHARD_COUNT", "0"))
- if count != len(LANES) or not 0 <= index < count:
- sys.exit(f"ci-test: shard {index} of {count}, but there are {len(LANES)} lanes; "
- f"name the step 30-test@{len(LANES)}")
- return run_lane(LANES[index][0])
+ shards = len(LANES) + len(EXTRA_SHARDS)
+ if count != shards or not 0 <= index < count:
+ sys.exit(f"ci-test: shard {index} of {count}, but there are {len(LANES)} lanes and "
+ f"{len(EXTRA_SHARDS)} extra shards; name the step 20-check@{shards}")
+ if index < len(LANES):
+ return run_lane(LANES[index][0])
+ targets = EXTRA_SHARDS[index - len(LANES)]
+ print(f"shard {index}: make {' '.join(targets)}", flush=True)
+ # runner-host reruns tests the lanes ran; the quarantine shard beside
+ # it is where a quarantined one of them runs, with its retry.
+ env = dict(os.environ, EQUIPO_QUARANTINE="skip") if targets == ["runner-host"] else None
+ return subprocess.call(["make", "--no-print-directory"] + targets, env=env)
# The quarantine.
@@ -310,11 +394,13 @@ def main(argv):
return run_lane(argv[1])
if argv == ["shard"]:
return run_shard()
+ if argv == ["compile"]:
+ return run_compile()
if argv == ["quarantine"]:
return run_quarantine()
if argv == ["lanes"]:
- for name, _ in LANES:
- print(name + ": " + " ".join(lane_packages(name)))
+ for name, _, _ in LANES:
+ print(name + ": " + " ".join(lane_packages(name) + lane_flags(name)))
return 0
print(__doc__, file=sys.stderr)
return 2
diff --git a/scripts/runner-prerequisites.py b/scripts/runner-prerequisites.py
index 54abe80f..15e62e3c 100644
--- a/scripts/runner-prerequisites.py
+++ b/scripts/runner-prerequisites.py
@@ -3,13 +3,19 @@
import hashlib
import os
from pathlib import Path
+import platform
import re
import shutil
import sys
root = Path(__file__).resolve().parent.parent
-source = (root / "internal/runner/provider/codex/launcher.go").read_text()
-pin = re.search(r'const ExecutableSHA256 = "([a-f0-9]{64})"', source)
+codex = root / "internal/runner/provider/codex"
+# The certified pin on x86-64; the same release's arm64 build on an arm64
+# CI machine (pins.go), where no certified release runs.
+if platform.machine().lower() in ("aarch64", "arm64"):
+ pin = re.search(r'ExecutableSHA256Arm64\s+= "([a-f0-9]{64})"', (codex / "pins.go").read_text())
+else:
+ pin = re.search(r'const ExecutableSHA256 = "([a-f0-9]{64})"', (codex / "launcher.go").read_text())
path = os.environ.get("EQUIPO_CODEX_PATH") or shutil.which("codex")
try:
if not pin or not path or not os.access(path, os.X_OK):