diff --git a/agents.md b/agents.md index 0276f9796..c448fa31a 100644 --- a/agents.md +++ b/agents.md @@ -27,6 +27,12 @@ Anything that opens a browser must set `ALBEDO_NO_BROWSER=1`; `test.sh` exports ### Test layout and the build lock +`test/resources.py` owns CPU and available-memory limits for builds and suites. +Gate entry points freeze its plan before starting concurrent work; standalone +E2E and Gleam runners use the same policy. Python fixtures delete owned session +families and release providers before their worker admits the next test. See +`robot-docs/testing.md` for resource discovery, overrides and teardown rules. + `./test.sh` is the gate. It runs `test/quick.sh` first, then cargo test + renderer install and the CLI build the Python e2e suite drives; then it compiles the daemon once and runs every suite at the same time (`gleam test`, each `test/harness/*_test.py`, Go unit tests, the Go e2e suite, the Python e2e suite), each into its own log, printed only when that suite fails. Without `--full` it runs the Python e2e tests `test/e2e/e2e_select.py` picks for the change (files sharing a word with a changed path, `test/e2e/areas.toml`, and a smoke set), capped at about 90 s of recorded test time, and the Go e2e suite only for a `cli/` change. Test daemons skip the post-boot module preload (`ALBEDO_PRELOAD=0`), and a timer-bound test may set `ALBEDO_TEST_TIME_SCALE` in its fixture's `prepare` to run the daemon's timers faster (robot-docs/runtime.md). Python test files are loaded through `test/python_test_runner.py`; a selected file with no unittest cases fails. The E2E runner also rejects an empty aggregate before boot. Gleam and Erlang discovery selects `_test` files with exported test functions or generators, excluding the `albedo_test.gleam` entrypoint and manual tools. Support modules remain compiled but are not suites. Put reusable Python fixtures in `_support.py` modules. Inspection transport belongs to `test/e2e/inspect_support.py`; probes use the typed session diagnostics described in `robot-docs/runtime.md`. diff --git a/cli/test/e2e/harness_test.go b/cli/test/e2e/harness_test.go index 6528fa7b6..d80a3acd1 100644 --- a/cli/test/e2e/harness_test.go +++ b/cli/test/e2e/harness_test.go @@ -298,6 +298,9 @@ func hermeticEnv(root, home, userHome, scratch, daemonExe, sshBin string) []stri "ALBEDO_NO_BROWSER=1", // An OS-picked intake port leaves 8088 to the developer's daemon. "ALBEDO_WEBHOOK_PORT=0", + "ALBEDO_IDLE_SECONDS=10", + "ALBEDO_KERNEL_GRACE_SECONDS=20", + "ALBEDO_PRELOAD=0", // Two schedulers keep a booting test VM from pinning every core. "ERL_FLAGS=+S 2:2 +SDcpu 2:2 +sbwt none +sbwtdcpu none +sbwtdio none", ) @@ -559,6 +562,7 @@ func newSession(t *testing.T, workspace string) string { if err != nil || created.ID == "" { t.Fatalf("creating a session on %s: %v", t.Name(), err) } + cleanupSession(t, created.ID) return created.ID } @@ -572,9 +576,44 @@ func cliSession(t *testing.T, workspace string) string { if err := json.Unmarshal([]byte(cli(t, "new", workspace)), &created); err != nil || created.Session == "" { t.Fatalf("albedo new did not report a session: %v", err) } + cleanupSession(t, created.Session) return created.Session } +func cleanupSession(t *testing.T, id string) { + t.Helper() + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + err := deleteTestSession(ctx, id) + if api, ok := errors.AsType[*daemon.APIError](err); ok && + (api.StatusCode == http.StatusNotFound || api.StatusCode == http.StatusGone) { + return + } + if err != nil { + t.Errorf("cleanup session %s: %v", id, err) + } + }) +} + +func deleteTestSession(ctx context.Context, id string) error { + configuration, err := daemon.GetSessionConfiguration(ctx, suite.conn, id) + if err != nil { + return err + } + session, err := daemon.GetSession(ctx, suite.conn, id) + if err != nil { + return err + } + result, err := daemon.DeleteSession(ctx, suite.conn, id, true, daemon.SessionCondition{ + ETag: configuration.ETag, FamilyRevision: session.FamilyRevision, + }) + if err == nil && !result.OK { + return errors.New(result.Message) + } + return err +} + // providerRoute registers and selects a profile named after the test. Call it // before t.Parallel(): Go finishes these selections and all serial tests before // resuming parallel bodies. Those bodies must not depend on the active profile @@ -585,6 +624,17 @@ func providerRoute(t *testing.T, reply func(map[string]any) string) string { if err := suite.provider.addProfile(t.Name(), reply); err != nil { t.Fatalf("provider route: %v", err) } + t.Cleanup(func() { + suite.provider.mu.Lock() + defer suite.provider.mu.Unlock() + route := suite.provider.byName[t.Name()] + delete(suite.provider.byName, t.Name()) + for segment, candidate := range suite.provider.byRoute { + if candidate == route { + delete(suite.provider.byRoute, segment) + } + } + }) return t.Name() } diff --git a/robot-docs/testing.md b/robot-docs/testing.md new file mode 100644 index 000000000..12daf06bd --- /dev/null +++ b/robot-docs/testing.md @@ -0,0 +1,17 @@ +# test execution + +`test/resources.py` owns test concurrency. `test.sh` and `test/quick.sh` source `test/resources.sh` before starting work. That freezes one plan so later suites do not each budget the same remaining memory again. Standalone Python E2E and Gleam runners read the same policy. + +The planner uses Linux `MemAvailable`, limited by `memory.max - memory.current` for the current cgroup and every ancestor. On macOS it uses free, inactive and speculative VM pages. Unknown hosts receive a conservative 2 GiB budget. A quarter remains outside the test budget. CPU affinity bounds scenarios; Linux CPU quota also bounds active build threads. + +The ordinary E2E limits remain four shared Python tests, eight private daemons and four Go scenarios. Half of the shared budget covers E2E scenarios, at 384 MiB per group of one shared case, two private daemons and one Go scenario. The remainder is divided between Gleam modules, Python harness files and build workers. Lower available memory reduces every pool. Less than 1 GiB available fails before work starts. Explicit Python `-j` and `-x` arguments override the plan for experiments. The exported `ALBEDO_TEST_*_JOBS` values can also pin a plan. These are concurrency limits, not hard limits on a test's allocations. The cell-limit scenarios deliberately run 384 MiB child processes. + +Gleam runs timed modules first and the remaining modules in bounded EUnit batches. Python harness files run in a bounded subprocess pool. Build limits also set Go package parallelism, `GOMAXPROCS`, Cargo jobs and Gleam's scheduler count. Large machines do not start an unbounded number of compilers or test VMs just because they have many CPUs. + +## fixture teardown + +A Python test owns every `Albedo` fixture and fake provider it creates. Successful session-creation PUTs record root IDs, independent of later workspace moves. After unittest cleanups, the runner deletes each shared fixture's captured session trees with fresh configuration and family revisions. This stops kernels and background jobs before the shared lane admits another test. A missing root is already cleaned; stale revisions are refreshed up to five times. Other failures fail the test. + +A private daemon is discarded synchronously in its worker. Finished tests no longer leave an unbounded queue of daemon-shutdown threads. Provider routes, recorded requests and scripts are released only after session teardown; held provider responses are then cancelled. Successful unittest objects are removed from discovery containers and outcomes retain their names rather than fixtures. Failure diagnostics read a bounded daemon-log tail. + +Go session helpers register subtree deletion with `t.Cleanup`. Provider-route cleanup follows session cleanup. Test daemons use explicit idle, grace and preload settings rather than the production ten-minute idle default. diff --git a/test.sh b/test.sh index 5a4beb670..9cfffba0f 100755 --- a/test.sh +++ b/test.sh @@ -22,6 +22,7 @@ case "${1:-}" in exit 2 ;; esac +source test/resources.sh export ALBEDO_NO_BROWSER=1 # a detached kernel a suite left behind ends soon after, not in an hour export ALBEDO_KERNEL_GRACE_SECONDS=20 @@ -84,13 +85,11 @@ settle() { } suite "gleam test" gleam test -for test in test/harness/*_test.py; do - suite "$test" python3 test/python_test_runner.py "$test" -done +suite "python harness" python3 test/python_test_runner.py --jobs "$ALBEDO_TEST_HARNESS_JOBS" test/harness/*_test.py suite "go test" go -C cli test ./internal/... ./cmd/... # the Go e2e suite builds its own CLI and boots a hermetic daemon, so it must # never reuse a cached run. Bound parallel scenarios while the other suites run. -go_parallel="$(python3 -c 'import os; print(max(1, min(4, (os.cpu_count() or 1) // 4)))')" +go_parallel="$ALBEDO_TEST_GO_JOBS" if $full; then # On a machine with fewer cores (CI's VM) the e2e suites' daemon boots starve # the unit suites' startup timeouts, so they run after them. diff --git a/test/albedo_test_runner.erl b/test/albedo_test_runner.erl index 52033f0af..b20ffee29 100644 --- a/test/albedo_test_runner.erl +++ b/test/albedo_test_runner.erl @@ -1,10 +1,5 @@ -%% gleeunit's runner with every test module started at once, after the timed -%% ones. A module's tests keep running in order, one after another, so tests -%% that share a module's fixtures never race each other: each module is its own -%% {inorder, _} group, since a bare module under {inparallel, _} inherits that -%% order and runs its tests concurrently too. There is no cap: -%% eunit's {inparallel, N, _} runs batches of N and waits out each batch's -%% slowest module. +%% Timed modules run first. Each remaining module keeps its tests in order; +%% test/resources.py bounds the number of modules in each parallel batch. -module(albedo_test_runner). -export([main/0]). @@ -33,10 +28,13 @@ main() -> {scale_timeouts, 10} ], Result = eunit:test( - [{inorder, Timed}, {inparallel, [{inorder, M} || M <- Modules -- Timed]}], Options), + [{inorder, Timed}, {inparallel, workers(), [{inorder, M} || M <- Modules -- Timed]}], Options), albedo_test_home:cleanup(), erlang:halt(case Result of ok -> 0; _ -> 1 end). +workers() -> + list_to_integer(string:trim(os:cmd("python3 test/resources.py --get gleam"))). + require_tests(Module) -> {module, Module} = code:ensure_loaded(Module), HasTests = lists:any(fun({Name, Arity}) -> diff --git a/test/e2e/harness.py b/test/e2e/harness.py index d7488f0f8..ae4336728 100644 --- a/test/e2e/harness.py +++ b/test/e2e/harness.py @@ -175,13 +175,19 @@ def _provider_server(): pass def do_GET(self): - self.provider()._get(self) + if provider := self.provider(): + provider._get(self) def do_POST(self): - self.provider()._post(self) + if provider := self.provider(): + provider._post(self) def provider(self): - return _providers[self.path.split("/", 3)[2]] + with _config_lock: + provider = _providers.get(self.path.split("/", 3)[2]) + if provider is None: + self.send_error(404) + return provider _server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) _server.daemon_threads = True @@ -198,11 +204,13 @@ class Provider: self.chunk_size = chunk_size self.requests: list[dict] = [] self._lock = threading.Lock() + self._closed = threading.Event() self.route = str(next(_provider_ids)) with _config_lock: _providers[self.route] = self self.server = _provider_server() self.url = f"http://127.0.0.1:{self.server.server_port}/t/{self.route}" + getattr(_current, "providers", []).append(self) def _get(owner, self): payload = json.dumps(owner.catalog).encode() @@ -226,7 +234,7 @@ class Provider: if isinstance(reply, (list, tuple)): reply = reply[min(index, len(reply) - 1)] if reply.silent: - time.sleep(60) + owner._closed.wait(60) return if reply.kind == "error": payload = json.dumps({"error": {"message": reply.value}}).encode() @@ -247,7 +255,7 @@ class Provider: try: if reply.hang: - time.sleep(60) + owner._closed.wait(60) return if reply.events is not None: for event in reply.events: @@ -279,16 +287,22 @@ class Provider: pass def close(self): - # Sessions can finish background turns after their test returns. Keep - # their route alive until the shared daemon has stopped. + # The runner releases routes after stopping this test's sessions. pass + def release(self): + self._closed.set() + with _config_lock: + _providers.pop(self.route, None) + with self._lock: + self.requests.clear() + self.script = lambda _: text("fixture closed") + _daemons: list[Daemon] = [] # The launcher of this run's daemon build; see snapshot_daemon(). _executable = None _daemons_lock = threading.RLock() -_discarding: list[threading.Thread] = [] _current = threading.local() daemon_boots = 0 restart_seconds = 0.0 @@ -350,6 +364,16 @@ class _Response(http.client.HTTPResponse): connection.close() +def log_tail(path, offset=0): + try: + with path.open("rb") as log: + log.seek(0, os.SEEK_END) + log.seek(max(offset, log.tell() - 8000)) + return log.read(8000).decode(errors="replace") + except FileNotFoundError: + return "" + + class Daemon: """One daemon and its hermetic home. A concurrent daemon is shared by tests that each keep to their own provider profile; any other serves one @@ -570,16 +594,13 @@ class Daemon: pass def discard(self): - """Shut the daemon down in the background; the test that used it is - done, and nothing waits on its teardown until the run ends.""" - thread = threading.Thread(target=self.shutdown) - thread.start() - with _daemons_lock: - _discarding.append(thread) + """Discard a finished test's daemon before its worker admits another.""" + self.kill() + self.shutdown() def _fail(self, message): - log = self.home / "daemon.log" - raise AssertionError(message + ("\n" + log.read_text() if log.exists() else "")) + tail = log_tail(self.home / "daemon.log") + raise AssertionError(message + ("\n" + tail if tail else "")) def _connection(self): connection = getattr(self._local, "connection", None) @@ -831,10 +852,34 @@ def on_daemon(daemon): """Run fixtures created on this thread against daemon.""" previous = getattr(_current, "daemon", None) _current.daemon = daemon + _current.fixtures = [] + _current.providers = [] try: yield daemon finally: _current.daemon = previous + _current.fixtures = [] + _current.providers = [] + + +def finish_test(): + """Stop owned session trees before releasing their scripted providers.""" + daemon = current_daemon() + failures = [] + try: + if daemon.concurrent: + for fixture in _current.fixtures: + try: + fixture.cleanup() + except Exception as error: + failures.append(error) + else: + daemon.discard() + finally: + for provider in _current.providers: + provider.release() + if failures: + raise ExceptionGroup("fixture teardown failed", failures) def shutdown(): @@ -846,9 +891,6 @@ def shutdown(): # session takes longer still. Their kernels exit with them. for daemon in list(_daemons): daemon.kill() - for thread in list(_discarding): - thread.join() - _discarding.clear() for daemon in list(_daemons): daemon.shutdown() if _server is not None: @@ -885,12 +927,14 @@ class Albedo: self.protocol = protocol self.providers = providers self.prepare = prepare + self._sessions = set() def __enter__(self): self.daemon = daemon = current_daemon() with daemon.lock: self.root, self.home, self.env = daemon.root, daemon.home, daemon.env self.workspace = Path(tempfile.mkdtemp(prefix="workspace-", dir=self.root)) + _current.fixtures.append(self) self._concurrent = daemon.concurrent if self.prepare: self.prepare(self) @@ -950,7 +994,10 @@ class Albedo: self.daemon._fail(message) def api(self, path, body=None, *, method=None, headers=None): - return self.daemon.api(path, body, method=method, headers=headers) + response = self.daemon.api(path, body, method=method, headers=headers) + if method == "PUT" and isinstance(body, dict) and body.get("kind") == "new": + self._sessions.add(path.split("?")[0].rsplit("/", 1)[-1]) + return response def cli(self, *args): return self.daemon.cli(*args) @@ -1068,6 +1115,19 @@ class Albedo: return None raise + def cleanup(self): + failures = [] + for session in self._sessions: + try: + outcome = self.delete_tree(session) + if outcome and outcome["state"] != "complete": + raise AssertionError(f"fixture deletion incomplete: {outcome}") + except Exception as error: + failures.append(error) + if failures: + raise ExceptionGroup("session teardown failed", failures) + shutil.rmtree(self.workspace, ignore_errors=True) + def __exit__(self, *_exc): if self._owns_provider: self.provider.close() diff --git a/test/e2e/harness_lifecycle_test.py b/test/e2e/harness_lifecycle_test.py new file mode 100644 index 000000000..1eae8da8e --- /dev/null +++ b/test/e2e/harness_lifecycle_test.py @@ -0,0 +1,54 @@ +"""A completed fixture releases its sessions, kernels and still-running jobs.""" + +import json +import unittest +import urllib.error + +from harness import Albedo, Provider, alive, operation_id, python, text, wait_until + + +class HarnessLifecycleTests(unittest.TestCase): + def test_cleanup_stops_owned_roots_and_their_jobs(self): + code = """ +from pathlib import Path +import os, sys +Path('kernel.pid').write_text(str(os.getpid())) +job = run(sys.executable, '-u', '-c', "import os,time; from pathlib import Path; Path('job.pid').write_text(str(os.getpid())); print('ready', flush=True); time.sleep(60)") +await job.wait_for('ready') +print('started') +""" + provider = Provider( + lambda request: ( + text("done") + if request["messages"][-1].get("role") == "tool" + else python(code) + ) + ) + self.addCleanup(provider.close) + with Albedo(provider) as app: + root = app.session() + direct = operation_id() + with app.api( + f"/sessions/{direct}", + {"kind": "new", "workspace": str(app.workspace)}, + method="PUT", + headers={"If-None-Match": "*"}, + ) as response: + self.assertEqual(json.load(response)["id"], direct) + app.prompt(root, "start a job").close() + app.idle(root) + kernel = int((app.workspace / "kernel.pid").read_text()) + child = int((app.workspace / "job.pid").read_text()) + self.assertTrue(alive(kernel)) + self.assertTrue(alive(child)) + app.cleanup() + wait_until( + lambda: not alive(kernel) and not alive(child), + 10, + "fixture processes survived cleanup", + ) + self.assertFalse(app.workspace.exists()) + for identity in (root, direct): + with self.assertRaises(urllib.error.HTTPError) as caught: + app.api(f"/sessions/{identity}?tail=0") + self.assertIn(caught.exception.code, (404, 410)) diff --git a/test/e2e/run.py b/test/e2e/run.py index bae9389ab..1e2a0527a 100644 --- a/test/e2e/run.py +++ b/test/e2e/run.py @@ -11,7 +11,6 @@ from concurrent.futures import ThreadPoolExecutor import fcntl import io import json -import os from pathlib import Path import resource import sys @@ -25,16 +24,18 @@ SUITE_DIR = Path(__file__).parent sys.path.insert(0, str(SUITE_DIR)) sys.path.insert(0, str(SUITE_DIR.parent)) from python_test_runner import suite_for # noqa: E402 +from resources import limits # noqa: E402 DURATIONS = scratch.ROOT / "e2e-durations.json" def cases(suite): - for item in suite: + for index, item in enumerate(suite): if isinstance(item, unittest.TestSuite): yield from cases(item) else: yield item + suite._removeTestAtIndex(index) def marked(test, mark): @@ -49,24 +50,18 @@ def execute(test, daemon): started = time.monotonic() with harness.on_daemon(daemon): result = unittest.TextTestRunner(stream=stream, verbosity=2).run(test) - duration = time.monotonic() - started - if not result.wasSuccessful() and log.exists(): - # The daemon's side of a failure; the shared daemon's log interleaves - # the tests that ran alongside this one. - with log.open("rb") as daemon_log: - daemon_log.seek(offset) - setattr( - result, "daemon_log", daemon_log.read()[-8000:].decode(errors="replace") - ) - return test, result, duration + if not result.wasSuccessful(): + # Capture before private teardown removes the daemon's home. + setattr(result, "daemon_log", harness.log_tail(log, offset)) + try: + harness.finish_test() + except Exception: + result.addError(test, sys.exc_info()) + return test.id(), result, time.monotonic() - started def execute_alone(test): - daemon = harness.Daemon("exclusive") - try: - return execute(test, daemon) - finally: - daemon.discard() + return execute(test, harness.Daemon("exclusive")) def run_suite(suite, jobs, exclusive_jobs): @@ -89,9 +84,12 @@ def run_suite(suite, jobs, exclusive_jobs): ): alone = [exclusive_pool.submit(execute_alone, test) for test in exclusive] together = [shared_pool.submit(execute, test, daemon) for test in shared] + selected.clear() + shared.clear() + exclusive.clear() outcomes = [future.result() for future in together + alone] report(outcomes) - durations.update({test.id(): duration for test, _, duration in outcomes}) + durations.update({identity: duration for identity, _, duration in outcomes}) DURATIONS.write_text(json.dumps(durations, indent=1, sort_keys=True)) return all(result.wasSuccessful() for _, result, _ in outcomes) @@ -99,17 +97,15 @@ def run_suite(suite, jobs, exclusive_jobs): def report(outcomes): for test, result, duration in outcomes: status = "ok" if result.wasSuccessful() else "FAILED" - print(f"{status:6} {test.id()} ({duration:.1f}s)", file=sys.stderr) + print(f"{status:6} {test} ({duration:.1f}s)", file=sys.stderr) for test, result, _duration in outcomes: for _case, traceback in result.failures + result.errors: - print(f"\n{test.id()}:\n{traceback}", file=sys.stderr) + print(f"\n{test}:\n{traceback}", file=sys.stderr) if getattr(result, "daemon_log", ""): - print( - f"daemon log during {test.id()}:\n{result.daemon_log}", file=sys.stderr - ) + print(f"daemon log during {test}:\n{result.daemon_log}", file=sys.stderr) print("slowest tests:", file=sys.stderr) for test, _result, duration in sorted(outcomes, key=lambda value: -value[2])[:10]: - print(f" {duration:.1f}s {test.id()}", file=sys.stderr) + print(f" {duration:.1f}s {test}", file=sys.stderr) failing = sum(not result.wasSuccessful() for _, result, _ in outcomes) print(f"Ran {len(outcomes)} tests; {failing} failing", file=sys.stderr) @@ -120,7 +116,7 @@ def main(): # most macOS's OPEN_MAX. Daemons boot on it unless a test pins their own. _, hard = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (min(hard, 10240), hard)) - cpus = os.cpu_count() or 1 + workers = limits() parser = argparse.ArgumentParser() parser.add_argument( "targets", @@ -131,14 +127,14 @@ def main(): "-j", "--jobs", type=int, - default=max(1, min(4, cpus // 4)), + default=workers["shared"], help="concurrent tests on the shared lane (default: %(default)s)", ) parser.add_argument( "-x", "--exclusive-jobs", type=int, - default=max(1, min(8, cpus // 2)), + default=workers["exclusive"], help="concurrent exclusive daemons (default: %(default)s)", ) args = parser.parse_args() diff --git a/test/harness/test_resources_test.py b/test/harness/test_resources_test.py new file mode 100644 index 000000000..c9939a9d1 --- /dev/null +++ b/test/harness/test_resources_test.py @@ -0,0 +1,80 @@ +"""Host resource policy must honor cgroup ancestors and not scale with huge CPU counts. + +Daemon E2E cannot change its host's memory or cgroup layout to cover these rules. +""" + +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import resources # noqa: E402 + + +class ResourceTests(unittest.TestCase): + def test_big_hosts_are_capped_and_memory_reduces_all_lanes(self): + ordinary = resources.plan(24, 4096 * resources.MIB, 10) + large = resources.plan(256, 64 * 1024 * resources.MIB, 256) + small = resources.plan(256, 1024 * resources.MIB, 256) + self.assertEqual( + (ordinary["shared"], ordinary["exclusive"], ordinary["go"]), (4, 8, 4) + ) + self.assertEqual(large, resources.plan(512, 128 * 1024 * resources.MIB, 512)) + for field in resources.FIELDS: + self.assertLessEqual(small[field], large[field]) + self.assertGreaterEqual(small[field], 1) + with self.assertRaisesRegex(ValueError, "available memory"): + resources.plan(1, 0, 1) + self.assertLess(small["exclusive"], ordinary["exclusive"]) + + def test_concurrent_reservations_fit_one_shared_budget(self): + for memory in (1024, 2048, 4096, 8192, 65536): + with self.subTest(memory=memory): + workers = resources.plan(256, memory * resources.MIB, 256) + reserved = ( + workers["shared"] * 384 + + workers["gleam"] * 4 + + workers["harness"] * 32 + + workers["build"] * 128 + ) + self.assertLessEqual(reserved, memory * 3 // 4) + + def test_a_frozen_plan_is_not_rediscovered(self): + frozen = {name: "1" for name in resources.ENVIRONMENT} + with ( + mock.patch.dict(os.environ, frozen), + mock.patch.object(resources, "available_memory", return_value=0), + ): + self.assertEqual(set(resources.limits().values()), {1}) + + def test_cgroup_headroom_includes_parent_usage(self): + with tempfile.TemporaryDirectory() as root: + parent = Path(root) + child = parent / "child" + child.mkdir() + (parent / "memory.max").write_text(str(1000 * resources.MIB)) + (parent / "memory.current").write_text(str(900 * resources.MIB)) + (child / "memory.max").write_text("max") + with mock.patch.object(resources, "cgroups", return_value=[child, parent]): + self.assertEqual(resources.available_memory(), 100 * resources.MIB) + + def test_cpu_quota_limits_builds_but_not_waiting_scenarios(self): + with tempfile.TemporaryDirectory() as root: + directory = Path(root) + (directory / "cpu.max").write_text("150000 100000") + with ( + mock.patch.object(resources, "cgroups", return_value=[directory]), + mock.patch.object(os, "cpu_count", return_value=24), + mock.patch.object( + os, "sched_getaffinity", return_value=set(range(24)), create=True + ), + ): + self.assertEqual(resources.cpu_count(), 2) + self.assertEqual(resources.cpu_count(include_quota=False), 24) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/harness/test_runner_test.py b/test/harness/test_runner_test.py index 7f295747c..870aad34f 100644 --- a/test/harness/test_runner_test.py +++ b/test/harness/test_runner_test.py @@ -105,6 +105,9 @@ for collect in [ root = Path(directory) tests = root / "test" tests.mkdir() + (tests / "resources.py").write_bytes( + (ROOT / "test/resources.py").read_bytes() + ) sources = [ ROOT / "test/albedo_test_runner.erl", ROOT / "test/albedo_test_home.erl", diff --git a/test/python_test_runner.py b/test/python_test_runner.py index 6c2ba3f69..1f76559d7 100644 --- a/test/python_test_runner.py +++ b/test/python_test_runner.py @@ -1,6 +1,9 @@ """Load unittest files without letting an empty selection report success.""" +import argparse +from concurrent.futures import ThreadPoolExecutor import importlib.util +import subprocess from pathlib import Path import sys import unittest @@ -25,9 +28,27 @@ def suite_for(path, test_name=None): return suite +def run_file(path): + result = subprocess.run( + [sys.executable, __file__, path], capture_output=True, text=True + ) + print(f"{'ok' if result.returncode == 0 else 'FAILED'} {path}", file=sys.stderr) + if result.returncode: + print(result.stdout + result.stderr, file=sys.stderr) + return result.returncode == 0 + + def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--jobs", type=int, default=1) + parser.add_argument("paths", nargs="+") + args = parser.parse_args() + if len(args.paths) > 1: + with ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool: + outcomes = list(pool.map(run_file, args.paths)) + return 0 if all(outcomes) else 1 try: - suite = suite_for(sys.argv[1]) + suite = suite_for(args.paths[0]) except ValueError as error: print(error, file=sys.stderr) return 1 diff --git a/test/quick.sh b/test/quick.sh index 35abb176f..6462f1f9e 100755 --- a/test/quick.sh +++ b/test/quick.sh @@ -7,6 +7,8 @@ set -euo pipefail cd "$(dirname "$0")/.." +source test/resources.sh + # treefmt: the formatters and linters CI runs (Gleam, Go, Nix, Python with Ruff # format and check, shell). It rewrites what it fixes and fails when it had to, # so commit the result diff --git a/test/resources.py b/test/resources.py new file mode 100644 index 000000000..4601ae5ee --- /dev/null +++ b/test/resources.py @@ -0,0 +1,135 @@ +"""Resource discovery for the test gate and standalone suite runners.""" + +from __future__ import annotations + +import os +from pathlib import Path +import re +import subprocess +import sys + +MIB = 1024 * 1024 + + +def cpu_count(*, include_quota: bool = True) -> int: + """Return CPUs available to this process, including a Linux quota.""" + cpus = os.cpu_count() or 1 + if hasattr(os, "sched_getaffinity"): + cpus = min(cpus, len(os.sched_getaffinity(0))) + for directory in cgroups() if include_quota else []: + try: + quota, period = (directory / "cpu.max").read_text().split() + if quota != "max": + cpus = min(cpus, max(1, (int(quota) + int(period) - 1) // int(period))) + except (OSError, ValueError): + pass + return max(1, cpus) + + +def cgroups() -> list[Path]: + """Return the Linux v2 cgroup and its ancestors.""" + root = Path("/sys/fs/cgroup") + try: + entry = next( + line[3:] + for line in Path("/proc/self/cgroup").read_text().splitlines() + if line.startswith("0::") + ) + except (OSError, StopIteration): + return [] + # A cgroup namespace may expose a path outside its mounted root. + directory = root / entry.lstrip("/") + if ".." in directory.parts or not directory.exists(): + directory = root + return [ + directory, + *[p for p in directory.parents if p == root or root in p.parents], + ] + + +def available_memory() -> int: + """Return reclaimable host memory limited by cgroup headroom.""" + available = None + try: + for line in Path("/proc/meminfo").read_text().splitlines(): + if line.startswith("MemAvailable:"): + available = int(line.split()[1]) * 1024 + break + except OSError: + pass + if available is None and sys.platform == "darwin": + try: + stats = subprocess.check_output(["vm_stat"], text=True) + page_size = int(re.search(r"page size of (\d+) bytes", stats)[1]) + pages = sum( + int(match[1]) + for match in re.finditer( + r"Pages (?:free|inactive|speculative):\s+(\d+)", stats + ) + ) + available = pages * page_size + except (OSError, subprocess.CalledProcessError, TypeError, ValueError): + pass + # Unknown hosts use a conservative budget, not total physical memory. + available = 2048 * MIB if available is None else available + for directory in cgroups(): + try: + limit = (directory / "memory.max").read_text().strip() + if limit != "max": + used = int((directory / "memory.current").read_text()) + available = min(available, max(0, int(limit) - used)) + except (OSError, ValueError): + pass + return available + + +FIELDS = ("shared", "exclusive", "go", "gleam", "harness", "build") +ENVIRONMENT = ( + "ALBEDO_TEST_JOBS", + "ALBEDO_TEST_EXCLUSIVE_JOBS", + "ALBEDO_TEST_GO_JOBS", + "ALBEDO_TEST_GLEAM_JOBS", + "ALBEDO_TEST_HARNESS_JOBS", + "ALBEDO_TEST_BUILD_JOBS", +) + + +def plan(cpus: int, memory: int, build_cpus: int) -> dict[str, int]: + """Return lane limits, leaving a quarter of available memory unused.""" + budget = memory * 3 // 4 + if budget < 768 * MIB: + raise ValueError("test gate needs at least 1 GiB of available memory") + # Half is for both E2E lanes; the rest is shared by unit suites and builds. + e2e_budget = budget // 2 + unit_budget = (budget - e2e_budget) // 3 + lanes = max(1, min(4, cpus // 4, e2e_budget // (384 * MIB))) + return dict( + shared=lanes, + exclusive=2 * lanes, + go=lanes, + gleam=max(1, min(128, cpus * 8, unit_budget // (4 * MIB))), + harness=max(1, min(32, cpus * 2, unit_budget // (32 * MIB))), + build=max(1, min(8, build_cpus, unit_budget // (128 * MIB))), + ) + + +def limits() -> dict[str, int]: + frozen = {f: os.environ.get(n) for f, n in zip(FIELDS, ENVIRONMENT)} + if all(frozen.values()): + return {f: max(1, int(v)) for f, v in frozen.items() if v} + # Scenarios wait on I/O; quota limits active build threads instead. + values = plan(cpu_count(include_quota=False), available_memory(), cpu_count()) + for field, name in zip(FIELDS, ENVIRONMENT): + if name in os.environ: + values[field] = max(1, int(os.environ[name])) + return values + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--get", choices=FIELDS) + args = parser.parse_args() + values = limits() + print(values[args.get] if args.get else " ".join(str(values[f]) for f in FIELDS)) diff --git a/test/resources.sh b/test/resources.sh new file mode 100644 index 000000000..9a787c8fd --- /dev/null +++ b/test/resources.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Freeze one plan before the gate starts competing with itself for memory. +if [ -z "${ALBEDO_TEST_PLAN:-}" ]; then + read -r ALBEDO_TEST_JOBS ALBEDO_TEST_EXCLUSIVE_JOBS ALBEDO_TEST_GO_JOBS ALBEDO_TEST_GLEAM_JOBS ALBEDO_TEST_HARNESS_JOBS ALBEDO_TEST_BUILD_JOBS < <(python3 test/resources.py) + export ALBEDO_TEST_JOBS ALBEDO_TEST_EXCLUSIVE_JOBS ALBEDO_TEST_GO_JOBS ALBEDO_TEST_GLEAM_JOBS ALBEDO_TEST_HARNESS_JOBS ALBEDO_TEST_BUILD_JOBS + export ALBEDO_TEST_PLAN=1 + echo "test plan: shared=$ALBEDO_TEST_JOBS exclusive=$ALBEDO_TEST_EXCLUSIVE_JOBS go=$ALBEDO_TEST_GO_JOBS gleam=$ALBEDO_TEST_GLEAM_JOBS harness=$ALBEDO_TEST_HARNESS_JOBS build=$ALBEDO_TEST_BUILD_JOBS" >&2 + export GOFLAGS="${GOFLAGS:-} -p=$ALBEDO_TEST_BUILD_JOBS" + export GOMAXPROCS="$ALBEDO_TEST_BUILD_JOBS" + export CARGO_BUILD_JOBS="$ALBEDO_TEST_BUILD_JOBS" + export ERL_FLAGS="${ERL_FLAGS:-} +S $ALBEDO_TEST_BUILD_JOBS:$ALBEDO_TEST_BUILD_JOBS" +fi