Skip to content
Merged
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
37 changes: 28 additions & 9 deletions apps/sandbox-executor/src/sandbox_executor/flow/review_restart.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import Any

from sandbox_executor.flow.context import FlowContext, FlowStage, StageResult, StageStatus
from sandbox_executor.flow.dispatch import _stage_failure
from sandbox_executor.flow.github.ci_final_head import _bookkeeping_only, _git_changed_paths
from sandbox_executor.flow.github.ci_head_checks import FAILED, PASSED
from sandbox_executor.flow.github.ci_reverify import _same_commit, approved_head_of
Expand All @@ -29,6 +30,7 @@
from sandbox_executor.git import run_git

MAX_MERGED_HEAD_REVIEW_RESTARTS = 3
NO_APPROVAL = "no Stage 4 approval recorded"


def _execution_head(context: FlowContext, seams: MergedHeadSeams) -> str | None:
Expand All @@ -54,7 +56,29 @@ def moved(approved: str, head: str) -> bool:
def _skip_reason(context: FlowContext) -> str | None:
if context.dry_run or context.skip_push or not context.execution_branch:
return "dry run" if context.dry_run else "push skipped" if context.skip_push else "no execution branch"
return None if approved_head_of(context) else "no Stage 4 approval recorded"
return None


def _refuse_unapproved(context: FlowContext, start: str) -> tuple[StageResult, dict[str, Any]]:
record = gate_record("refused", "", [], [], NO_APPROVAL)
error = (
f"Calibrate stage refused: {NO_APPROVAL} for execution branch {context.execution_branch}; "
"nothing was calibrated or pushed. Run the review stage first (resume from review) to record an approval."
)
return _stage_failure(context, FlowStage.CALIBRATE, start, error, merged_head_ci=record), record


def _settled_before_head_check(context: FlowContext, start: str) -> tuple[StageResult | None, dict[str, Any]] | None:
resumed = resumed_restart(context, start)
# why: a resume after a withdrawal or a scoped restart runs Stage 4 again first.
if resumed is not None:
return resumed
skip = _skip_reason(context)
if skip:
context.log(f"Merged-head CI gate skipped: {skip}.")
return None, skipped_record(None, skip)
# why: dry run and skip_push publish nothing, so only a publishing run needs a recorded approval.
return None if approved_head_of(context) else _refuse_unapproved(context, start)


def _decide(
Expand All @@ -71,14 +95,9 @@ def stage5_merged_head_gate(
context: FlowContext, seams: MergedHeadSeams | None = None
) -> tuple[StageResult | None, dict[str, Any]]:
seams, start = seams or MergedHeadSeams(), datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
resumed = resumed_restart(context, start)
# why: a resume after a withdrawal or a scoped restart runs Stage 4 again first.
if resumed is not None:
return resumed
skip = _skip_reason(context)
if skip:
context.log(f"Merged-head CI gate skipped: {skip}.")
return None, skipped_record(None, skip)
settled = _settled_before_head_check(context, start)
if settled is not None:
return settled
approved, head = str(approved_head_of(context)), _execution_head(context, seams)
if not head:
record = gate_record("unknown", "", [], [], "the execution head could not be read")
Expand Down
41 changes: 39 additions & 2 deletions apps/sandbox-executor/tests/calibrate_scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
import json
import os
import subprocess
from collections.abc import Callable, Sequence
from collections.abc import Callable, Iterator, Sequence
from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import patch

import pytest
from sandbox_executor.flow import FlowContext, StageResult
from sandbox_executor.flow import FlowContext, FlowStage, StageResult, StageStatus
from sandbox_executor.flow.calibrate_rerun import RerunSeams
from sandbox_executor.flow.calibrate_stale_warning import STALE_MARKER_FAMILY
from sandbox_executor.flow.github.approval_invalidation import CommentRecord
Expand All @@ -26,6 +28,7 @@
CAL_REPORT_REL = f"plans/I-1-x/{PLAN_ID}_calibration.md"
LEDGER_REL = "holon-knowledge/ledger/executions.jsonl"
TARGET_REF = "refs/remotes/origin/main"
APPROVED_HEAD = "a" * 40
SYNC_GIT_ENV = {
"GIT_AUTHOR_NAME": "t",
"GIT_AUTHOR_EMAIL": "t@example.com",
Expand All @@ -52,6 +55,40 @@ def commit_sync_file(repo: Path, name: str, text: str = "x") -> str:
return run_sync_git(repo, "rev-parse", "HEAD")


def record_stage4_approval(ctx: FlowContext, target_commit: str, pr_number: str = "7") -> None:
ctx.stage_results["review"] = StageResult(
stage=FlowStage.REVIEW,
status=StageStatus.APPROVED,
payload={
"consensus": {"approved": True, "target_commit": target_commit, "pr_number": pr_number},
"posting": {"dual_posted": True},
"ci_checks": {"checks": [{"name": "unit", "bucket": "pass", "link": "https://x/actions/runs/5/job/1"}]},
},
)


def approve_execution_head(ctx: FlowContext, repo: Path, branch: str, pr_number: str = "7") -> str:
refs = (f"refs/remotes/origin/{branch}", f"refs/heads/{branch}")
head = next(sha for ref in refs if (sha := _verified_ref(repo, ref)))
record_stage4_approval(ctx, head, pr_number)
return head


# why: a repository with no origin execution ref would make the gate ask GitHub for the pull request head
@contextmanager
def approved_at_execution_head(ctx: FlowContext, head: str = APPROVED_HEAD) -> Iterator[str]:
record_stage4_approval(ctx, head)
with patch("sandbox_executor.flow.review_restart._execution_head", return_value=head):
yield head


def _verified_ref(repo: Path, ref: str) -> str:
res = subprocess.run(
["git", "rev-parse", "--verify", "-q", ref], cwd=repo, capture_output=True, text=True, check=False
)
return res.stdout.strip() if res.returncode == 0 else ""


def own_copy(template: SimpleNamespace, target: Path) -> SimpleNamespace:
copy_template(template.root, target)
built = vars(template.repos)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from sandbox_executor.ledger import read_merged_rows, read_merged_rows_at_ref
from sandbox_executor.review_report import _mergeability_word

from tests.calibrate_scenarios import approved_at_execution_head
from tests.flow.github.fake_github import view_for
from tests.flow.helpers import _git
from tests.ledger_conflict_repos import BRANCH, LEDGER, build_conflicting_repos, refuse_test_runs
Expand Down Expand Up @@ -231,8 +232,10 @@ def test_stage5_proceeds_on_a_clean_or_freshly_merged_head(tmp_path, monkeypatch
monkeypatch.setattr(sync_points, "sync_review_head", _RecordingSync(outcome))
monkeypatch.setattr(conflict_gate.stage_conflicts, "check_pr_mergeability", lambda *a, **k: dict(probe))
monkeypatch.setattr(calibrate, "_calibrate_execution_branch", MagicMock(return_value=expected))
ctx = _stage5_context(tmp_path)

assert calibrate.run_calibrate_stage(_stage5_context(tmp_path)) is expected
with approved_at_execution_head(ctx):
assert calibrate.run_calibrate_stage(ctx) is expected


def test_ledger_only_conflict_is_merged_and_pushed_but_the_approval_is_not_posted(conflicting_repos, monkeypatch):
Expand Down
12 changes: 8 additions & 4 deletions apps/sandbox-executor/tests/flow/review/test_sync_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from sandbox_executor.review_ensemble import build_review_request
from sandbox_executor.review_target import ReviewTarget

from tests.calibrate_scenarios import approved_at_execution_head
from tests.flow.helpers import _git
from tests.flow.sync_boundary_repos import (
APP,
Expand Down Expand Up @@ -301,7 +302,8 @@ def test_stage5_entry_and_retry_sync_resolve_conflicts_and_block_cleanly(
ctx = _ctx(work)

# Stage 5 entry sync resolves mechanical ledger conflict.
assert sync_before_calibration(ctx, "2026-11-24T00:00:00Z") is None
with approved_at_execution_head(ctx):
assert sync_before_calibration(ctx, "2026-11-24T00:00:00Z") is None
rows = read_merged_rows_at_ref(str(work), f"origin/{FLOW_BRANCH}", "executions.jsonl")
assert any(r.get("action") == "target_sync" and r.get("boundary") == "calibrate" for r in rows)

Expand All @@ -324,7 +326,7 @@ def flaky_calibrate(**kwargs):
)
from tests.flow.sleep_patch import scoped_sleep_patch

with scoped_sleep_patch("sandbox_executor.flow.calibrate_retry"):
with approved_at_execution_head(ctx), scoped_sleep_patch("sandbox_executor.flow.calibrate_retry"):
assert wrapped() == {"ok": True}
assert calls == 2

Expand Down Expand Up @@ -416,15 +418,17 @@ def test_prepare_execution_branch_syncs_before_calibrated_and_retry_reanchors(
# Mechanical sync_before_calibration runs before prepare_calibrated_branch so /calibrated starts at merged SHA.
work2 = sync_work(tmp_path_factory, tmp_path / "r2", ledger_conflict(2), base=CODE_BASE)
ctx_ok = _ctx(work2)
failure2, start_sha, created2 = cal_stage._prepare_execution_branch(ctx_ok, "2026-11-24T00:00:00Z")
with approved_at_execution_head(ctx_ok):
failure2, start_sha, created2 = cal_stage._prepare_execution_branch(ctx_ok, "2026-11-24T00:00:00Z")
assert failure2 is None and created2 is True and start_sha is not None
assert _git(work2, "rev-parse", f"refs/heads/{calibrated}") == start_sha
assert _git(work2, "rev-parse", f"refs/heads/{FLOW_BRANCH}") == start_sha

# Mechanical retry sync re-anchors /calibrated and updates start_sha so publish_calibration --ff-only succeeds.
_inject_ledger_conflict(work2, FLOW_BRANCH, 3)
updated_shas: list[str] = []
make_calibrate_retry_sync(ctx_ok, on_head_updated=updated_shas.append)(1)
with approved_at_execution_head(ctx_ok):
make_calibrate_retry_sync(ctx_ok, on_head_updated=updated_shas.append)(1)
assert len(updated_shas) == 1 and updated_shas[0] != start_sha
assert _git(work2, "rev-parse", f"refs/heads/{calibrated}") == updated_shas[0]
_git(work2, "checkout", calibrated)
Expand Down
6 changes: 5 additions & 1 deletion apps/sandbox-executor/tests/flow/test_git_refs.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from sandbox_executor.flow.git_refs import _append_ledger_row
from sandbox_executor.git import run_git as real_run_git

from tests.calibrate_scenarios import approved_at_execution_head
from tests.flow.github.fake_github import FakeGitHub, ci_checks_payload
from tests.flow.helpers import (
_REAL_RESOLVE_REVIEWED_TARGET,
Expand Down Expand Up @@ -250,7 +251,10 @@ def test_calibrate_stage_fails_cleanly_when_execution_branch_cannot_be_checked_o
ctx.execution_branch = ctx.execution_branch.replace("/E-", "/E-missing-")
status_before = _git(host, "status", "--porcelain")

with patch("sandbox_executor.flow.stages.calibrate.run_calibrate") as mock_calibrate:
with (
approved_at_execution_head(ctx),
patch("sandbox_executor.flow.stages.calibrate.run_calibrate") as mock_calibrate,
):
res = run_calibrate_stage(ctx)

assert res.status == StageStatus.FAILED
Expand Down
5 changes: 5 additions & 0 deletions apps/sandbox-executor/tests/flow/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
from sandbox_executor.intent_assumption_rules import default_assumptions_fields
from sandbox_executor.ledger import read_merged_rows, read_merged_text

from tests.calibrate_scenarios import approved_at_execution_head
from tests.flow.helpers import SteppingClock, _dispatch_context, _prefix, _review_loop_gh_stubs, seed_empty_ledger
from tests.flow.hermetic_repos import hermetic_repos_copy
from tests.flow.lookup_patch import patch_lookup_sites
Expand Down Expand Up @@ -210,6 +211,7 @@ def test_stage5_calibrate_mocked(self, tmp_path):
mock_report.to_dict.return_value = {"calibrated_branch": mock_report.calibrated_branch, "accuracy_score": 0.95}

with (
approved_at_execution_head(ctx),
patch("sandbox_executor.flow.stages.calibrate._checkout_execution_branch", return_value=None),
patch("sandbox_executor.flow.stages.calibrate.run_calibrate", return_value=mock_report) as mock_run,
):
Expand All @@ -228,6 +230,7 @@ def test_stage5_calibrate_failure_writes_no_report(self, tmp_path):
)

with (
approved_at_execution_head(ctx),
patch("sandbox_executor.flow.stages.calibrate._checkout_execution_branch", return_value=None),
patch(
"sandbox_executor.flow.stages.calibrate.run_calibrate", side_effect=RuntimeError("calibration failed")
Expand Down Expand Up @@ -426,6 +429,7 @@ def test_stage5_prettier_check_failure_fails_stage_and_never_pushes(self, tmp_pa
"(check exited 1); reproduce with: npx prettier --check plans/I-100-intent/P-200-plan_calibration.md"
)
with (
approved_at_execution_head(ctx),
patch("sandbox_executor.flow.stages.calibrate._checkout_execution_branch", return_value=None),
patch("sandbox_executor.flow.stages.calibrate.sync_before_calibration", return_value=None),
patch("sandbox_executor.flow.stages.calibrate.run_calibrate", side_effect=error),
Expand Down Expand Up @@ -457,6 +461,7 @@ def test_stage5_calibration_success_still_pushes(self, tmp_path):
mock_report.calibrated_branch = "I-100-intent/P-200-plan/E-300-exec/calibrated"
mock_report.to_dict.return_value = {"calibrated_branch": mock_report.calibrated_branch}
with (
approved_at_execution_head(ctx),
patch("sandbox_executor.flow.stages.calibrate._checkout_execution_branch", return_value=None),
patch("sandbox_executor.flow.stages.calibrate.sync_before_calibration", return_value=None),
patch("sandbox_executor.flow.stages.calibrate.run_calibrate", return_value=mock_report),
Expand Down
139 changes: 139 additions & 0 deletions apps/sandbox-executor/tests/flow/test_stage5_no_approval_refusal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
from __future__ import annotations

import logging
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock, patch

import pytest
from sandbox_executor.flow import FlowContext, FlowStage, StageResult, StageStatus
from sandbox_executor.flow.review.merged_head_gate import MergedHeadSeams
from sandbox_executor.flow.review_restart import NO_APPROVAL, stage5_merged_head_gate
from sandbox_executor.flow.stages.calibrate import run_calibrate_stage

from tests.calibrate_scenarios import (
SYNC_CALIBRATED,
SYNC_EXEC,
approve_execution_head,
build_sync_repos,
own_copy,
run_sync_git,
)
from tests.repo_templates import shared_template

OLD_PASS_THROUGH = f"Merged-head CI gate skipped: {NO_APPROVAL}"
APPROVED = "a" * 40


@pytest.fixture(scope="session")
def execution_repos_template(tmp_path_factory: pytest.TempPathFactory, hermetic_git_config: str) -> SimpleNamespace:
root, built = shared_template(tmp_path_factory, "stage5-no-approval-template", build_sync_repos)
return SimpleNamespace(root=root, repos=built)


@pytest.fixture
def repos(execution_repos_template: SimpleNamespace, tmp_path: Path) -> SimpleNamespace:
return own_copy(execution_repos_template, tmp_path)


def _branch_heads(repos: SimpleNamespace) -> tuple[str, str]:
local = run_sync_git(repos.host, "rev-parse", f"refs/heads/{SYNC_EXEC}")
return local, run_sync_git(repos.origin, "rev-parse", f"refs/heads/{SYNC_EXEC}")


def _run_stage5(ctx: FlowContext) -> tuple[StageResult, MagicMock]:
calibrated = StageResult(stage=FlowStage.CALIBRATE, status=StageStatus.SUCCESS)
with (
patch("sandbox_executor.flow.stages.calibrate._stage5_conflict_gate", return_value=None),
patch("sandbox_executor.flow.stages.calibrate._calibrate_execution_branch", return_value=calibrated) as spy,
):
return run_calibrate_stage(ctx), spy


def _execution_ctx(repos: SimpleNamespace) -> FlowContext:
return FlowContext(target_worktree=str(repos.host), execution_branch=SYNC_EXEC, agent="a", model="m")


def _review(**consensus: Any) -> StageResult:
return StageResult(stage=FlowStage.REVIEW, status=StageStatus.APPROVED, payload={"consensus": consensus})


def test_stage5_without_an_approval_calibrates_commits_and_pushes_nothing(
repos: SimpleNamespace, caplog: pytest.LogCaptureFixture
) -> None:
caplog.set_level(logging.INFO)
ctx, heads_before = _execution_ctx(repos), _branch_heads(repos)

result, calibration = _run_stage5(ctx)

assert (result.status, result.stage) == (StageStatus.FAILED, FlowStage.CALIBRATE)
assert "no Stage 4 approval recorded" in result.error and "nothing was calibrated or pushed" in result.error
assert "Run the review stage first" in result.error
assert result.payload["merged_head_ci"]["state"] != "skipped"
calibration.assert_not_called()
assert _branch_heads(repos) == heads_before
assert run_sync_git(repos.host, "branch", "--list", SYNC_CALIBRATED) == ""
assert OLD_PASS_THROUGH not in caplog.text and OLD_PASS_THROUGH not in "\n".join(ctx.logs)


def test_stage5_with_an_approval_at_the_execution_head_still_calibrates(repos: SimpleNamespace) -> None:
ctx = _execution_ctx(repos)
approve_execution_head(ctx, repos.host, SYNC_EXEC)

result, calibration = _run_stage5(ctx)

assert result.status is StageStatus.SUCCESS
calibration.assert_called_once()
assert calibration.call_args.args[1]["state"] == "stage4"


@pytest.mark.parametrize(
("flags", "reason"),
[
({"dry_run": True}, "dry run"),
({"skip_push": True}, "push skipped"),
({"execution_branch": None}, "no execution branch"),
],
)
def test_runs_that_publish_nothing_keep_the_skipped_record_without_an_approval(
tmp_path: Path, caplog: pytest.LogCaptureFixture, flags: dict[str, Any], reason: str
) -> None:
caplog.set_level(logging.INFO)
ctx = FlowContext(repo_dir=str(tmp_path), **{"execution_branch": SYNC_EXEC, **flags})

stopped, record = stage5_merged_head_gate(ctx)

assert stopped is None
assert (record["state"], record["reason"]) == ("skipped", reason)
assert OLD_PASS_THROUGH not in caplog.text and OLD_PASS_THROUGH not in "\n".join(ctx.logs)


@pytest.mark.parametrize(
"consensus",
[
{"approved": False, "withdrawn": {"merged_head": "b" * 40, "approved_head": APPROVED}},
{"approved": False, "pipeline_defect": {"head_sha": "b" * 40, "approved_head": APPROVED}},
],
)
def test_a_pending_withdrawal_or_scoped_restart_still_reenters_stage4(
tmp_path: Path, consensus: dict[str, Any]
) -> None:
ctx = FlowContext(repo_dir=str(tmp_path), execution_branch=SYNC_EXEC)
ctx.stage_results["review"] = _review(**consensus)

stopped, _ = stage5_merged_head_gate(ctx)

assert stopped is not None and stopped.status is StageStatus.SKIPPED
assert stopped.payload["review_restart"] is True
assert "no Stage 4 approval recorded" not in (stopped.error or "")


def test_an_approval_at_the_execution_head_relies_on_stage4_ci(tmp_path: Path) -> None:
ctx = FlowContext(repo_dir=str(tmp_path), execution_branch=SYNC_EXEC)
ctx.stage_results["review"] = _review(approved=True, target_commit=APPROVED)

stopped, record = stage5_merged_head_gate(ctx, MergedHeadSeams(head_reader=lambda: APPROVED))

assert stopped is None
assert (record["state"], record["head_sha"]) == ("stage4", APPROVED)
Loading
Loading