Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/9fcce7e83fe160e7 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#583 (code only) closed derived `9fcce7e83fe160e7` #583 Imported from GitHub aien-dev/aien-sovereign-core-mv#583 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `26303a9ec008ae380c860095f275af12b0d443b7` · Head `902198547de712a2575449fac68eac5bea35d513` ### Apply it ``` git checkout -b patch-9fcce7e83fe160e7 26303a9ec008ae380c860095f275af12b0d443b7 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/9fcce7e83fe160e7.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 583 902198547de712a2575449fac68eac5bea35d513 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":583,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/583","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:35Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index f1d77dbe..6e6fc607 100644 --- a/.crumb +++ b/.crumb @@ -65,68 +65,68 @@ "children": [ { "digest": "4e7f370019e67f6c71565d1544530851eb1b3b1bed61c2712f4ac7d9614a89bf", - "last_commit": "6bbe2ec2", + "last_commit": "6bbe2ec", "name": "crates/aien-allen", "purpose": "ALLEN identity gate: resolve-only subject check, host pin record, deployment record (ADR 0035). " }, { "digest": "40a231c50dba92af7de2527ab33879c5d1eaaa6e7ea5d6a5ebaa9d60c7542075", - "last_commit": "b9b52f9c", + "last_commit": "b9b52f9", "name": "crates/aien-allen-memory", "purpose": "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying for" }, { "digest": "44dc482b8c9db8919a68ec69b019cd77967232a6ec8b1910c0dfe3cd4d71f141", - "last_commit": "b9b52f9c", + "last_commit": "b9b52f9", "name": "crates/aien-allen-profile", "purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; " }, { "digest": "f5571bcc0bb95b44dd8bf8f0b47ded3bcb1e1ee76c81b4ff5edb87ac237d66d8", - "last_commit": "f8eea420", + "last_commit": "f8eea42", "name": "crates/aien-cli", "purpose": "" }, { "digest": "25fd9f8afbea19702750f8ddba2ef4aeafc5bc4515aa695340a5af6931989c03", - "last_commit": "8cca8020", + "last_commit": "8cca802", "name": "crates/aien-scheduler/src/bin", "purpose": "" }, { "digest": "a0a981f6168d15e43a6b036c3aa82d44547aadfc3b6c62139a5a3afab0644514", - "last_commit": "8cca8020", + "last_commit": "8cca802", "name": "crates/spark-cockpit-rs", "purpose": "" }, { "digest": "f38ccede5d794040581cf48d409424c923d705a2fc206140b52691ef7fb186ef", - "last_commit": "deff6f7a", + "last_commit": "deff6f7", "name": "scripts", "purpose": "" }, { "digest": "75e439cb2ae120e1807af894b70b6454971028f5527f56451f9d6558f503c88b", - "last_commit": "fa73e778", + "last_commit": "fa73e77", "name": "skills", "purpose": "" }, { - "digest": "b95ea9baa15ce7ddc69a3ef4dc25cdcccba52ec1f5fd99e19f0f24af9181a306", - "last_commit": "247e0927", + "digest": "c79a239162623ddeba74973ab18ef6e3e9c6ecd581f5890215700510093da830", + "last_commit": "8b29aa0", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], - "children_root": "sha256:7d8cf5937a13dd896fe511aee80a0873f4917a0a5eb07cbe0fe3690c0c878cbb", - "compiled_at": "2026-10-16T15:26:31Z", + "children_root": "sha256:e7293c3b3b3e851866f34a16afe89225d8e69c6d3a04669054e6f8f04971819d", + "compiled_at": "2026-10-16T18:44:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:5c3262fb97f4051b7780f820f039da497a16ac9d1cf8d077e593d3b2e786ba89", + "digest": "sha256:47314ef30a6c97a6e1e877babdab918bf58502643a900b554e2b3003e8c99758", "evidence_files": 1578, "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160", - "files": 5889, - "generated_at_commit": "228809d2f65ded6e8bbc011bc817209d82255bb5", - "source_tree": "sha256:7bdcd0cf99ffd24054c17de9287bf4506d8059c855d566eab42a2280024ec2a2" + "files": 5894, + "generated_at_commit": "8b29aa05a529edaca12710fcc9e6f43c208e240e", + "source_tree": "sha256:1f3cab54db2f9d2e07a7d832de43c8c8137a58d3205257501739f5c9351b489d" } }, "history": [], diff --git a/tools/aien-local-ci/.crumb b/tools/aien-local-ci/.crumb index 602ce99d..0e597780 100644 --- a/tools/aien-local-ci/.crumb +++ b/tools/aien-local-ci/.crumb @@ -3,14 +3,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-16T05:31:46Z", + "compiled_at": "2026-10-16T10:11:29Z", "compiler": "crumb-compile/1", - "digest": "sha256:b95ea9baa15ce7ddc69a3ef4dc25cdcccba52ec1f5fd99e19f0f24af9181a306", + "digest": "sha256:c79a239162623ddeba74973ab18ef6e3e9c6ecd581f5890215700510093da830", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 12, - "generated_at_commit": "db857500b1867559a663d4aa1c78b8200655d6b5", - "source_tree": "sha256:f5eb6931b7a33500be48cede1b99e7448b5369a48a401e3dc2ef56aba3915525" + "files": 16, + "generated_at_commit": "c184a1d6f0431066ff4a50bdd088e3db6f99059e", + "source_tree": "sha256:2e5d791a4426437eb9e4e69536f98620d3f1e496ffe3d76776ce2deabba34a93" } }, "layer": "infra", diff --git a/tools/aien-local-ci/README.md b/tools/aien-local-ci/README.md index af8d9224..a873f9ca 100644 --- a/tools/aien-local-ci/README.md +++ b/tools/aien-local-ci/README.md @@ -18,6 +18,10 @@ AIENOS. | `tests/run.sh` | proofs of the contract on this host (33 checks with two wt.sh worktrees present) | | `pipeline.sh` | ADR 0033 phase 3: publish verified bundles to aien-receipts, rerun the GitHub thin gate, merge `ready-to-merge` PRs behind guards | | `tests/pipeline_test.sh` | offline proofs of `pipeline.sh` with fake `gh`, fake `aien-test` and throwaway git repositories (56 checks) | +| `cron-tick.sh` | the cron entry point (every 2 min): worker keepalive + one `pipeline.sh round`, thinned out while quiet (below); installed by `install.sh` to `~/.local/lib/aien-local-ci/` | +| `tests/cron_tick_test.sh` | offline proofs of `cron-tick.sh` (PAUSE, QUIET-SINCE, WAKE, stale heartbeat, garbage markers; 17 checks) | +| `prime` | warm-standby prime map: which cargo builds of main seed `target//pr` | +| `cold-warm-proof.sh` | periodic proof that a warm pr target gives the same verdicts and receipt cores as a cold one | ## C8 exec contract @@ -206,3 +210,85 @@ Measured 2026-10-11 (sovereign-core 5ef7720, 20 cores, caches seeded): cold `car --locked --offline` as aien-run 65.0 s (target dir 27 GB); warm rebuild after touching one crate 2.2 s. After the read-only home change: full workspace build of worktree 62542eb into the existing `pr` target 49.9 s (new worktree path, so workspace crates rebuilt; dependencies reused), exit 0. + +## Power saving and warm standby (2026-10-16) + +Markers, all in `~/.local/state/aien-local-ci/` (the merge train and anything else may read them): + +| marker | written by | meaning | +|---|---|---| +| `QUIET-SINCE` | the worker, only with `--github` | one line ` `: the time of the last activity the worker saw. Present = nothing moved since then. Removed the moment anything moves. Absent, empty or not a number = **not quiet** (readers fail open to full cadence). | +| `WAKE` | anyone (`touch`) | "full cadence now". Never removed by a reader: each reader compares its mtime with the last one it acted on (the worker in memory, `cron-tick.sh` against `cron-last-round`). | +| `PAUSE` | the operator | unchanged: `cron-tick.sh` exits at once (no keepalive, no round). PAUSE present -> absent wakes both the worker and the next tick. | +| `cron-last-round` | `cron-tick.sh` | mtime = start of its last `pipeline.sh round`. | +| `warm/.json` | the worker | `{"class":"pr","complete":true,"primed_from_main":,"utc":..}`: `target//pr` was primed from that main. Removed before priming starts and by `--cold`, `gc.sh` and the proof; written only when every prime line exited 0. | + +Activity (worker): a trigger file, a GitHub poll that differs from the previous one for a repository (new head, +`ready-to-merge` added or removed, main moved), a head run that had not already failed to run in this loop, a wake. +Priming is never activity. + +Cheap check vs expensive work. The cheap check never backs off. Every `--poll` (60 s, as installed) the worker makes +ONE GraphQL call for all enrolled repositories (`gh api graphql`: per repository the main head and up to 50 open pull +request heads with their labels). A repository the answer does not cover (no main line, or a second page of pull +requests or labels: `hasNextPage`) is polled the old way (two REST calls), and a failed probe polls every repository the old way; a partial answer never reads as "no pull +requests". Measured on 2026-10-16 for the 11 enrolled repositories (`worker --probe`, 5 runs): about 1.0 s wall and +0.07 CPU-s (user+sys) per probe, against about 13.4 s wall and 1.4 CPU-s for the 22 REST calls it replaces; at 60 s +that is about 0.1 % of one core. So a new head or label is seen within one poll (60 s), quiet or not, and its gates +start in that round. Only the expensive work backs off: retrying a head that already failed to run (a fetch and a +sibling sync) waits the backed-off interval (60 s, doubling to `--backoff-cap` 900 s once nothing moved for +`--quiet-after` 600 s), and `cron-tick.sh` thins pipeline rounds while QUIET-SINCE is old. A label seen while quiet +removes QUIET-SINCE at once, so the next cron tick (at most 2 min) runs the merge round. The worker sleeps in 5 s +slices that only stat WAKE, PAUSE and the trigger dir and rewrite the heartbeat (no network, no process), so WAKE, +PAUSE removal or a trigger file ends the sleep within 5 s. + +`cron-tick.sh`: the keepalive runs every tick. The round is skipped only while QUIET-SINCE is at least 600 s old, +the worker heartbeat is younger than 1200 s (a dead or hung worker never silences the pipeline) and the last round +started less than 600 s ago; so while quiet there is still one round every 10 min. Each round logs its own child +CPU (`round rc=.. child_cpu user=..s sys=..s`). + +Fetching: a run fetches its trusted clone only when `git ls-remote origin`, mapped through `remote.origin.fetch`, +shows a ref (or any tag) the clone does not have at the same sha, or the commit is missing; anything unclear +fetches as before. At most once per clone per round. Sibling clones are refreshed the same way once per round, and +`wt.sh sync` runs only when the clone's refs changed since the last sync in that round. + +Warm standby: when nothing waits and the quiet flag is clear (`quietlock check` rc 0, else `~/workspace/.spark-quiet` +absent), the worker primes one repository whose `warm/.json` does not name the main head polled this round: +it checks out that main head (asserted on the base line and equal to the polled head) with its siblings and runs +each `prime` line through the exec helper, profile `host`, `CARGO_TARGET_DIR=/var/lib/aien-run/target//pr`. +Main is trusted, so its build may seed the lower class; nothing ever writes the `main` class from priming, and a pr +build never reaches `main`. Every 5 s it checks the trigger dir, WAKE, PAUSE and the quiet flag, and once a minute +GitHub (the same one-call probe) for a head without a bundle that has not already failed to run in this loop (a +head that errored never gets a bundle, so it must not stop priming every round); any of them sends SIGTERM to the +helper (its trap stops the scope). Only a new head, WAKE, PAUSE removal or a trigger file counts as activity, and +then the loop runs the next round at once instead of sleeping; the quiet flag, PAUSE present or the disk bound do +neither. Everything priming runs (cargo, du, the wipe) runs as `nice -n 19 ionice -c 3` inside the sandbox, below +the gates. Never gb10, never QEMU, never a booted VM. + +Disk bound. Priming takes the target dir lock, `/locks/target/.lock` (the flock the +runner holds around a cargo gate, sc #584). It retries every 5 s and gives up on any stop reason, and never holds the +GPU or proof locks. Holding it, priming measures `du -sk target//{pr,main}` (inside the sandbox, as aien-run) +and the filesystem's free space, then: +* total (main + pr) at most `--target-quota-gb` (120, as gc.sh) and at least `--disk-floor-gb` (50) free: prime; +* over, but main alone fits and emptying pr restores the floor: empty pr (the lowest class, a cache the next run + rebuilds), then prime; +* otherwise (main alone over the quota, or the floor even with pr empty): do not prime, and leave pr as it is (what + PR runs put there is gc.sh's to bound). The outcome is `cold` in the journal, that main is not tried again, and no + bundle claims warm until space is freed. + +While priming, free space is checked every 5 s and the repository total once a minute; going over, or a check that +cannot measure, stops the build, empties pr and leaves it cold. After the last line the total is measured again under the same rule. The worker log +carries the disk before and after (`PRIME disk before: ...`). + +Every bundle carries a signed top-level member `target`: `{"class":"main|pr|unsandboxed","warm":bool, +"primed_from_main":sha|null,"primed_utc":..,"cold":bool}`. `warm` = the complete record existed and the pr dir was +not empty when the run started. It means "primed from main "; the pr dir may also hold earlier PR builds, as it +always has. `bundle::validate` ignores members it does not know and the signature covers every member, so this +needs no schema bump; `target` is the first such member, on purpose. + +`worker --once REPO SHA --cold` empties `target//pr` from inside the sandbox first (pr heads only; the main +class is never emptied); `worker --once REPO MAIN --prime-only [--cold]` primes by hand. `cold-warm-proof.sh +` runs warm (empty, prime, run) then cold (empty, run), both `--no-cache` into their own state dirs, and +compares per gate the verdict and the receipt core minus the stdout/stderr digests. It refuses unless PAUSE exists +and the live worker is stopped, because it shares the pr dir. Not built: a crumb tool cache (the gate builds it in +`$TMP` from its pin in about 3 s, inside the repos' `run.sh`) and a boot image per main sha (aienos `ck_gates.sh` +builds its images itself; both need repo-side gate changes). diff --git a/tools/aien-local-ci/cold-warm-proof.sh b/tools/aien-local-ci/cold-warm-proof.sh new file mode 100755 index 00000000..47361caa --- /dev/null +++ b/tools/aien-local-ci/cold-warm-proof.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# cold-warm-proof.sh: the periodic proof that a warm pull request target dir gives the same answers as a cold one. +# +# cold-warm-proof.sh +# +# Order (so the warm run is warm from priming, not from the cold run): +# 1. empty target//pr, prime it from the trusted clone's origin/main, run the head (warm), --no-cache +# 2. empty target//pr, run the head (cold), --no-cache +# 3. compare: per gate, the verdict and the digest of the receipt's `core` minus stdout_sha256/stderr_sha256 (cargo's +# "Compiling" lines differ between cold and warm by construction; `volatile`, the timings, is never compared); the warm bundle must say target.warm=true, the cold one target.cold=true. Exit 0 only if equal. +# 4. prime again from main, so the live worker finds the dir warm. +# +# It shares /var/lib/aien-run/target//pr with the live worker (the exec helper allows no other dir), so it +# REFUSES unless ~/.local/state/aien-local-ci/PAUSE exists and the live worker is not running: +# touch ~/.local/state/aien-local-ci/PAUSE && aien-local-ci stop +# Its bundles go to a separate state dir (never published, no --github). Results: /result.txt. +set -euo pipefail +repo=${1:?repo}; sha=${2:?pr-head-sha40} +[[ $repo =~ ^[A-Za-z0-9_-][A-Za-z0-9._-]*$ && $sha =~ ^[0-9a-f]{40}$ ]] || { echo "bad repo or sha" >&2; exit 2; } +BIN=${AIEN_TEST_BIN:-$HOME/workspace/pipeline/target-sc/release/aien-test} +CLONES=${AIEN_CLONES:-$HOME/workspace/pipeline/clones} +LIVE=${AIEN_STATE:-$HOME/.local/state/aien-local-ci} +[[ -e $LIVE/PAUSE ]] || { echo "refused: $LIVE/PAUSE must exist (the proof empties the shared pr target dir)" >&2; exit 2; } +if [[ -f $LIVE/worker.pid ]] && kill -0 "$(cat "$LIVE/worker.pid")" 2>/dev/null; then + echo "refused: the live worker (pid $(cat "$LIVE/worker.pid")) is running; aien-local-ci stop first" >&2; exit 2 +fi +P=${AIEN_PROOF_DIR:-$HOME/.local/state/aien-local-ci-proof/$repo-${sha:0:12}-$(date -u +%Y%m%dT%H%M%SZ)} +mkdir -p "$P/warm" "$P/cold" +git -C "$CLONES/$repo" fetch -q --all +main=$(git -C "$CLONES/$repo" rev-parse --verify 'refs/remotes/origin/main^{commit}') +w() { "$BIN" worker --clones "$CLONES" --sandbox user "$@"; } +# The live warm record must never outlive what this script does to the shared dir. +rm -f "$LIVE/warm/$repo.json" +t0=$(date +%s) +w --state-dir "$P/warm" --once "$repo" "$main" --prime-only --cold | tee "$P/warm/prime.txt" +t1=$(date +%s) +w --state-dir "$P/warm" --once "$repo" "$sha" --no-cache > "$P/warm/run.txt" || true +t2=$(date +%s) +w --state-dir "$P/cold" --once "$repo" "$sha" --no-cache --cold > "$P/cold/run.txt" || true +t3=$(date +%s) +# Re-prime for the live worker, recorded in the live state dir. +w --state-dir "$LIVE" --once "$repo" "$main" --prime-only | tee "$P/warm/reprime.txt" || true +gates() { # -> " " per receipt, sorted + for f in "$1/evidence/$repo/$sha"/*.json; do + jq -r '[.core.gate, .core.derived_verdict, (.core | del(.stdout_sha256, .stderr_sha256) | tostring)] | @tsv' "$f" \ + | while IFS=$'\t' read -r g v core; do printf '%s %s %s\n' "$g" "$v" "$(printf '%s' "$core" | jq -cS . | sha256sum | cut -c1-16)"; done + done | sort +} +gates "$P/warm" > "$P/warm/gates.txt"; gates "$P/cold" > "$P/cold/gates.txt" +wb=$P/warm/bundles/$repo/$sha/bundle.json cb=$P/cold/bundles/$repo/$sha/bundle.json +rc=0 +{ + echo "repo=$repo head=$sha main=$main prime_s=$((t1 - t0)) warm_run_s=$((t2 - t1)) cold_run_s=$((t3 - t2))" + echo "warm target: $(jq -c .target "$wb" 2>/dev/null)" + echo "cold target: $(jq -c .target "$cb" 2>/dev/null)" + jq -e '.target.warm == true and .target.primed_from_main == "'"$main"'"' "$wb" >/dev/null 2>&1 || { echo "FAIL warm bundle does not say warm from $main"; rc=1; } + jq -e '.target.cold == true and .target.warm == false' "$cb" >/dev/null 2>&1 || { echo "FAIL cold bundle does not say cold"; rc=1; } + [[ -s $P/warm/gates.txt ]] || { echo "FAIL no receipts"; rc=1; } + if diff "$P/cold/gates.txt" "$P/warm/gates.txt" > "$P/diff.txt"; then echo "EQUAL $(wc -l < "$P/warm/gates.txt") gates (verdict + receipt core digest)" + else echo "DIFFERENT (see $P/diff.txt)"; rc=1; fi +} | tee "$P/result.txt" +grep -q '^FAIL\|^DIFFERENT' "$P/result.txt" && exit 1 +exit $rc diff --git a/tools/aien-local-ci/cron-tick.sh b/tools/aien-local-ci/cron-tick.sh new file mode 100755 index 00000000..2e1a723f --- /dev/null +++ b/tools/aien-local-ci/cron-tick.sh @@ -0,0 +1,46 @@ +#!/bin/bash +# AIEN Spark pipeline tick (cron, every 2 min; no systemd by rule). +# 1) keeps the continuous worker (--github, all enrolled repos) alive: `aien-local-ci start` is a no-op when it runs. +# 2) runs one pipeline round: publish signed bundles, rerun stale checks, merge green PRs labelled ready-to-merge. +# Stop everything: touch ~/.local/state/aien-local-ci/PAUSE ; aien-local-ci stop +# +# Power saving (2026-10-16). Markers in $S (see tools/aien-local-ci/README.md, "Power saving"): +# QUIET-SINCE written by the worker: " " of the last activity it saw; absent = not quiet. +# WAKE touched by anyone to ask for full cadence now; never removed by a reader. +# PAUSE unchanged: present = this script exits at once (nothing runs, the worker is not restarted). +# While QUIET-SINCE is at least QUIET_AFTER old (and the worker heartbeat is fresh), the round runs only every +# QUIET_ROUND seconds; WAKE newer than the last round, or PAUSE just removed, runs it at once. Anything unreadable +# runs the round (fail open = full cadence). The keepalive below is never skipped. +export PATH=$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin +S=${AIEN_STATE:-$HOME/.local/state/aien-local-ci} +LIB=${AIEN_CI_LIB:-$HOME/.local/lib/aien-local-ci} +QUIET_AFTER=${AIEN_QUIET_AFTER:-600} # seconds of no activity before rounds thin out +QUIET_ROUND=${AIEN_QUIET_ROUND:-600} # while quiet, one round this often +BEAT_MAX=${AIEN_BEAT_MAX:-1200} # heartbeat older than this: the worker is not trusted to be watching +if [ -e "$S/PAUSE" ]; then touch "$S/.paused-seen" 2>/dev/null; exit 0; fi +nice -n 10 aien-local-ci start --github >/dev/null + +now=$(date +%s) +age() { local m; m=$(stat -c %Y "$1" 2>/dev/null) || { echo -1; return; }; echo $(( now - m )); } +why="" +if [ -e "$S/.paused-seen" ]; then rm -f "$S/.paused-seen"; why="PAUSE removed" +elif [ -e "$S/WAKE" ] && { [ ! -e "$S/cron-last-round" ] || [ "$S/WAKE" -nt "$S/cron-last-round" ]; }; then why="WAKE" +fi +if [ -z "$why" ]; then + since=$(awk 'NR==1{print $1}' "$S/QUIET-SINCE" 2>/dev/null) + beat=$(age "$S/worker.heartbeat") + last=$(age "$S/cron-last-round") + if [[ $since =~ ^[0-9]+$ ]] && (( now - since >= QUIET_AFTER )) && (( beat >= 0 && beat < BEAT_MAX )) \ + && (( last >= 0 && last < QUIET_ROUND )); then + echo "$(date -u +%FT%TZ) skip quiet since=$since last_round_age=${last}s" + exit 0 + fi +fi +[ -n "$why" ] && echo "$(date -u +%FT%TZ) wake: $why" +touch "$S/cron-last-round" +nice -n 10 /bin/bash "$LIB/pipeline.sh" round +rc=$? +# The round's own CPU (this shell's children), so the idle cost is measured, not guessed. +cpu=$(times | awk 'NR==2{for(i=1;i<=2;i++){split($i,a,"m"); sub("s","",a[2]); t[i]=a[1]*60+a[2]} printf "user=%.2fs sys=%.2fs", t[1], t[2]}') +echo "$(date -u +%FT%TZ) round rc=$rc child_cpu $cpu" +exit $rc diff --git a/tools/aien-local-ci/gc.sh b/tools/aien-local-ci/gc.sh index 5c953c10..33c471b6 100755 --- a/tools/aien-local-ci/gc.sh +++ b/tools/aien-local-ci/gc.sh @@ -48,6 +48,8 @@ for r in "$RUN_HOME"/target/*/; do for sub in pr main; do [[ -d $r/$sub ]] || continue act sudo -n find "$r/$sub" -mindepth 1 -delete + # A wiped pr dir is no longer warm (aien-test worker warm standby record). + if [[ $sub == pr ]]; then act rm -f "$HOME/.local/state/aien-local-ci/warm/$(basename "$r").json"; fi (( apply )) || break used_gb=$(( $(sudo -n du -sk "$r" | cut -f1) / 1024 / 1024 )) (( used_gb > quota_gb )) || break diff --git a/tools/aien-local-ci/install.sh b/tools/aien-local-ci/install.sh index 807592a3..e2f88aaf 100755 --- a/tools/aien-local-ci/install.sh +++ b/tools/aien-local-ci/install.sh @@ -132,4 +132,14 @@ S visudo -cf "$tmp/sudoers" >/dev/null S install -o root -g root -m 0440 "$tmp/sudoers" /etc/sudoers.d/aien-local-ci S visudo -c >/dev/null && say "sudoers OK" +# 6. cron tick (operator-owned; the crontab line itself is the operator's: */2 * * * * $HOME/.local/lib/aien-local-ci/cron-tick.sh) +LIB=${AIEN_CI_LIB:-$OP_HOME/.local/lib/aien-local-ci} +install -d -m 0755 "$LIB" +if ! cmp -s "$here/cron-tick.sh" "$LIB/cron-tick.sh" 2>/dev/null; then + install -m 0755 "$here/cron-tick.sh" "$LIB/cron-tick.sh" + say "installed $LIB/cron-tick.sh" +else + say "$LIB/cron-tick.sh current" +fi + say "done. verify with: $here/tests/run.sh" diff --git a/tools/aien-local-ci/prime b/tools/aien-local-ci/prime new file mode 100644 index 00000000..c178f53f --- /dev/null +++ b/tools/aien-local-ci/prime @@ -0,0 +1,16 @@ +# prime: the warm-standby map (aien-test worker --prime; default beside the sibling map). +# After main moves in , the worker builds main's tree into /var/lib/aien-run/target//pr (the pull +# request class) inside the sandbox, so the next PR run starts warm. Main is trusted, so it may seed the lower +# class; nothing here ever writes the main class. Lowest priority: never while a head waits, the quiet flag is +# raised or PAUSE exists; a new head stops it. +# [K=V ...] cargo build|check|clippy|test (cargo test only with --no-run) +# Each line mirrors a cargo invocation of that repo's tests/gates/run.sh (same package set, flags and the env the +# compile sees), so cargo's fingerprints match and the gate reuses the artifacts. A line that does not match +# only costs build time; it can never change a verdict (cargo rebuilds what does not match). +aien-sovereign-core cargo check --workspace --all-targets +aien-sovereign-core cargo clippy --workspace --all-targets -- -D warnings +aien-sovereign-core CI=true AIEN_DEV_FALLBACK=1 cargo test --workspace --no-run +aienos cargo test --locked --offline -p aienos-crypto --no-run +aienos cargo clippy --locked --offline -p aienos-crypto --all-targets -- -D warnings +aienos cargo clippy -p aienos-infer --all-targets -- -D warnings +aienos cargo test -p aienos-infer --no-run diff --git a/tools/aien-local-ci/tests/cron_tick_test.sh b/tools/aien-local-ci/tests/cron_tick_test.sh new file mode 100644 index 00000000..f2c78d4b --- /dev/null +++ b/tools/aien-local-ci/tests/cron_tick_test.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# cron_tick_test.sh: offline proofs for tools/aien-local-ci/cron-tick.sh (power saving: QUIET-SINCE, WAKE, PAUSE). +# Fakes: aien-local-ci (logs "start") and pipeline.sh (logs "round"); a throwaway state directory. +# bash tools/aien-local-ci/tests/cron_tick_test.sh +set -euo pipefail +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +TICK=$HERE/../cron-tick.sh +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT +pass=0 fail=0 +ok() { pass=$((pass + 1)); echo "ok $*"; } +bad() { fail=$((fail + 1)); echo "FAIL $*"; } +export HOME=$T/home AIEN_STATE=$T/state AIEN_CI_LIB=$T/lib +mkdir -p "$HOME/.local/bin" "$AIEN_STATE" "$AIEN_CI_LIB" +LOG=$T/calls.log +printf '#!/bin/bash\necho "$*" >> %s\n' "$LOG" > "$HOME/.local/bin/aien-local-ci" +printf '#!/bin/bash\necho "round $*" >> %s\n' "$LOG" > "$AIEN_CI_LIB/pipeline.sh" +chmod +x "$HOME/.local/bin/aien-local-ci" "$AIEN_CI_LIB/pipeline.sh" +S=$AIEN_STATE +now=$(date +%s) +ago() { touch -d "@$(( now - $1 ))" "$2"; } +tick() { : > "$LOG"; bash "$TICK" > "$T/out" 2>&1 || true; } +ran() { grep -q '^round round$' "$LOG"; } +started() { grep -q '^start --github$' "$LOG"; } +reset() { rm -f "$S"/QUIET-SINCE "$S"/WAKE "$S"/PAUSE "$S"/.paused-seen "$S"/cron-last-round "$S"/worker.heartbeat; } +quiet() { echo "$(( now - $1 )) 2026-10-16T00:00:00Z" > "$S/QUIET-SINCE"; } # last activity $1 s ago +beat() { : > "$S/worker.heartbeat"; ago "$1" "$S/worker.heartbeat"; } +last() { : > "$S/cron-last-round"; ago "$1" "$S/cron-last-round"; } + +reset; tick +{ ran && started; } && ok "no markers: keepalive and round" || bad "no markers" + +reset; : > "$S/PAUSE"; tick +{ ! ran && ! started; } && ok "PAUSE: nothing runs, the worker is not started" || bad "PAUSE" +[[ -e $S/.paused-seen ]] && ok "PAUSE leaves .paused-seen" || bad ".paused-seen missing" + +rm -f "$S/PAUSE"; quiet 3000; beat 10; last 60; tick +{ ran && grep -q 'wake: PAUSE removed' "$T/out"; } && ok "PAUSE removal runs the round even while quiet" || bad "PAUSE removal" +[[ ! -e $S/.paused-seen ]] && ok ".paused-seen consumed" || bad ".paused-seen kept" + +reset; quiet 100; beat 10; last 60; tick +ran && ok "QUIET-SINCE younger than QUIET_AFTER: full cadence" || bad "young QUIET-SINCE skipped" + +reset; quiet 3000; beat 10; last 60; tick +{ ! ran && started && grep -q 'skip quiet' "$T/out"; } && ok "quiet: round skipped, keepalive kept" || bad "quiet skip" + +reset; quiet 3000; beat 10; last 700; tick +ran && ok "quiet: one round every 10 min" || bad "10-min fallback" + +reset; quiet 3000; beat 10; last 60; : > "$S/WAKE"; tick +{ ran && grep -q 'wake: WAKE' "$T/out"; } && ok "WAKE newer than the last round runs it" || bad "WAKE" +tick +! ran && ok "the same WAKE wakes once" || bad "WAKE woke twice" +[[ -e $S/WAKE ]] && ok "WAKE is never removed by cron-tick" || bad "WAKE removed" + +reset; quiet 3000; beat 5000; last 60; tick +ran && ok "stale heartbeat: QUIET-SINCE ignored" || bad "stale heartbeat honoured" + +reset; quiet 3000; last 60; tick +ran && ok "no heartbeat: QUIET-SINCE ignored" || bad "missing heartbeat honoured" + +reset; echo "garbage" > "$S/QUIET-SINCE"; beat 10; last 60; tick +ran && ok "unreadable QUIET-SINCE: full cadence" || bad "garbage honoured" + +reset; quiet 3000; beat 10; tick +ran && ok "no cron-last-round: runs" || bad "first round skipped" +[[ -e $S/cron-last-round ]] && ok "cron-last-round written" || bad "cron-last-round missing" +grep -q 'round rc=0 child_cpu user=' "$T/out" && ok "round CPU logged" || bad "round CPU not logged" + +echo "cron_tick_test: $pass passed, $fail failed" +[[ $fail -eq 0 ]] diff --git a/tools/aien-test/src/cli.rs b/tools/aien-test/src/cli.rs index ddb30bb6..7da91705 100644 --- a/tools/aien-test/src/cli.rs +++ b/tools/aien-test/src/cli.rs @@ -12,6 +12,8 @@ //! aien-test verify COMMIT [--repo NAME] [--base REF] [--state-dir DIR] [--release] //! aien-test worker [--once REPO SHA] [--poll SECS] [--repos LIST] [--github] [--iterations N] //! [--state-dir DIR] [--key FILE] [--clones DIR] [--wt-root DIR] [--wt-tool FILE] [--siblings FILE] [--sandbox user|none --dev-unsandboxed] +//! [--backoff-cap SECS] [--quiet-after SECS] [--prime FILE] [--cold] [--prime-only] (the last two with --once) +//! [--target-quota-gb G] [--disk-floor-gb G] [--probe] //! ``` //! //! `--host/--qemu/--gb10` and `--mutants` are later slices and are refused. @@ -113,6 +115,24 @@ pub struct Cli { pub once: Option<(String, String)>, /// worker: `--poll SECS` (default 30). pub poll: Option, + /// worker: `--backoff-cap SECS` ceiling of the backed-off retries (default 900). + pub backoff_cap: Option, + /// worker: `--quiet-after SECS` idle time before backing off (default 600). + pub quiet_after: Option, + /// worker: `--cold`: empty the pr class target dir first (with --once). + pub cold: bool, + /// worker: `--prime-only` (with --once REPO MAIN): prime the pr class dir + /// from that main head and run nothing (with --cold: empty it first). + pub prime_only: bool, + /// worker: `--prime FILE` the warm-standby prime map (default + /// `/aien-sovereign-core/tools/aien-local-ci/prime`). + pub prime: Option, + /// worker: `--target-quota-gb G` per-repository target dir quota (default 120). + pub target_quota_gb: Option, + /// worker: `--disk-floor-gb G` free space priming keeps (default 50). + pub disk_floor_gb: Option, + /// worker: `--probe`: print the cheap GitHub probe once and exit. + pub probe: bool, /// worker: `--repos A,B`. pub repos: Vec, /// worker: `--github`: poll GitHub and post commit statuses. @@ -145,7 +165,15 @@ fn parse_selection(s: &str) -> Result { const COMMANDS: [&str; 9] = [ "run", "test", "why", "list", "identity", "plan", "status", "verify", "worker", ]; -const WORKER_FLAGS: [&str; 13] = [ +const WORKER_FLAGS: [&str; 21] = [ + "--target-quota-gb", + "--disk-floor-gb", + "--probe", + "--prime-only", + "--backoff-cap", + "--quiet-after", + "--cold", + "--prime", "--dev-unsandboxed", "--key", "--clones", @@ -195,6 +223,14 @@ pub fn parse_args(argv: &[String]) -> Result { let mut siblings: Option = None; let mut once: Option<(String, String)> = None; let mut poll: Option = None; + let mut backoff_cap: Option = None; + let mut quiet_after: Option = None; + let mut cold = false; + let mut prime_only = false; + let mut prime: Option = None; + let mut target_quota_gb: Option = None; + let mut disk_floor_gb: Option = None; + let mut probe = false; let mut repos: Vec = Vec::new(); let mut github = false; let mut iterations: Option = None; @@ -272,6 +308,51 @@ pub fn parse_args(argv: &[String]) -> Result { v.parse::() .map_err(|_| format!("--poll needs seconds, not {v:?}"))?, ); + } else if a == "--backoff-cap" || a == "--quiet-after" { + worker_flags.push(if a == "--backoff-cap" { + "--backoff-cap" + } else { + "--quiet-after" + }); + let v = value(&mut i, a)?; + let n = v + .parse::() + .map_err(|_| format!("{a} needs seconds, not {v:?}"))?; + if a == "--backoff-cap" { + backoff_cap = Some(n); + } else { + quiet_after = Some(n); + } + } else if a == "--target-quota-gb" || a == "--disk-floor-gb" { + let quota = a == "--target-quota-gb"; + worker_flags.push(if quota { + "--target-quota-gb" + } else { + "--disk-floor-gb" + }); + let v = value(&mut i, a)?; + let n = v + .parse::() + .ok() + .filter(|n| *n > 0 && *n < 1 << 20) + .ok_or_else(|| format!("{a} needs whole GiB above 0, not {v:?}"))?; + if quota { + target_quota_gb = Some(n); + } else { + disk_floor_gb = Some(n); + } + } else if a == "--probe" { + worker_flags.push("--probe"); + probe = true; + } else if a == "--prime-only" { + worker_flags.push("--prime-only"); + prime_only = true; + } else if a == "--cold" { + worker_flags.push("--cold"); + cold = true; + } else if a == "--prime" { + worker_flags.push("--prime"); + prime = Some(PathBuf::from(value(&mut i, a)?)); } else if a == "--iterations" { worker_flags.push("--iterations"); let v = value(&mut i, a)?; @@ -310,6 +391,14 @@ pub fn parse_args(argv: &[String]) -> Result { .to_string(), ); } + if prime_only && once.is_none() { + return Err("--prime-only needs --once REPO MAIN-SHA".to_string()); + } + if cold && once.is_none() { + return Err( + "--cold only applies to worker --once (it empties the pr class target dir)".to_string(), + ); + } if name != "worker" { if let Some(f) = worker_flags .iter() @@ -389,6 +478,14 @@ pub fn parse_args(argv: &[String]) -> Result { siblings, once, poll, + backoff_cap, + quiet_after, + cold, + prime_only, + prime, + target_quota_gb, + disk_floor_gb, + probe, repos, github, iterations, @@ -609,6 +706,35 @@ mod tests { assert!(parse_args(&v(&["list", "--repo", "x"])).is_err()); } + #[test] + fn power_and_warm_flags() { + let sha = "c".repeat(40); + let c = parse_args(&v(&[ + "worker", + "--backoff-cap", + "300", + "--quiet-after", + "120", + "--prime", + "/p", + ])) + .unwrap(); + assert_eq!((c.backoff_cap, c.quiet_after), (Some(300), Some(120))); + assert_eq!(c.prime, Some(PathBuf::from("/p"))); + assert!(!c.cold); + let c = parse_args(&v(&["worker", "--once", "r", &sha, "--cold"])).unwrap(); + assert!(c.cold); + assert!(parse_args(&v(&["worker", "--cold"])) + .unwrap_err() + .contains("--cold only applies")); + assert!(parse_args(&v(&["worker", "--backoff-cap", "x"])).is_err()); + assert!(parse_args(&v(&["worker", "--quiet-after"])).is_err()); + assert!(parse_args(&v(&["status", "--backoff-cap", "5"])) + .unwrap_err() + .contains("only applies to worker")); + assert!(parse_args(&v(&["status", "--prime", "/p"])).is_err()); + } + #[test] fn worker_flags() { let sha = "c".repeat(40); diff --git a/tools/aien-test/src/idle.rs b/tools/aien-test/src/idle.rs new file mode 100644 index 00000000..022ce531 --- /dev/null +++ b/tools/aien-test/src/idle.rs @@ -0,0 +1,1286 @@ +//! Power saving and warm standby for the worker: the pure parts. +//! +//! Everything here is decided from plain data (texts, times, file states) so +//! each rule has a unit test; `worker.rs` wires it to git, GitHub and the +//! sandbox. +//! +//! Markers in the state directory (`~/.local/state/aien-local-ci/`), shared +//! with `cron-tick.sh` and the merge train: +//! +//! ```text +//! QUIET-SINCE written by the worker (only with --github): one line +//! " " = the time of the last activity it saw. +//! Present = nothing has moved since then. Removed the moment +//! anything moves. Absent or unreadable = not quiet. +//! WAKE touched by anyone (operator, train, coordinator). Never +//! removed by a reader: each reader compares its mtime with the +//! last one it saw. A newer mtime = wake to full cadence now. +//! PAUSE unchanged (cron-tick exits; `aien-local-ci stop`). The +//! worker treats PAUSE present -> absent as a wake. +//! warm/.json the warm-standby record of target//pr (below). +//! ``` + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime}; + +pub const QUIET_SINCE: &str = "QUIET-SINCE"; +pub const WAKE: &str = "WAKE"; +pub const PAUSE: &str = "PAUSE"; +/// The label the merge pipeline acts on. +pub const MERGE_LABEL: &str = "ready-to-merge"; +/// Default: nothing moved for this long before the expensive work backs off. +pub const DEFAULT_QUIET_AFTER: Duration = Duration::from_secs(600); +/// Default ceiling of the backed-off retry interval (heads that failed to run). +pub const DEFAULT_BACKOFF_CAP: Duration = Duration::from_secs(900); +/// The sliced sleep checks the local wake sources this often. +pub const SLICE: Duration = Duration::from_secs(5); +/// Default per-repository target dir quota (KiB): 120 GiB, as gc.sh. +pub const DEFAULT_TARGET_QUOTA_KB: u64 = 120 << 20; +/// Default free space the filesystem keeps (KiB): 50 GiB. +pub const DEFAULT_DISK_FLOOR_KB: u64 = 50 << 20; + +/// The interval of the expensive work (retrying heads that failed to run, +/// which means a fetch and a sibling sync): `base` while anything moved within +/// `quiet_after`, then doubling every idle round up to `cap`. Any activity +/// resets it to `base`. The cheap probe itself never backs off. +#[derive(Debug, Clone)] +pub struct Backoff { + pub base: Duration, + pub cap: Duration, + pub quiet_after: Duration, + current: Duration, + last_activity: SystemTime, +} + +impl Backoff { + pub fn new(base: Duration, cap: Duration, quiet_after: Duration, now: SystemTime) -> Backoff { + let base = base.max(Duration::from_secs(1)); + Backoff { + base, + cap: cap.max(base), + quiet_after, + current: base, + last_activity: now, + } + } + + /// Something moved: full cadence from now on. + pub fn activity(&mut self, now: SystemTime) { + self.current = self.base; + self.last_activity = now; + } + + /// One round finished with nothing moving: returns the next interval. + pub fn idle_round(&mut self, now: SystemTime) -> Duration { + if self.quiet(now) { + self.current = (self.current * 2).min(self.cap); + } else { + self.current = self.base; + } + self.current + } + + pub fn interval(&self) -> Duration { + self.current + } + + pub fn last_activity(&self) -> SystemTime { + self.last_activity + } + + /// Nothing moved for at least `quiet_after`. + pub fn quiet(&self, now: SystemTime) -> bool { + now.duration_since(self.last_activity) + .map(|d| d >= self.quiet_after) + .unwrap_or(false) + } +} + +/// One open pull request head as polled: its sha and whether it carries the +/// merge label. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct PrHead { + pub sha: String, + pub labeled: bool, +} + +/// What one GitHub poll of one repository saw. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Polled { + pub prs: Vec, + pub main: Option, +} + +/// Parse the pulls query output: one ` ` per line. Lines +/// that are not that are ignored (the sha check is the safety rule; a bad +/// label field reads as unlabeled). +pub fn parse_pulls(text: &str) -> Vec { + let mut out: Vec = Vec::new(); + for l in text.lines() { + let mut f = l.split_whitespace(); + let sha = f.next().unwrap_or("").to_ascii_lowercase(); + if !crate::worker::valid_sha(&sha) { + continue; + } + let labeled = f.next() == Some("true"); + out.push(PrHead { sha, labeled }); + } + out.sort(); + out.dedup(); + out +} + +/// Did anything move between two polls of one repository: a new or changed +/// head, a label added or removed, or main moved. The first poll of a +/// repository (`prev` None) counts as movement. +pub fn moved(prev: Option<&Polled>, now: &Polled) -> bool { + match prev { + None => true, + Some(p) => p != now, + } +} + +/// The heads to run this round in service order: labeled heads first (the +/// merge is waiting on them), then the rest, each group in sha order; heads +/// that already have a bundle are dropped by the caller. +pub fn service_order(mut heads: Vec) -> Vec { + heads.sort_by(|a, b| b.labeled.cmp(&a.labeled).then(a.sha.cmp(&b.sha))); + heads +} + +// ---------------------------------------------------------------- cheap probe + +/// A name GitHub accepts as an owner or repository and that is safe to place +/// inside a GraphQL string literal (no quote, backslash or space). +fn probe_name_ok(s: &str) -> bool { + !s.is_empty() + && s.len() <= 100 + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') +} + +/// The one GraphQL query that sees every repository at once: per repository +/// (alias `r`) the main head and the open pull request heads with their +/// labels. `None` when a name is not safe to embed. +pub fn probe_query(repos: &[(String, String)]) -> Option { + let mut q = String::from("query{"); + for (i, (owner, name)) in repos.iter().enumerate() { + if !probe_name_ok(owner) || !probe_name_ok(name) { + return None; + } + q.push_str(&format!( + "r{i}:repository(owner:\"{owner}\",name:\"{name}\"){{ref(qualifiedName:\"refs/heads/main\"){{target{{oid}}}} pullRequests(states:OPEN,first:50){{pageInfo{{hasNextPage}} nodes{{headRefOid labels(first:30){{pageInfo{{hasNextPage}} nodes{{name}}}}}}}}}}" + )); + } + q.push('}'); + Some(q) +} + +/// The jq filter applied to the probe answer: `r main ` and +/// `r pr ` lines. A repository GitHub could not resolve +/// (null) prints nothing, so the caller falls back to the per-repository poll. +pub fn probe_jq() -> String { + format!( + ".data | to_entries[] | select(.value != null) | .key as $k | \ + ((.value.ref.target.oid // empty | \"\\($k) main \\(.)\"), \ + (if .value.pullRequests.pageInfo.hasNextPage or any(.value.pullRequests.nodes[]; .labels.pageInfo.hasNextPage) then \"\\($k) more\" else empty end), \ + (.value.pullRequests.nodes[] | \"\\($k) pr \\(.headRefOid) \\([.labels.nodes[].name] | index(\"{MERGE_LABEL}\") != null)\"))" + ) +} + +/// Parse the probe lines into one `Polled` per repository index. A repository +/// is present only when its `main` line was seen with a valid sha and no `more` +/// line (a second page of pull requests or labels) came for it (a partial +/// answer never reads as "no pull requests"); bad lines are ignored. +pub fn parse_probe(text: &str, n: usize) -> Vec> { + let mut out: Vec> = vec![None; n]; + let mut prs: Vec> = vec![Vec::new(); n]; + let mut more = vec![false; n]; + for l in text.lines() { + let f: Vec<&str> = l.split_whitespace().collect(); + let Some(i) = f + .first() + .and_then(|k| k.strip_prefix('r')) + .and_then(|k| k.parse::().ok()) + .filter(|i| *i < n) + else { + continue; + }; + if f.len() == 2 && f[1] == "more" { + more[i] = true; + continue; + } + let sha = f.get(2).map(|s| s.to_ascii_lowercase()).unwrap_or_default(); + if !crate::worker::valid_sha(&sha) { + continue; + } + match f.get(1) { + Some(&"main") if f.len() == 3 => { + out[i] = Some(Polled { + prs: Vec::new(), + main: Some(sha), + }) + } + Some(&"pr") if f.len() == 4 => prs[i].push(PrHead { + sha, + labeled: f[3] == "true", + }), + _ => {} + } + } + for (i, p) in out.iter_mut().enumerate() { + // More than one page (pull requests or labels): never trusted. + if more[i] { + *p = None; + } + if let Some(p) = p { + let mut v = std::mem::take(&mut prs[i]); + v.sort(); + v.dedup(); + p.prs = v; + } + } + out +} + +// ---------------------------------------------------------------- priming stops + +/// While priming: the first polled head (pull request or main) that still +/// needs a run, i.e. has no bundle and has not already failed to run. +pub fn unserved_head<'a>( + polls: &'a [(String, Polled)], + has_bundle: &dyn Fn(&str, &str) -> bool, + errored: &BTreeSet<(String, String)>, +) -> Option<(&'a str, &'a str)> { + polls.iter().find_map(|(repo, p)| { + p.prs + .iter() + .map(|h| h.sha.as_str()) + .chain(p.main.as_deref()) + .find(|s| !has_bundle(repo, s) && !errored.contains(&(repo.clone(), s.to_string()))) + .map(|s| (repo.as_str(), s)) + }) +} + +/// Does a priming interrupt count as activity (resets the backoff, removes +/// QUIET-SINCE)? Only something that means work: a new head, WAKE, PAUSE +/// removed, a trigger file. +pub fn interrupt_is_activity(why: &str) -> bool { + ["new head ", "WAKE touched", "PAUSE removed", "trigger file"] + .iter() + .any(|p| why.starts_with(p)) +} + +/// After priming was interrupted for `why`, should the loop sleep before the +/// next round? +pub fn sleep_after_interrupt(why: Option<&str>) -> bool { + !why.is_some_and(interrupt_is_activity) +} + +/// The disk check during priming (KiB). `total` is None between the +/// once-a-minute measurements. +pub fn disk_verdict( + free: Result, + total: Option>, + quota: u64, + floor: u64, +) -> Option { + // A check that cannot measure stops priming (fail closed to cold). + match free { + Err(e) => return Some(format!("disk: free space unknown: {e}")), + Ok(f) if f < floor => return disk_over(0, quota, f, floor), + Ok(_) => {} + } + match total { + Some(Err(e)) => Some(format!("disk: target size unknown: {e}")), + Some(Ok(t)) => disk_over(t, quota, u64::MAX, floor), + None => None, + } +} + +/// Priming runs below the gates: `nice -n 19 ionice -c 3 ` +/// inside the sandbox (the unprivileged user may lower its own priority). +pub fn low_priority(program: &str, args: &[String]) -> (String, Vec) { + let mut a: Vec = ["-n", "19", "ionice", "-c", "3", program] + .iter() + .map(|s| s.to_string()) + .collect(); + a.extend(args.iter().cloned()); + ("nice".to_string(), a) +} + +// ---------------------------------------------------------------- target lock + +/// The flock file that serialises everything building in `target_dir` (gates +/// and priming): `/.lock`, where sanitising replaces +/// every byte of the path as given outside `[A-Za-z0-9._-]` with `_`. Same +/// rule as the runner's `resources::target_lock_path` (fix/target-dir-serialise), +/// so both sides lock the same file; the kernel serialises them. +pub fn target_lock_path(lock_dir: &Path, target_dir: &Path) -> PathBuf { + let s: String = target_dir + .display() + .to_string() + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-' { + c + } else { + '_' + } + }) + .collect(); + lock_dir.join(format!("{s}.lock")) +} + +// ---------------------------------------------------------------- disk bound + +/// What the disk allows before priming `target//pr`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DiskPlan { + /// Under the quota and above the floor: prime into the dir as it is. + Prime, + /// Over: empty the pr class dir first (the lowest class, a cache the next + /// run rebuilds); that alone brings the repository under the quota. + WipeThenPrime, + /// Over even without the pr class dir (main alone, or the disk floor): + /// do not prime and leave pr as it is (what PR runs put there is gc.sh's + /// to bound). No warm claim; runs are cold-from-main until space is freed. + NoPrime(String), +} + +/// The rule (sizes in KiB): the repository's target total (main + pr) must be +/// at most `quota`, and the filesystem must keep `floor` free. The pr class +/// dir is the only thing priming may evict; the main class is never touched. +pub fn disk_plan(total: u64, pr: u64, quota: u64, free: u64, floor: u64) -> DiskPlan { + if total <= quota && free >= floor { + return DiskPlan::Prime; + } + let rest = total.saturating_sub(pr); + if rest <= quota && free.saturating_add(pr) >= floor { + return DiskPlan::WipeThenPrime; + } + DiskPlan::NoPrime(format!( + "target total {} GiB without pr is {} GiB (quota {} GiB), {} GiB free with pr emptied (floor {} GiB)", + total >> 20, + rest >> 20, + quota >> 20, + free.saturating_add(pr) >> 20, + floor >> 20 + )) +} + +/// While priming: stop when the repository's total went over the quota or +/// the filesystem fell under the floor (sizes in KiB). +pub fn disk_over(total: u64, quota: u64, free: u64, floor: u64) -> Option { + if total > quota { + return Some(format!( + "disk: target total {} GiB over the {} GiB quota", + total >> 20, + quota >> 20 + )); + } + if free < floor { + return Some(format!( + "disk: {} GiB free, under the {} GiB floor", + free >> 20, + floor >> 20 + )); + } + None +} + +// ---------------------------------------------------------------- fetch skip + +/// One fetch refspec of `remote.origin.fetch`, glob or exact. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Refspec { + src: String, + dst: String, + glob: bool, +} + +fn parse_refspec(s: &str) -> Option { + let s = s.trim().trim_start_matches('+'); + if s.starts_with('^') { + return None; // negative refspec: not mapped, fetch as before + } + let (src, dst) = s.split_once(':')?; + let (sg, dg) = (src.matches('*').count(), dst.matches('*').count()); + match (sg, dg) { + (0, 0) if !src.is_empty() && !dst.is_empty() => Some(Refspec { + src: src.into(), + dst: dst.into(), + glob: false, + }), + (1, 1) if src.ends_with('*') && dst.ends_with('*') => Some(Refspec { + src: src.trim_end_matches('*').into(), + dst: dst.trim_end_matches('*').into(), + glob: true, + }), + _ => None, + } +} + +fn map_ref(specs: &[Refspec], name: &str) -> Option { + for s in specs { + if s.glob { + if let Some(rest) = name.strip_prefix(&s.src) { + return Some(format!("{}{rest}", s.dst)); + } + } else if name == s.src { + return Some(s.dst.clone()); + } + } + None +} + +fn sha_lines(text: &str) -> Option> { + let mut m = BTreeMap::new(); + for l in text.lines() { + if l.trim().is_empty() { + continue; + } + let (sha, name) = l.split_once(char::is_whitespace)?; + let (sha, name) = (sha.trim().to_ascii_lowercase(), name.trim()); + if !crate::worker::valid_sha(&sha) || name.is_empty() { + return None; + } + if name.ends_with("^{}") { + continue; // peeled tag line: the tag object line is compared + } + m.insert(name.to_string(), sha); + } + Some(m) +} + +/// Would `git fetch` change anything? `ls_remote` is `git ls-remote origin`, +/// `refspecs` the values of `remote.origin.fetch`, `local` is +/// `git for-each-ref --format='%(objectname) %(refname)'`. +/// +/// `Some(true)` only when every remote ref a refspec maps, and every remote +/// tag, is present locally at the same sha (local extras are ignored: fetch +/// does not prune). `None` when anything cannot be read or mapped: the caller +/// then fetches exactly as before. Remote refs no refspec maps +/// (`refs/pull/*` with the default refspec, `HEAD`) are not fetched by +/// `fetch --all` and are ignored. +pub fn refs_unchanged(ls_remote: &str, refspecs: &[String], local: &str) -> Option { + if refspecs.is_empty() { + return None; + } + let specs: Vec = refspecs + .iter() + .map(|s| parse_refspec(s)) + .collect::>>()?; + let remote = sha_lines(ls_remote)?; + let local = sha_lines(local)?; + if remote.is_empty() { + return None; + } + for (name, sha) in &remote { + let dst = if name.starts_with("refs/tags/") { + Some(name.clone()) + } else { + map_ref(&specs, name) + }; + if let Some(dst) = dst { + if local.get(&dst) != Some(sha) { + return Some(false); + } + } + } + Some(true) +} + +// -------------------------------------------------------------- warm standby + +/// One priming line of the operator's prime map +/// (`tools/aien-local-ci/prime`): ` [K=V ...] cargo `. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PrimeLine { + pub env: Vec<(String, String)>, + pub args: Vec, +} + +/// Names the exec helper refuses (or that would change what the sandbox is). +const ENV_REFUSED: [&str; 8] = [ + "PATH", + "HOME", + "CARGO_HOME", + "RUSTUP_HOME", + "CARGO_TARGET_DIR", + "BASH_ENV", + "ENV", + "RUSTC_WRAPPER", +]; + +fn env_name_ok(k: &str) -> bool { + let mut b = k.bytes(); + matches!(b.next(), Some(c) if c.is_ascii_uppercase() || c == b'_') + && b.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') + && !k.starts_with("LD_") + && !k.starts_with("AIEN_RUN") + && !ENV_REFUSED.contains(&k) +} + +/// Parse the prime map and return the lines of `repo`. Every line is checked +/// (a broken map refuses priming for every repository). The program is +/// always `cargo`; arguments are plain words without quoting, `=`-free in +/// the program position, never starting the line with a flag. +pub fn parse_prime(text: &str, repo: &str) -> Result, String> { + let mut out = Vec::new(); + for (n, raw) in text.lines().enumerate() { + let line = raw.split('#').next().unwrap_or("").trim(); + if line.is_empty() { + continue; + } + let bad = |why: &str| format!("prime map line {}: {why}: {raw:?}", n + 1); + let f: Vec<&str> = line.split_whitespace().collect(); + if !crate::worker::valid_repo_key(f[0]) { + return Err(bad("the repository must be a plain name")); + } + let mut env = Vec::new(); + let mut i = 1; + while i < f.len() && f[i].contains('=') { + let (k, v) = f[i].split_once('=').unwrap_or(("", "")); + if !env_name_ok(k) { + return Err(bad("environment name refused")); + } + env.push((k.to_string(), v.to_string())); + i += 1; + } + if f.get(i) != Some(&"cargo") { + return Err(bad("the program must be cargo")); + } + let args: Vec = f[i + 1..].iter().map(|s| s.to_string()).collect(); + if args.is_empty() || args[0].starts_with('-') { + return Err(bad("needs a cargo subcommand")); + } + if !["build", "check", "clippy", "test"].contains(&args[0].as_str()) { + return Err(bad("cargo subcommand must be build, check, clippy or test")); + } + if args[0] == "test" && !args.iter().any(|a| a == "--no-run") { + return Err(bad("cargo test primes only with --no-run")); + } + if f[0] == repo { + out.push(PrimeLine { env, args }); + } + } + Ok(out) +} + +/// What `warm/.json` says about `target//pr`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WarmRecord { + pub primed_from_main: String, + pub utc: String, +} + +pub fn warm_path(state_root: &Path, repo: &str) -> PathBuf { + state_root.join("warm").join(format!("{repo}.json")) +} + +/// The record, only when it is complete and well formed. +pub fn read_warm(state_root: &Path, repo: &str) -> Option { + let t = fs::read_to_string(warm_path(state_root, repo)).ok()?; + let v: serde_json::Value = serde_json::from_str(&t).ok()?; + if v["complete"] != serde_json::Value::Bool(true) || v["class"] != "pr" { + return None; + } + let sha = v["primed_from_main"].as_str()?.to_string(); + crate::worker::valid_sha(&sha).then(|| WarmRecord { + primed_from_main: sha, + utc: v["utc"].as_str().unwrap_or("").to_string(), + }) +} + +pub fn write_warm( + state_root: &Path, + repo: &str, + rec: &WarmRecord, + lines: usize, +) -> Result<(), String> { + let p = warm_path(state_root, repo); + let dir = p.parent().unwrap_or(state_root); + fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + let v = serde_json::json!({ + "class": "pr", + "complete": true, + "primed_from_main": rec.primed_from_main, + "utc": rec.utc, + "lines": lines, + }); + let tmp = dir.join(format!(".{repo}.json.tmp")); + fs::write(&tmp, v.to_string()).map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; + fs::rename(&tmp, &p).map_err(|e| format!("cannot write {}: {e}", p.display())) +} + +pub fn clear_warm(state_root: &Path, repo: &str) { + let _ = fs::remove_file(warm_path(state_root, repo)); +} + +/// The bundle member `target`: which cargo target dir the gates used and +/// whether it was warm (primed from main) when the run started. +pub fn target_member(class: &str, warm: Option<&WarmRecord>, cold: bool) -> serde_json::Value { + let warm = if cold { None } else { warm }; + serde_json::json!({ + "class": class, + "warm": warm.is_some(), + "primed_from_main": warm.map(|w| w.primed_from_main.clone()), + "primed_utc": warm.map(|w| w.utc.clone()), + "cold": cold, + }) +} + +// ------------------------------------------------------------------- markers + +/// Write QUIET-SINCE (atomic) with the time of the last activity. +pub fn write_quiet_since(state_root: &Path, last_activity: SystemTime) -> Result<(), String> { + let secs = last_activity + .duration_since(SystemTime::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let p = state_root.join(QUIET_SINCE); + let tmp = state_root.join(format!(".{QUIET_SINCE}.tmp")); + fs::write( + &tmp, + format!("{secs} {}\n", crate::evidence::utc_string(secs)), + ) + .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; + fs::rename(&tmp, &p).map_err(|e| format!("cannot write {}: {e}", p.display())) +} + +pub fn remove_quiet_since(state_root: &Path) { + let _ = fs::remove_file(state_root.join(QUIET_SINCE)); +} + +/// The epoch in QUIET-SINCE, None when absent or not a number. +pub fn read_quiet_since(state_root: &Path) -> Option { + fs::read_to_string(state_root.join(QUIET_SINCE)) + .ok()? + .split_whitespace() + .next()? + .parse() + .ok() +} + +/// Watches the local wake sources without any network or process: WAKE +/// touched since last seen, PAUSE removed, a trigger file waiting. +#[derive(Debug, Clone)] +pub struct WakeWatch { + root: PathBuf, + wake_seen: Option, + paused: bool, +} + +fn mtime(p: &Path) -> Option { + fs::metadata(p).and_then(|m| m.modified()).ok() +} + +impl WakeWatch { + pub fn new(state_root: &Path) -> WakeWatch { + WakeWatch { + root: state_root.to_path_buf(), + wake_seen: mtime(&state_root.join(WAKE)), + paused: state_root.join(PAUSE).exists(), + } + } + + /// Why to wake now, if anything; each WAKE touch and each PAUSE removal + /// is reported once. + pub fn check(&mut self) -> Option<&'static str> { + let w = mtime(&self.root.join(WAKE)); + let woke = match (w, self.wake_seen) { + (Some(a), Some(b)) => a > b, + (Some(_), None) => true, + _ => false, + }; + if w.is_some() { + self.wake_seen = w; + } + let paused = self.root.join(PAUSE).exists(); + let unpaused = self.paused && !paused; + self.paused = paused; + if woke { + Some("WAKE touched") + } else if unpaused { + Some("PAUSE removed") + } else if trigger_waiting(&self.root.join("trigger")) { + Some("trigger file") + } else { + None + } + } + + pub fn paused(&self) -> bool { + self.paused + } +} + +fn trigger_waiting(dir: &Path) -> bool { + fs::read_dir(dir) + .map(|rd| { + rd.flatten().any(|e| { + // Only a name the worker would serve (`.`): a stray + // file is never removed, so it must not wake the loop forever. + let n = e.file_name().to_string_lossy().into_owned(); + n.rsplit_once('.').is_some_and(|(r, s)| { + crate::worker::valid_repo_key(r) + && crate::worker::valid_sha(&s.to_ascii_lowercase()) + }) + }) + }) + .unwrap_or(false) +} + +#[cfg(test)] +mod tests { + use super::*; + + const A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + const C: &str = "cccccccccccccccccccccccccccccccccccccccc"; + + fn t(s: u64) -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000 + s) + } + + #[test] + fn probe_query_covers_every_repo_and_refuses_unsafe_names() { + let q = probe_query(&[ + ("aien-dev".into(), "aienos".into()), + ("aien-spark".into(), "aien-sovereign-core".into()), + ]) + .unwrap(); + assert!(q.starts_with("query{r0:repository(owner:\"aien-dev\",name:\"aienos\")")); + assert!(q.contains("r1:repository(owner:\"aien-spark\",name:\"aien-sovereign-core\")")); + assert!(q.contains("refs/heads/main") && q.contains("states:OPEN,first:50")); + assert_eq!(q.matches('{').count(), q.matches('}').count()); + for bad in ["a\"b", "a b", "a\\b", "", "a{b"] { + assert!( + probe_query(&[("o".into(), bad.into())]).is_none(), + "{bad:?}" + ); + } + assert!(probe_jq().contains("index(\"ready-to-merge\") != null")); + } + + #[test] + fn review_a_an_errored_head_never_stops_priming() { + let polls = vec![( + "r".to_string(), + Polled { + prs: vec![PrHead { + sha: B.into(), + labeled: false, + }], + main: Some(A.into()), + }, + )]; + let bundled = |_: &str, s: &str| s == A; + let mut errored = BTreeSet::new(); + assert_eq!(unserved_head(&polls, &bundled, &errored), Some(("r", B))); + errored.insert(("r".to_string(), B.to_string())); + assert_eq!( + unserved_head(&polls, &bundled, &errored), + None, + "errored head skipped" + ); + // An errored main (no plan, say) is skipped the same way. + let none = |_: &str, _: &str| false; + errored.insert(("r".to_string(), A.to_string())); + assert_eq!(unserved_head(&polls, &none, &errored), None); + } + + #[test] + fn review_a_b_only_work_interrupts_count_and_skip_the_sleep() { + for w in [ + "new head r abc", + "WAKE touched", + "PAUSE removed", + "trigger file", + ] { + assert!(interrupt_is_activity(w), "{w}"); + assert!(!sleep_after_interrupt(Some(w)), "{w}: run it now"); + } + for w in [ + "RAISED by x", + "unknown (quietlock missing)", + "PAUSE present", + "disk: 3 GiB free, under the 50 GiB floor", + ] { + assert!(!interrupt_is_activity(w), "{w}"); + assert!(sleep_after_interrupt(Some(w)), "{w}"); + } + assert!(sleep_after_interrupt(None)); + } + + #[test] + fn review_c_more_than_one_page_falls_back() { + let text = format!("r0 main {A}\nr0 pr {B} true\nr0 more\nr1 main {A}\n"); + let p = parse_probe(&text, 2); + assert_eq!(p[0], None, "a truncated answer is never trusted"); + assert!(p[1].is_some()); + let q = probe_query(&[("o".into(), "n".into())]).unwrap(); + assert!(q.contains("pageInfo{hasNextPage}"), "{q}"); + assert!(probe_jq().contains("hasNextPage")); + } + + #[test] + fn review_d_a_failed_disk_check_stops_priming() { + let g = 1u64 << 20; + let (q, f) = (120 * g, 50 * g); + assert_eq!(disk_verdict(Ok(100 * g), None, q, f), None); + assert_eq!(disk_verdict(Ok(100 * g), Some(Ok(100 * g)), q, f), None); + assert!(disk_verdict(Ok(100 * g), Some(Ok(121 * g)), q, f) + .unwrap() + .starts_with("disk:")); + assert!(disk_verdict(Ok(10 * g), None, q, f) + .unwrap() + .starts_with("disk:")); + let e = disk_verdict(Err("statvfs: EIO".into()), None, q, f).expect("free unknown: stop"); + assert!(e.starts_with("disk:") && e.contains("EIO"), "{e}"); + let e = disk_verdict(Ok(100 * g), Some(Err("du did not report".into())), q, f) + .expect("size unknown: stop"); + assert!( + e.starts_with("disk:") && e.contains("du did not report"), + "{e}" + ); + } + + #[test] + fn req3_priming_runs_niced_and_idle_io() { + let (p, a) = low_priority("cargo", &["check".to_string()]); + assert_eq!(p, "nice"); + assert_eq!(a, ["-n", "19", "ionice", "-c", "3", "cargo", "check"]); + } + + #[test] + fn parse_probe_needs_main_and_ignores_bad_lines() { + let text = format!( + "r0 main {A}\nr0 pr {B} true\nr0 pr {C} false\nr0 pr {B} true\n\ + r1 pr {C} true\nr2 main {A}\nr9 main {A}\nx main {A}\nr2 pr nope true\nr2 main short\n" + ); + let p = parse_probe(&text, 3); + assert_eq!( + p[0], + Some(Polled { + prs: vec![ + PrHead { + sha: B.into(), + labeled: true + }, + PrHead { + sha: C.into(), + labeled: false + } + ], + main: Some(A.into()) + }) + ); + assert_eq!(p[1], None, "no main line: fall back, never 'no PRs'"); + assert_eq!( + p[2], + Some(Polled { + prs: vec![], + main: Some(A.into()) + }) + ); + assert_eq!(parse_probe("", 2), vec![None, None]); + } + + #[test] + fn target_lock_path_matches_the_runner_rule() { + assert_eq!( + target_lock_path( + Path::new("/s/locks/target"), + Path::new("/var/lib/aien-run/target/aien-sovereign-core/pr") + ), + PathBuf::from("/s/locks/target/_var_lib_aien-run_target_aien-sovereign-core_pr.lock") + ); + // Nothing can climb out of the lock dir. + let p = target_lock_path(Path::new("/l"), Path::new("../../x y")); + assert_eq!(p, PathBuf::from("/l/.._.._x_y.lock")); + assert_eq!(p.parent(), Some(Path::new("/l"))); + } + + #[test] + fn disk_plan_evicts_pr_first_and_fails_closed_to_cold() { + let g = 1u64 << 20; // KiB per GiB + let (quota, floor) = (120 * g, 50 * g); + assert_eq!( + disk_plan(100 * g, 40 * g, quota, 200 * g, floor), + DiskPlan::Prime + ); + assert_eq!( + disk_plan(120 * g, 40 * g, quota, 200 * g, floor), + DiskPlan::Prime + ); + // Over the quota, main alone under it: empty pr, then prime. + assert_eq!( + disk_plan(150 * g, 60 * g, quota, 200 * g, floor), + DiskPlan::WipeThenPrime + ); + // Under the floor; emptying pr gives the room back. + assert_eq!( + disk_plan(100 * g, 40 * g, quota, 20 * g, floor), + DiskPlan::WipeThenPrime + ); + // Main alone over the quota (the live sc state on 2026-10-16: 122 + 148). + assert!(matches!( + disk_plan(270 * g, 148 * g, quota, 150 * g, floor), + DiskPlan::NoPrime(w) if w.contains("122 GiB") + )); + // The disk floor even with pr emptied. + assert!(matches!( + disk_plan(60 * g, 10 * g, quota, 5 * g, floor), + DiskPlan::NoPrime(_) + )); + assert_eq!(disk_over(120 * g, quota, 50 * g, floor), None); + assert!(disk_over(120 * g + 1, quota, 60 * g, floor) + .unwrap() + .contains("quota")); + assert!(disk_over(10 * g, quota, 49 * g, floor) + .unwrap() + .contains("floor")); + } + + #[test] + fn backoff_holds_base_until_quiet_then_doubles_to_the_cap() { + let mut b = Backoff::new( + Duration::from_secs(60), + Duration::from_secs(900), + Duration::from_secs(600), + t(0), + ); + assert_eq!(b.idle_round(t(60)), Duration::from_secs(60)); + assert_eq!(b.idle_round(t(599)), Duration::from_secs(60)); + assert!(!b.quiet(t(599))); + assert_eq!(b.idle_round(t(600)), Duration::from_secs(120)); + assert_eq!(b.idle_round(t(720)), Duration::from_secs(240)); + assert_eq!(b.idle_round(t(960)), Duration::from_secs(480)); + assert_eq!(b.idle_round(t(1440)), Duration::from_secs(900)); + assert_eq!(b.idle_round(t(2340)), Duration::from_secs(900), "capped"); + b.activity(t(2400)); + assert_eq!(b.interval(), Duration::from_secs(60), "activity resets"); + assert_eq!(b.idle_round(t(2460)), Duration::from_secs(60)); + } + + #[test] + fn backoff_never_goes_below_one_second_or_cap_below_base() { + let mut b = Backoff::new(Duration::ZERO, Duration::ZERO, Duration::ZERO, t(0)); + assert_eq!(b.interval(), Duration::from_secs(1)); + assert_eq!(b.idle_round(t(10)), Duration::from_secs(1)); + // A clock that goes backwards is never "quiet". + let b = Backoff::new( + Duration::from_secs(60), + Duration::from_secs(900), + Duration::from_secs(1), + t(100), + ); + assert!(!b.quiet(t(0))); + } + + #[test] + fn pulls_parse_labels_and_refuse_bad_shas() { + let txt = format!("{A} true\n{B} false\nnot-a-sha true\n{C}\n{A} true\nZZZ\n"); + let p = parse_pulls(&txt); + assert_eq!( + p, + vec![ + PrHead { + sha: A.into(), + labeled: true + }, + PrHead { + sha: B.into(), + labeled: false + }, + PrHead { + sha: C.into(), + labeled: false + }, + ] + ); + assert!(parse_pulls("").is_empty()); + assert!( + !parse_pulls(&format!("{A} TRUE"))[0].labeled, + "only exactly true" + ); + } + + #[test] + fn movement_is_any_head_label_or_main_change() { + let base = Polled { + prs: vec![PrHead { + sha: A.into(), + labeled: false, + }], + main: Some(B.into()), + }; + assert!(moved(None, &base), "first poll counts"); + assert!(!moved(Some(&base), &base.clone()), "same poll is quiet"); + let mut l = base.clone(); + l.prs[0].labeled = true; + assert!(moved(Some(&base), &l), "label added"); + assert!(moved(Some(&l), &base), "label removed"); + let mut h = base.clone(); + h.prs[0].sha = C.into(); + assert!(moved(Some(&base), &h), "new head"); + let mut m = base.clone(); + m.main = Some(C.into()); + assert!(moved(Some(&base), &m), "main moved"); + } + + #[test] + fn labeled_heads_are_served_first() { + let o = service_order(vec![ + PrHead { + sha: C.into(), + labeled: false, + }, + PrHead { + sha: B.into(), + labeled: true, + }, + PrHead { + sha: A.into(), + labeled: false, + }, + ]); + let s: Vec<&str> = o.iter().map(|h| h.sha.as_str()).collect(); + assert_eq!(s, vec![B, A, C]); + } + + fn default_spec() -> Vec { + vec!["+refs/heads/*:refs/remotes/origin/*".to_string()] + } + + #[test] + fn fetch_skip_only_when_every_mapped_ref_matches() { + let remote = format!( + "{A}\tHEAD\n{A}\trefs/heads/main\n{B}\trefs/heads/feat\n{C}\trefs/pull/7/head\n{B}\trefs/tags/v1\n{C}\trefs/tags/v1^{{}}\n" + ); + let local = format!( + "{A} refs/remotes/origin/main\n{B} refs/remotes/origin/feat\n{B} refs/tags/v1\n{C} refs/remotes/origin/gone\n{A} refs/heads/main\n" + ); + assert_eq!( + refs_unchanged(&remote, &default_spec(), &local), + Some(true), + "peeled and pull lines ignored, local extras ignored" + ); + // branch moved + let moved = remote.replace( + &format!("{B}\trefs/heads/feat"), + &format!("{C}\trefs/heads/feat"), + ); + assert_eq!(refs_unchanged(&moved, &default_spec(), &local), Some(false)); + // branch added + let added = format!("{remote}{C}\trefs/heads/new\n"); + assert_eq!(refs_unchanged(&added, &default_spec(), &local), Some(false)); + // tag moved / tag added + let tag = remote.replace( + &format!("{B}\trefs/tags/v1\n"), + &format!("{A}\trefs/tags/v1\n"), + ); + assert_eq!(refs_unchanged(&tag, &default_spec(), &local), Some(false)); + let tag2 = format!("{remote}{A}\trefs/tags/v2\n"); + assert_eq!(refs_unchanged(&tag2, &default_spec(), &local), Some(false)); + } + + #[test] + fn fetch_skip_maps_a_configured_pull_refspec() { + let specs = vec![ + "+refs/heads/*:refs/remotes/origin/*".to_string(), + "+refs/pull/*/head:refs/remotes/origin/pr/*".to_string(), + ]; + // A refspec with the glob in the middle cannot be mapped: fetch as before. + assert_eq!( + refs_unchanged( + &format!("{A}\trefs/heads/main\n"), + &specs, + &format!("{A} refs/remotes/origin/main\n") + ), + None + ); + let specs = vec![ + "+refs/heads/*:refs/remotes/origin/*".to_string(), + "+refs/pull/*:refs/remotes/origin/pull/*".to_string(), + ]; + let remote = format!("{A}\trefs/heads/main\n{C}\trefs/pull/7/head\n"); + let local = format!("{A} refs/remotes/origin/main\n"); + assert_eq!( + refs_unchanged(&remote, &specs, &local), + Some(false), + "pull ref mapped and missing" + ); + let local = format!("{local}{C} refs/remotes/origin/pull/7/head\n"); + assert_eq!(refs_unchanged(&remote, &specs, &local), Some(true)); + } + + #[test] + fn fetch_skip_refuses_what_it_cannot_read() { + let r = format!("{A}\trefs/heads/main\n"); + let l = format!("{A} refs/remotes/origin/main\n"); + assert_eq!(refs_unchanged(&r, &[], &l), None, "no refspec"); + assert_eq!( + refs_unchanged(&r, &["^refs/heads/x".into()], &l), + None, + "negative refspec" + ); + assert_eq!( + refs_unchanged(&r, &["refs/heads/*:refs/x".into()], &l), + None, + "unbalanced glob" + ); + assert_eq!(refs_unchanged("garbage line\n", &default_spec(), &l), None); + assert_eq!(refs_unchanged(&r, &default_spec(), "zz refs/x\n"), None); + assert_eq!( + refs_unchanged("", &default_spec(), &l), + None, + "empty remote answer" + ); + // an exact refspec maps + assert_eq!( + refs_unchanged(&r, &["refs/heads/main:refs/remotes/origin/main".into()], &l), + Some(true) + ); + } + + #[test] + fn prime_map_selects_the_repo_and_refuses_bad_lines() { + let m = "# comment\nsc CI=true X_1=a cargo test --workspace --no-run\nsc cargo check --workspace --all-targets\nomega cargo build\n"; + let p = parse_prime(m, "sc").unwrap(); + assert_eq!(p.len(), 2); + assert_eq!( + p[0].env, + vec![("CI".into(), "true".into()), ("X_1".into(), "a".into())] + ); + assert_eq!(p[0].args, vec!["test", "--workspace", "--no-run"]); + assert!(parse_prime(m, "nobody").unwrap().is_empty()); + for bad in [ + "sc bash -c x", + "sc cargo", + "sc cargo --version", + "sc cargo run", + "sc cargo install x", + "sc cargo test --workspace", + "sc PATH=/x cargo build", + "sc LD_PRELOAD=/x cargo build", + "sc CARGO_TARGET_DIR=/x cargo build", + "sc AIEN_RUN_NESTED=0 cargo build", + "sc lower=1 cargo build", + "../x cargo build", + "sc =1 cargo build", + ] { + assert!( + parse_prime(&format!("{m}{bad}\n"), "omega").is_err(), + "{bad} must refuse" + ); + } + } + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("aien-idle-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn warm_record_round_trip_and_incomplete_records_are_cold() { + let d = scratch("warm"); + assert_eq!(read_warm(&d, "sc"), None); + let rec = WarmRecord { + primed_from_main: A.into(), + utc: "2026-10-16T10:00:00Z".into(), + }; + write_warm(&d, "sc", &rec, 3).unwrap(); + assert_eq!(read_warm(&d, "sc"), Some(rec.clone())); + let m = target_member("pr", Some(&rec), false); + assert_eq!(m["warm"], true); + assert_eq!(m["primed_from_main"], A); + let c = target_member("pr", Some(&rec), true); + assert_eq!(c["warm"], false, "a cold run is never warm"); + assert_eq!(c["cold"], true); + assert_eq!(c["primed_from_main"], serde_json::Value::Null); + fs::write( + warm_path(&d, "sc"), + format!(r#"{{"class":"pr","complete":false,"primed_from_main":"{A}"}}"#), + ) + .unwrap(); + assert_eq!(read_warm(&d, "sc"), None, "incomplete"); + fs::write( + warm_path(&d, "sc"), + format!(r#"{{"class":"main","complete":true,"primed_from_main":"{A}"}}"#), + ) + .unwrap(); + assert_eq!(read_warm(&d, "sc"), None, "wrong class"); + fs::write(warm_path(&d, "sc"), "garbage").unwrap(); + assert_eq!(read_warm(&d, "sc"), None); + clear_warm(&d, "sc"); + assert!(!warm_path(&d, "sc").exists()); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn quiet_since_round_trip() { + let d = scratch("quiet"); + assert_eq!(read_quiet_since(&d), None); + write_quiet_since(&d, t(5)).unwrap(); + assert_eq!(read_quiet_since(&d), Some(1_000_005)); + fs::write(d.join(QUIET_SINCE), "nonsense\n").unwrap(); + assert_eq!(read_quiet_since(&d), None); + remove_quiet_since(&d); + assert!(!d.join(QUIET_SINCE).exists()); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn wake_watch_sees_wake_pause_removal_and_triggers_once() { + let d = scratch("wake"); + fs::create_dir_all(d.join("trigger")).unwrap(); + let mut w = WakeWatch::new(&d); + assert_eq!(w.check(), None); + fs::write(d.join(WAKE), "").unwrap(); + assert_eq!(w.check(), Some("WAKE touched")); + assert_eq!(w.check(), None, "reported once"); + fs::write(d.join(PAUSE), "").unwrap(); + assert_eq!(w.check(), None, "pausing is no wake"); + assert!(w.paused()); + fs::remove_file(d.join(PAUSE)).unwrap(); + assert_eq!(w.check(), Some("PAUSE removed")); + assert_eq!(w.check(), None); + fs::write(d.join("trigger/.tmp"), "").unwrap(); + assert_eq!(w.check(), None, "dot files are no trigger"); + fs::write(d.join("trigger/stray-file"), "").unwrap(); + fs::write(d.join("trigger/sc.not-a-sha"), "").unwrap(); + assert_eq!( + w.check(), + None, + "names the worker would not serve are no trigger" + ); + fs::write(d.join(format!("trigger/sc.{A}")), "").unwrap(); + assert_eq!(w.check(), Some("trigger file")); + // WAKE touched again later (mtime moves forward) + let later = SystemTime::now() + Duration::from_secs(5); + let f = fs::File::options().write(true).open(d.join(WAKE)).unwrap(); + f.set_modified(later).unwrap(); + assert_eq!(w.check(), Some("WAKE touched")); + let _ = fs::remove_dir_all(&d); + } +} + +#[cfg(test)] +mod shipped_map { + /// The prime map shipped beside the sibling map parses. + #[test] + fn shipped_prime_map_parses() { + let text = include_str!("../../aien-local-ci/prime"); + for repo in ["aien-sovereign-core", "aienos"] { + let l = super::parse_prime(text, repo).unwrap(); + assert!(!l.is_empty(), "{repo} has prime lines"); + } + } +} diff --git a/tools/aien-test/src/lib.rs b/tools/aien-test/src/lib.rs index a2b449b0..ad1d5139 100644 --- a/tools/aien-test/src/lib.rs +++ b/tools/aien-test/src/lib.rs @@ -42,6 +42,7 @@ pub mod cli; pub mod evidence; pub mod graph; pub mod identity; +pub mod idle; pub mod manifest; pub mod plan; pub mod process; diff --git a/tools/aien-test/src/main.rs b/tools/aien-test/src/main.rs index 41f449fc..f4d7a9da 100644 --- a/tools/aien-test/src/main.rs +++ b/tools/aien-test/src/main.rs @@ -557,8 +557,61 @@ fn cmd_worker(cli: &Cli) -> i32 { cfg.operator = cli.operator; cfg.jobs = cli.jobs; cfg.no_cache = cli.no_cache; + cfg.backoff_cap = Duration::from_secs( + cli.backoff_cap + .unwrap_or(aien_test::idle::DEFAULT_BACKOFF_CAP.as_secs()), + ); + cfg.quiet_after = Duration::from_secs( + cli.quiet_after + .unwrap_or(aien_test::idle::DEFAULT_QUIET_AFTER.as_secs()), + ); + cfg.cold = cli.cold; + // The warm-standby prime map, beside the sibling map in the trusted clone. + // A missing default file means no priming. + cfg.prime = match &cli.prime { + Some(f) => Some(f.clone()), + None => Some(clones.join("aien-sovereign-core/tools/aien-local-ci/prime")) + .filter(|p| p.is_file()), + }; + if let Some(g) = cli.target_quota_gb { + cfg.target_quota_kb = g << 20; + } + if let Some(g) = cli.disk_floor_gb { + cfg.disk_floor_kb = g << 20; + } cfg.hardware_identity = cli.hardware_identity.clone().unwrap_or_default(); + if cli.probe { + // One cheap probe, as the loop does it (falls back per repository). + let mut rc = 0; + for (repo, p) in worker::poll_all(&cfg) { + match p { + Ok(p) => println!( + "PROBE {repo} main {} prs {} labeled {}", + p.main.as_deref().unwrap_or("-"), + p.prs.len(), + p.prs.iter().filter(|h| h.labeled).count() + ), + Err(e) => { + println!("PROBE {repo} unreachable: {e}"); + rc = 1; + } + } + } + return rc; + } if let Some((repo, sha)) = &cli.once { + if cli.prime_only { + return match worker::prime_now(&cfg, repo, sha) { + Ok(o) => { + println!("PRIME {repo} {sha} {o:?}"); + i32::from(o != worker::PrimeOutcome::Warm) + } + Err(e) => { + println!("PRIME {repo} {sha} refused: {e}"); + 2 + } + }; + } return match worker::run_once(&cfg, repo, sha) { Ok(s) => { for n in &s.notes { diff --git a/tools/aien-test/src/worker.rs b/tools/aien-test/src/worker.rs index 39288d3c..c521cf7c 100644 --- a/tools/aien-test/src/worker.rs +++ b/tools/aien-test/src/worker.rs @@ -27,19 +27,21 @@ use crate::bundle; use crate::evidence::{canonical, canonical_digest, sha256_hex, utc_string}; use crate::graph; +use crate::idle::{self, Polled, PrHead}; use crate::plan::{self, Known, Section}; use crate::process; use crate::resources::{Hardware, JobsSpec}; use crate::runner::{self, CacheNote, Options}; -use crate::sandbox::Sandbox; +use crate::sandbox::{self, Sandbox}; use crate::verdict::Verdict; use crate::verify; use serde_json::{json, Value}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub const CONTEXT: &str = "AIEN Verification (Spark)"; @@ -239,6 +241,25 @@ pub struct Config { pub jobs: JobsSpec, /// `--no-cache`: run every selected gate, reuse no receipt. pub no_cache: bool, + /// Ceiling of the backed-off retry interval (`--backoff-cap`, default 900 s). + pub backoff_cap: Duration, + /// Nothing moved for this long before retries back off and QUIET-SINCE is + /// written (`--quiet-after`). + pub quiet_after: Duration, + /// `--cold`: wipe the pr class target dir before the run (cold-equals-warm + /// proof); the bundle then says `target.cold`. + pub cold: bool, + /// The operator's prime map (`tools/aien-local-ci/prime`, beside the + /// sibling map): what warm standby builds. None: no priming. + pub prime: Option, + /// Per-repository target dir quota in KiB (main + pr; `--target-quota-gb`, + /// default 120 GiB like gc.sh). Priming never goes past it. + pub target_quota_kb: u64, + /// Free space the filesystem keeps in KiB (`--disk-floor-gb`, default 50). + pub disk_floor_kb: u64, + /// What this loop round already fetched and synced (shared by clones of + /// this config; cleared at the start of every round). + pub memo: Arc>, } impl Config { @@ -264,6 +285,13 @@ impl Config { siblings: None, jobs: JobsSpec::default(), no_cache: false, + backoff_cap: idle::DEFAULT_BACKOFF_CAP, + quiet_after: idle::DEFAULT_QUIET_AFTER, + cold: false, + prime: None, + target_quota_kb: idle::DEFAULT_TARGET_QUOTA_KB, + disk_floor_kb: idle::DEFAULT_DISK_FLOOR_KB, + memo: Arc::new(Mutex::new(RoundMemo::default())), } } @@ -324,10 +352,99 @@ fn git(cwd: &Path, args: &[&str]) -> Result { run_cmd(cwd, "git", args) } +/// Per-round memory of the trusted side's network and mirror work, so a +/// round that runs several heads fetches each clone at most once and syncs +/// each mirror only when its clone's refs changed. +#[derive(Debug, Default)] +pub struct RoundMemo { + /// Clones fetched (or found unchanged) this round. + pub fetched: BTreeSet, + /// Mirror synced this round, keyed by repository: the clone's ref digest. + pub synced: BTreeMap, +} + +impl Config { + fn memo(&self) -> std::sync::MutexGuard<'_, RoundMemo> { + self.memo.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// Start a new round: forget what was fetched and synced. + pub fn new_round(&self) { + let mut m = self.memo(); + m.fetched.clear(); + m.synced.clear(); + } +} + +/// `git fetch --quiet --all` in a trusted clone, skipped when the clone has +/// exactly one remote (`origin`) and `git ls-remote origin` shows nothing the +/// configured refspecs would bring in (`idle::refs_unchanged`). Anything +/// unclear fetches exactly as before. `force` (a needed commit is missing) +/// always fetches. At most once per clone per round. +fn fetch_if_changed( + cfg: &Config, + key: &str, + clone: &Path, + force: bool, +) -> Result<&'static str, String> { + if !force && cfg.memo().fetched.contains(key) { + return Ok("fetched earlier this round"); + } + let unchanged = + !force && git(clone, &["remote"]).is_ok_and(|r| r.split_whitespace().eq(["origin"])) && { + let specs: Vec = git(clone, &["config", "--get-all", "remote.origin.fetch"]) + .unwrap_or_default() + .lines() + .map(|l| l.to_string()) + .collect(); + match ( + git(clone, &["ls-remote", "--quiet", "origin"]), + git( + clone, + &["for-each-ref", "--format=%(objectname) %(refname)"], + ), + ) { + (Ok(remote), Ok(local)) => { + idle::refs_unchanged(&remote, &specs, &local) == Some(true) + } + _ => false, + } + }; + let how = if unchanged { + "unchanged on origin, fetch skipped" + } else { + git(clone, &["fetch", "--quiet", "--all"])?; + "fetched" + }; + cfg.memo().fetched.insert(key.to_string()); + Ok(how) +} + +/// `wt.sh sync ` unless this round already synced the mirror +/// from the same clone refs. +fn sync_once(cfg: &Config, tool: &str, repo: &str, clone: &Path) -> Result<(), String> { + let refs = git( + clone, + &["for-each-ref", "--format=%(objectname) %(refname)"], + ) + .map(|r| sha256_hex(r.as_bytes())) + .unwrap_or_default(); + if !refs.is_empty() && cfg.memo().synced.get(repo) == Some(&refs) { + return Ok(()); + } + let clone_s = clone.display().to_string(); + run_cmd(clone, tool, &["sync", repo, &clone_s])?; + if !refs.is_empty() { + cfg.memo().synced.insert(repo.to_string(), refs); + } + Ok(()) +} + /// One sibling checkout a repository's gates reach as `../`: a /// read-only checkout of `/` at `refs/remotes/origin/` -/// as that trusted clone has it when the run starts (never fetched for the -/// run, never the network). +/// as that trusted clone has it when the run starts. The trusted side refreshes +/// the clone at most once per worker round (fetch only when origin moved); +/// the sandbox never reaches the network. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Sibling { pub dir: String, @@ -543,6 +660,15 @@ fn provision_siblings( } for s in sibs { let src = cfg.clones.join(&s.source); + // Refreshed once per round (fetch only when origin moved), so a sibling + // follows its ref without a fetch per run. + match fetch_if_changed(cfg, &s.source, &src, false) { + Ok(how) => notes.push(format!("sibling clone {}: {how}", s.source)), + Err(e) => notes.push(format!( + "sibling clone {}: fetch failed, using what it has: {e}", + s.source + )), + } let want = format!("refs/remotes/origin/{}^{{commit}}", s.git_ref); let sib_sha = match git(&src, &["rev-parse", "--verify", "--quiet", &want]) { Ok(o) if valid_sha(o.trim()) => o.trim().to_string(), @@ -563,8 +689,7 @@ fn provision_siblings( .as_ref() .map(|t| t.display().to_string()) .unwrap_or_default(); - let src_s = src.display().to_string(); - run_cmd(&src, &tool, &["sync", &s.source, &src_s]).and_then(|_| { + sync_once(cfg, &tool, &s.source, &src).and_then(|_| { run_cmd( &src, &tool, @@ -627,7 +752,7 @@ fn checkout_for_sandbox( })?; let tool = tool.display().to_string(); let clone_s = clone.display().to_string(); - run_cmd(clone, &tool, &["sync", repo, &clone_s])?; + sync_once(cfg, &tool, repo, clone)?; let mirror = cfg.mirror_root.join(format!("{repo}.git")); let commit = format!("{sha}^{{commit}}"); if git(&mirror, &["cat-file", "-e", &commit]).is_err() { @@ -714,12 +839,13 @@ fn checkout( return Err(format!("no trusted clone at {}", clone.display())); } let present = |c: &Path| git(c, &["cat-file", "-e", &format!("{sha}^{{commit}}")]).is_ok(); - if !present(&clone) { - if let Err(e) = git(&clone, &["fetch", "--quiet", "--all"]) { - notes.push(format!("fetch failed: {e}")); - } - } else if let Err(e) = git(&clone, &["fetch", "--quiet", "--all"]) { - notes.push(format!("fetch failed (commit already present): {e}")); + // Fetch only when origin shows a change (or the commit is missing); at + // most once per clone per round. + let had = present(&clone); + match fetch_if_changed(cfg, repo, &clone, !had) { + Ok(how) => notes.push(format!("{repo}: {how}")), + Err(e) if had => notes.push(format!("fetch failed (commit already present): {e}")), + Err(e) => notes.push(format!("fetch failed: {e}")), } if !present(&clone) { return Err(format!("commit {sha} is not in {}", clone.display())); @@ -921,6 +1047,8 @@ fn run_in_worktree( opts.sandbox = cfg.sandbox; opts.cargo_target_dir = target_dir_for(cfg, repo, on_main); opts.target_lock_dir = cfg.state.target_lock_dir(); + // Warm standby bookkeeping: which class dir, primed from which main, cold. + let target = target_state(cfg, repo, wt, on_main, notes)?; opts.pool_sizes = opts.pool_sizes.with(cfg.jobs); opts.pins = pins; if fresh || cfg.no_cache { @@ -1041,6 +1169,10 @@ fn run_in_worktree( "removed": plan.removed, "blocked": plan.blocked, }, + // Which cargo target dir the gates used and whether warm standby had + // primed it from main (signed with the rest; `validate` allows + // extra members, this is the first). + "target": target, }); let signed = bundle::sign(&unsigned, &key).map_err(|r| format!("cannot sign bundle: {r}"))?; let bytes = canonical(&signed).map_err(|e| e.to_string())?; @@ -1367,47 +1499,155 @@ pub fn triggers(state: &StateDir) -> Vec<(String, String, PathBuf)> { out } -/// Open PR heads and the main head of `repo` from GitHub (bounded: one call -/// per list). Errors are returned, never fatal to the loop. -pub fn github_heads(gh: &str, repository: &str) -> Result, String> { +/// What one GitHub poll of `repo` sees: open pull request heads with their +/// merge label, and the main head (bounded: one call per list). Errors are +/// returned, never fatal to the loop. +pub fn github_poll(gh: &str, repository: &str) -> Result { let or = owner_repo(repository).ok_or("bad repository name")?; - let mut shas = Vec::new(); - for args in [ - vec![ - "api", - &format!("repos/{or}/pulls?state=open&per_page=50"), - "--jq", - ".[].head.sha", - ], - vec!["api", &format!("repos/{or}/commits/main"), "--jq", ".sha"], - ] { + let call = |path: String, jq: &str| -> Result { let mut cmd = Command::new(gh); - cmd.args(&args); + cmd.args(["api", &path, "--jq", jq]); let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {gh}: {e}"))?; if !out.status.success() { return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); } - for l in String::from_utf8_lossy(&out.stdout).lines() { - let l = l.trim().to_ascii_lowercase(); - if valid_sha(&l) { - shas.push(l); - } - } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) + }; + let pulls = call( + format!("repos/{or}/pulls?state=open&per_page=50"), + &format!( + ".[] | \"\\(.head.sha) \\([.labels[].name] | index(\"{}\") != null)\"", + idle::MERGE_LABEL + ), + )?; + let main = call(format!("repos/{or}/commits/main"), ".sha")?; + let main = main.trim().to_ascii_lowercase(); + Ok(Polled { + prs: idle::parse_pulls(&pulls), + main: valid_sha(&main).then_some(main), + }) +} + +/// The cheap change check: ONE GraphQL call for every repository (open pull +/// request heads with the merge label, and main). Entry `i` answers +/// `repositories[i]`; None for a repository the answer did not cover (the +/// caller polls that one per repository). Err: the call itself failed. +pub fn github_probe(gh: &str, repositories: &[String]) -> Result>, String> { + let pairs: Vec<(String, String)> = repositories + .iter() + .map(|r| { + owner_repo(r) + .and_then(|or| { + or.split_once('/') + .map(|(o, n)| (o.to_string(), n.to_string())) + }) + .ok_or_else(|| format!("bad repository name {r:?}")) + }) + .collect::>()?; + let query = idle::probe_query(&pairs).ok_or("repository name not safe for the probe")?; + let mut cmd = Command::new(gh); + cmd.args([ + "api", + "graphql", + "-f", + &format!("query={query}"), + "--jq", + &idle::probe_jq(), + ]); + let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {gh}: {e}"))?; + if !out.status.success() { + return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); } + Ok(idle::parse_probe( + &String::from_utf8_lossy(&out.stdout), + repositories.len(), + )) +} + +/// Every repository's poll: the probe first, the per-repository REST poll +/// only for what the probe did not cover. Each entry is `(repo, result)`. +pub fn poll_all(cfg: &Config) -> Vec<(String, Result)> { + let names: Vec = cfg + .repos + .iter() + .map(|r| plan::repository_name(&cfg.clones.join(r), None)) + .collect(); + let probed = match github_probe(&cfg.gh, &names) { + Ok(p) => p, + Err(e) => { + println!("GITHUB probe failed: {e} (polling per repository)"); + vec![None; names.len()] + } + }; + cfg.repos + .iter() + .zip(names) + .zip(probed) + .map(|((repo, name), p)| { + let r = match p { + Some(p) => Ok(p), + None => github_poll(&cfg.gh, &name), + }; + (repo.clone(), r) + }) + .collect() +} + +/// Open PR heads and the main head of `repo` from GitHub, as shas. +pub fn github_heads(gh: &str, repository: &str) -> Result, String> { + let p = github_poll(gh, repository)?; + let mut shas: Vec = p.prs.into_iter().map(|h| h.sha).collect(); + shas.extend(p.main); shas.sort(); shas.dedup(); Ok(shas) } -/// The loop: flush the outbox, serve trigger files, poll GitHub when asked, -/// sleep. `iterations` bounds the rounds (None: forever). Returns the number -/// of heads served. +/// Why the chip side wants the machine quiet right now, if it does: +/// `quietlock check` (or the flag file without it). Unknown counts as raised. +pub fn quiet_raised() -> Option { + let q = crate::status::quiet_flag(&crate::resources::GpuConfig::detect()); + (!q.starts_with("clear")).then_some(q) +} + +/// The loop: flush the outbox, serve trigger files, probe GitHub when asked +/// (one GraphQL call for all repositories, every `cfg.poll`, never backed +/// off), run what is new (labeled heads first), prime the pr target dir from +/// main when nothing else waits, then sleep `cfg.poll` in slices that wake on +/// WAKE, PAUSE removal or a trigger file. Only the expensive work backs off: +/// retrying heads that failed to run (fetch, sibling sync) waits the backed-off +/// interval, and cron-tick thins pipeline rounds while QUIET-SINCE is old. +/// `iterations` bounds the rounds (None: forever). Returns the number of heads +/// served. +/// +/// Activity (resets the poll to `cfg.poll`, removes QUIET-SINCE): a trigger +/// file, a poll that differs from the previous one for a repository (new +/// head, label added or removed, main moved), a head run that had not failed +/// to run before, a wake. Priming is never activity. pub fn run_loop(cfg: &Config, iterations: Option) -> usize { let mut served = 0; let mut round = 0u64; + let root = cfg.state.root.clone(); + let mut backoff = idle::Backoff::new( + cfg.poll, + cfg.backoff_cap, + cfg.quiet_after, + SystemTime::now(), + ); + let mut watch = idle::WakeWatch::new(&root); + let mut seen: BTreeMap = BTreeMap::new(); + let mut errored: BTreeSet<(String, String)> = BTreeSet::new(); + let mut prime_failed: BTreeSet<(String, String)> = BTreeSet::new(); + let mut last_retry = std::time::Instant::now(); + if cfg.github { + idle::remove_quiet_since(&root); + } loop { round += 1; + cfg.new_round(); cfg.state.beat("-", "-", "poll"); + let mut activity = false; + let mut run_now = false; // Posting is the operator's choice (--github). A loop without it leaves // queued statuses where they are, so `aien-local-ci start` after an // offline --github run never posts them behind the operator's back. @@ -1423,22 +1663,62 @@ pub fn run_loop(cfg: &Config, iterations: Option) -> usize { .into_iter() .map(|(r, s, f)| (r, s, Some(f))) .collect(); + activity |= !heads.is_empty(); + let mut mains: BTreeMap = BTreeMap::new(); if cfg.github { - for repo in &cfg.repos { - let repository = plan::repository_name(&cfg.clones.join(repo), None); - match github_heads(&cfg.gh, &repository) { - Ok(shas) => { - for s in shas { - if !cfg.state.bundle_path(repo, &s).exists() { - heads.push((repo.clone(), s, None)); + let mut new: Vec<(String, PrHead)> = Vec::new(); + for (repo, polled) in poll_all(cfg) { + let repo = &repo; + match polled { + Ok(p) => { + activity |= idle::moved(seen.get(repo), &p); + let mut all = p.prs.clone(); + if let Some(m) = &p.main { + mains.insert(repo.clone(), m.clone()); + all.push(PrHead { + sha: m.clone(), + labeled: false, + }); + } + for h in all { + if !cfg.state.bundle_path(repo, &h.sha).exists() { + new.push((repo.clone(), h)); } } + seen.insert(repo.clone(), p); } Err(e) => println!("GITHUB unreachable for {repo}: {e} (will retry)"), } } + // Labeled heads first (the merge waits on them), across repositories. + new.sort_by(|(ra, a), (rb, b)| { + b.labeled + .cmp(&a.labeled) + .then(ra.cmp(rb)) + .then(a.sha.cmp(&b.sha)) + }); + new.dedup(); + for (repo, h) in new { + if !heads.iter().any(|(r, s, _)| *r == repo && *s == h.sha) { + heads.push((repo, h.sha, None)); + } + } + } + // A head that already failed to run is retried only once the backed-off + // interval has passed (a retry is a fetch and a sibling sync); the cheap + // probe above runs every round regardless. + let retry_due = last_retry.elapsed() >= backoff.interval(); + heads.retain(|(r, s, t)| { + t.is_some() || retry_due || !errored.contains(&(r.clone(), s.clone())) + }); + if retry_due { + last_retry = std::time::Instant::now(); } + let had_work = !heads.is_empty(); for (repo, sha, trigger) in heads { + // A head that already failed to run in this loop is retried every + // round but does not keep the worker awake. + activity |= trigger.is_some() || !errored.contains(&(repo.clone(), sha.clone())); match run_once(cfg, &repo, &sha) { Ok(s) => { println!( @@ -1449,9 +1729,11 @@ pub fn run_loop(cfg: &Config, iterations: Option) -> usize { s.publication ); served += 1; + errored.remove(&(repo.clone(), sha.clone())); } Err(e) => { println!("HEAD {repo} {sha} ERROR {e}"); + errored.insert((repo.clone(), sha.clone())); let _ = cfg.state.journal_append(&json!({ "utc": utc_string(now_secs()), "repo": repo, @@ -1466,18 +1748,681 @@ pub fn run_loop(cfg: &Config, iterations: Option) -> usize { let _ = fs::remove_file(f); } } + // Warm standby: lowest priority, only in a round with nothing to run. + if cfg.github && !had_work && !watch.paused() { + if let Some(why) = prime_pending(cfg, &mains, &mut prime_failed, &errored, &mut watch) { + println!("PRIME interrupted: {why}"); + activity |= idle::interrupt_is_activity(&why); + run_now = !idle::sleep_after_interrupt(Some(&why)); + } + } + let now = SystemTime::now(); + if activity { + backoff.activity(now); + if cfg.github { + idle::remove_quiet_since(&root); + } + } else { + backoff.idle_round(now); + if cfg.github && idle::read_quiet_since(&root).is_none() { + if let Err(e) = idle::write_quiet_since(&root, backoff.last_activity()) { + println!("QUIET-SINCE not written: {e}"); + } + } + } if iterations.is_some_and(|n| round >= n) { break; } - std::thread::sleep(cfg.poll); + // A new head or a wake stopped priming: serve it now, no sleep. + if run_now { + continue; + } + // The probe is cheap, so it runs every `cfg.poll`, quiet or not: a new + // head or label is seen within one poll. Only retries back off. + if let Some(why) = sliced_sleep(cfg, cfg.poll, &mut watch) { + println!("WAKE {why}"); + backoff.activity(SystemTime::now()); + if cfg.github { + idle::remove_quiet_since(&root); + } + } } served } +/// Sleep up to `wait` in `idle::SLICE` steps, writing the heartbeat each +/// step (no network, no process) and returning early with the reason when a +/// local wake source fires. +fn sliced_sleep(cfg: &Config, wait: Duration, watch: &mut idle::WakeWatch) -> Option<&'static str> { + let start = std::time::Instant::now(); + loop { + let left = wait.saturating_sub(start.elapsed()); + if left.is_zero() { + return None; + } + std::thread::sleep(left.min(idle::SLICE)); + cfg.state.beat("-", "-", "sleep"); + if let Some(w) = watch.check() { + return Some(w); + } + } +} + +/// The prime lines of `repo` from `cfg.prime` (none without a map). +fn prime_for(cfg: &Config, repo: &str) -> Result, String> { + let Some(path) = &cfg.prime else { + return Ok(Vec::new()); + }; + let text = fs::read_to_string(path) + .map_err(|e| format!("cannot read the prime map {}: {e}", path.display()))?; + idle::parse_prime(&text, repo) +} + +/// Prime the first repository whose pr target dir is not warm from its +/// current main (as polled this round). Returns the reason when a real head, +/// a wake or the quiet flag stopped it. +fn prime_pending( + cfg: &Config, + mains: &BTreeMap, + failed: &mut BTreeSet<(String, String)>, + errored: &BTreeSet<(String, String)>, + watch: &mut idle::WakeWatch, +) -> Option { + if cfg.sandbox != Sandbox::User { + return None; + } + for repo in &cfg.repos { + let Some(main) = mains.get(repo) else { + continue; + }; + let key = (repo.clone(), main.clone()); + if failed.contains(&key) + || idle::read_warm(&cfg.state.root, repo).is_some_and(|w| w.primed_from_main == *main) + { + continue; + } + match prime_for(cfg, repo) { + Ok(l) if l.is_empty() => continue, + Ok(_) => {} + Err(e) => { + println!("PRIME refused: {e}"); + return None; + } + } + if let Some(q) = quiet_raised() { + return Some(q); + } + let started = now_secs(); + let outcome = prime_once(cfg, repo, main, main, &mut |c| { + prime_stop(c, watch, errored) + }); + let (word, why) = match &outcome { + Ok(PrimeOutcome::Warm) => ("warm", None), + Ok(PrimeOutcome::Interrupted(w)) => ("interrupted", Some(w.clone())), + Ok(PrimeOutcome::Cold(_)) => { + failed.insert(key); + ("cold", None) + } + Ok(PrimeOutcome::Failed(_)) | Err(_) => { + failed.insert(key); + ("failed", None) + } + }; + let detail = match &outcome { + Ok(PrimeOutcome::Failed(d)) + | Ok(PrimeOutcome::Interrupted(d)) + | Ok(PrimeOutcome::Cold(d)) => d.clone(), + Err(e) => e.clone(), + _ => String::new(), + }; + println!("PRIME {repo} {main} {word} {detail}"); + let _ = cfg.state.journal_append(&json!({ + "utc": utc_string(now_secs()), + "kind": "prime", + "repo": repo, + "sha": main, + "class": "pr", + "outcome": word, + "detail": detail, + "secs": now_secs().saturating_sub(started), + })); + // One repository per round keeps the round short; the next idle + // round primes the next one. + return why; + } + None +} + +/// While priming: stop for a trigger file, WAKE, PAUSE (either way), the +/// quiet flag, or (once a minute) any polled head without a bundle. +fn prime_stop( + cfg: &Config, + watch: &mut idle::WakeWatch, + errored: &BTreeSet<(String, String)>, +) -> Option { + thread_local! { + static LAST_POLL: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + if let Some(w) = watch.check() { + return Some(w.to_string()); + } + if watch.paused() || cfg.state.root.join(idle::PAUSE).exists() { + return Some("PAUSE present".to_string()); + } + if let Some(q) = quiet_raised() { + return Some(q); + } + let now = now_secs(); + if now.saturating_sub(LAST_POLL.with(|c| c.get())) >= 60 { + LAST_POLL.with(|c| c.set(now)); + let polls: Vec<(String, Polled)> = poll_all(cfg) + .into_iter() + .filter_map(|(r, p)| p.ok().map(|p| (r, p))) + .collect(); + let bundled = |r: &str, s: &str| cfg.state.bundle_path(r, s).exists(); + if let Some((repo, s)) = idle::unserved_head(&polls, &bundled, errored) { + return Some(format!("new head {repo} {s}")); + } + } + None +} + +/// How one priming ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PrimeOutcome { + /// Every prime line exited 0: `warm/.json` written. + Warm, + /// A real head, a wake or the quiet flag stopped it (no record). + Interrupted(String), + /// A prime line failed (no record). + Failed(String), + /// The disk bound refused priming (pr left as it is) or stopped it (pr + /// emptied); no record: runs are not warm until space is freed. + Cold(String), +} + +/// Warm standby for one repository: check out `sha` (which must be the main +/// head polled this round and on the base line), run every prime line inside +/// the sandbox (profile host, never gb10 or qemu) with the pr class target +/// dir. Main is trusted, so its build may seed the lower class; nothing ever +/// writes the main class from here. The warm record is removed first and +/// written only when every line exited 0. +pub fn prime_once( + cfg: &Config, + repo: &str, + sha: &str, + polled_main: &str, + stop: &mut dyn FnMut(&Config) -> Option, +) -> Result { + if !valid_repo_key(repo) || !valid_sha(sha) { + return Err(format!("refusing to prime {repo:?} {sha:?}")); + } + if sha != polled_main { + return Err(format!( + "prime sha {sha} is not the polled main head {polled_main}" + )); + } + if cfg.sandbox != Sandbox::User || cfg.wt_tool.is_none() { + return Err("priming needs --sandbox user and the worktree tool".to_string()); + } + let lines = prime_for(cfg, repo)?; + if lines.is_empty() { + return Err(format!("no prime lines for {repo}")); + } + let target = target_dir_for(cfg, repo, false).ok_or("no pr class target dir")?; + if target != cfg.target_root.join(repo).join("pr") { + return Err(format!( + "prime target {} is not the pr class dir", + target.display() + )); + } + let sibs = siblings_for(cfg, repo)?; + let pins = pins_for(cfg, repo)?; + let mut notes = Vec::new(); + cfg.state.beat(repo, sha, "prime"); + let co = checkout(cfg, repo, sha, &mut notes)?; + ensure_pins(&cfg.clones, &pins, &sibs, &mut notes); + let _ = provision_siblings(cfg, repo, sha, &co, &sibs, &pins, &mut notes); + let trust = process::trust_worktree(&co.wt); + let result = (|| { + let (_, on_main) = plan::base_for(&co.wt, &cfg.base_ref, sha)?; + if !on_main { + return Err(format!("{sha} is not on {}: never primed", cfg.base_ref)); + } + idle::clear_warm(&cfg.state.root, repo); + // The target dir lock (shared with the gates that build there) is held + // for the disk decision, any eviction and every prime line. + let _lock = match lock_target_wait(cfg, &target, &mut || stop(cfg))? { + Ok(l) => l, + Err(why) => return Ok(PrimeOutcome::Interrupted(why)), + }; + let d = disk_now(cfg, repo, &co.wt)?; + let before = format!( + "disk before: target {} GiB (pr {} GiB), {} GiB free", + d.total >> 20, + d.pr >> 20, + d.free >> 20 + ); + println!("PRIME {repo} {before}"); + match idle::disk_plan( + d.total, + d.pr, + cfg.target_quota_kb, + d.free, + cfg.disk_floor_kb, + ) { + idle::DiskPlan::Prime => {} + idle::DiskPlan::WipeThenPrime => { + println!("PRIME {repo} {}", wipe_pr_dir_locked(cfg, repo, &co.wt)?); + } + idle::DiskPlan::NoPrime(why) => { + // Emptying pr would not make room for priming; what PR runs + // left there is gc.sh's to bound, so it stays as it is. + return Ok(PrimeOutcome::Cold(format!("{why}; {before}"))); + } + } + let log = cfg.state.root.join("warm").join(format!("{repo}.log")); + let mut last_du = std::time::Instant::now(); + let mut disk_stop = || -> Option { + // statvfs every ask (no process); the repository total once a + // minute. A check that fails stops priming (idle::disk_verdict). + let total = (last_du.elapsed() >= Duration::from_secs(60)).then(|| { + last_du = std::time::Instant::now(); + disk_now(cfg, repo, &co.wt).map(|d| d.total) + }); + idle::disk_verdict( + free_kb(&cfg.target_root), + total, + cfg.target_quota_kb, + cfg.disk_floor_kb, + ) + }; + for l in &lines { + let mut env = sandbox::env_pairs(Some(&target)); + env.extend(l.env.iter().cloned()); + let mut ask = || stop(cfg).or_else(&mut disk_stop); + match sandbox_exec(&co.wt, "cargo", &l.args, &env, 3600, &log, Some(&mut ask))? { + ExecEnd::Exit(0) => {} + ExecEnd::Exit(rc) => { + return Ok(PrimeOutcome::Failed(format!( + "cargo {} exited {rc} (log {})", + l.args.join(" "), + log.display() + ))) + } + ExecEnd::Stopped(why) if why.starts_with("disk:") => { + // Fail closed: never leave a half-primed dir past the bound. + println!("PRIME {repo} {}", wipe_pr_dir_locked(cfg, repo, &co.wt)?); + return Ok(PrimeOutcome::Cold(why)); + } + ExecEnd::Stopped(why) => return Ok(PrimeOutcome::Interrupted(why)), + } + } + let d = disk_now(cfg, repo, &co.wt)?; + let after = format!( + "disk after: target {} GiB (pr {} GiB), {} GiB free", + d.total >> 20, + d.pr >> 20, + d.free >> 20 + ); + println!("PRIME {repo} {after}"); + if let Some(why) = idle::disk_over(d.total, cfg.target_quota_kb, d.free, cfg.disk_floor_kb) + { + println!("PRIME {repo} {}", wipe_pr_dir_locked(cfg, repo, &co.wt)?); + return Ok(PrimeOutcome::Cold(format!( + "{why} after priming; {before}; {after}" + ))); + } + idle::write_warm( + &cfg.state.root, + repo, + &idle::WarmRecord { + primed_from_main: sha.to_string(), + utc: utc_string(now_secs()), + }, + lines.len(), + )?; + Ok(PrimeOutcome::Warm) + })(); + drop(trust); + if let Some(tool) = &cfg.wt_tool { + let tool = tool.display().to_string(); + if let Err(e) = run_cmd(&co.clone, &tool, &["remove", repo, sha]) { + println!("PRIME worktree not removed: {e}"); + } + } + cfg.state.beat("-", "-", "idle"); + result +} + +/// How a sandboxed command ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ExecEnd { + Exit(i32), + Stopped(String), +} + +/// Run `program args` through the exec helper (profile host) in `cwd`, output +/// to `log`. `stop` is asked every `idle::SLICE`; when it answers, the helper +/// gets SIGTERM (its trap stops the whole scope), SIGKILL after 30 s more. +fn sandbox_exec( + cwd: &Path, + program: &str, + args: &[String], + env: &[(String, String)], + timeout_secs: u64, + log: &Path, + mut stop: Option<&mut dyn FnMut() -> Option>, +) -> Result { + // Everything run here is warm standby or its housekeeping: below the gates. + let (program, args) = idle::low_priority(program, args); + let (prog, argv) = sandbox::command( + Sandbox::User, + Path::new(&program), + &args, + cwd, + timeout_secs, + "host", + env, + ); + if let Some(d) = log.parent() { + let _ = fs::create_dir_all(d); + } + let out = fs::File::create(log).map_err(|e| format!("cannot write {}: {e}", log.display()))?; + let err = out.try_clone().map_err(|e| e.to_string())?; + let mut child = Command::new(&prog) + .args(&argv) + .stdin(std::process::Stdio::null()) + .stdout(out) + .stderr(err) + .spawn() + .map_err(|e| format!("cannot run {}: {e}", prog.display()))?; + let mut last_ask = std::time::Instant::now(); + loop { + if let Some(st) = child.try_wait().map_err(|e| e.to_string())? { + return Ok(ExecEnd::Exit(st.code().unwrap_or(-1))); + } + if last_ask.elapsed() >= idle::SLICE { + last_ask = std::time::Instant::now(); + if let Some(why) = stop.as_mut().and_then(|s| s()) { + // SAFETY: plain kill(2) on our own child's pid. + unsafe { + libc::kill(child.id() as libc::pid_t, libc::SIGTERM); + } + let t = std::time::Instant::now(); + while t.elapsed() < Duration::from_secs(30) { + if child.try_wait().map_err(|e| e.to_string())?.is_some() { + return Ok(ExecEnd::Stopped(why)); + } + std::thread::sleep(Duration::from_millis(200)); + } + let _ = child.kill(); + let _ = child.wait(); + return Ok(ExecEnd::Stopped(why)); + } + } + std::thread::sleep(Duration::from_millis(500)); + } +} + +/// Empty `target//pr` from inside the sandbox (as aien-run, who owns +/// what is in it) and drop the warm record. `cwd` is a worktree of the run or +/// the sandbox home itself (the exec helper allows both). Never the main class. +pub fn wipe_pr_target(cfg: &Config, repo: &str, cwd: &Path) -> Result { + if cfg.sandbox != Sandbox::User { + return Err("emptying the pr class dir needs --sandbox user".to_string()); + } + let dir = target_dir_for(cfg, repo, false).ok_or("no pr class target dir")?; + // Waits for whatever builds there now (an operator action: no stop). + let _lock = lock_target_wait(cfg, &dir, &mut || None)? + .map_err(|w| format!("target lock not taken: {w}"))?; + wipe_pr_dir_locked(cfg, repo, cwd) +} + +/// The target dir flock for `dir` (`/locks/target/.lock`, +/// the same file the runner locks around a cargo gate). Tries without +/// blocking every `idle::SLICE` and gives up with `stop`'s reason; the inner +/// Err is that reason, the outer one an I/O failure. Released on drop; the +/// descriptor is close-on-exec, so no child inherits it. +fn lock_target_wait( + cfg: &Config, + dir: &Path, + stop: &mut dyn FnMut() -> Option, +) -> Result, String> { + use std::os::fd::AsRawFd; + let p = idle::target_lock_path(&cfg.state.root.join("locks").join("target"), dir); + if let Some(d) = p.parent() { + fs::create_dir_all(d).map_err(|e| format!("cannot create {}: {e}", d.display()))?; + } + let f = fs::OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(&p) + .map_err(|e| format!("cannot open {}: {e}", p.display()))?; + loop { + // SAFETY: flock(2) on a descriptor this function owns. + if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + return Ok(Ok(f)); + } + let e = std::io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::EWOULDBLOCK) { + return Err(format!("cannot lock {}: {e}", p.display())); + } + if let Some(why) = stop() { + return Ok(Err(why)); + } + cfg.state.beat("-", "-", "wait-target-lock"); + std::thread::sleep(idle::SLICE); + } +} + +/// Disk state of one repository's target dirs, in KiB. +struct DiskNow { + total: u64, + pr: u64, + free: u64, +} + +/// Free KiB for unprivileged use on the filesystem holding `path`. +fn free_kb(path: &Path) -> Result { + use std::os::unix::ffi::OsStrExt; + let c = std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(|e| e.to_string())?; + // SAFETY: statvfs(3) into a zeroed struct we own, with a valid C string. + let mut s: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statvfs(c.as_ptr(), &mut s) } != 0 { + return Err(format!( + "statvfs {}: {}", + path.display(), + std::io::Error::last_os_error() + )); + } + Ok((s.f_bavail as u64).saturating_mul(s.f_frsize as u64) / 1024) +} + +/// `du -sk` of `target//{pr,main}` from inside the sandbox (aien-run +/// owns them) plus the filesystem's free space. A dir that does not exist is +/// 0; one du did not report is an error (never read as empty). +fn disk_now(cfg: &Config, repo: &str, cwd: &Path) -> Result { + let base = cfg.target_root.join(repo); + let (pr, main) = (base.join("pr"), base.join("main")); + let dirs: Vec<&PathBuf> = [&pr, &main].into_iter().filter(|d| d.exists()).collect(); + let mut sizes: BTreeMap = BTreeMap::new(); + if !dirs.is_empty() { + let log = cfg.state.root.join("warm").join(format!("{repo}.du.log")); + let mut args = vec!["-sk".to_string()]; + args.extend(dirs.iter().map(|d| d.display().to_string())); + // du exits 1 when a file vanished under it (a build running); the + // totals it prints are still the sizes, so the exit code is not used. + sandbox_exec( + cwd, + "du", + &args, + &sandbox::env_pairs(Some(&pr)), + 600, + &log, + None, + )?; + let text = + fs::read_to_string(&log).map_err(|e| format!("cannot read {}: {e}", log.display()))?; + for l in text.lines() { + if let Some((n, p)) = l.split_once('\t') { + if let Ok(n) = n.trim().parse::() { + sizes.insert(p.trim_end_matches('/').to_string(), n); + } + } + } + for d in &dirs { + if !sizes.contains_key(&d.display().to_string()) { + return Err(format!( + "du did not report {} (log {})", + d.display(), + log.display() + )); + } + } + } + let pr_kb = sizes.get(&pr.display().to_string()).copied().unwrap_or(0); + let main_kb = sizes.get(&main.display().to_string()).copied().unwrap_or(0); + Ok(DiskNow { + total: pr_kb + main_kb, + pr: pr_kb, + free: free_kb(&cfg.target_root)?, + }) +} + +/// Empty `target//pr` (the caller holds its target lock) and drop the +/// warm record. +fn wipe_pr_dir_locked(cfg: &Config, repo: &str, cwd: &Path) -> Result { + let dir = target_dir_for(cfg, repo, false).ok_or("no pr class target dir")?; + if dir != cfg.target_root.join(repo).join("pr") { + return Err(format!("{} is not the pr class dir", dir.display())); + } + idle::clear_warm(&cfg.state.root, repo); + let log = cfg.state.root.join("warm").join(format!("{repo}.cold.log")); + let args: Vec = vec![ + dir.display().to_string(), + "-mindepth".into(), + "1".into(), + "-delete".into(), + ]; + match sandbox_exec( + cwd, + "find", + &args, + &sandbox::env_pairs(Some(&dir)), + 600, + &log, + None, + )? { + ExecEnd::Exit(0) => Ok(format!("cold: emptied {}", dir.display())), + other => Err(format!( + "cold: could not empty {}: {other:?} (log {})", + dir.display(), + log.display() + )), + } +} + +/// `worker --once REPO MAIN --prime-only [--cold]`: the operator's priming +/// (the cold-equals-warm proof uses it). MAIN must be the trusted clone's +/// `origin/main` after a fetch; with `cold` the pr class dir is emptied first. +/// Stops only for the quiet flag. +pub fn prime_now(cfg: &Config, repo: &str, sha: &str) -> Result { + if !valid_repo_key(repo) || !valid_sha(sha) { + return Err(format!("refusing to prime {repo:?} {sha:?}")); + } + let clone = cfg.clones.join(repo); + fetch_if_changed(cfg, repo, &clone, false)?; + let main = git( + &clone, + &["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"], + )?; + let main = main.trim(); + if cfg.cold { + let home = cfg + .target_root + .parent() + .unwrap_or(Path::new("/var/lib/aien-run")); + println!("NOTE {}", wipe_pr_target(cfg, repo, home)?); + } + prime_once(cfg, repo, sha, main, &mut |_| quiet_raised()) +} + +/// The `target` member for this run, and the cold wipe when asked: under the +/// user sandbox the class dir is `main` or `pr`; a pr run is warm when the +/// complete warm record existed at run start. `--cold` empties the pr class +/// dir from inside the sandbox (as aien-run, the only one who can) and drops +/// the record; it refuses a head on main (the main class is never wiped). +fn target_state( + cfg: &Config, + repo: &str, + wt: &Path, + on_main: bool, + notes: &mut Vec, +) -> Result { + if cfg.sandbox != Sandbox::User { + if cfg.cold { + return Err( + "--cold needs --sandbox user (it empties the pr class target dir)".to_string(), + ); + } + return Ok(idle::target_member("unsandboxed", None, false)); + } + let class = if on_main { "main" } else { "pr" }; + if cfg.cold { + if on_main { + return Err("--cold empties only the pr class dir; this head is on main".to_string()); + } + notes.push(wipe_pr_target(cfg, repo, wt)?); + return Ok(idle::target_member(class, None, true)); + } + // Warm needs the complete record and a class dir that is not empty (a + // dir emptied behind the worker's back, by gc.sh say, is cold). + let pr_dir = cfg.target_root.join(repo).join("pr"); + let non_empty = fs::read_dir(&pr_dir).is_ok_and(|mut d| d.next().is_some()); + let warm = if on_main || !non_empty { + None + } else { + idle::read_warm(&cfg.state.root, repo) + }; + Ok(idle::target_member(class, warm.as_ref(), false)) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn target_lock_excludes_a_second_holder_and_gives_up_on_stop() { + use std::os::fd::AsRawFd; + let d = std::env::temp_dir().join(format!("aien-test-lock-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + let cfg = Config::new(StateDir::new(&d), &d, &d, &d); + let dir = Path::new("/var/lib/aien-run/target/r/pr"); + let held = lock_target_wait(&cfg, dir, &mut || None).unwrap().unwrap(); + let p = d.join("locks/target/_var_lib_aien-run_target_r_pr.lock"); + assert!(p.is_file(), "lock file at the shared path"); + // flock locks belong to the open file: a second open of the same file + // (another process, or this one) cannot take it while `held` lives. + let mut asked = 0; + let r = lock_target_wait(&cfg, dir, &mut || { + asked += 1; + Some("WAKE touched".to_string()) + }) + .unwrap(); + assert_eq!(r.unwrap_err(), "WAKE touched"); + assert_eq!(asked, 1); + // SAFETY: test-only flock probe on a descriptor we own. + assert_eq!(unsafe { libc::flock(held.as_raw_fd(), libc::LOCK_UN) }, 0); + drop(held); + assert!(lock_target_wait(&cfg, dir, &mut || Some("x".into())) + .unwrap() + .is_ok()); + let _ = fs::remove_dir_all(&d); + } + #[test] fn pin_list_selects_the_repository_and_refuses_bad_lines() { let sha = "353b7d4be3f00169545caec1615cffa61f7d311a"; diff --git a/tools/aien-test/tests/local_ci.rs b/tools/aien-test/tests/local_ci.rs index 277c2b34..5a3fc575 100644 --- a/tools/aien-test/tests/local_ci.rs +++ b/tools/aien-test/tests/local_ci.rs @@ -11,6 +11,7 @@ use aien_test::bundle; use aien_test::evidence::canonical; +use aien_test::idle; use aien_test::plan::{self, Request}; use aien_test::runner::{self, Options}; use aien_test::sandbox::Sandbox; @@ -1558,3 +1559,185 @@ fn worker_operator_run_of_a_config_change_is_ready_and_posts_success() { "{journal}" ); } + +/// A fake `gh` for the loop: `pulls` answers from `/pulls.txt`, `commits/main` +/// from `/main.txt`, statuses are logged. +fn poll_gh(w: &World, pulls: &str, main: &str) -> PathBuf { + let r = &w.state.root; + fs::create_dir_all(r).unwrap(); + fs::write(r.join("pulls.txt"), pulls).unwrap(); + fs::write(r.join("main.txt"), format!("{main}\n")).unwrap(); + let fake = r.join("poll-gh"); + fs::write( + &fake, + format!( + "#!/bin/sh\nroot={}\necho \"$@\" >> \"$root/gh.log\"\ncase \"$2\" in graphql) cat \"$root/probe.txt\" 2>/dev/null;; *pulls*) cat \"$root/pulls.txt\";; *commits/main*) cat \"$root/main.txt\";; esac\nexit 0\n", + r.display() + ), + ) + .unwrap(); + fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap(); + fake +} + +#[test] +fn quiet_loop_writes_quiet_since_and_a_failing_head_does_not_keep_it_awake() { + let w = world(); + // An open PR whose head is not in any clone: it fails to run every round. + let ghost = "dddddddddddddddddddddddddddddddddddddddd"; + let fake = poll_gh(&w, &format!("{} true\n{ghost} false\n", w.head), &w.base); + let mut cfg = w.config(); + cfg.github = true; + cfg.gh = fake.display().to_string(); + cfg.repos = vec![REPO.to_string()]; + cfg.poll = std::time::Duration::from_secs(1); + cfg.quiet_after = std::time::Duration::ZERO; + let quiet = w.state.root.join(idle::QUIET_SINCE); + fs::write(&quiet, "1 stale\n").unwrap(); + // Round 1: first poll moves, heads run (the ghost fails); round 2: nothing + // moved and the ghost has failed before, so the worker goes quiet. + let served = worker::run_loop(&cfg, Some(2)); + // main (the root commit, no parent to plan against) fails to run, like the ghost. + assert_eq!(served, 1, "the labeled head served once"); + let since = idle::read_quiet_since(&w.state.root).expect("QUIET-SINCE written"); + assert!( + since > 1, + "the stale marker was removed at start and rewritten" + ); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + assert!(since <= now && now - since < 120); + // The labeled head was served before main (labeled first). + let j = fs::read_to_string(w.state.journal()).unwrap(); + let head_at = j.find(&w.head).unwrap(); + let ghost_at = j.find(ghost).unwrap(); + assert!(head_at < ghost_at, "labeled head first"); + // Every bundle says which target it used. + let b = w.read_bundle(&w.head); + assert_eq!(b["target"]["class"], "unsandboxed"); + assert_eq!(b["target"]["warm"], false); + assert_eq!(b["target"]["cold"], false); +} + +#[test] +fn a_loop_without_github_never_writes_quiet_since() { + let w = world(); + let mut cfg = w.config(); + cfg.poll = std::time::Duration::from_secs(1); + cfg.quiet_after = std::time::Duration::ZERO; + fs::create_dir_all(&w.state.root).unwrap(); + worker::run_loop(&cfg, Some(2)); + assert!(!w.state.root.join(idle::QUIET_SINCE).exists()); +} + +#[test] +fn fetch_is_skipped_when_origin_did_not_move() { + let w = world(); + let cfg = w.config(); + let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); + assert!( + s.notes + .iter() + .any(|n| n.contains("unchanged on origin, fetch skipped")), + "{:?}", + s.notes + ); + // Same round: no second look at origin. + let s = worker::run_once(&cfg, REPO, &w.head_h).expect("worker"); + assert!( + s.notes + .iter() + .any(|n| n.contains("fetched earlier this round")), + "{:?}", + s.notes + ); + // Origin moves: the next round fetches, and the new branch arrives. + git(&w.origin, &["checkout", "-q", "-b", "later", "main"]); + write(&w.origin, "a/a.txt", "3\n", false); + git(&w.origin, &["add", "-A"]); + git(&w.origin, &["commit", "-q", "-m", "later"]); + let later = git(&w.origin, &["rev-parse", "HEAD"]); + git(&w.origin, &["checkout", "-q", "main"]); + cfg.new_round(); + let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); + assert!( + s.notes.iter().any(|n| n.ends_with(": fetched")), + "{:?}", + s.notes + ); + assert_eq!( + git(&w.clone, &["rev-parse", "refs/remotes/origin/later"]), + later + ); + // A missing commit always fetches, even when fetched earlier this round. + git(&w.origin, &["checkout", "-q", "-b", "later2", "main"]); + write(&w.origin, "a/a.txt", "4\n", false); + git(&w.origin, &["add", "-A"]); + git(&w.origin, &["commit", "-q", "-m", "later2"]); + let later2 = git(&w.origin, &["rev-parse", "HEAD"]); + git(&w.origin, &["checkout", "-q", "main"]); + let s = worker::run_once(&cfg, REPO, &later2).expect("missing commit is fetched"); + assert_eq!(s.sha, later2); +} + +#[test] +fn cold_and_priming_refuse_outside_the_user_sandbox() { + let w = world(); + let mut cfg = w.config(); + cfg.cold = true; + let e = worker::run_once(&cfg, REPO, &w.head).unwrap_err(); + assert!(e.contains("--cold needs --sandbox user"), "{e}"); + cfg.cold = false; + let mut never = |_: &Config| -> Option { None }; + let e = worker::prime_once(&cfg, REPO, &w.base, &w.base, &mut never).unwrap_err(); + assert!(e.contains("--sandbox user"), "{e}"); + let e = worker::prime_once(&cfg, REPO, &w.base, &w.head, &mut never).unwrap_err(); + assert!(e.contains("is not the polled main head"), "{e}"); + let e = worker::prime_once(&cfg, "../x", &w.base, &w.base, &mut never).unwrap_err(); + assert!(e.contains("refusing to prime"), "{e}"); +} + +#[test] +fn one_probe_call_serves_the_loop_and_a_partial_probe_falls_back_to_rest() { + let w = world(); + // REST would offer nothing new; only the probe names the labeled head. + let fake = poll_gh(&w, "", &w.base); + fs::write( + w.state.root.join("probe.txt"), + format!("r0 main {}\nr0 pr {} true\n", w.base, w.head), + ) + .unwrap(); + let mut cfg = w.config(); + cfg.github = true; + cfg.gh = fake.display().to_string(); + cfg.repos = vec![REPO.to_string()]; + cfg.poll = std::time::Duration::from_secs(1); + let served = worker::run_loop(&cfg, Some(1)); + assert_eq!(served, 1, "the labeled head from the probe ran"); + let log = fs::read_to_string(w.state.root.join("gh.log")).unwrap(); + assert!(log.contains("api graphql"), "{log}"); + assert!( + !log.contains("pulls") && !log.contains("commits/main"), + "no per-repository REST call when the probe answered: {log}" + ); + // A probe answer without the main line never reads as "no pull + // requests": that repository is polled per repository instead. + fs::write( + w.state.root.join("probe.txt"), + format!("r0 pr {} true\n", w.head_h), + ) + .unwrap(); + fs::remove_file(w.state.root.join("gh.log")).unwrap(); + worker::run_loop(&cfg, Some(1)); + let log = fs::read_to_string(w.state.root.join("gh.log")).unwrap(); + assert!( + log.contains("pulls") && log.contains("commits/main"), + "{log}" + ); + assert!( + !cfg.state.bundle_path(REPO, &w.head_h).exists(), + "a head only a partial probe named was not trusted" + ); +} ```