diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b3ad934e2..35a782403 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -171,7 +171,13 @@ starts only while the machine has `MO_CI_LANE_MIN_FREE_MB` of memory available ( 8192, plus as much again for each lane started in the last 30 seconds; `0` turns it off), so a run on a busy machine queues its lanes. Without that check the run drove the machine down to the out-of-memory killer, and a killed test host looked like a test crash. -`scripts/test-ci-lane-memory.sh` (in the `gates` lane) pins the rule. `--quick` and +`scripts/test-ci-lane-memory.sh` (in the `gates` lane) pins the rule. One checkout runs one +`scripts/ci-local.sh` at a time: a second run started while the first is going refuses and +names the first, because two runs rebuild `server/java` and `server/rust` under each other and +fail each other's lanes. Sibling worktrees are separate checkouts and run side by side. +A run killed mid-claim can leave its lock directory `mo-ci-local.claim.lock` in the worktree's +git directory; remove it by hand if a later run refuses on a lock. `scripts/test-ci-checkout-claim.sh` +(in the `gates` lane) pins that. `--quick` and `--only` run serially. `MO_CI_PY_WORKERS` (default 8), `MO_CI_TS_WORKERS` (default 6) and `MO_CI_JVM_FORKS` (default 3) set the worker counts for pytest-xdist, the TypeScript integration suite and the TypeScript `codegen-ts` conformance suite, and the JVM diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 72a526341..1be5c69a8 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -416,7 +416,7 @@ gate_uv_lock_version() { scripts/check-uv-lock-version.sh; } # test — a wrong answer here does not fail, it silently stops testing a port. gate_ci_port_selection() { scripts/test-ci-affected-ports.sh && scripts/test-ci-ports-to-run.sh && scripts/test-ci-lane-selection.sh \ - && scripts/test-ci-lane-memory.sh + && scripts/test-ci-lane-memory.sh && scripts/test-ci-checkout-claim.sh } # ── the no-magic-physical-names gate is wired in all five ports ─────────────── @@ -1538,6 +1538,7 @@ kill_tree() { local c; for c in $(pgrep -P "$1" 2>/dev/null); do kill_tree "$c"; ci_cleanup() { local p; for p in "${LANE_PID[@]:-}"; do [ -n "$p" ] && kill -0 "$p" 2>/dev/null && kill_tree "$p"; done stop_pg_sidecar + [ -n "${CI_CLAIM:-}" ] && rm -f "$CI_CLAIM" rm -rf "$CI_TMP" ${CI_M2_OWNED:+"$CI_M2_OWNED"} ${CI_SCRATCH:+"$CI_SCRATCH"} } trap ci_cleanup EXIT @@ -1814,6 +1815,64 @@ if [ "${MO_CI_LIST_ONLY:-0}" = "1" ]; then echo "Steps that would run:" fi +# ── One run per checkout ────────────────────────────────────────────────────── +# Two runs in ONE checkout share every build directory a lane writes, and each corrupts the +# other: `mvn clean verify` in server/java deletes the classes the other run's tests are +# loading (NoClassDefFoundError across the metadata module), and the Rust codegen tests in +# both build their generated crates into server/rust/target, where cargo takes one run's +# build of a crate for the other's (the api_contract `rules` probe answering 404 on a route +# its model declares). Found 2026-12-01, when two --affected runs started in the same second +# in one gate worktree: java-reactor and conformance: rust went red, and each was green run +# alone, so it read as a flake under load. A run therefore claims its checkout, and a second +# one refuses, naming the first, instead of running beside it. +# +# The claim is a file in this worktree's own git directory (every worktree has its own, so +# sibling worktrees never contend) holding the claiming run's pid and that process's start +# time, read in one fixed locale and time zone so that two callers read the same text. A +# claim is judged and written only while holding the claim's lock directory, so one run at +# a time can find it free or left over. A run that cannot take the lock refuses; a run +# killed while holding it leaves the directory for a person to remove. A claim whose process +# is gone, or whose pid now belongs to a process that started at another time, is left over +# from a run that was killed, and is replaced. MO_CI_LIST_ONLY runs nothing and claims +# nothing. ci_cleanup releases the claim. +# +# A run started BY the claiming run is not a second run: the integration suite's +# reaper-kill test starts `ci-local.sh --integration-only --only python` to kill it, and +# refusing it there fails that test on every full run. The claimant exports its claim as +# MO_CI_CLAIM_HOLDER; a run that inherited exactly the live claim runs inside it, neither +# taking nor releasing it. A run started anywhere else does not carry the variable. +ci_proc_start() { LC_ALL=C TZ=UTC0 ps -o lstart= -p "$1" 2>/dev/null | sed 's/^ *//; s/ *$//'; } +CI_CLAIM="" +claim_checkout() { + local gitdir file lock holder hpid hstart + gitdir="$(git rev-parse --absolute-git-dir 2>/dev/null)" || return 0 + file="$gitdir/mo-ci-local.claim" + lock="$file.lock" + holder="$(cat "$file" 2>/dev/null)" + if [ -n "${MO_CI_CLAIM_HOLDER:-}" ] && [ "$holder" = "$MO_CI_CLAIM_HOLDER" ]; then return 0; fi + if ! mkdir "$lock" 2>/dev/null; then + echo "" >&2 + echo "✖ could not claim this checkout: another scripts/ci-local.sh run is claiming it." >&2 + echo " If no run is going, remove $lock and start again." >&2 + exit 2 + fi + holder="$(cat "$file" 2>/dev/null)" + hpid="${holder%% *}"; hstart="${holder#* }" + if [ -n "$hpid" ] && [ -n "$hstart" ] && [ "$(ci_proc_start "$hpid")" = "$hstart" ]; then + rmdir "$lock" + echo "" >&2 + echo "✖ another scripts/ci-local.sh run (pid $hpid, started $hstart UTC) is using this checkout." >&2 + echo " Two runs in one checkout rebuild the same server/java and server/rust trees under" >&2 + echo " each other and fail each other's lanes. Wait for that run to finish, or stop it." >&2 + exit 2 + fi + MO_CI_CLAIM_HOLDER="$$ $(ci_proc_start "$$")" + printf '%s\n' "$MO_CI_CLAIM_HOLDER" > "$file" + rmdir "$lock" + CI_CLAIM="$file"; export MO_CI_CLAIM_HOLDER +} +[ "${MO_CI_LIST_ONLY:-0}" = "1" ] || claim_checkout + # ── Step invocations ────────────────────────────────────────────────────────── run_or_list_lanes() { if [ "${MO_CI_LIST_ONLY:-0}" = "1" ]; then diff --git a/scripts/test-ci-checkout-claim.sh b/scripts/test-ci-checkout-claim.sh new file mode 100755 index 000000000..b7297558d --- /dev/null +++ b/scripts/test-ci-checkout-claim.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# Test of the one-run-per-checkout claim in scripts/ci-local.sh (claim_checkout). +# +# Two runs in one checkout rebuild server/java and server/rust under each other and fail +# each other's lanes (java-reactor NoClassDefFoundError, the Rust api_contract probe's 404), +# so a run claims the checkout and a second one refuses. A claim left by a killed run, or +# one whose pid now names another process, must not lock the checkout for good. +# +# Part 1 reads the functions out of ci-local.sh itself, so it tests the shipped code; the +# script cannot be sourced whole because it runs CI. Part 2 runs the real ci-local.sh with a +# stand-in cargo. Both run in a throwaway git repository under $DEV_SCRATCH, removed at the +# end. +set -uo pipefail +cd "$(dirname "$0")/.." || exit 1 + +fails=0 +check() { # check "" "" "" + if [ "$2" != "$1" ]; then + echo "FAIL: $3 -> '$2' (expected '$1')" >&2; fails=$((fails+1)) + else + echo "ok: $3 -> '$2'" + fi +} + +defs="$(sed -n '/^ci_proc_start() {/p; /^claim_checkout() {/,/^}/p' scripts/ci-local.sh)" +[ -n "$defs" ] || { echo "FAIL: claim_checkout not found in scripts/ci-local.sh" >&2; exit 1; } +eval "$defs" + +tmp="$(mktemp -d "${DEV_SCRATCH:-${TMPDIR:-/tmp}}/mo-ci-claim.XXXXXX")" +sleeper="" +trap '[ -n "$sleeper" ] && kill "$sleeper" 2>/dev/null; rm -rf "$tmp"' EXIT +git init -q "$tmp/repo" +claim="$(cd "$tmp/repo" && git rev-parse --absolute-git-dir)/mo-ci-local.claim" + +# attempt — claim the checkout in a subshell (a refusal exits); prints the outcome. +attempt() { + ( cd "$tmp/repo" && CI_CLAIM="" && claim_checkout 2>/dev/null && [ "$CI_CLAIM" = "$claim" ] && echo claimed ) \ + || echo refused +} + +check claimed "$(attempt)" "a free checkout is claimed" +check "$$ $(ci_proc_start $$)" "$(cat "$claim")" "the claim names this run's pid and start time" +rm -f "$claim" +exported="$(cd "$tmp/repo" && MO_CI_CLAIM_HOLDER="" && claim_checkout 2>/dev/null && bash -c 'echo "$MO_CI_CLAIM_HOLDER"')" +check "$(cat "$claim")" "$exported" "a claiming run exports its claim to the runs it starts" +check 0 "$(find "$(dirname "$claim")" -name 'mo-ci-local.claim.*' | wc -l | tr -d ' ')" \ + "no claim lock is left behind" + +sleep 300 & sleeper=$! +printf '%s %s\n' "$sleeper" "$(ci_proc_start "$sleeper")" > "$claim" +check refused "$(attempt)" "a claim held by a live run is refused" +check "$sleeper" "$(cut -d' ' -f1 "$claim")" "a refusal leaves the live claim in place" +printf '%s %s\n' "$sleeper" "$(TZ=UTC0 ci_proc_start "$sleeper")" > "$claim" +check refused "$(export TZ=JST-9; attempt)" "a live claim is refused from another time zone" +# nested — a run started by the claimant inherits MO_CI_CLAIM_HOLDER (the reaper-kill test +# starts ci-local from inside a full run); it runs without taking or releasing the claim. +nested() { + ( cd "$tmp/repo" && CI_CLAIM="" && MO_CI_CLAIM_HOLDER="$1" && claim_checkout 2>/dev/null \ + && [ -z "$CI_CLAIM" ] && echo nested ) || echo refused +} +check nested "$(nested "$(cat "$claim")")" "a run started by the live claimant runs inside its claim" +check "$sleeper" "$(cut -d' ' -f1 "$claim")" "a nested run leaves the claimant's claim in place" +check refused "$(nested "$sleeper Thu Jan 1 00:00:00 1970")" \ + "a run carrying some other claim is still refused" + +printf '%s %s\n' "$sleeper" "Thu Jan 1 00:00:00 1970" > "$claim" +check claimed "$(attempt)" "a claim whose pid now belongs to a later process is replaced" + +kill "$sleeper" 2>/dev/null; wait "$sleeper" 2>/dev/null; gone="$sleeper"; sleeper="" +printf '%s %s\n' "$gone" "Thu Jan 1 00:00:00 1970" > "$claim" +check claimed "$(attempt)" "a claim left by a run that is gone is replaced" + +# rival — while one run is judging a left-over claim, a second run tries for it too. +printf '%s %s\n' "$gone" "Thu Jan 1 00:00:00 1970" > "$claim" +first="$( + eval "real_$(declare -f ci_proc_start)" + ci_proc_start() { + if [ "$1" = "$gone" ] && [ ! -e "$tmp/rival" ]; then + : > "$tmp/rival" + ( ci_proc_start() { real_ci_proc_start "$@"; }; attempt ) > "$tmp/rival" + fi + real_ci_proc_start "$1" + } + attempt +)" +check "claimed refused" "$first $(cat "$tmp/rival")" "two runs after one left-over claim: only one gets it" +rm -f "$claim" + +# ── 2. the real ci-local.sh ─────────────────────────────────────────────────── +mkdir -p "$tmp/repo/scripts/lib" "$tmp/repo/server/rust" "$tmp/bin" +cp scripts/ci-local.sh scripts/ci-select-lanes.sh "$tmp/repo/scripts/" +cp scripts/lib/maven-private-repo.sh "$tmp/repo/scripts/lib/" +cat > "$tmp/bin/cargo" <<'STUB' +#!/usr/bin/env bash +echo ran >> "$CLAIM_TEST_DIR/cargo-calls" +if [ ! -e "$CLAIM_TEST_DIR/second" ]; then + : > "$CLAIM_TEST_DIR/second" + env -u MO_CI_CLAIM_HOLDER "$CLAIM_TEST_DIR/repo/scripts/ci-local.sh" --only rust --no-integration >/dev/null 2>&1 + echo $? > "$CLAIM_TEST_DIR/second" +fi +exit 1 +STUB +chmod +x "$tmp/bin/cargo" +real_run() { # prints the exit status of a real run that selects the rust lane + ( cd "$tmp/repo" && env -u MO_CI_CLAIM_HOLDER MO_CI_LIST_ONLY=0 CLAIM_TEST_DIR="$tmp" PATH="$tmp/bin:$PATH" \ + scripts/ci-local.sh --only rust --no-integration >/dev/null 2>&1 ) + echo $? +} + +sleep 300 & sleeper=$! +printf '%s %s\n' "$sleeper" "$(ci_proc_start "$sleeper")" > "$claim" +check 2 "$(real_run)" "ci-local.sh refuses while a live claim exists" +check no "$([ -e "$tmp/cargo-calls" ] && echo yes || echo no)" "a refused ci-local.sh runs no lane" +kill "$sleeper" 2>/dev/null; wait "$sleeper" 2>/dev/null; sleeper="" +rm -f "$claim" + +check 1 "$(real_run)" "a claimed ci-local.sh run reaches its lane (the stand-in cargo fails it)" +check 2 "$(cat "$tmp/second" 2>/dev/null)" "a second run started while the first is going refuses" +check no "$([ -e "$claim" ] && echo yes || echo no)" "the claim file is gone after a claimed run exits" + +if [ "$fails" -gt 0 ]; then echo "$fails check(s) failed" >&2; exit 1; fi +echo "checkout claim: all checks passed" diff --git a/server/rust/metaobjects-codegen/tests/common/mod.rs b/server/rust/metaobjects-codegen/tests/common/mod.rs index ca8c49825..caf970afb 100644 --- a/server/rust/metaobjects-codegen/tests/common/mod.rs +++ b/server/rust/metaobjects-codegen/tests/common/mod.rs @@ -221,7 +221,7 @@ pub fn copy_tree(from: &Path, to: &Path) { copy_tree(&entry.path(), &to.join(entry.file_name())); } } else { - std::fs::copy(from, to).unwrap(); + std::fs::write(to, std::fs::read(from).unwrap()).unwrap(); } } @@ -235,11 +235,53 @@ pub fn gen_lock() -> PathBuf { const UPDATE_GEN_LOCK: &str = "UPDATE_GEN_LOCK"; +/// A [`generated_workspace`]: a [`Scratch`] that holds the [`target_dir`] lock while it lives. +/// +/// Every generated workspace builds into the one shared target directory, and cargo names a +/// path crate's build by its path RELATIVE to the workspace root. So `out/acme_purchasing_http` +/// in one workspace and `out/acme_purchasing_http` in another are the same build to cargo, +/// and so is every workspace's `probe`; a build is then judged fresh when the workspace's own +/// sources are older than it. Two workspaces alive at once — two tests of one binary, which +/// run on parallel threads, or two `cargo test` processes in one checkout — therefore link +/// and run each other's code: a probe built from one model answers another model's requests +/// (a `404` on a route the other model never declared). Holding an exclusive lock on the +/// target directory from creation to drop makes the workspaces take turns, so each build and +/// each run sees only its own sources. The lock is released when the workspace drops, also +/// on a panic, and by the OS when the process dies. +pub struct Workspace { + scratch: Scratch, + _lock: std::fs::File, +} + +impl std::ops::Deref for Workspace { + type Target = Scratch; + + fn deref(&self) -> &Scratch { + &self.scratch + } +} + +/// Wait for, and take, the exclusive lock on the shared [`target_dir`]. +fn lock_target_dir() -> std::fs::File { + let dir = target_dir(); + std::fs::create_dir_all(&dir).unwrap(); + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(dir.join("generated-workspace.lock")) + .unwrap(); + lock.lock().expect("the generated-workspace lock"); + lock +} + /// A scratch Cargo workspace holding a copy of the project's `generated` tree under `out/`, /// plus a `probe` crate when one is given (its manifest's dependencies and its `main.rs`). /// The workspace starts from [`gen_lock`], so cargo resolves the versions that file names. -/// Cargo is not run offline: a fresh machine has not downloaded them yet. -pub fn generated_workspace(tag: &str, project: &Scratch, probe: Option<(&str, &str)>) -> Scratch { +/// Cargo is not run offline: a fresh machine has not downloaded them yet. It holds the +/// target-directory lock until it drops ([`Workspace`] says why). +pub fn generated_workspace(tag: &str, project: &Scratch, probe: Option<(&str, &str)>) -> Workspace { + let lock = lock_target_dir(); let ws = Scratch::new(tag); copy_tree(&project.path().join("generated"), &ws.path().join("out")); let members = if probe.is_some() { @@ -269,7 +311,10 @@ pub fn generated_workspace(tag: &str, project: &Scratch, probe: Option<(&str, &s ); ws.write("probe/src/main.rs", main); } - ws + Workspace { + scratch: ws, + _lock: lock, + } } /// Every generated crate of the workspace is already in rustfmt's output form under the diff --git a/server/rust/metaobjects-codegen/tests/render_helper_conformance.rs b/server/rust/metaobjects-codegen/tests/render_helper_conformance.rs index cb966c6f7..9157a19c2 100644 --- a/server/rust/metaobjects-codegen/tests/render_helper_conformance.rs +++ b/server/rust/metaobjects-codegen/tests/render_helper_conformance.rs @@ -49,15 +49,9 @@ fn generate(project: &Scratch) -> Result<(), String> { .map_err(|e| e.to_string()) } -/// Every probe workspace builds into the one shared target directory, and each names its -/// binary `probe`: two built at once would run each other's. -static BUILD: std::sync::Mutex<()> = std::sync::Mutex::new(()); - -/// Generate `project`, build it with `probe` and return what the probe printed. +/// Generate `project`, build it with `probe` and return what the probe printed. Every probe +/// names its binary `probe`; the workspace's lock keeps two from running each other's. fn render(tag: &str, project: &Scratch, dependencies: &str, main: &str) -> String { - let _serial = BUILD - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); generate(project).unwrap_or_else(|e| panic!("{tag}: gen failed: {e}")); let ws = generated_workspace(tag, project, Some((dependencies, main))); assert_formatted(&ws); diff --git a/server/typescript/packages/cli/test/eject-contract.test.ts b/server/typescript/packages/cli/test/eject-contract.test.ts index 62054d79c..0b2446ac2 100644 --- a/server/typescript/packages/cli/test/eject-contract.test.ts +++ b/server/typescript/packages/cli/test/eject-contract.test.ts @@ -260,9 +260,26 @@ function filesUnder(dir: string): string[] { * `import("…").Type`, and a dynamic `import("…")`, which is counted as the module it names. */ function outsideEngineSurface(files: readonly string[]): string[] { - const sources = files.filter((f) => /\.tsx?$/.test(f)); - const program = ts.createProgram({ rootNames: sources, options: COMPILER_OPTIONS }); + return engineSurfaceScanner(files)(files); +} + +/** + * One compiler program over `files`, and the scan of any subset of them against it. The + * program is the expensive part — it loads and binds the codegen packages every owned copy + * imports — so the depth check builds one for all the copies and scans each copy's files + * through it, rather than one program per copy (30-odd full loads of the same packages, + * which is what outran the test's limit on a busy machine). Each copy lives in its own + * directory, so no file of one is a file of another, and a binding resolves to the same + * declaration whichever program holds it. + */ +function engineSurfaceScanner(files: readonly string[]): (subset: readonly string[]) => string[] { + const isSource = (f: string): boolean => /\.tsx?$/.test(f); + const program = ts.createProgram({ rootNames: files.filter(isSource), options: COMPILER_OPTIONS }); const checker = program.getTypeChecker(); + return (subset) => scanImports(program, checker, subset.filter(isSource)); +} + +function scanImports(program: ts.Program, checker: ts.TypeChecker, sources: readonly string[]): string[] { const outside = new Set(); const recordFile = (fileName: string): void => { @@ -462,8 +479,9 @@ describe("eject contract — depth", () => { test("an owned copy imports only the engine surface", () => { const waiting = pending("depth"); const problems: string[] = []; + const scan = engineSurfaceScanner([...owned.values()].flatMap((copy) => copy.files)); for (const [name, copy] of owned) { - const actual = outsideEngineSurface(copy.files); + const actual = scan(copy.files); const expected = (waiting.get(name) ?? []).flatMap((p) => p.outside ?? []).sort(); if (JSON.stringify(actual) === JSON.stringify(expected)) continue; if (expected.length === 0) { diff --git a/server/typescript/packages/integration-tests/src/mysql-container.ts b/server/typescript/packages/integration-tests/src/mysql-container.ts index aa5ef9135..8a1de89ac 100644 --- a/server/typescript/packages/integration-tests/src/mysql-container.ts +++ b/server/typescript/packages/integration-tests/src/mysql-container.ts @@ -53,23 +53,32 @@ export async function startMysql(): Promise { await docker(["run", "-d", ...(await reaperLabelArgs()), "--name", name, ...ramVolume(MYSQL_8_DATA_DIR), "-e", `MYSQL_ROOT_PASSWORD=${PASSWORD}`, "-e", `MYSQL_DATABASE=${DATABASE}`, "-p", "127.0.0.1::3306", IMAGE, "--innodb-use-native-aio=0"]); - url = `mysql://root:${PASSWORD}@127.0.0.1:${await publishedPort(name)}/${DATABASE}`; + // MySQL 8.4 authenticates root with caching_sha2_password, which on a non-TLS connection + // needs the server's RSA key. mysql2 3.26 stopped fetching that key by default, so without + // this flag every connection is refused (PUBLIC_KEY_RETRIEVAL_NOT_ALLOWED) and the readiness + // poll below waits out its whole deadline. The key-substitution risk it guards against does + // not apply to a throwaway server on 127.0.0.1. The flag rides in the URL so that every + // consumer — a bare URL or a `{ uri }` option — picks it up. + url = `mysql://root:${PASSWORD}@127.0.0.1:${await publishedPort(name)}/${DATABASE}?allowPublicKeyRetrieval=true`; } catch (e) { stop(); throw e; } const deadline = Date.now() + READY_DEADLINE_MS; + let connectError = "(no connection attempted: the final server never logged port 3306)"; while (Date.now() < deadline) { const text = await docker(["logs", name]).catch(() => ""); - if (text.includes("ready for connections") && text.includes("port: 3306") && (await canConnect(url))) { - return { url, stop }; + if (text.includes("ready for connections") && text.includes("port: 3306")) { + const failure = await connectFailure(url); + if (failure === undefined) return { url, stop }; + connectError = failure; } await new Promise((r) => setTimeout(r, 500)); } const logs = await docker(["logs", "--tail", "40", name]).catch((e: unknown) => String(e)); stop(); - throw new Error(`mysql container ${name} not ready in ${READY_DEADLINE_MS}ms:\n${logs}`); + throw new Error(`mysql container ${name} not ready in ${READY_DEADLINE_MS}ms; last connect error: ${connectError}\n${logs}`); } /** The host port docker bound to the container's 3306, as `docker port` prints it. */ @@ -80,14 +89,17 @@ async function publishedPort(name: string): Promise { return Number(m[1]); } -async function canConnect(url: string): Promise { +/** Undefined when a real connection to the database succeeds, otherwise why it did not: a + * timeout report that shows only the server log reads as "never came up" when the server was + * ready and the client was refusing it. */ +async function connectFailure(url: string): Promise { try { const c = await mysql.createConnection(url); await c.query("SELECT 1"); await c.end(); - return true; - } catch { - return false; + return undefined; + } catch (e) { + return e instanceof Error ? e.message : String(e); } }