Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
61 changes: 60 additions & 1 deletion scripts/ci-local.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 ───────────────
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
122 changes: 122 additions & 0 deletions scripts/test-ci-checkout-claim.sh
Original file line number Diff line number Diff line change
@@ -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 "<expected>" "<got>" "<what>"
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"
53 changes: 49 additions & 4 deletions server/rust/metaobjects-codegen/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

Expand All @@ -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() {
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
24 changes: 21 additions & 3 deletions server/typescript/packages/cli/test/eject-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>();

const recordFile = (fileName: string): void => {
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading