diff --git a/loopx/canary/premerge.py b/loopx/canary/premerge.py index 7b862073ff..396a60dd10 100644 --- a/loopx/canary/premerge.py +++ b/loopx/canary/premerge.py @@ -1,14 +1,23 @@ from __future__ import annotations +import os import subprocess import sys import time +from collections.abc import Mapping from pathlib import Path from typing import Any, Callable from ..contract import scan_public_boundary from .planner import REPO_ROOT, resolve_canary_catalog_path -from .runner import MAINTAINABILITY_RATCHET_SCRIPT, build_canary_smoke_suite_run, check_output_tail +from .runner import ( + MAINTAINABILITY_RATCHET_SCRIPT, + _coerce_parallel_jobs, + _run_scoped_node_compile_cache, + build_canary_smoke_suite_run, + check_output_tail, + premerge_check_reuse_key, +) PREMERGE_GATE_SCHEMA_VERSION = "loopx_premerge_validation_gate_v0" @@ -123,6 +132,7 @@ def _synthetic_smoke_suite_run( "matched_check_count": len(selected_checks), "selected_check_count": len(selected_checks), "executed_check_count": len(executed_checks), + "reused_check_count": 0, "failure_count": len(failures), "git_required_skip_count": 0, "timeout_count": 0, @@ -726,13 +736,31 @@ def _run_summary(run: dict[str, Any] | None) -> dict[str, Any] | None: executed_checks = [ check for check in selected_checks if str(check.get("status") or "") not in {"", "ready", "skipped"} + and not check.get("reused") ] + reused_checks = [check for check in selected_checks if check.get("reused")] failures = [check for check in selected_checks if check.get("ok") is False] + executed_count = ( + int(run["executed_check_count"]) + if run.get("executed_check_count") is not None + else len(executed_checks) + ) + reused_count = ( + int(run["reused_check_count"]) + if run.get("reused_check_count") is not None + else len(reused_checks) + ) + failure_count = ( + int(run["failure_count"]) + if run.get("failure_count") is not None + else len(failures) + ) return { "ok": bool(run.get("ok")), "selected_check_count": int(run.get("selected_check_count") or len(selected_checks)), - "executed_check_count": int(run.get("executed_check_count") or len(executed_checks)), - "failure_count": int(run.get("failure_count") or len(failures)), + "executed_check_count": executed_count, + "reused_check_count": reused_count, + "failure_count": failure_count, "warning_count": int(run.get("warning_count") or 0), "advisory_failure_count": int(run.get("advisory_failure_count") or 0), "selected_commands": [_check_command(check) for check in selected_checks], @@ -746,6 +774,7 @@ def build_validation_summary( catalog_run: dict[str, Any], risk_profile_run: dict[str, Any] | None, boundary_run: dict[str, Any] | None, + parallel_jobs: int | None = None, ) -> dict[str, Any]: direct_failures = [check for check in direct_checks if check.get("ok") is False] direct_commands = [str(check.get("command") or "") for check in direct_checks] @@ -764,7 +793,10 @@ def build_validation_summary( selected_commands.extend(summary["selected_commands"]) failed_commands.extend(summary["failed_commands"]) failed_commands.extend(str(check.get("command") or "") for check in direct_failures) - return { + reused_check_count = sum( + int(summary.get("reused_check_count") or 0) for summary in active_run_summaries + ) + summary_payload: dict[str, Any] = { "schema_version": PREMERGE_VALIDATION_SUMMARY_SCHEMA_VERSION, "direct_check_count": len(direct_checks), "direct_failure_count": len(direct_failures), @@ -774,6 +806,7 @@ def build_validation_summary( "executed_check_count": sum( int(summary["executed_check_count"]) for summary in active_run_summaries ), + "reused_check_count": reused_check_count, "failure_count": len(direct_failures) + sum(int(summary["failure_count"]) for summary in active_run_summaries), "warning_count": sum(int(summary["warning_count"]) for summary in active_run_summaries), @@ -786,6 +819,9 @@ def build_validation_summary( "failed_commands": [command for command in failed_commands if command], "runs": run_summaries, } + if parallel_jobs is not None: + summary_payload["parallel_jobs"] = _coerce_parallel_jobs(parallel_jobs) + return summary_payload def apply_change_quality_verification( @@ -906,6 +942,71 @@ def _tier_limits(tier: str) -> dict[str, int | bool]: return {"catalog_limit": 10, "profile_limit": 8, "deep": False} +_REUSABLE_PREMERGE_STATUSES = frozenset({ + "passed", + "failed", + "advisory_inherited_failure", + "timed_out", +}) + + +def default_premerge_parallel_jobs(*, fail_fast: bool = False) -> int: + """Return bounded default parallelism for premerge canary smoke sections.""" + if fail_fast: + return 1 + return min(4, max(1, (os.cpu_count() or 2) // 2)) + + +def _reusable_results_from_run( + run: Mapping[str, Any] | None, + *, + section: str, + cli_output_base_ref: str, +) -> dict[tuple[tuple[str, ...], str], dict[str, Any]]: + if not isinstance(run, Mapping): + return {} + reusable: dict[tuple[tuple[str, ...], str], dict[str, Any]] = {} + for check in run.get("selected_checks", []): + if not isinstance(check, dict): + continue + if check.get("status") not in _REUSABLE_PREMERGE_STATUSES: + continue + if check.get("tracked_side_effects"): + continue + normalized = check.get("normalized") + if ( + not isinstance(normalized, dict) + or not normalized.get("ok") + or not normalized.get("argv") + ): + continue + key = premerge_check_reuse_key( + normalized, + cli_output_base_ref=cli_output_base_ref, + ) + reusable[key] = {**check, "section": check.get("section") or section} + return reusable + + +def _attach_compile_cache_cleanup_failures( + cleanup_failures: list[dict[str, object]], + *, + target_run: dict[str, Any] | None, +) -> None: + if not cleanup_failures or not isinstance(target_run, dict): + return + existing_cleanup = target_run.get("cleanup_failures") + cleanup_list = list(existing_cleanup) if isinstance(existing_cleanup, list) else [] + cleanup_list.extend(cleanup_failures) + target_run["cleanup_failures"] = cleanup_list + existing_failures = target_run.get("failures") + failure_list = list(existing_failures) if isinstance(existing_failures, list) else [] + failure_list.extend(cleanup_failures) + target_run["failures"] = failure_list + target_run["failure_count"] = int(target_run.get("failure_count") or 0) + len(cleanup_failures) + target_run["ok"] = False + + def build_premerge_validation_gate( *, changed_files: list[str] | None = None, @@ -915,6 +1016,7 @@ def build_premerge_validation_gate( timeout_seconds: float = 120.0, fail_fast: bool = False, include_deep_checks: bool | None = None, + parallel_jobs: int | None = None, progress_callback: ProgressCallback | None = None, repo_root: Path | None = None, catalog_path: Path | None = None, @@ -927,6 +1029,15 @@ def build_premerge_validation_gate( classification = classify_premerge_surfaces(files, repo_root=target_repo_root) limits = _tier_limits(tier) include_deep = bool(limits["deep"] if include_deep_checks is None else include_deep_checks) + effective_parallel_jobs = ( + 1 + if fail_fast + else ( + _coerce_parallel_jobs(parallel_jobs) + if parallel_jobs is not None + else default_premerge_parallel_jobs(fail_fast=False) + ) + ) if progress_callback and execute: progress_callback( { @@ -966,100 +1077,124 @@ def build_premerge_validation_gate( direct_checks.append(module_colocation) catalog_run: dict[str, Any] - if files: - catalog_progress = _section_progress_callback( - progress_callback, - section="catalog_canaries", - ) - _emit_section_progress( - catalog_progress, - event="section_started", - selected_hint=int(limits["catalog_limit"]), - ) - catalog_run = build_canary_smoke_suite_run( - suite="catalog-plan", - repo_root=target_repo_root, - catalog_path=catalog_path, - changed_files=files, - include_deep_checks=include_deep, - max_checks_per_family=3, - max_checks_per_profile=4, - limit=int(limits["catalog_limit"]), - execute=execute, - timeout_seconds=timeout_seconds, - fail_fast=fail_fast, - progress_callback=catalog_progress if execute else None, - cli_output_base_ref=base_ref, - ) - _emit_section_progress( - catalog_progress, - event="section_finished", - status="passed" if catalog_run.get("ok") else "failed", - ok=bool(catalog_run.get("ok")), - selected_check_count=catalog_run.get("selected_check_count"), - executed_check_count=catalog_run.get("executed_check_count"), - failure_count=catalog_run.get("failure_count"), - ) - adjusted_catalog_run = downgrade_inherited_baseline_failures( - catalog_run, - changed_files=files, - ) - assert adjusted_catalog_run is not None # A dictionary input retains a result. - catalog_run = adjusted_catalog_run - else: - catalog_run = _empty_smoke_suite_run( - suite="catalog-plan", - reason=( - "No changed files were provided, so premerge only runs direct " - "diff hygiene checks and skips catalog/risk/boundary smokes." - ), - execute=execute, - timeout_seconds=timeout_seconds, - repo_root=target_repo_root, - ) - risk_profiles = list(classification["risk_profiles"]) risk_profile_run: dict[str, Any] | None = None profile_limit = int(limits["profile_limit"]) run_risk_profiles = bool(risk_profiles) and not ( tier == "quick" and profile_limit == 0 ) - if run_risk_profiles: - risk_progress = _section_progress_callback( - progress_callback, - section="risk_profile_smokes", - ) - _emit_section_progress( - risk_progress, - event="section_started", - profiles=risk_profiles, - selected_hint=profile_limit, - ) - risk_profile_run = build_canary_smoke_suite_run( - suite="default-public", - repo_root=target_repo_root, - catalog_path=catalog_path, - profiles=risk_profiles, - include_deep_checks=include_deep, - limit=profile_limit, - execute=execute, - timeout_seconds=timeout_seconds, - fail_fast=fail_fast, - progress_callback=risk_progress if execute else None, - cli_output_base_ref=base_ref, - ) - _emit_section_progress( - risk_progress, - event="section_finished", - status="passed" if risk_profile_run.get("ok") else "failed", - ok=bool(risk_profile_run.get("ok")), - selected_check_count=risk_profile_run.get("selected_check_count"), - executed_check_count=risk_profile_run.get("executed_check_count"), - failure_count=risk_profile_run.get("failure_count"), + cache_cleanup_failures: list[dict[str, object]] = [] + with _run_scoped_node_compile_cache( + cache_cleanup_failures, + enabled=execute and bool(files), + ): + if files: + catalog_progress = _section_progress_callback( + progress_callback, + section="catalog_canaries", + ) + _emit_section_progress( + catalog_progress, + event="section_started", + selected_hint=int(limits["catalog_limit"]), + ) + catalog_run = build_canary_smoke_suite_run( + suite="catalog-plan", + repo_root=target_repo_root, + catalog_path=catalog_path, + changed_files=files, + include_deep_checks=include_deep, + max_checks_per_family=3, + max_checks_per_profile=4, + limit=int(limits["catalog_limit"]), + execute=execute, + timeout_seconds=timeout_seconds, + fail_fast=fail_fast, + parallel_jobs=effective_parallel_jobs, + progress_callback=catalog_progress if execute else None, + cli_output_base_ref=base_ref, + ) + _emit_section_progress( + catalog_progress, + event="section_finished", + status="passed" if catalog_run.get("ok") else "failed", + ok=bool(catalog_run.get("ok")), + selected_check_count=catalog_run.get("selected_check_count"), + executed_check_count=catalog_run.get("executed_check_count"), + reused_check_count=catalog_run.get("reused_check_count"), + failure_count=catalog_run.get("failure_count"), + ) + adjusted_catalog_run = downgrade_inherited_baseline_failures( + catalog_run, + changed_files=files, + ) + assert adjusted_catalog_run is not None # A dictionary input retains a result. + catalog_run = adjusted_catalog_run + else: + catalog_run = _empty_smoke_suite_run( + suite="catalog-plan", + reason=( + "No changed files were provided, so premerge only runs direct " + "diff hygiene checks and skips catalog/risk/boundary smokes." + ), + execute=execute, + timeout_seconds=timeout_seconds, + repo_root=target_repo_root, + ) + + reusable_results = ( + _reusable_results_from_run( + catalog_run, + section="catalog_canaries", + cli_output_base_ref=base_ref, + ) + if execute and files + else {} ) - risk_profile_run = downgrade_inherited_baseline_failures( - risk_profile_run, - changed_files=files, + if run_risk_profiles: + risk_progress = _section_progress_callback( + progress_callback, + section="risk_profile_smokes", + ) + _emit_section_progress( + risk_progress, + event="section_started", + profiles=risk_profiles, + selected_hint=profile_limit, + ) + risk_profile_run = build_canary_smoke_suite_run( + suite="default-public", + repo_root=target_repo_root, + catalog_path=catalog_path, + profiles=risk_profiles, + include_deep_checks=include_deep, + limit=profile_limit, + execute=execute, + timeout_seconds=timeout_seconds, + fail_fast=fail_fast, + parallel_jobs=effective_parallel_jobs, + progress_callback=risk_progress if execute else None, + cli_output_base_ref=base_ref, + reusable_results_by_command=reusable_results or None, + ) + _emit_section_progress( + risk_progress, + event="section_finished", + status="passed" if risk_profile_run.get("ok") else "failed", + ok=bool(risk_profile_run.get("ok")), + selected_check_count=risk_profile_run.get("selected_check_count"), + executed_check_count=risk_profile_run.get("executed_check_count"), + reused_check_count=risk_profile_run.get("reused_check_count"), + failure_count=risk_profile_run.get("failure_count"), + ) + risk_profile_run = downgrade_inherited_baseline_failures( + risk_profile_run, + changed_files=files, + ) + if cache_cleanup_failures: + _attach_compile_cache_cleanup_failures( + cache_cleanup_failures, + target_run=risk_profile_run if isinstance(risk_profile_run, dict) else catalog_run, ) boundary_run: dict[str, Any] | None = None @@ -1103,6 +1238,7 @@ def build_premerge_validation_gate( catalog_run=catalog_run, risk_profile_run=risk_profile_run, boundary_run=boundary_run, + parallel_jobs=effective_parallel_jobs, ) ok = gate["status"] in {"passed", "no_changes"} or ( not execute and gate["status"] in {"preview_only", "manual_review_required", "no_changes"} @@ -1117,12 +1253,15 @@ def build_premerge_validation_gate( "executes_checks": execute, "writes_evidence": False, "creates_runtime_contract": False, + "parallel_jobs": effective_parallel_jobs, + "reused_check_count": validation_summary["reused_check_count"], "changed_files": files, "classification": classification, "direct_checks": direct_checks, "catalog_run": catalog_run, "risk_profile_run": risk_profile_run, "boundary_run": boundary_run, + **({"cleanup_failures": cache_cleanup_failures} if cache_cleanup_failures else {}), "validation_summary": validation_summary, "gate": gate, "recommended_pr_comment_fields": [ @@ -1211,6 +1350,8 @@ def render_premerge_validation_gate_markdown(payload: dict[str, Any]) -> str: f"`{str((gate.get('self_merge_authority') or {}).get('reason') or '')}`", f"- tier: `{payload.get('tier')}`", f"- dry_run: `{str(payload.get('dry_run')).lower()}`", + f"- parallel_jobs: `{payload.get('parallel_jobs')}`", + f"- reused_checks: `{payload.get('reused_check_count') or 0}`", f"- changed_files: `{classification.get('changed_file_count')}`", f"- surfaces: `{', '.join(classification.get('surfaces') or [])}`", f"- risk_profiles: `{', '.join(classification.get('risk_profiles') or [])}`", @@ -1242,6 +1383,7 @@ def append_run(title: str, run: Any) -> None: f"- ok: `{str(run.get('ok')).lower()}`", f"- selected_checks: `{run.get('selected_check_count')}`", f"- executed_checks: `{run.get('executed_check_count')}`", + f"- reused_checks: `{run.get('reused_check_count') or 0}`", f"- failures: `{run.get('failure_count')}`", f"- advisory_failures: `{run.get('advisory_failure_count') or 0}`", f"- warnings: `{run.get('warning_count')}`", @@ -1253,7 +1395,8 @@ def append_run(title: str, run: Any) -> None: normalized_value = check.get('normalized') normalized = normalized_value if isinstance(normalized_value, dict) else {} command = " ".join(str(part) for part in normalized.get("display_argv") or []) - lines.append(f"- `{check.get('status') or 'ready'}` {command or check.get('command')}") + reused_suffix = " (reused)" if check.get("reused") else "" + lines.append(f"- `{check.get('status') or 'ready'}` {command or check.get('command')}{reused_suffix}") if check.get("advisory_reason"): lines.append(f" advisory_reason: {check.get('advisory_reason')}") @@ -1261,6 +1404,13 @@ def append_run(title: str, run: Any) -> None: append_run("Risk Profile Smokes", payload.get("risk_profile_run")) append_run("Public Boundary", payload.get("boundary_run")) + cleanup_failures = payload.get("cleanup_failures") or [] + if cleanup_failures: + lines.extend(["", "## Cleanup Failures"]) + for failure in cleanup_failures: + if isinstance(failure, dict): + lines.append(f"- {failure.get('reason')}") + quality = ( payload.get("change_quality_qualification") if isinstance(payload.get("change_quality_qualification"), dict) diff --git a/loopx/canary/runner.py b/loopx/canary/runner.py index ebb832c47b..39f32917e1 100644 --- a/loopx/canary/runner.py +++ b/loopx/canary/runner.py @@ -8,10 +8,11 @@ import sys import tempfile import time -from collections.abc import Iterator, Sequence +from collections.abc import Iterator, Mapping, Sequence from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import contextmanager from contextvars import ContextVar, copy_context +from copy import deepcopy from functools import partial from pathlib import Path from typing import Any, Callable @@ -449,7 +450,11 @@ def _should_propagate_node_compile_cache() -> bool: def _run_scoped_node_compile_cache( cleanup_failures: list[dict[str, object]], *, enabled: bool, ) -> Iterator[None]: - if not enabled or not _should_propagate_node_compile_cache(): + if ( + not enabled + or not _should_propagate_node_compile_cache() + or _ACTIVE_NODE_COMPILE_CACHE.get() is not None + ): yield return cache_dir = Path(tempfile.mkdtemp(prefix="loopx-smoke-compile-cache-")) @@ -775,6 +780,59 @@ def _progress_check_started( ) +_TERMINAL_REUSABLE_STATUSES = frozenset({ + "passed", + "failed", + "advisory_inherited_failure", + "timed_out", +}) + + +def premerge_check_reuse_key( + normalized: Mapping[str, Any] | None, + *, + cli_output_base_ref: str | None = None, +) -> tuple[tuple[str, ...], str]: + """Build the command/environment identity key used for premerge cross-section reuse.""" + argv = normalized.get("argv") if isinstance(normalized, Mapping) else None + return (tuple(str(part) for part in (argv or ())), cli_output_base_ref or "") + + +def _reused_check_result( + check: Mapping[str, Any], + prior: Mapping[str, Any], + *, + check_index: int, + check_count: int, +) -> dict[str, Any]: + result: dict[str, Any] = {**check} + for field in ("profile_id", "family", "module"): + if field in check: + result[field] = check[field] + result["check_index"] = check_index + result["check_count"] = check_count + for field in ( + "ok", + "status", + "returncode", + "stdout_tail", + "stderr_tail", + "normalized", + "maintainability_failure_paths", + "tracked_side_effects", + "inherited_baseline_failure", + "advisory_reason", + ): + if field in prior: + result[field] = deepcopy(prior[field]) + if not prior.get("ok") and "reason" in prior: + result["reason"] = deepcopy(prior["reason"]) + result["duration_seconds"] = 0.0 + result["reused"] = True + result["reused_from_section"] = prior.get("section") or "catalog_canaries" + return result + + def _progress_check_finished( progress_callback: ProgressCallback | None, *, @@ -793,6 +851,7 @@ def _progress_check_finished( "status": result.get("status"), "ok": bool(result.get("ok")), "duration_seconds": result.get("duration_seconds"), + **({"reused": True} if result.get("reused") else {}), } ) @@ -821,6 +880,7 @@ def build_canary_smoke_suite_run( progress_callback: ProgressCallback | None = None, repo_root: Path | None = None, cli_output_base_ref: str | None = None, + reusable_results_by_command: Mapping[tuple[tuple[str, ...], str], dict[str, Any]] | None = None, ) -> dict[str, Any]: """Build and optionally execute a continue-on-failure smoke suite. @@ -921,94 +981,194 @@ def build_canary_smoke_suite_run( "tracked_side_effects": [], "auto_restored": False, } + reused_check_count = 0 if execute: - run_check = partial( - _run_check, - timeout_seconds=max(1.0, timeout_seconds), - check_count=len(selected), - repo_root=repo_root, - ) - if cli_output_base_ref is not None: - run_check = partial(run_check, cli_output_base_ref=cli_output_base_ref) - git_ok, tracked_before, git_stderr = _tracked_change_paths(repo_root=repo_root) - clean_start = git_ok and not tracked_before - if allow_tracked_side_effects: - enforcement_reason = "tracked_side_effects_explicitly_allowed" - elif not git_ok: - enforcement_reason = "git_worktree_unavailable" + reusable_matches: dict[int, dict[str, Any]] = {} + if reusable_results_by_command: + for index, (check, item) in enumerate(zip(selected, normalized, strict=True), start=1): + norm = item.get("normalized") + if not isinstance(norm, dict) or not norm.get("ok") or not norm.get("argv"): + continue + key = premerge_check_reuse_key(norm, cli_output_base_ref=cli_output_base_ref) + prior = reusable_results_by_command.get(key) + if ( + isinstance(prior, Mapping) + and not prior.get("tracked_side_effects") + and prior.get("status") in _TERMINAL_REUSABLE_STATUSES + ): + reusable_matches[index] = _reused_check_result( + check, + prior, + check_index=index, + check_count=len(selected), + ) + uncached_indexes = [ + index for index in range(1, len(selected) + 1) if index not in reusable_matches + ] + if selected and not uncached_indexes: + side_effect_guard["enforcement_reason"] = "all_checks_reused" + for index, check in enumerate(selected, start=1): + _progress_check_started( + progress_callback, + index=index, + total=len(selected), + check=check, + repo_root=repo_root, + ) + result = reusable_matches[index] + _progress_check_finished( + progress_callback, + index=index, + total=len(selected), + result=result, + ) + results.append(result) + if fail_fast and not result.get("ok"): + break else: - enforcement_reason = "tracked_side_effect_guard_active" - side_effect_guard.update( - { - "git_status_ok": git_ok, - "clean_start": clean_start, - "tracked_before": _display_git_paths(tracked_before), - "enforced": bool(git_ok and not allow_tracked_side_effects), - "enforcement_reason": enforcement_reason, + run_check = partial( + _run_check, + timeout_seconds=max(1.0, timeout_seconds), + check_count=len(selected), + repo_root=repo_root, + ) + if cli_output_base_ref is not None: + run_check = partial(run_check, cli_output_base_ref=cli_output_base_ref) + git_ok, tracked_before, git_stderr = _tracked_change_paths(repo_root=repo_root) + clean_start = git_ok and not tracked_before + if allow_tracked_side_effects: + enforcement_reason = "tracked_side_effects_explicitly_allowed" + elif not git_ok: + enforcement_reason = "git_worktree_unavailable" + else: + enforcement_reason = "tracked_side_effect_guard_active" + side_effect_guard.update( + { + "git_status_ok": git_ok, + "clean_start": clean_start, + "tracked_before": _display_git_paths(tracked_before), + "enforced": bool(git_ok and not allow_tracked_side_effects), + "enforcement_reason": enforcement_reason, + } + ) + if git_stderr: + side_effect_guard["git_status_unavailable_reason"] = git_stderr[-800:] + serial_indexes = { + index + for index in uncached_indexes + if _serial_smoke_reason(selected[index - 1], repo_root=repo_root) } - ) - if git_stderr: - side_effect_guard["git_status_unavailable_reason"] = git_stderr[-800:] - serial_indexes = { - index - for index, check in enumerate(selected, start=1) - if _serial_smoke_reason(check, repo_root=repo_root) - } - serial_check_count = len(serial_indexes) - parallel_check_count = len(selected) - serial_check_count - if selected and not fail_fast and parallel_check_count: - effective_parallel_jobs = min(requested_parallel_jobs, parallel_check_count) - with _run_scoped_node_compile_cache(cleanup_failures, enabled=bool(selected)): - if effective_parallel_jobs <= 1: - for index, check in enumerate(selected, start=1): - _progress_check_started( - progress_callback, - index=index, - total=len(selected), - check=check, - repo_root=repo_root, - ) - result = run_check(check, check_index=index) - if side_effect_guard["enforced"]: - after_ok, tracked_after, after_stderr = _tracked_change_paths(repo_root=repo_root) - side_effects = sorted(set(tracked_after) - set(tracked_before)) - if side_effects: - result.update( - { + serial_check_count = len(serial_indexes) + parallel_check_count = len(uncached_indexes) - serial_check_count + if uncached_indexes and not fail_fast and parallel_check_count: + effective_parallel_jobs = min(requested_parallel_jobs, parallel_check_count) + with _run_scoped_node_compile_cache(cleanup_failures, enabled=bool(uncached_indexes)): + if effective_parallel_jobs <= 1: + for index, check in enumerate(selected, start=1): + _progress_check_started( + progress_callback, + index=index, + total=len(selected), + check=check, + repo_root=repo_root, + ) + if index in reusable_matches: + result = reusable_matches[index] + else: + result = run_check(check, check_index=index) + if side_effect_guard["enforced"]: + after_ok, tracked_after, after_stderr = _tracked_change_paths(repo_root=repo_root) + side_effects = sorted(set(tracked_after) - set(tracked_before)) + if side_effects: + result.update( + { + "ok": False, + "status": "failed_tracked_side_effect", + "tracked_side_effects": _display_git_paths(side_effects), + } + ) + if clean_start: + restore = _restore_tracked_paths( + side_effects, + repo_root=repo_root, + expected_paths=tracked_before, + ) + result["tracked_side_effect_restore"] = restore + side_effect_guard["auto_restored"] = ( + bool(side_effect_guard.get("auto_restored")) + or bool(restore.get("ok")) + ) + if not after_ok and after_stderr: + result["tracked_side_effect_stderr_tail"] = after_stderr[-800:] + _progress_check_finished( + progress_callback, + index=index, + total=len(selected), + result=result, + ) + results.append(result) + if fail_fast and not result.get("ok"): + break + else: + indexed_results: dict[int, dict[str, Any]] = {} + for index in sorted(reusable_matches): + check = selected[index - 1] + reused = reusable_matches[index] + _progress_check_started( + progress_callback, + index=index, + total=len(selected), + check=check, + repo_root=repo_root, + ) + indexed_results[index] = reused + _progress_check_finished( + progress_callback, + index=index, + total=len(selected), + result=reused, + ) + with ThreadPoolExecutor(max_workers=effective_parallel_jobs) as executor: + futures = {} + for index in uncached_indexes: + if index in serial_indexes: + continue + check = selected[index - 1] + _progress_check_started( + progress_callback, + index=index, + total=len(selected), + check=check, + repo_root=repo_root, + ) + future = executor.submit(copy_context().run, run_check, check, check_index=index) + futures[future] = (index, check) + for future in as_completed(futures): + index, check = futures[future] + try: + result = future.result() + except Exception as exc: + result = { + **check, + "status": "failed", "ok": False, - "status": "failed_tracked_side_effect", - "tracked_side_effects": _display_git_paths(side_effects), + "reason": f"smoke runner exception: {exc}", + "returncode": None, + "duration_seconds": None, + "check_index": index, + "check_count": len(selected), } + indexed_results[index] = result + _progress_check_finished( + progress_callback, + index=index, + total=len(selected), + result=result, ) - if clean_start: - restore = _restore_tracked_paths( - side_effects, - repo_root=repo_root, - expected_paths=tracked_before, - ) - result["tracked_side_effect_restore"] = restore - side_effect_guard["auto_restored"] = ( - bool(side_effect_guard.get("auto_restored")) - or bool(restore.get("ok")) - ) - if not after_ok and after_stderr: - result["tracked_side_effect_stderr_tail"] = after_stderr[-800:] - _progress_check_finished( - progress_callback, - index=index, - total=len(selected), - result=result, - ) - results.append(result) - if fail_fast and not result.get("ok"): - break - else: - indexed_results: dict[int, dict[str, Any]] = {} - with ThreadPoolExecutor(max_workers=effective_parallel_jobs) as executor: - futures = {} - for index, check in enumerate(selected, start=1): - if index in serial_indexes: + for index in uncached_indexes: + if index not in serial_indexes: continue + check = selected[index - 1] _progress_check_started( progress_callback, index=index, @@ -1016,23 +1176,9 @@ def build_canary_smoke_suite_run( check=check, repo_root=repo_root, ) - future = executor.submit(copy_context().run, run_check, check, check_index=index) - futures[future] = (index, check) - for future in as_completed(futures): - index, check = futures[future] - try: - result = future.result() - except Exception as exc: - result = { - **check, - "status": "failed", - "ok": False, - "reason": f"smoke runner exception: {exc}", - "returncode": None, - "duration_seconds": None, - "check_index": index, - "check_count": len(selected), - } + result = run_check(check, check_index=index) + result["serial_execution_required"] = True + result["serial_execution_reason"] = _serial_smoke_reason(check, repo_root=repo_root) indexed_results[index] = result _progress_check_finished( progress_callback, @@ -1040,61 +1186,42 @@ def build_canary_smoke_suite_run( total=len(selected), result=result, ) - for index, check in enumerate(selected, start=1): - if index not in serial_indexes: - continue - _progress_check_started( - progress_callback, - index=index, - total=len(selected), - check=check, - repo_root=repo_root, - ) - result = run_check(check, check_index=index) - result["serial_execution_required"] = True - result["serial_execution_reason"] = _serial_smoke_reason(check, repo_root=repo_root) - indexed_results[index] = result - _progress_check_finished( - progress_callback, - index=index, - total=len(selected), - result=result, - ) - results = [indexed_results[index] for index in sorted(indexed_results)] - if side_effect_guard["enforced"]: - final_ok, tracked_after, final_stderr = _tracked_change_paths(repo_root=repo_root) - side_effects = sorted(set(tracked_after) - set(tracked_before)) - side_effect_guard.update( - { - "git_status_final_ok": final_ok, - "tracked_after": _display_git_paths(tracked_after), - "tracked_side_effects": _display_git_paths(side_effects), - } - ) - if final_stderr: - side_effect_guard["git_status_final_stderr_tail"] = final_stderr[-800:] - if effective_parallel_jobs > 1 and side_effects: - guard_failure = { - "schema_version": "canary_smoke_suite_guard_failure_v0", - "status": "failed_tracked_side_effect", - "ok": False, - "reason": ( - "parallel smoke-suite run produced tracked side effects; " - "rerun with --jobs 1 to attribute the script precisely" - ), - "tracked_side_effects": _display_git_paths(side_effects), - } - if clean_start: - restore = _restore_tracked_paths( - side_effects, - repo_root=repo_root, - expected_paths=tracked_before, - ) - guard_failure["tracked_side_effect_restore"] = restore - side_effect_guard["auto_restored"] = ( - bool(side_effect_guard.get("auto_restored")) or bool(restore.get("ok")) - ) - suite_guard_failures.append(guard_failure) + results = [indexed_results[index] for index in sorted(indexed_results)] + if side_effect_guard["enforced"]: + final_ok, tracked_after, final_stderr = _tracked_change_paths(repo_root=repo_root) + side_effects = sorted(set(tracked_after) - set(tracked_before)) + side_effect_guard.update( + { + "git_status_final_ok": final_ok, + "tracked_after": _display_git_paths(tracked_after), + "tracked_side_effects": _display_git_paths(side_effects), + } + ) + if final_stderr: + side_effect_guard["git_status_final_stderr_tail"] = final_stderr[-800:] + if effective_parallel_jobs > 1 and side_effects: + guard_failure = { + "schema_version": "canary_smoke_suite_guard_failure_v0", + "status": "failed_tracked_side_effect", + "ok": False, + "reason": ( + "parallel smoke-suite run produced tracked side effects; " + "rerun with --jobs 1 to attribute the script precisely" + ), + "tracked_side_effects": _display_git_paths(side_effects), + } + if clean_start: + restore = _restore_tracked_paths( + side_effects, + repo_root=repo_root, + expected_paths=tracked_before, + ) + guard_failure["tracked_side_effect_restore"] = restore + side_effect_guard["auto_restored"] = ( + bool(side_effect_guard.get("auto_restored")) or bool(restore.get("ok")) + ) + suite_guard_failures.append(guard_failure) + reused_check_count = sum(1 for item in results if item.get("reused")) display_items = results if execute else normalized failures = [item for item in results if not item.get("ok")] + suite_guard_failures + cleanup_failures @@ -1108,7 +1235,7 @@ def build_canary_smoke_suite_run( unsafe = [ item for item in normalized - if not isinstance(item.get("normalized"), dict) or not item["normalized"].get("ok") + if not isinstance((norm := item.get("normalized")), dict) or not norm.get("ok") ] ok = not failures and (execute or not unsafe) and not warnings return { @@ -1130,7 +1257,8 @@ def build_canary_smoke_suite_run( "limit": max(0, limit), "matched_check_count": matched_check_count, "selected_check_count": len(selected), - "executed_check_count": len(results), + "executed_check_count": len(results) - reused_check_count, + "reused_check_count": reused_check_count, "failure_count": len(failures), **({"cleanup_failures": cleanup_failures} if cleanup_failures else {}), "git_required_skip_count": len(git_required_skips), @@ -1232,7 +1360,7 @@ def build_catalog_canary_run( unsafe = [ item for item in normalized - if not isinstance(item.get("normalized"), dict) or not item["normalized"].get("ok") + if not isinstance((norm := item.get("normalized")), dict) or not norm.get("ok") ] ok = not failures and (execute or not unsafe) return { @@ -1334,6 +1462,7 @@ def render_canary_smoke_suite_run_markdown(payload: dict[str, Any]) -> str: f"- limit: `{payload.get('limit')}`", f"- selected_checks: `{payload.get('selected_check_count')}`", f"- executed_checks: `{payload.get('executed_check_count')}`", + f"- reused_checks: `{payload.get('reused_check_count') or 0}`", f"- parallel_jobs: `{payload.get('parallel_jobs')}`", f"- effective_parallel_jobs: `{payload.get('effective_parallel_jobs')}`", f"- serial_check_count: `{payload.get('serial_check_count')}`", diff --git a/loopx/cli_commands/canary.py b/loopx/cli_commands/canary.py index 557813319b..14c81800d4 100644 --- a/loopx/cli_commands/canary.py +++ b/loopx/cli_commands/canary.py @@ -295,10 +295,12 @@ def _print_smoke_suite_progress(event: dict[str, Any]) -> None: status = str(event.get("status") or "") selected = event.get("selected_check_count") executed = event.get("executed_check_count") + reused = event.get("reused_check_count") failures = event.get("failure_count") + reused_part = f" reused={reused}" if reused else "" print( f"[loopx canary] done {section_prefix.strip() or 'section'}: {status} " - f"selected={selected} executed={executed} failures={failures}", + f"selected={selected} executed={executed}{reused_part} failures={failures}", file=sys.stderr, flush=True, ) @@ -312,8 +314,9 @@ def _print_smoke_suite_progress(event: dict[str, Any]) -> None: elif kind == "check_finished": status = str(event.get("status") or "") duration = event.get("duration_seconds") + reused_suffix = ", reused" if event.get("reused") else "" print( - f"[loopx canary] done {section_prefix}{index}/{total}: {status} ({duration}s)", + f"[loopx canary] done {section_prefix}{index}/{total}: {status} ({duration}s{reused_suffix})", file=sys.stderr, flush=True, ) @@ -629,6 +632,17 @@ def register_canary_commands( action="store_true", help="Stop smoke-suite sections after the first failed check.", ) + premerge_parser.add_argument( + "-j", + "--jobs", + type=int, + default=None, + help=( + "Run up to this many smoke checks concurrently in catalog and " + "risk-profile sections; defaults to bounded CPU parallelism unless " + "--fail-fast is set." + ), + ) premerge_parser.add_argument( "--no-progress", action="store_true", @@ -775,6 +789,7 @@ def handle_canary_command( timeout_seconds=float(args.timeout_seconds or 120.0), fail_fast=bool(args.fail_fast), include_deep_checks=bool(args.include_deep_checks), + parallel_jobs=args.jobs, repo_root=target_repo_root, progress_callback=( None diff --git a/tests/canary/test_premerge_parallel_and_dedup.py b/tests/canary/test_premerge_parallel_and_dedup.py new file mode 100644 index 0000000000..1877d9a22c --- /dev/null +++ b/tests/canary/test_premerge_parallel_and_dedup.py @@ -0,0 +1,464 @@ +"""Pre-merge validation bounded parallelism, cross-section dedup, and shared cache tests.""" + +from __future__ import annotations + +import json +import subprocess +import tempfile +from pathlib import Path +from typing import Any + +import pytest + +from loopx.canary import planner, premerge, runner +from loopx.canary.planner import DEFAULT_CATALOG_PATH +from loopx.canary.premerge import ( + build_premerge_validation_gate, + default_premerge_parallel_jobs, + render_premerge_validation_gate_markdown, +) +from loopx.canary.runner import build_canary_smoke_suite_run, premerge_check_reuse_key +from loopx.cli import main + + +def _git(repo: Path, *args: str) -> None: + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True) + + +def _clear_compile_cache_env(monkeypatch: pytest.MonkeyPatch, scratch: Path) -> None: + for var in ("NODE_COMPILE_CACHE", "NODE_DISABLE_COMPILE_CACHE", "NODE_V8_COVERAGE"): + monkeypatch.delenv(var, raising=False) + for var in ("TMPDIR", "TEMP", "TMP"): + monkeypatch.setenv(var, str(scratch)) + monkeypatch.setattr(tempfile, "tempdir", str(scratch)) + + +def _write_repo_fixture( + tmp_path: Path, + *, + shared_exit_code: int = 0, + include_unique_risk_script: bool = True, + include_second_shared_script: bool = False, +) -> tuple[Path, Path]: + repo = tmp_path / "repo" + examples = repo / "examples" / "canary" + examples.mkdir(parents=True) + counter_file = tmp_path / "shared_probe_count.txt" + counter_file.write_text("0\n", encoding="utf-8") + + (repo / "tracked.txt").write_text("baseline\n", encoding="utf-8") + (examples / "catalog-planner-smoke.py").write_text( + "import json, os, sys\n" + "from pathlib import Path\n" + f"counter = Path({str(counter_file)!r})\n" + "count = int(counter.read_text(encoding='utf-8').strip()) + 1\n" + "counter.write_text(f'{count}\\n', encoding='utf-8')\n" + "print(json.dumps({'script': 'shared', 'count': count, 'cache': os.environ.get('NODE_COMPILE_CACHE')}))\n" + + ( + f"print('shared probe failed', file=sys.stderr)\nsys.exit({shared_exit_code})\n" + if shared_exit_code != 0 + else "" + ), + encoding="utf-8", + ) + if include_second_shared_script: + (examples / "catalog-run-e2e-smoke.py").write_text( + "import json, os\n" + "print(json.dumps({'script': 'shared2', 'cache': os.environ.get('NODE_COMPILE_CACHE')}))\n", + encoding="utf-8", + ) + if include_unique_risk_script: + (examples / "smoke-suite-runner-smoke.py").write_text( + "import json, os\n" + "print(json.dumps({'script': 'risk_only', 'cache': os.environ.get('NODE_COMPILE_CACHE')}))\n", + encoding="utf-8", + ) + + catalog = repo / "docs" / "concepts" / "interaction-pattern-catalog.md" + catalog.parent.mkdir(parents=True) + catalog.write_bytes(DEFAULT_CATALOG_PATH.read_bytes()) + + _git(repo, "init") + _git(repo, "config", "user.name", "Canary Fixture") + _git(repo, "config", "user.email", "canary@example.invalid") + _git(repo, "add", "tracked.txt", "examples", "docs") + _git(repo, "commit", "-m", "fixture") + return repo, counter_file + + +def _wire_catalog_and_risk_scripts( + monkeypatch: pytest.MonkeyPatch, + *, + catalog_scripts: list[str], +) -> None: + monkeypatch.setitem( + planner.FAMILY_CHECKS, + "Canary fixture", + [{"command": f"python3 {script}"} for script in catalog_scripts], + ) + monkeypatch.setattr( + premerge, + "classify_premerge_surfaces", + lambda files, **_kwargs: { + "changed_files": list(files), + "changed_file_count": len(files), + "python_files": [f for f in files if f.endswith(".py")], + "surfaces": ["canary_runner"], + "risk_profiles": ["canary-runner"], + "manual_holds": [], + "public_boundary_scan_recommended": False, + }, + ) + monkeypatch.setattr( + runner, + "build_catalog_canary_plan", + lambda **_kwargs: { + "schema_version": "catalog_canary_plan_v0", + "source": "test", + "profiles": [], + "domain_profiles": [], + }, + ) + monkeypatch.setattr( + runner, + "flatten_catalog_canary_checks", + lambda _plan: [ + {"profile_id": "catalog-fixture", "family": "Canary fixture", "command": f"python3 {script}"} + for script in catalog_scripts + ], + ) + + +def test_default_premerge_parallel_jobs_and_cli_override( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + for cpu_count, expected in ((None, 1), (2, 1), (4, 2), (8, 4), (16, 4)): + monkeypatch.setattr(premerge.os, "cpu_count", lambda count=cpu_count: count) + assert default_premerge_parallel_jobs() == expected + assert default_premerge_parallel_jobs(fail_fast=True) == 1 + + monkeypatch.setattr(premerge.os, "cpu_count", lambda: 12) + repo, _ = _write_repo_fixture(tmp_path) + + default_gate = build_premerge_validation_gate( + repo_root=repo, + changed_files=["tracked.txt"], + base_ref="HEAD", + execute=False, + ) + assert default_gate["parallel_jobs"] == 4 + assert default_gate["validation_summary"]["parallel_jobs"] == 4 + assert default_gate["reused_check_count"] == 0 + assert default_gate["validation_summary"]["reused_check_count"] == 0 + + serial_gate = build_premerge_validation_gate( + repo_root=repo, + changed_files=["tracked.txt"], + base_ref="HEAD", + execute=False, + parallel_jobs=1, + ) + assert serial_gate["parallel_jobs"] == 1 + assert serial_gate["validation_summary"]["parallel_jobs"] == 1 + + fail_fast_gate = build_premerge_validation_gate( + repo_root=repo, + changed_files=["tracked.txt"], + base_ref="HEAD", + execute=False, + fail_fast=True, + parallel_jobs=4, + ) + assert fail_fast_gate["parallel_jobs"] == 1 + assert fail_fast_gate["validation_summary"]["parallel_jobs"] == 1 + + monkeypatch.chdir(repo) + code = main([ + "--format", "json", + "canary", "premerge", + "--changed-file", "tracked.txt", + "--git-diff-base", "HEAD", + "--no-execute", + "-j", "1", + ]) + assert code == 0 + cli_payload = json.loads(capsys.readouterr().out) + assert cli_payload["parallel_jobs"] == 1 + assert cli_payload["validation_summary"]["parallel_jobs"] == 1 + + code_jobs = main([ + "--format", "json", + "canary", "premerge", + "--changed-file", "tracked.txt", + "--git-diff-base", "HEAD", + "--no-execute", + "--jobs", "3", + ]) + assert code_jobs == 0 + cli_payload_jobs = json.loads(capsys.readouterr().out) + assert cli_payload_jobs["parallel_jobs"] == 3 + + +def test_premerge_check_reuse_key_tracks_argv_and_cli_output_base_ref() -> None: + key_main = premerge_check_reuse_key( + {"ok": True, "argv": ["python3", "examples/canary/smoke.py"]}, + cli_output_base_ref="origin/main", + ) + key_main_again = premerge_check_reuse_key( + {"ok": True, "argv": ["python3", "examples/canary/smoke.py"]}, + cli_output_base_ref="origin/main", + ) + key_head = premerge_check_reuse_key( + {"ok": True, "argv": ["python3", "examples/canary/smoke.py"]}, + cli_output_base_ref="HEAD", + ) + key_none = premerge_check_reuse_key( + {"ok": True, "argv": ["python3", "examples/canary/smoke.py"]}, + cli_output_base_ref=None, + ) + assert key_main == key_main_again + assert key_main != key_head + assert key_head != key_none + assert key_none[1] == "" + + +@pytest.mark.parametrize("shared_exit_code", [0, 3]) +def test_premerge_dedups_shared_check_pass_and_fail_and_shares_compile_cache( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + shared_exit_code: int, +) -> None: + scratch = tmp_path / "scratch" + scratch.mkdir() + _clear_compile_cache_env(monkeypatch, scratch) + repo, counter_file = _write_repo_fixture( + tmp_path, + shared_exit_code=shared_exit_code, + include_unique_risk_script=True, + ) + _wire_catalog_and_risk_scripts( + monkeypatch, + catalog_scripts=["examples/canary/catalog-planner-smoke.py"], + ) + + payload = build_premerge_validation_gate( + repo_root=repo, + changed_files=["tracked.txt"], + base_ref="HEAD", + execute=True, + parallel_jobs=2, + ) + + expected_ok = shared_exit_code == 0 + assert payload["ok"] is expected_ok, payload + assert payload["gate"]["merge_gate_passed"] is expected_ok + assert int(counter_file.read_text(encoding="utf-8").strip()) == 1 + + catalog_run = payload["catalog_run"] + risk_run = payload["risk_profile_run"] + assert risk_run is not None + assert catalog_run["reused_check_count"] == 0 + assert catalog_run["executed_check_count"] == 1 + assert risk_run["selected_check_count"] == 2 + assert risk_run["reused_check_count"] == 1 + assert risk_run["executed_check_count"] == 1 + assert payload["reused_check_count"] == 1 + assert payload["validation_summary"]["reused_check_count"] == 1 + assert payload["validation_summary"]["executed_check_count"] == 2 + + reused_item = next( + item for item in risk_run["selected_checks"] + if item["normalized"]["script"] == "examples/canary/catalog-planner-smoke.py" + ) + risk_only_item = next( + item for item in risk_run["selected_checks"] + if item["normalized"]["script"] == "examples/canary/smoke-suite-runner-smoke.py" + ) + assert catalog_run["selected_checks"][0]["profile_id"] == "catalog-fixture" + assert reused_item["reused"] is True + assert reused_item["reused_from_section"] == "catalog_canaries" + assert reused_item["duration_seconds"] == 0.0 + assert reused_item["profile_id"] == "smoke-suite" + assert reused_item["returncode"] == shared_exit_code + assert reused_item["ok"] is expected_ok + assert reused_item["status"] == ("passed" if expected_ok else "failed") + if not expected_ok: + assert "shared probe failed" in reused_item["stderr_tail"] + assert payload["gate"]["status"] == "failed" + + catalog_probe = json.loads(str(catalog_run["selected_checks"][0]["stdout_tail"]).strip()) + risk_probe = json.loads(str(risk_only_item["stdout_tail"]).strip()) + assert catalog_probe["cache"] == risk_probe["cache"] + cache_path = Path(str(catalog_probe["cache"])) + assert cache_path.parent == scratch + assert cache_path.name.startswith("loopx-smoke-compile-cache-") + assert not cache_path.exists() + assert runner._ACTIVE_NODE_COMPILE_CACHE.get() is None + + markdown = render_premerge_validation_gate_markdown(payload) + assert "- reused_checks: `1`" in markdown + assert "(reused)" in markdown + + +def test_all_reused_section_skips_executor_and_tracked_path_scan( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + scratch = tmp_path / "scratch" + scratch.mkdir() + _clear_compile_cache_env(monkeypatch, scratch) + repo, counter_file = _write_repo_fixture( + tmp_path, + shared_exit_code=0, + include_unique_risk_script=False, + include_second_shared_script=True, + ) + _wire_catalog_and_risk_scripts( + monkeypatch, + catalog_scripts=[ + "examples/canary/catalog-planner-smoke.py", + "examples/canary/catalog-run-e2e-smoke.py", + ], + ) + + real_tracked = runner._tracked_change_paths + real_executor = runner.ThreadPoolExecutor + tracked_calls = 0 + executor_calls = 0 + + def spy_tracked(*args: Any, **kwargs: Any) -> tuple[bool, list[bytes], str]: + nonlocal tracked_calls + tracked_calls += 1 + return real_tracked(*args, **kwargs) + + class SpyExecutor: + def __init__(self, *args: Any, **kwargs: Any) -> None: + nonlocal executor_calls + executor_calls += 1 + self._inner = real_executor(*args, **kwargs) + + def __enter__(self) -> Any: + return self._inner.__enter__() + + def __exit__(self, *args: Any) -> Any: + return self._inner.__exit__(*args) + + monkeypatch.setattr(runner, "_tracked_change_paths", spy_tracked) + monkeypatch.setattr(runner, "ThreadPoolExecutor", SpyExecutor) + + payload = build_premerge_validation_gate( + repo_root=repo, + changed_files=["tracked.txt"], + base_ref="HEAD", + execute=True, + parallel_jobs=2, + ) + + assert payload["ok"] is True, payload + assert int(counter_file.read_text(encoding="utf-8").strip()) == 1 + # Catalog ran 2 checks concurrently (executor_calls=1, before/after tracked_change_paths=2); + # risk_profile_run reused both checks and made 0 tracked_change_paths / ThreadPoolExecutor calls. + assert tracked_calls == 2 + assert executor_calls == 1 + risk_run = payload["risk_profile_run"] + assert risk_run is not None + assert risk_run["selected_check_count"] == 2 + assert risk_run["executed_check_count"] == 0 + assert risk_run["reused_check_count"] == 2 + assert risk_run["side_effect_guard"]["enforcement_reason"] == "all_checks_reused" + assert payload["validation_summary"]["runs"]["risk_profile_run"]["executed_check_count"] == 0 + assert payload["validation_summary"]["runs"]["risk_profile_run"]["reused_check_count"] == 2 + + +def test_reused_results_ignore_entries_with_tracked_side_effects(tmp_path: Path) -> None: + repo, _ = _write_repo_fixture(tmp_path, include_unique_risk_script=False) + cmd = "python3 examples/canary/catalog-planner-smoke.py" + normalized = runner.normalize_canary_command(cmd, repo_root=repo) + key = premerge_check_reuse_key(normalized, cli_output_base_ref="HEAD") + bad_prior = { + "ok": False, + "status": "passed", + "returncode": 0, + "stdout_tail": "stale", + "stderr_tail": "", + "normalized": normalized, + "tracked_side_effects": ["tracked.txt"], + } + suite_run = build_canary_smoke_suite_run( + repo_root=repo, + scripts=["catalog-planner-smoke.py"], + execute=True, + cli_output_base_ref="HEAD", + reusable_results_by_command={key: bad_prior}, + ) + assert suite_run["reused_check_count"] == 0 + assert suite_run["executed_check_count"] == 1 + + +def test_premerge_cleans_shared_compile_cache_on_exception_and_surfaces_cleanup_failure( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + scratch = tmp_path / "scratch" + scratch.mkdir() + _clear_compile_cache_env(monkeypatch, scratch) + repo, _ = _write_repo_fixture(tmp_path, include_unique_risk_script=True) + _wire_catalog_and_risk_scripts( + monkeypatch, + catalog_scripts=["examples/canary/catalog-planner-smoke.py"], + ) + + seen_caches: list[Path] = [] + real_suite_run = runner.build_canary_smoke_suite_run + call_count = 0 + + def abort_on_risk_section(*args: Any, **kwargs: Any) -> dict[str, Any]: + nonlocal call_count + call_count += 1 + active = runner._ACTIVE_NODE_COMPILE_CACHE.get() + assert isinstance(active, Path) + seen_caches.append(active) + if call_count == 2: + raise RuntimeError("simulated risk section crash") + return real_suite_run(*args, **kwargs) + + monkeypatch.setattr(premerge, "build_canary_smoke_suite_run", abort_on_risk_section) + with pytest.raises(RuntimeError, match="simulated risk section crash"): + build_premerge_validation_gate( + repo_root=repo, + changed_files=["tracked.txt"], + base_ref="HEAD", + execute=True, + parallel_jobs=2, + ) + assert len(seen_caches) == 2 + assert seen_caches[0] == seen_caches[1] + assert not seen_caches[0].exists() + assert runner._ACTIVE_NODE_COMPILE_CACHE.get() is None + + # Restore real suite runner and test outer cleanup PermissionError surfacing. + monkeypatch.setattr(premerge, "build_canary_smoke_suite_run", real_suite_run) + real_remove = runner.remove_owned_tree + + def fail_cache_cleanup(path: Path) -> None: + if path.name.startswith("loopx-smoke-compile-cache-"): + raise PermissionError("readonly compile cache") + real_remove(path) + + monkeypatch.setattr(runner, "remove_owned_tree", fail_cache_cleanup) + failed_gate = build_premerge_validation_gate( + repo_root=repo, + changed_files=["tracked.txt"], + base_ref="HEAD", + execute=True, + parallel_jobs=2, + ) + assert failed_gate["ok"] is False + assert failed_gate["gate"]["status"] == "failed" + assert failed_gate["gate"]["merge_gate_passed"] is False + assert failed_gate["validation_summary"]["failure_count"] >= 1 + assert any("readonly compile cache" in str(item.get("reason")) for item in failed_gate["cleanup_failures"]) + assert "readonly compile cache" in render_premerge_validation_gate_markdown(failed_gate) + assert runner._ACTIVE_NODE_COMPILE_CACHE.get() is None