From 5410795411e4d6e643c78b562b63dbec85d33af1 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 6 Dec 2026 13:01:07 +0800 Subject: [PATCH] fix(release): serialize integrated canary smoke, cap macOS shards, add --ensure-chat-bundle Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/canary/runner.py | 4 + scripts/qualify_release_commit.py | 82 +++++++++- .../test_premerge_parallel_and_dedup.py | 83 ++++++++++ .../test_release_commit_qualification.py | 146 +++++++++++++++++- 4 files changed, 308 insertions(+), 7 deletions(-) diff --git a/loopx/canary/runner.py b/loopx/canary/runner.py index e3816a0c9e..1c4781cdec 100644 --- a/loopx/canary/runner.py +++ b/loopx/canary/runner.py @@ -60,6 +60,10 @@ "creates a temporary git repository and can race host git cleanup when " "run beside other git-heavy smokes" ), + "control-plane-integrated-canary-smoke.py": ( + "enforces a strict <= 60s wall-clock latency budget across real File+SQLite " + "loops and false-fails under parallel CPU contention" + ), } PYTHON_BINARIES = {"python", "python3"} NODE_BINARIES = {"node"} diff --git a/scripts/qualify_release_commit.py b/scripts/qualify_release_commit.py index 64f91530d7..3f9014e2e5 100644 --- a/scripts/qualify_release_commit.py +++ b/scripts/qualify_release_commit.py @@ -37,6 +37,7 @@ PYTEST_SUMMARY_SCHEMA_VERSION = EXPECTED_RESULT_SCHEMA_BY_QUALIFICATION["pytest"] _STRIPPED_ENV_PREFIXES = ("CODEX_", "LOOPX_", "ANTIGRAVITY_") _MAX_DEFAULT_SHARDS = 12 +_MAX_DARWIN_DEFAULT_SHARDS = 8 _PUBLIC_SAFETY_SURFACE_PREFIXES = ( "loopx/public_safe_text.py", "loopx/chat.py", @@ -50,11 +51,18 @@ ) -def default_pytest_parallelism(cpu_count: int | None = None) -> int: - """Choose single-wave shard concurrency sized to two-thirds of host CPUs (1..12).""" +def default_pytest_parallelism( + cpu_count: int | None = None, + *, + platform_name: str | None = None, +) -> int: + """Choose single-wave shard concurrency; cap macOS at 8 (half CPUs) to avoid P-core contention.""" cpus = cpu_count if cpu_count is not None else (os.cpu_count() or 4) if cpus < 1: cpus = 1 + platform = (platform_name or sys.platform).lower() + if platform == "darwin": + return min(_MAX_DARWIN_DEFAULT_SHARDS, max(1, cpus // 2)) return max(1, min(_MAX_DEFAULT_SHARDS, round(cpus * 2 / 3))) @@ -424,6 +432,62 @@ def _require_clean_source(repo_root: Path) -> dict[str, Any]: return source +def _ensure_chat_bundle( + *, + repo_root: Path, + python_bin: Path, + extra_bin_dirs: Sequence[Path] = (), +) -> dict[str, Any]: + """Verify the source chat bundle, building and re-verifying if missing or stale.""" + script_path = repo_root / "scripts" / "chat_bundle.py" + if not script_path.is_file(): + raise RuntimeError(f"chat bundle script not found: {script_path}") + env = dict(os.environ) + prefix_bins = [str(python_bin.parent), *(str(item) for item in extra_bin_dirs)] + if env.get("PATH"): + prefix_bins.append(env["PATH"]) + env["PATH"] = os.pathsep.join(prefix_bins) + verify_cmd = [str(python_bin), str(script_path), "verify", "--source"] + verify_first = subprocess.run( + verify_cmd, + cwd=repo_root, + env=env, + capture_output=True, + text=True, + check=False, + ) + if verify_first.returncode == 0: + return {"verified_initially": True, "built": False} + build_cmd = [str(python_bin), str(script_path), "build", "--install"] + build_res = subprocess.run( + build_cmd, + cwd=repo_root, + env=env, + capture_output=True, + text=True, + check=False, + ) + if build_res.returncode != 0: + detail = (build_res.stderr or build_res.stdout).strip() + raise RuntimeError( + f"chat_bundle.py build --install failed (exit {build_res.returncode}): {detail}" + ) + verify_second = subprocess.run( + verify_cmd, + cwd=repo_root, + env=env, + capture_output=True, + text=True, + check=False, + ) + if verify_second.returncode != 0: + detail = (verify_second.stderr or verify_second.stdout).strip() + raise RuntimeError( + f"chat_bundle.py verify --source failed after build (exit {verify_second.returncode}): {detail}" + ) + return {"verified_initially": False, "built": True} + + def run_preflight( *, repo_root: Path, @@ -648,6 +712,11 @@ def _parser() -> argparse.ArgumentParser: parser.add_argument("--extra-bin-dir", type=Path, action="append", default=[]) parser.add_argument("--pytest-arg", type=str, action="append", default=[]) parser.add_argument("--no-keep-failed-namespaces", action="store_true") + parser.add_argument( + "--ensure-chat-bundle", + action="store_true", + help="Verify scripts/chat_bundle.py --source and build+re-verify if missing or stale.", + ) return parser @@ -667,6 +736,15 @@ def main(argv: Sequence[str] | None = None) -> int: extra_bins = [path.expanduser().resolve() for path in args.extra_bin_dir] source = _require_clean_source(repo_root) + if args.ensure_chat_bundle: + _ensure_chat_bundle( + repo_root=repo_root, + python_bin=python_bin, + extra_bin_dirs=extra_bins, + ) + post_bundle_source = _require_clean_source(repo_root) + if post_bundle_source != source: + raise RuntimeError("candidate source changed while ensuring chat bundle") (output_dir / "source-identity.json").write_text( json.dumps(source, indent=2) + "\n", encoding="utf-8" ) diff --git a/tests/canary/test_premerge_parallel_and_dedup.py b/tests/canary/test_premerge_parallel_and_dedup.py index 1cbba3c844..1ba7c77f30 100644 --- a/tests/canary/test_premerge_parallel_and_dedup.py +++ b/tests/canary/test_premerge_parallel_and_dedup.py @@ -723,3 +723,86 @@ def test_premerge_parallel_and_serial_preserve_tracked_write_block_alongside_inh assert risk_run["advisory_failure_count"] == 1 assert payload["validation_summary"]["runs"]["risk_profile_run"]["advisory_failure_count"] == 1 assert payload["validation_summary"]["advisory_failure_count"] == 2 + + +def test_control_plane_integrated_canary_smoke_is_classified_serial( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + reason = runner._serial_smoke_reason( + {"command": "python3 examples/control_plane/control-plane-integrated-canary-smoke.py"} + ) + assert "60s" in reason + assert "contention" in reason + + repo = tmp_path / "repo" + (repo / "examples" / "control_plane").mkdir(parents=True) + (repo / "examples" / "canary").mkdir(parents=True) + (repo / "examples" / "control_plane" / "control-plane-integrated-canary-smoke.py").write_text( + "print('ok')\n", encoding="utf-8" + ) + (repo / "examples" / "canary" / "fast-parallel-a-smoke.py").write_text( + "print('ok')\n", encoding="utf-8" + ) + (repo / "examples" / "canary" / "fast-parallel-b-smoke.py").write_text( + "print('ok')\n", encoding="utf-8" + ) + + execution_order: list[str] = [] + + def fake_run_check( + check: dict[str, Any], + *, + timeout_seconds: float, + check_index: int | None = None, + check_count: int | None = None, + repo_root: Path | None = None, + ) -> dict[str, Any]: + normalized = runner.normalize_canary_command( + str(check.get("command") or ""), repo_root=repo_root + ) + script = str(normalized.get("script") or "") + execution_order.append(script) + return { + **check, + "normalized": normalized, + "ok": True, + "status": "passed", + "returncode": 0, + "duration_seconds": 0.01, + "check_index": check_index, + "check_count": check_count, + "timeout_seconds": timeout_seconds, + } + + monkeypatch.setattr(runner, "_tracked_change_paths", lambda **_kwargs: (True, [], "")) + monkeypatch.setattr(runner, "_run_check", fake_run_check) + + suite_run = build_canary_smoke_suite_run( + suite="full-public", + repo_root=repo, + scripts=[ + "control_plane/control-plane-integrated-canary-smoke.py", + "canary/fast-parallel-a-smoke.py", + "canary/fast-parallel-b-smoke.py", + ], + execute=True, + parallel_jobs=4, + ) + + assert suite_run["ok"] is True + assert suite_run["serial_check_count"] == 1 + assert suite_run["effective_parallel_jobs"] == 2 + assert execution_order[-1] == "examples/control_plane/control-plane-integrated-canary-smoke.py" + assert set(execution_order[:2]) == { + "examples/canary/fast-parallel-a-smoke.py", + "examples/canary/fast-parallel-b-smoke.py", + } + serial_result = next( + item + for item in suite_run["selected_checks"] + if item["normalized"]["script"] + == "examples/control_plane/control-plane-integrated-canary-smoke.py" + ) + assert serial_result["serial_execution_required"] is True + assert serial_result["serial_execution_reason"] == reason diff --git a/tests/control_plane/test_release_commit_qualification.py b/tests/control_plane/test_release_commit_qualification.py index 8913b20592..4d06997910 100644 --- a/tests/control_plane/test_release_commit_qualification.py +++ b/tests/control_plane/test_release_commit_qualification.py @@ -510,14 +510,33 @@ def fake_portfolio(*_args: object, **kwargs: object) -> dict[str, object]: assert observed_workers == [6, 1] -def test_qualify_release_commit_parallelism_and_preflight_selection(tmp_path: Path) -> None: +def test_qualify_release_commit_parallelism_and_preflight_selection( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: runner = runpy.run_path(str(REPO_ROOT / "scripts" / "qualify_release_commit.py")) parallelism = runner["default_pytest_parallelism"] - assert parallelism(4) == 3 - assert parallelism(12) == 8 + assert parallelism(1, platform_name="linux") == 1 + assert parallelism(4, platform_name="linux") == 3 + assert parallelism(12, platform_name="linux") == 8 + assert parallelism(18, platform_name="linux") == 12 + assert parallelism(32, platform_name="linux") == 12 + + assert parallelism(1, platform_name="darwin") == 1 + assert parallelism(4, platform_name="darwin") == 2 + assert parallelism(12, platform_name="darwin") == 6 + assert parallelism(16, platform_name="darwin") == 8 + assert parallelism(18, platform_name="darwin") == 8 + assert parallelism(32, platform_name="darwin") == 8 + + monkeypatch.setattr(sys, "platform", "darwin") + assert parallelism(18) == 8 + monkeypatch.setattr(sys, "platform", "linux") assert parallelism(18) == 12 - assert parallelism(32) == 12 - assert parallelism(1) == 1 + + parser = runner["_parser"]() + assert parser.parse_args(["--output-dir", str(tmp_path / "out"), "--shards", "5"]).shards == 5 + assert parser.parse_args(["--output-dir", str(tmp_path / "out")]).ensure_chat_bundle is False repo = tmp_path / "repo" for rel in ( @@ -959,3 +978,120 @@ def test_only_preflight_requires_preflight_since_and_isolated_node_compile_cache cov_env = isolated_env(cov_root, repo_root=REPO_ROOT, python_bin=Path(sys.executable), extra_bin_dirs=[]) assert "NODE_COMPILE_CACHE" not in cov_env assert not (cov_root / "node-compile-cache").exists() + + +def test_qualify_release_commit_ensure_chat_bundle_flag(tmp_path: Path) -> None: + repo = tmp_path / "bundle-repo" + (repo / "loopx").mkdir(parents=True) + (repo / "scripts").mkdir(parents=True) + (repo / "tests").mkdir(parents=True) + (repo / ".gitignore").write_text("__pycache__/\n*.pyc\n/loopx/web/chat/\n", encoding="utf-8") + (repo / "pyproject.toml").write_text( + f'[project]\nname = "loopx"\nversion = "{__version__}"\n', + encoding="utf-8", + ) + (repo / "loopx" / "__init__.py").write_text( + f'__version__ = "{__version__}"\n', + encoding="utf-8", + ) + (repo / "tests" / "test_ok.py").write_text("def test_ok(): pass\n", encoding="utf-8") + log_path = tmp_path / "chat-bundle-calls.log" + (repo / "scripts" / "chat_bundle.py").write_text( + "import sys\n" + "from pathlib import Path\n" + f"log_path = Path({str(log_path)!r})\n" + "with log_path.open('a', encoding='utf-8') as fh:\n" + " fh.write(' '.join(sys.argv[1:]) + '\\n')\n" + "bundle_dir = Path('loopx/web/chat')\n" + "marker = bundle_dir / 'manifest.json'\n" + "if sys.argv[1:] == ['verify', '--source']:\n" + " raise SystemExit(0 if marker.is_file() else 1)\n" + "if sys.argv[1:] == ['build', '--install']:\n" + " bundle_dir.mkdir(parents=True, exist_ok=True)\n" + " marker.write_text('{}', encoding='utf-8')\n" + " raise SystemExit(0)\n" + "raise SystemExit(2)\n", + encoding="utf-8", + ) + for args in ( + ("init",), + ("config", "user.email", "loopx@example.invalid"), + ("config", "user.name", "LoopX Test"), + ("add", "."), + ("commit", "-m", "init"), + ): + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True) + + # Default off: chat_bundle.py is never invoked even when the bundle is missing. + out_default = tmp_path / "out-default" + res_default = subprocess.run( + [ + sys.executable, + str(REPO_ROOT / "scripts" / "qualify_release_commit.py"), + "--repo-root", + str(repo), + "--output-dir", + str(out_default), + "--shards", + "1", + "--no-pytest-split", + ], + cwd=REPO_ROOT, + check=False, + capture_output=True, + text=True, + ) + assert res_default.returncode == 0, res_default.stdout + res_default.stderr + assert not log_path.exists() + + # Opt-in --ensure-chat-bundle builds and re-verifies into gitignored loopx/web/chat/. + out_build = tmp_path / "out-build" + res_build = subprocess.run( + [ + sys.executable, + str(REPO_ROOT / "scripts" / "qualify_release_commit.py"), + "--repo-root", + str(repo), + "--output-dir", + str(out_build), + "--shards", + "1", + "--no-pytest-split", + "--ensure-chat-bundle", + ], + cwd=REPO_ROOT, + check=False, + capture_output=True, + text=True, + ) + assert res_build.returncode == 0, res_build.stdout + res_build.stderr + assert log_path.read_text(encoding="utf-8").splitlines() == [ + "verify --source", + "build --install", + "verify --source", + ] + assert _git(repo, "status", "--porcelain") == "" + + # Second run sees verified bundle immediately and skips build --install. + log_path.unlink() + out_cached = tmp_path / "out-cached" + res_cached = subprocess.run( + [ + sys.executable, + str(REPO_ROOT / "scripts" / "qualify_release_commit.py"), + "--repo-root", + str(repo), + "--output-dir", + str(out_cached), + "--shards", + "1", + "--no-pytest-split", + "--ensure-chat-bundle", + ], + cwd=REPO_ROOT, + check=False, + capture_output=True, + text=True, + ) + assert res_cached.returncode == 0, res_cached.stdout + res_cached.stderr + assert log_path.read_text(encoding="utf-8").splitlines() == ["verify --source"]