diff --git a/.github/workflows/mcpx-test.yml b/.github/workflows/mcpx-test.yml index 030459c9fa..62fae75c78 100644 --- a/.github/workflows/mcpx-test.yml +++ b/.github/workflows/mcpx-test.yml @@ -93,6 +93,8 @@ jobs: run: python3 -m unittest discover -s pkgs/mcpx/scripts/tests -p 'test_affected_untracked.py' -v - name: Run-seed wrapper regressions (#1949) run: python3 -m unittest discover -s pkgs/mcpx/scripts/tests -p 'test_mcpx_test_seed.py' -v + - name: Shard-packer discovery regressions (#6906) + run: python3 -m unittest discover -s pkgs/mcpx/scripts/tests -p 'test_e2e_shard_packer.py' -v # Same runtimes as mcpx.yml's test job: non-e2e packages (examples) # shell out to deno/bun/node too, and a missing runtime reads as a # test failure (first run of this workflow, PR #2888). diff --git a/pkgs/mcpx/scripts/ci/e2e-shard-packer.py b/pkgs/mcpx/scripts/ci/e2e-shard-packer.py index 366d471d39..8c4496fcd6 100755 --- a/pkgs/mcpx/scripts/ci/e2e-shard-packer.py +++ b/pkgs/mcpx/scripts/ci/e2e-shard-packer.py @@ -51,11 +51,178 @@ DEFAULT_SECONDS = 3.0 +# --- Build-constraint awareness (#6906) ----------------------------------- +# The shard legs run `go test` with no -tags on linux/amd64 runners +# (.github/workflows/mcpx-test.yml), so discovery must return exactly the +# tests that untagged build contains. A text-only scan also returns tests +# behind unsatisfied //go:build constraints (e.g. the realsoftware-tagged +# e2e tests): those are dealt into shards, counted in matrix.count, and can +# never be reported by the leg that owns them, so the leg's count check +# fails. The rules below mirror go/build's default-context matching for +# the legs' context: GOOS/GOARCH filename suffixes plus //go:build (and +# legacy // +build) expressions evaluated with no custom tags set. + +DEFAULT_GOOS = "linux" +DEFAULT_GOARCH = "amd64" + +_KNOWN_GOOS = { + "aix", "android", "darwin", "dragonfly", "freebsd", "hurd", "illumos", + "ios", "js", "linux", "netbsd", "openbsd", "plan9", "solaris", + "wasip1", "windows", +} +_KNOWN_GOARCH = { + "386", "amd64", "arm", "arm64", "loong64", "mips", "mips64", "mipsle", + "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "sparc64", "wasm", +} + +# Tags the default build satisfies beyond GOOS/GOARCH: "unix" (linux is a +# unix GOOS), the "gc" compiler, and cumulative go1.x release tags (the +# legs build with the repo's current Go from go.mod, so a release tag at +# or below any plausible toolchain version is satisfied; a future go1.x +# tag beyond the toolchain would also gate new code the legs cannot run +# yet, which discovery cannot resolve without invoking go list). +_SATISFIED_TAGS = {DEFAULT_GOOS, DEFAULT_GOARCH, "unix", "gc"} + + +def _tag_satisfied(tag: str) -> bool: + if tag in _SATISFIED_TAGS: + return True + if re.fullmatch(r"go1\.\d+", tag): + return True + return False + + +_TOKEN_RE = re.compile(r"\s*(?:(&&)|(\|\|)|(!)|(\()|(\))|([A-Za-z0-9_.]+))") + + +def _eval_build_expr(expr: str) -> bool: + """Evaluate a //go:build expression under the default build context.""" + tokens: list[str] = [] + pos = 0 + while pos < len(expr): + m = _TOKEN_RE.match(expr, pos) + if not m or m.end() == pos: + raise ValueError(f"unparseable build expression: {expr!r}") + pos = m.end() + tokens.append(next(g for g in m.groups() if g is not None)) + state = {"i": 0} + + def peek() -> str | None: + return tokens[state["i"]] if state["i"] < len(tokens) else None + + def parse_or() -> bool: + value = parse_and() + while peek() == "||": + state["i"] += 1 + rhs = parse_and() + value = value or rhs + return value + + def parse_and() -> bool: + value = parse_unary() + while peek() == "&&": + state["i"] += 1 + rhs = parse_unary() + value = value and rhs + return value + + def parse_unary() -> bool: + tok = peek() + if tok == "!": + state["i"] += 1 + return not parse_unary() + if tok == "(": + state["i"] += 1 + value = parse_or() + if peek() != ")": + raise ValueError(f"unbalanced build expression: {expr!r}") + state["i"] += 1 + return value + if tok is None or tok in ("&&", "||", ")"): + raise ValueError(f"unexpected token in build expression: {expr!r}") + state["i"] += 1 + return _tag_satisfied(tok) + + result = parse_or() + if state["i"] != len(tokens): + raise ValueError(f"trailing tokens in build expression: {expr!r}") + return result + + +def _eval_plus_build(lines: list[str]) -> bool: + """Evaluate legacy // +build lines: lines AND together, space-separated + options OR together, comma-separated terms AND together (! negates).""" + for line in lines: + line_ok = False + for option in line.split(): + term_ok = True + for term in option.split(","): + if term.startswith("!"): + term_ok = term_ok and not _tag_satisfied(term[1:]) + else: + term_ok = term_ok and _tag_satisfied(term) + line_ok = line_ok or term_ok + if not line_ok: + return False + return True + + +def _filename_included(path: str) -> bool: + """Mirror go/build's GOOS/GOARCH filename-suffix rule.""" + base = os.path.basename(path) + if base.endswith("_test.go"): + base = base[: -len("_test.go")] + parts = base.split("_") + if len(parts) >= 2 and parts[-1] in _KNOWN_GOARCH: + if parts[-1] != DEFAULT_GOARCH: + return False + parts = parts[:-1] + if len(parts) >= 2 and parts[-1] in _KNOWN_GOOS: + if parts[-1] != DEFAULT_GOOS: + return False + return True + + +def _constraints_included(text: str) -> bool: + """Evaluate the file's build constraints (header block only).""" + go_build: str | None = None + plus_build: list[str] = [] + for line in text.splitlines(): + stripped = line.strip() + if stripped.startswith("package "): + break + if stripped.startswith("//go:build"): + go_build = stripped[len("//go:build"):].strip() + elif stripped.startswith("// +build"): + plus_build.append(stripped[len("// +build"):].strip()) + elif stripped and not stripped.startswith("//"): + break + if go_build is not None: + return _eval_build_expr(go_build) + if plus_build: + return _eval_plus_build(plus_build) + return True + + +def _file_included(path: str, text: str) -> bool: + return _filename_included(path) and _constraints_included(text) + + def discover(tests_dir: str) -> list[str]: names: set[str] = set() for path in sorted(glob.glob(os.path.join(tests_dir, "*_test.go"))): with open(path, errors="replace") as fh: - names.update(TEST_RE.findall(fh.read())) + text = fh.read() + try: + included = _file_included(path, text) + except ValueError as exc: + raise SystemExit(f"coverage defect: {path}: {exc}") + if not included: + continue + # TestMain is the package test entry point, not a test: go test + # -list never reports it and a -run leg can never report it either, + # so counting it breaks the same count contract (#6906). + names.update(n for n in TEST_RE.findall(text) if n != "TestMain") return sorted(names) diff --git a/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py b/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py new file mode 100644 index 0000000000..079c28acb0 --- /dev/null +++ b/pkgs/mcpx/scripts/tests/test_e2e_shard_packer.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Regression tests for pkgs/mcpx/scripts/ci/e2e-shard-packer.py discovery. + +Issue #6906: the packer discovered tests by regex over raw file text, +ignoring Go build constraints, so tests behind an unsatisfied +//go:build tag (e.g. realsoftware) were dealt into shards whose untagged +`go test` legs could never report them — the leg's count check then +failed. The oracle for every case here is the default build context the +shard legs run under (no -tags, linux/amd64): a fixture file's tests are +discovered iff an untagged linux/amd64 `go test` build would contain +them. + +Run: python3 -m unittest discover -s pkgs/mcpx/scripts/tests -p 'test_e2e_shard_packer.py' -v +""" + +import importlib.util +import os +import tempfile +import unittest + +PACKER = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "ci", "e2e-shard-packer.py") +) + + +def load_packer(): + spec = importlib.util.spec_from_file_location("e2e_shard_packer", PACKER) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def go_file(body: str, build_line: str | None = None) -> str: + header = f"{build_line}\n\n" if build_line else "" + return f"{header}package e2e_test\n\n{body}\n" + + +def test_fn(name: str) -> str: + return f"func {name}(t *testing.T) {{}}" + + +class DiscoverBuildConstraintTests(unittest.TestCase): + def setUp(self): + self.packer = load_packer() + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def write(self, filename: str, content: str): + with open(os.path.join(self.tmp.name, filename), "w") as fh: + fh.write(content) + + def discover(self): + return self.packer.discover(self.tmp.name) + + def test_untagged_tests_discovered(self): + self.write("plain_test.go", go_file(test_fn("TestPlain") + "\n" + test_fn("TestAlsoPlain"))) + self.assertEqual(self.discover(), ["TestAlsoPlain", "TestPlain"]) + + def test_unsatisfied_tag_excluded(self): + self.write("real_test.go", go_file(test_fn("TestRealSoftware"), "//go:build realsoftware")) + self.write("plain_test.go", go_file(test_fn("TestPlain"))) + self.assertEqual(self.discover(), ["TestPlain"]) + + def test_ignore_tag_excluded(self): + self.write("ignored_test.go", go_file(test_fn("TestIgnored"), "//go:build ignore")) + self.assertEqual(self.discover(), []) + + def test_other_os_excluded_and_default_os_included(self): + self.write("win_test.go", go_file(test_fn("TestWindows"), "//go:build windows")) + self.write("lin_test.go", go_file(test_fn("TestLinux"), "//go:build linux && amd64")) + self.write("notwin_test.go", go_file(test_fn("TestNotWindows"), "//go:build !windows")) + self.write("either_test.go", go_file(test_fn("TestEitherOS"), "//go:build linux || darwin")) + self.assertEqual( + self.discover(), ["TestEitherOS", "TestLinux", "TestNotWindows"] + ) + + def test_parenthesised_and_negated_custom_tag(self): + self.write( + "combo_test.go", + go_file(test_fn("TestCombo"), "//go:build (linux && amd64) && !realsoftware"), + ) + self.write( + "combo2_test.go", + go_file(test_fn("TestComboTagged"), "//go:build linux && realsoftware"), + ) + self.assertEqual(self.discover(), ["TestCombo"]) + + def test_legacy_plus_build_lines(self): + self.write("legacy_win_test.go", go_file(test_fn("TestLegacyWin"), "// +build windows")) + self.write("legacy_lin_test.go", go_file(test_fn("TestLegacyLin"), "// +build linux,amd64")) + self.assertEqual(self.discover(), ["TestLegacyLin"]) + + def test_filename_suffix_rules(self): + self.write("thing_windows_test.go", go_file(test_fn("TestFileWindows"))) + self.write("thing_linux_test.go", go_file(test_fn("TestFileLinux"))) + self.write("thing_arm64_test.go", go_file(test_fn("TestFileArm64"))) + self.write("thing_amd64_test.go", go_file(test_fn("TestFileAmd64"))) + self.assertEqual(self.discover(), ["TestFileAmd64", "TestFileLinux"]) + + def test_testmain_is_not_a_test(self): + self.write( + "main_test.go", + go_file("func TestMain(m *testing.M) {}\n" + test_fn("TestReal")), + ) + self.assertEqual(self.discover(), ["TestReal"]) + + def test_mixed_fixture_pack_counts_match_discovery(self): + self.write("plain_test.go", go_file(test_fn("TestA") + "\n" + test_fn("TestB"))) + self.write("tagged_test.go", go_file(test_fn("TestTagged"), "//go:build realsoftware")) + self.write("lin_test.go", go_file(test_fn("TestC"), "//go:build linux")) + names = self.discover() + self.assertEqual(names, ["TestA", "TestB", "TestC"]) + weights, _ = self.packer.load_weights(None, names) + shards, buckets = self.packer.pack(names, weights, 170.0, 6) + self.packer.assert_covered(names, buckets) + self.assertEqual(sum(len(b) for b in buckets), len(names)) + self.assertGreaterEqual(shards, 1) + + +if __name__ == "__main__": + unittest.main()