Skip to content
Open
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
129 changes: 129 additions & 0 deletions .github/scripts/rust-test-shard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""Plan or run one of the four Cargo test shards."""

import argparse
import json
import shlex
import subprocess


SHARDS = 4
LIB_KINDS = {"lib", "rlib", "dylib", "cdylib", "staticlib", "proc-macro"}
# Keep these large ACP suites off the lib shard and off each other's shard.
RESERVED = {"acp_delegation_e2e_tests": 1, "acp_delegation_policy_tests": 2}
# Rounded suite seconds from CI run 46893014430. Only the suites taking at
# least 40s need individual weights; the rest averaged ~8s. These hints affect
# placement, not eligibility: renamed and new targets still run.
WEIGHTS = {
"acp_delegation_e2e_tests": 389,
"acp_delegation_policy_tests": 325,
"agent_loop_tests": 102,
"agent_rss_contract_tests": 47,
"auth_cli_contract_tests": 51,
"auth_cli_subprocess_tests": 47,
"coding_agent_e2e_tests": 43,
"coding_agent_edge_e2e_tests": 96,
"effect_commit_recovery_tests": 507,
"effect_contract_tests": 123,
"gateway_contract_tests": 378,
"gateway_provider_config_tests": 89,
"mcp_tool_server_tests": 45,
"mcp_tool_stdio_tests": 73,
"packaging_startup_tests": 105,
"plugin_admin_api_tests": 161,
"plugin_effect_api_e2e_tests": 303,
"plugin_hot_reload_tests": 41,
"plugin_state_migration_tests": 338,
"plugin_store_recovery_tests": 55,
"provider_codec_tests": 67,
"provider_durable_replay_loop_tests": 569,
"provider_loop_tests": 65,
"release_packaging_tests": 83,
"rss_corpus_compile_tests": 115,
"rss_tools_contract_tests": 59,
"run_lifecycle_tests": 70,
"service_tests": 267,
"storage_tests": 165,
"telegram_tests": 145,
"tools_pin_production_ab": 87,
"tools_pin_six_variants": 69,
"tools_pinned_process_lifecycle": 54,
}


def plan(metadata):
# Match `cargo test` from the workspace root, without widening its package
# selection to --workspace. A named --test selector applies to each
# selected package with that name, so assign duplicate names together.
members = set(metadata["workspace_default_members"])
targets = [
target for package in metadata["packages"] if package["id"] in members
for target in package["targets"]
]
kinds = {kind for target in targets for kind in target["kind"]}
names = {target["name"] for target in targets if target["kind"] == ["test"]}
selected = [[] for _ in range(SHARDS)]
extra = [[] for _ in range(SHARDS)]
loads = [0] * SHARDS

# Use broad selectors for non-integration targets to match --all-targets,
# including examples even when their default `test` setting is false.
# --all-targets does not select doctests.
if kinds & LIB_KINDS:
extra[0].append("--lib")
loads[0] = 1263
for kind, flag in (("bin", "--bins"), ("example", "--examples"), ("bench", "--benches")):
if kind in kinds:
extra[3].append(flag)
if "bin" in kinds:
loads[3] = 17

def weight(name):
return WEIGHTS.get(name, 8)

for name, shard in RESERVED.items():
if name in names:
selected[shard].append(name)
loads[shard] += weight(name)

# Place longer suites first on the least loaded shard. Break ties by suite
# count, then shard index, to keep the plan independent of metadata order.
for name in sorted(names - RESERVED.keys(), key=lambda name: (-weight(name), name)):
shard = min(range(SHARDS), key=lambda i: (loads[i], len(selected[i]), i))
selected[shard].append(name)
loads[shard] += weight(name)

return [
[*flags, *(arg for name in sorted(tests) for arg in ("--test", name))]
for flags, tests in zip(extra, selected)
]


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("shard", type=int, help="one-based shard number")
parser.add_argument("total", type=int, help="total number of shards")
parser.add_argument("--list", action="store_true", help="print the selected Cargo argv as JSON")
args = parser.parse_args()
if args.total != SHARDS:
parser.error(f"this workflow requires exactly {SHARDS} shards")
if not 1 <= args.shard <= args.total:
parser.error("expected 1 <= shard <= total")

metadata = json.loads(subprocess.check_output([
"cargo", "metadata", "--locked", "--all-features", "--no-deps", "--format-version", "1",
]))
selectors = plan(metadata)[args.shard - 1]
if not selectors:
parser.error(f"shard {args.shard}/{args.total} has no targets")
command = ["cargo", "test", "--locked", "--all-features", "--no-fail-fast", *selectors]
if args.list:
print(json.dumps(command))
return 0
print(shlex.join(command), flush=True)
status = subprocess.call(command)
print(f"Cargo exit code: {status}", flush=True)
return status


if __name__ == "__main__":
raise SystemExit(main())
160 changes: 160 additions & 0 deletions .github/scripts/test_rust_test_shard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
"""Exercise the shard CLI against a compact Cargo metadata fixture."""

import contextlib
import io
import json
from pathlib import Path
import runpy
import subprocess
import sys
import unittest
from collections import Counter
from unittest.mock import patch


SCRIPT = Path(__file__).with_name("rust-test-shard.py")
LIB = "rustscript_agent"
GATEWAY = "acp_delegation_e2e_tests"
POLICY = "acp_delegation_policy_tests"
TESTS = [GATEWAY, POLICY, *(f"suite_{i:02}" for i in range(20))]
METADATA_CMD = [
"cargo", "metadata", "--locked", "--all-features", "--no-deps", "--format-version", "1",
]
TEST_CMD = ["cargo", "test", "--locked", "--all-features", "--no-fail-fast"]


def target(name, kind, **fields):
return {"name": name, "kind": [kind], **fields}


def package(id_, targets):
return {"id": id_, "targets": targets}


def fixture():
return {
"workspace_default_members": ["main", "support"],
"workspace_members": ["main", "support", "nondefault"],
"packages": [
package("main", [
*(target(name, "test", **{"required-features": ["fixtures"]}) for name in TESTS),
target(LIB, "lib"),
target("agent", "bin"),
target("disabled_by_default", "example", test=False),
target("throughput", "bench"),
target("build-script-build", "custom-build"),
]),
package("support", [target(TESTS[-1], "test"), target("derive", "proc-macro")]),
package("nondefault", [target("not_selected", "test")]),
],
}


def invoke(*args, metadata=None, cargo_exit=0):
if metadata is None:
metadata = fixture()
output, errors = io.StringIO(), io.StringIO()
with (
patch.object(sys, "argv", [str(SCRIPT), *args]),
patch("subprocess.check_output", return_value=json.dumps(metadata)) as discover,
patch("subprocess.call", return_value=cargo_exit) as cargo,
contextlib.redirect_stdout(output),
contextlib.redirect_stderr(errors),
):
try:
runpy.run_path(str(SCRIPT), run_name="__main__")
except SystemExit as exit_:
return exit_.code, output.getvalue(), errors.getvalue(), discover, cargo
raise AssertionError("shard CLI did not report an exit code")


class ShardTests(unittest.TestCase):
def test_four_plans_cover_each_old_selector_once_and_separate_heavy_targets(self):
plans = []
for shard in range(1, 5):
status, output, _, discover, cargo = invoke(str(shard), "4", "--list")
self.assertEqual(status, 0)
discover.assert_called_once_with(METADATA_CMD)
cargo.assert_not_called()
argv = json.loads(output)
self.assertEqual(argv[:len(TEST_CMD)], TEST_CMD)
plans.append(argv[len(TEST_CMD):])

selected = Counter()
broad = Counter()
for plan in plans:
args = iter(plan)
for selector in args:
if selector == "--test":
selected[next(args)] += 1
else:
broad[selector] += 1
self.assertEqual(selected, Counter(TESTS))
self.assertEqual(broad, Counter(["--lib", "--bins", "--examples", "--benches"]))
self.assertIn("--lib", plans[0])
self.assertIn(GATEWAY, plans[1])
self.assertIn(POLICY, plans[2])
self.assertEqual(len({
next(i for i, plan in enumerate(plans) if item in plan)
for item in ("--lib", GATEWAY, POLICY)
}), 3)

def test_target_order_has_no_effect(self):
metadata = fixture()
metadata["packages"].reverse()
for pkg in metadata["packages"]:
pkg["targets"].reverse()
for shard in range(1, 5):
argv = (str(shard), "4", "--list")
self.assertEqual(invoke(*argv, metadata=metadata)[:3], invoke(*argv)[:3])

def test_only_emits_broad_selectors_for_target_kinds_present(self):
metadata = fixture()
metadata["workspace_default_members"] = ["main"]
metadata["packages"][0]["targets"] = [target(name, "test") for name in TESTS]
status, output, _, _, _ = invoke("1", "4", "--list", metadata=metadata)
self.assertEqual(status, 0)
self.assertNotIn("--lib", json.loads(output))
status, output, _, _, _ = invoke("4", "4", "--list", metadata=metadata)
self.assertEqual(status, 0)
self.assertTrue(all(arg == "--test" for arg in json.loads(output)[len(TEST_CMD)::2]))

def test_invalid_shards_fail_before_cargo(self):
for shard, total in [("0", "4"), ("5", "4"), ("1", "3"), ("1", "5")]:
with self.subTest(shard=shard, total=total):
status, _, errors, discover, cargo = invoke(shard, total)
self.assertEqual(status, 2)
self.assertIn("error:", errors)
discover.assert_not_called()
cargo.assert_not_called()

def test_empty_plan_fails_instead_of_running_cargos_default_suite(self):
metadata = fixture()
metadata["workspace_default_members"] = ["main"]
metadata["packages"][0]["targets"] = [target(GATEWAY, "test")]
status, _, errors, _, cargo = invoke("3", "4", metadata=metadata)
self.assertEqual(status, 2)
self.assertIn("shard 3/4 has no targets", errors)
cargo.assert_not_called()

def test_discovery_failure_is_not_treated_as_an_empty_or_successful_plan(self):
failure = subprocess.CalledProcessError(101, METADATA_CMD)
with patch("subprocess.check_output", side_effect=failure), patch("subprocess.call") as cargo:
with self.assertRaises(subprocess.CalledProcessError) as raised:
with patch.object(sys, "argv", [str(SCRIPT), "1", "4"]):
runpy.run_path(str(SCRIPT), run_name="__main__")
self.assertIs(raised.exception, failure)
cargo.assert_not_called()

def test_launches_the_printed_plan_without_filters_and_reports_cargo_failure(self):
planned = json.loads(invoke("3", "4", "--list")[1])
for cargo_exit in (0, 101):
with self.subTest(cargo_exit=cargo_exit):
status, output, _, _, cargo = invoke("3", "4", cargo_exit=cargo_exit)
cargo.assert_called_once_with(planned)
self.assertEqual(status, cargo_exit)
self.assertIn(f"Cargo exit code: {cargo_exit}", output)


if __name__ == "__main__":
unittest.main()
Loading
Loading