Files
Pulse/scripts/release_control/run_go_rest_shard.py
pulse-triage[bot] bd151403a0 Require observed roots for ordinary backend CI verdicts
Compare each ordinary package's race-enabled test listing with its completed JSON events. Preserve actual Go exits separately from coverage failures, explicit skips, zero-root packages, bounded scheduling and source-bound receipts. Keep existing workflow commands and stable-patch recorder compatibility.

Contract-Neutral: Backend CI execution and proof accounting only; no product, installer, runtime or subsystem behavior changes.
Change-source: pulse-maintainer
2026-11-15 05:32:15 +00:00

261 lines
13 KiB
Python

#!/usr/bin/env python3
"""Share four package slots between source-listed slices and ordinary packages.
The old recipe reserved two ordinary package workers even after both slow
slices finished. A single queue releases those slots without adding jobs or
increasing the four-binary envelope. Timing weights schedule, never select,
the source-derived ordinary package inventory.
"""
from __future__ import annotations
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
ROOT = Path(__file__).resolve().parents[2]
MODULE = "github.com/rcourtman/pulse-go-rewrite/"
SLICED = ("internal/monitoring", "scripts/installtests")
SLOTS = 4
ORDINARY_COMMAND = "go test -race -timeout 50m $pkgs"
RECORDER = ROOT / ".github/scripts/record-internal-api-test-seconds.py"
def empty_package_coverage(stream, name: str, output: Path) -> int:
"""Verify a zero-root listing's package result without inventing a test.
The shared shard recorder deliberately rejects empty selections. Keep its
contract unchanged (including on stable patches) and admit only this exact
package's complete, zero-test JSON stream here.
"""
terminal = None
terminal_count = invalid = 0
for raw in stream:
try:
event = json.loads(raw)
except ValueError:
event = None
if (not isinstance(event, dict) or event.get("Package") != name or
event.get("Test", "") != "" or terminal_count or
event.get("Action") not in ("start", "output", "pass", "skip")):
invalid += 1
if not isinstance(event, dict):
print(raw, end="", flush=True)
continue
text = event.get("Output", "")
if isinstance(text, str):
print(text, end="", flush=True)
else:
invalid += 1
if event.get("Action") in ("pass", "skip", "fail") and not event.get("Test"):
terminal = event["Action"]
terminal_count += 1
exit_code = 0 if terminal in ("pass", "skip") and terminal_count == 1 and invalid == 0 else 1
(output / "empty-coverage.json").write_text(json.dumps({
"listed_roots": 0, "package_terminal_action": terminal,
"package_terminal_count": terminal_count, "invalid_event_count": invalid,
"coverage_exit": exit_code,
}, indent=2) + "\n")
if exit_code:
print("Empty ordinary package evidence is incomplete or inconsistent.", file=sys.stderr)
return exit_code
def ordinary_execution(name: str, command: list[str], env: dict,
output: Path) -> dict:
"""Require the listed roots, not just a successful Go driver exit.
A TestMain/helper can return zero without calling m.Run. Go then reports a
successful package even though listed tests never ran. Use the same recorder
as the sliced packages, preserving explicit skips and original Go exits.
The extra list reuses the same race build objects and occupies this task's
existing slot; it admits no additional parallel binary or cached verdict.
"""
output.mkdir(parents=True, exist_ok=True)
listing = subprocess.run(["go", "test", "-race", "-json=false", "-list", ".", name],
cwd=ROOT, env=env, capture_output=True, text=True)
if listing.returncode:
sys.stdout.write(listing.stdout)
sys.stderr.write(listing.stderr)
return {"started": False, "exit": None, "listing_exit": listing.returncode,
"coverage_exit": None}
names = [line for line in listing.stdout.splitlines()
if line.startswith(("Test", "Fuzz", "Example")) and line.isidentifier()]
if len(names) != len(set(names)):
print("Ordinary package listing repeats roots; no runtime tests started.", file=sys.stderr)
return {"started": False, "exit": None, "listing_exit": 0, "coverage_exit": 2}
selection = output / "listed.tests"
selection.write_text("".join(test + "\n" for test in names))
# Keep the stable-shipped literal command template. Explicit GOFLAGS owns
# JSON just as it already owns fresh, unfiltered ordinary test execution.
runtime_env = {**env, "GOFLAGS": env["GOFLAGS"] + " -json=true"}
recorder = [sys.executable, str(RECORDER), str(output / "timings.txt"), str(selection), name]
with subprocess.Popen(command, cwd=ROOT, env=runtime_env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True) as process:
try:
coverage_exit = (subprocess.run(recorder, cwd=ROOT, stdin=process.stdout).returncode
if names else empty_package_coverage(process.stdout, name, output))
except OSError as error:
# Runtime already started. A failed recorder/read/write must not
# be misreported as a Go process that never launched.
print(f"Ordinary coverage collection failed: {error}", file=sys.stderr)
coverage_exit = None
finally:
process.stdout.close()
test_exit = process.wait()
return {"started": True, "exit": test_exit, "listing_exit": 0,
"coverage_exit": coverage_exit, "listed_roots": len(names)}
def ordinary_packages(index: int) -> list[str]:
listing = subprocess.run(["go", "list", "./..."], cwd=ROOT,
capture_output=True, text=True, check=True)
packages = listing.stdout.splitlines()
required = {MODULE + name for name in (*SLICED, "internal/api")}
if (not required.issubset(packages) or len(packages) != len(set(packages))
or any(not name.startswith(MODULE) for name in packages)):
raise ValueError("incomplete, duplicate or foreign source package inventory")
ordinary = [name for name in packages if name not in required]
selection = subprocess.run(
[sys.executable, str(ROOT / ".github/scripts/select-go-package-shard.py"),
str(ROOT / ".github/scripts/go-package-test-seconds.txt"), "2", str(index)],
cwd=ROOT, input="\n".join(ordinary) + "\n",
capture_output=True, text=True, check=True)
selected = selection.stdout.splitlines()
if (not selected or len(selected) != len(set(selected))
or not set(selected).issubset(ordinary)):
raise ValueError("empty or invalid ordinary package shard")
return selected
def tasks(packages: list[str], index: int, output: Path,
ordinary_command: str) -> list[tuple[str, list[str]]]:
sliced = [(name, [sys.executable, str(ROOT / "scripts/release_control/run_go_package_slice.py"),
"--package", name, "--index", str(index),
"--output", str(output / name.rsplit("/", 1)[-1])])
for name in SLICED]
# One package per lease. -p=1 bounds its compiler as well as its binary;
# GOMAXPROCS=2 still bounds each binary, exactly as in the previous recipe.
# A completed slice can immediately admit another ordinary package.
return sliced + [(name, ["bash", "-euo", "pipefail", "-c", ordinary_command])
for name in packages]
def run_task(task: tuple[str, list[str]], output: Path | None = None) -> dict:
name, command = task
start = time.monotonic()
try:
env = dict(os.environ)
if name not in SLICED:
env["pkgs"] = name
# Keep the bounded compiler assignment compatible with frozen
# source contracts when main's controls are copied to patches.
env["GOFLAGS"] = env.get("GOFLAGS", "") + " -p=1"
# Reuse compiled objects, never an earlier test verdict. Go's
# result cache cannot see fixture bytes read by shell children.
# Append after ambient flags so even -count=0 cannot omit tests.
env["GOFLAGS"] += " -count=1"
# This worker owns complete ordinary test execution, not ambient
# selections, listing, wrappers or fuzz sessions. Empty selectors
# restore Go's unfiltered defaults; compiler/module flags survive.
# Keep fail-fast off so a failed root cannot hide later assertions.
env["GOFLAGS"] += " -run= -skip= -list= -exec= -fuzz= -short=false -failfast=false"
# Build-only and dry-run modes can also return success without any
# test execution. Keep these distinct from the compile-only gate.
env["GOFLAGS"] += " -c=false -n=false"
if name not in SLICED and command == ["bash", "-euo", "pipefail", "-c", ORDINARY_COMMAND]:
if output is None:
# Direct callers get the same verification without retaining
# fixture artifacts in the source checkout.
with tempfile.TemporaryDirectory(prefix="ordinary-coverage-") as temporary:
observation = ordinary_execution(name, command, env, Path(temporary))
else:
observation = ordinary_execution(name, command, env, output / "ordinary" / name)
else:
result = subprocess.run(command, cwd=ROOT, env=env)
observation = {"started": True, "exit": result.returncode}
except OSError as error:
print(f"Could not start backend package {name}: {error}", file=sys.stderr)
# No process exit was observed. In particular, do not manufacture the
# shell's command-not-found exit for a process that never started.
observation = {"started": False, "exit": None, "start_error_errno": error.errno}
return {"package": name, **observation,
"seconds": round(time.monotonic() - start, 3)}
def retain_results(output: Path, index: int, planned: list[str], results: dict,
start: float, *, complete: bool = False) -> None:
# Record only returned observations, in the original source order. A
# planned/unobserved task is not evidence of execution or current liveness.
receipt = {"schema_version": 1, "index": index, "slots": SLOTS,
"planned_packages": planned, "collection_complete": complete,
"unobserved_packages": [name for name in planned if name not in results],
"tasks": [results[name] for name in planned if name in results],
"seconds": round(time.monotonic() - start, 3)}
# Readers and the existing always-run artifact upload must see either the
# previous complete JSON snapshot or this one, never a truncated overwrite.
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=output,
prefix=".ordinary-packages-", delete=False) as stream:
temporary = Path(stream.name)
json.dump(receipt, stream, indent=2)
stream.write("\n")
temporary.replace(output / "ordinary-packages.json")
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--index", type=int, choices=(0, 1), required=True)
parser.add_argument("--output", type=Path, required=True)
# Only the existing fixed Go recipe is supported, not arbitrary shell
# input. Keeping it in the workflow also preserves stable-shipped source
# contract tests when main's controls are copied to a mechanical patch.
parser.add_argument("--ordinary-command", choices=(ORDINARY_COMMAND,), required=True)
args = parser.parse_args()
try:
packages = ordinary_packages(args.index)
if sys.stdin.read().splitlines() != packages:
raise ValueError("supplied package order differs from the complete source selection")
except (OSError, ValueError, subprocess.CalledProcessError) as error:
print(f"Backend package admission failed: {error}", file=sys.stderr)
if isinstance(error, subprocess.CalledProcessError):
sys.stdout.write(error.stdout or "")
sys.stderr.write(error.stderr or "")
return 1
args.output.mkdir(parents=True, exist_ok=True)
print("Ordinary packages in this shard:\n" + "\n".join(packages), flush=True)
start = time.monotonic()
admitted = tasks(packages, args.index, args.output, args.ordinary_command)
planned = [name for name, _ in admitted]
observed = {}
retain_results(args.output, args.index, planned, observed, start)
# Drain every admitted task even when a sibling fails. Collect in completion
# order so a slow first task cannot hide already returned results. Retained
# snapshots still use source order, including the final legacy tasks list.
with ThreadPoolExecutor(max_workers=SLOTS) as pool:
futures = {pool.submit(run_task, task, args.output): task[0] for task in admitted}
for future in as_completed(futures):
observed[futures[future]] = future.result()
retain_results(args.output, args.index, planned, observed, start)
retain_results(args.output, args.index, planned, observed, start, complete=True)
# Keep the final ordered list and verdict recipe compatible with source
# contracts on the current stable when these main controls are copied.
results = [observed[name] for name in planned]
return 0 if (all(result["exit"] == 0 for result in results) and
all(result.get("coverage_exit", 0) == 0 for result in results)) else 1
if __name__ == "__main__":
raise SystemExit(main())