| # Copyright 2026 The Fuchsia Authors | |
| # | |
| # Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| # <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| # license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| # This file may not be copied, modified, or distributed except according to | |
| # those terms. | |
| """Unit tests for `ci/run_experimental_ci.py`.""" | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| import shutil | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import unittest | |
| from unittest import mock | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import run_experimental_ci as rec | |
| def _git(repo: Path, *args: str) -> str: | |
| proc = subprocess.run( | |
| ["git", "-C", str(repo), *args], | |
| capture_output=True, | |
| text=True, | |
| check=True, | |
| ) | |
| return proc.stdout.strip() | |
| class RunExperimentalCiTests(unittest.TestCase): | |
| def test_discover_and_sandbox_argv_variants(self): | |
| with tempfile.TemporaryDirectory(prefix="anneal-exp-ci-") as tmp: | |
| root = Path(tmp) | |
| (root / ".git").mkdir() | |
| exp = root / "experimental/clock-seqlock" | |
| exp.mkdir(parents=True) | |
| (exp / "EXPERIMENT.toml").write_text( | |
| 'owners = ["@joshlf"]\n' | |
| 'tracking_issue = "https://github.com/google/anneal/issues/1"\n' | |
| 'expires_on = "2027-01-15"\n' | |
| 'ci_command = ["./ci.sh", "--fast"]\n', | |
| encoding="utf-8", | |
| ) | |
| self.assertEqual(rec.discover_all_slugs(root), ["clock-seqlock"]) | |
| cmd = rec.load_ci_command(root, "clock-seqlock") | |
| self.assertEqual(cmd, ["./ci.sh", "--fast"]) | |
| argv = rec.build_sandbox_argv(root, "clock-seqlock", cmd, timeout_secs=120) | |
| self.assertEqual(argv[:4], ["/usr/bin/timeout", "--kill-after=15s", "120s", "bwrap"]) | |
| for flag in ( | |
| "--die-with-parent", | |
| "--clearenv", | |
| "--new-session", | |
| "--unshare-user", | |
| "--disable-userns", | |
| "--unshare-net", | |
| "--unshare-pid", | |
| "--unshare-ipc", | |
| "--unshare-uts", | |
| "--unshare-cgroup-try", | |
| ): | |
| self.assertIn(flag, argv) | |
| cap_idx = argv.index("--cap-drop") | |
| self.assertEqual(argv[cap_idx + 1], "ALL") | |
| ws_tmpfs_idx = argv.index("/workspace") | |
| self.assertEqual(argv[ws_tmpfs_idx - 1], "--tmpfs") | |
| exp_dst_idx = argv.index("/workspace/experimental") | |
| self.assertEqual(argv[exp_dst_idx - 2], "--ro-bind") | |
| self.assertEqual( | |
| argv[exp_dst_idx - 1], str((root / "experimental").resolve()) | |
| ) | |
| remount_idx = argv.index("--remount-ro") | |
| self.assertEqual(argv[remount_idx + 1], "/workspace") | |
| self.assertIn("/etc/alternatives", argv) | |
| self.assertNotIn("/workspace/.git", argv) | |
| self.assertEqual(argv[-3:], ["--", "./ci.sh", "--fast"]) | |
| # Worktree regular `.git` file is also omitted from `/workspace`. | |
| (root / ".git").rmdir() | |
| (root / ".git").write_text("gitdir: /tmp/elsewhere\n", encoding="utf-8") | |
| wt_argv = rec.build_sandbox_argv(root, "clock-seqlock", cmd) | |
| self.assertNotIn("/workspace/.git", wt_argv) | |
| # Dangling `.git` symlink is omitted rather than mounted over. | |
| (root / ".git").unlink() | |
| (root / ".git").symlink_to(root / "nonexistent-git-target") | |
| sym_argv = rec.build_sandbox_argv(root, "clock-seqlock", cmd) | |
| self.assertNotIn("/workspace/.git", sym_argv) | |
| def test_rejects_invalid_slugs_symlinks_refs_and_commands(self): | |
| with tempfile.TemporaryDirectory(prefix="anneal-exp-ci-") as tmp: | |
| root = Path(tmp) | |
| outside = root / "outside" | |
| outside.mkdir() | |
| (outside / "EXPERIMENT.toml").write_text( | |
| 'ci_command = ["./ci.sh"]\n', encoding="utf-8" | |
| ) | |
| exp_root = root / "experimental" | |
| exp_root.mkdir() | |
| (exp_root / "sym-exp").symlink_to(outside) | |
| bad_manifest_exp = exp_root / "bad-manifest" | |
| bad_manifest_exp.mkdir() | |
| (bad_manifest_exp / "EXPERIMENT.toml").symlink_to( | |
| outside / "EXPERIMENT.toml" | |
| ) | |
| self.assertEqual(rec.discover_all_slugs(root), []) | |
| for bad_slug in ("../outside", "0leading-digit", "a" * 65, "sym-exp", "bad-manifest"): | |
| with self.assertRaises(ValueError): | |
| rec.load_ci_command(root, bad_slug) | |
| with self.assertRaises(ValueError): | |
| rec.discover_changed_slugs(root, "--evil", "HEAD") | |
| with self.assertRaises(ValueError): | |
| rec.build_sandbox_argv(root, "clock-seqlock", ["./ci.sh"], timeout_secs=0) | |
| for bad_cmd in (["./ci.sh\x00"], ["/usr/bin/env", "sh"], ["../escape.sh"]): | |
| with self.assertRaises(ValueError): | |
| rec.build_sandbox_argv(root, "clock-seqlock", bad_cmd) | |
| broken = exp_root / "broken-cmd" | |
| broken.mkdir() | |
| (broken / "EXPERIMENT.toml").write_text( | |
| "ci_command = []\n", encoding="utf-8" | |
| ) | |
| slug, rc, out = rec.run_one_slug(root, "broken-cmd") | |
| self.assertEqual(slug, "broken-cmd") | |
| self.assertEqual(rc, 2) | |
| self.assertIn("invalid ci_command", out) | |
| def test_streaming_bounded_capture_handles_non_utf8_and_caps_output(self): | |
| decoded = rec.decode_capped_output(b"ok-\xff\xfe", b"-err") | |
| self.assertIn("ok-", decoded) | |
| self.assertIn("\ufffd", decoded) | |
| self.assertIn("-err", decoded) | |
| rc, out = rec.run_bounded_capture( | |
| [ | |
| sys.executable, | |
| "-I", | |
| "-B", | |
| "-c", | |
| "import sys; sys.stdout.buffer.write(b'\\xff' + b'x' * 4096)", | |
| ], | |
| max_bytes=512, | |
| ) | |
| self.assertEqual(rc, 0) | |
| self.assertIn("\ufffd", out) | |
| self.assertTrue(out.endswith("\n... [output truncated]")) | |
| self.assertLess(len(out), 600) | |
| def test_live_bwrap_symlink_git_omission_and_readonly_workspace(self): | |
| if shutil.which("bwrap") is None: | |
| self.skipTest("bwrap not installed") | |
| try: | |
| rec.probe_sandbox() | |
| except RuntimeError as exc: | |
| self.skipTest(f"bwrap unavailable in test environment: {exc}") | |
| with tempfile.TemporaryDirectory(prefix="anneal-exp-live-") as tmp: | |
| root = Path(tmp) | |
| (root / ".git").symlink_to(root / "dangling-git") | |
| exp = root / "experimental/live-check" | |
| exp.mkdir(parents=True) | |
| script = exp / "ci.sh" | |
| script.write_text( | |
| "#!/bin/sh\n" | |
| "set -eu\n" | |
| "if [ -e /workspace/.git ] || [ -L /workspace/.git ]; then exit 41; fi\n" | |
| "if touch /workspace/nope 2>/dev/null; then exit 42; fi\n" | |
| "if unshare -Ur id >/dev/null 2>&1; then exit 43; fi\n" | |
| "printf 'ok-\\377\\n'\n", | |
| encoding="utf-8", | |
| ) | |
| script.chmod(0o755) | |
| (exp / "EXPERIMENT.toml").write_text( | |
| 'ci_command = ["./ci.sh"]\n', encoding="utf-8" | |
| ) | |
| slug, rc, out = rec.run_one_slug(root, "live-check") | |
| self.assertEqual(slug, "live-check") | |
| self.assertEqual(rc, 0, out) | |
| self.assertIn("ok-\ufffd", out) | |
| def test_discover_changed_slugs_and_main_exit_modes(self): | |
| with tempfile.TemporaryDirectory(prefix="anneal-exp-git-") as tmp: | |
| root = Path(tmp) | |
| _git(root, "init", "-q") | |
| _git(root, "config", "user.name", "Test") | |
| _git(root, "config", "user.email", "test@example.com") | |
| (root / "README.md").write_text("base\n", encoding="utf-8") | |
| _git(root, "add", "README.md") | |
| _git(root, "commit", "-q", "-m", "base") | |
| base_sha = _git(root, "rev-parse", "HEAD") | |
| for slug in ("alpha-ok", "beta-fail"): | |
| exp = root / "experimental" / slug | |
| exp.mkdir(parents=True) | |
| (exp / "EXPERIMENT.toml").write_text( | |
| 'ci_command = ["./ci.sh"]\n', encoding="utf-8" | |
| ) | |
| _git(root, "add", "experimental") | |
| _git(root, "commit", "-q", "-m", "add experiments") | |
| head_sha = _git(root, "rev-parse", "HEAD") | |
| self.assertEqual( | |
| rec.discover_changed_slugs(root, base_sha, head_sha), | |
| ["alpha-ok", "beta-fail"], | |
| ) | |
| def fake_run_one(_root, slug, **_kwargs): | |
| return (slug, 0, "ok") if slug == "alpha-ok" else (slug, 1, "boom\ufffd") | |
| status_path = root / "out/status.json" | |
| with ( | |
| mock.patch.object(rec, "probe_sandbox", return_value=None), | |
| mock.patch.object(rec, "run_one_slug", side_effect=fake_run_one), | |
| ): | |
| rc_changed = rec.main([ | |
| "--root", | |
| str(root), | |
| "--mode", | |
| "changed", | |
| "--base", | |
| base_sha, | |
| "--head", | |
| head_sha, | |
| ]) | |
| self.assertEqual(rc_changed, 1) | |
| rc_sweep = rec.main([ | |
| "--root", | |
| str(root), | |
| "--mode", | |
| "sweep", | |
| "--main-sha", | |
| head_sha, | |
| "--run-url", | |
| "https://example.invalid/run/1", | |
| "--status-out", | |
| str(status_path), | |
| ]) | |
| self.assertEqual(rc_sweep, 0) | |
| report = json.loads(status_path.read_text(encoding="utf-8")) | |
| self.assertEqual(report["schema"], "ci_exp_status.v1") | |
| self.assertEqual(report["experiments"]["alpha-ok"]["result"], "pass") | |
| self.assertEqual(report["experiments"]["beta-fail"]["result"], "fail") | |
| # Broken sandbox probe fails closed without writing status JSON. | |
| poison_path = root / "out/poison.json" | |
| with mock.patch.object( | |
| rec, "probe_sandbox", side_effect=RuntimeError("bwrap denied") | |
| ): | |
| rc_broken = rec.main([ | |
| "--root", | |
| str(root), | |
| "--mode", | |
| "sweep", | |
| "--status-out", | |
| str(poison_path), | |
| ]) | |
| self.assertEqual(rc_broken, 2) | |
| self.assertFalse(poison_path.exists()) | |
| def test_render_status_report_schema(self): | |
| report = rec.render_status_report( | |
| "a" * 40, | |
| "https://github.com/google/anneal/actions/runs/1", | |
| {"alpha": 0, "beta": 1}, | |
| generated_at="2026-12-01T12:00:00Z", | |
| ) | |
| self.assertEqual(report["schema"], "ci_exp_status.v1") | |
| self.assertEqual(report["experiments"]["alpha"]["result"], "pass") | |
| self.assertEqual(report["experiments"]["beta"]["result"], "fail") | |
| if __name__ == "__main__": | |
| unittest.main() |