"""Integration tests combining two or more escalation-ladder rungs at once. Every existing test elsewhere exercises exactly one rung (parallel dispatch, foreman decompose, best-of-N, merge-conflict retry) in isolation. This file specifically combines them -- real git repos, real worktrees, real threads -- per the architecture review's finding that the 6-rung escalation ladder (retries -> semantic repair -> foreman decompose -> subtask retries -> best-of-N -> stall consult -> human) was "tested individually, never in combination." All tests here use fake Worker/reasoner backends (never a real LLM call) but real ``git.Repo``/worktrees and real ``threading.Thread`` concurrency, mirroring exactly how ``campaign work --workers N`` dispatches ``execute_plan(..., only_task_id=X, isolation="worktree")`` once per thread. """ import json import threading from pathlib import Path from git import Repo from afk_developer.backends.fake import FakeReasonerBackend from afk_developer.config import Config from afk_developer.planner.task_model import TaskNode, TaskPlan, TaskStatus from afk_developer.recovery import RecoveryMode, RecoverySettings from afk_developer.scheduler import queue from afk_developer.scheduler.reviewer import ReviewResult def _init_repo(project: Path, *, seed_filename: str = "seed.txt") -> Repo: project.mkdir() repo = Repo.init(project, initial_branch="main") with repo.config_writer() as config_writer: config_writer.set_value("user", "name", "AFK Test") config_writer.set_value("user", "email", "afk-test@example.invalid") (project / seed_filename).write_text("seed\n", encoding="utf-8") repo.git.add(seed_filename) repo.index.commit("Initial project") return repo class _FakeCortex: def write_fading(self, **_kwargs) -> None: pass def test_workers_concurrent_decompose_respects_shared_budget(tmp_path: Path, monkeypatch) -> None: """Two independent stuck tasks, each run via execute_plan in its own thread (mirroring exactly how `campaign work --workers 2` dispatches), race to decompose against a shared plan-wide budget of one. Only one may win; the loser must escalate cleanly through the real execute_plan path -- this also exercises the decompose-budget lock end-to-end (test_queue.py has a narrower unit test that calls _maybe_decompose_task directly).""" project = tmp_path / "project" repo = _init_repo(project) class FakeWorker: def __init__(self, *_args, **_kwargs) -> None: pass def execute_task(self, task): return TaskStatus.FAILED, f"{task.id} never passes", [] barrier = threading.Barrier(2) class BarrierSyncedForeman(FakeReasonerBackend): def complete(self, *, system_prompt, user_prompt, temperature=0.0): # Force both threads to be mid-flight on their own foreman call at # the same time, so both reach the commit section's budget # re-check at effectively the same moment. barrier.wait(timeout=5) return super().complete( system_prompt=system_prompt, user_prompt=user_prompt, temperature=temperature ) class FakeForemanRegistry: def __init__(self, _config) -> None: pass def get_foreman(self) -> BarrierSyncedForeman: return BarrierSyncedForeman( [ json.dumps( { "decision": "decompose", "subtasks": [ { "title": "Sub A", "description": "Do part A", "covers": ["criterion:Never passes"], }, { "title": "Sub B", "description": "Do part B", "covers": [], "depends_on": [1], }, ], "summary": "Split into two independent parts.", } ) ] ) monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr(queue, "BackendRegistry", FakeForemanRegistry) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: ReviewResult(False, False, True) ) plan = TaskPlan( project_name="workers-decompose-example", goal="Race two stuck tasks under --workers against one shared decompose budget", intent="implement", tasks=[ TaskNode(id="stuck-a", title="Stuck task A", description="Never passes", max_retries=0), TaskNode(id="stuck-b", title="Stuck task B", description="Never passes", max_retries=0), ], recovery=RecoverySettings( mode=RecoveryMode.BOUNDED, max_decompositions=1, require_supervisor_decomposition_approval=False, ), ) config = Config(projects_dir=tmp_path / "state") git_lock = threading.Lock() def _run(task_id: str) -> None: queue.execute_plan( plan, config, _FakeCortex(), project, "", "", isolation="worktree", only_task_id=task_id, git_lock=git_lock, ) threads = [threading.Thread(target=_run, args=(tid,)) for tid in ("stuck-a", "stuck-b")] for thread in threads: thread.start() for thread in threads: thread.join(timeout=15) assert not any(thread.is_alive() for thread in threads) assert plan.decompositions_used == 1 statuses = {task.id: task.status for task in plan.tasks if task.id in ("stuck-a", "stuck-b")} assert sorted(status.value for status in statuses.values()) == sorted( status.value for status in (TaskStatus.DECOMPOSED, TaskStatus.ESCALATED) ) winner_id = next( task_id for task_id, status in statuses.items() if status is TaskStatus.DECOMPOSED ) winner = next(task for task in plan.tasks if task.id == winner_id) assert len(winner.subtask_ids) == 2 assert len(plan.tasks) == 4 # Note: worktrees/branches for an ESCALATED or DECOMPOSED task are # deliberately NOT auto-discarded (TaskNode.discard_branch_on_failure # defaults to False) so a human can inspect what the coder actually did -- # unlike the PASSED path, cleanup here is opt-in, not unconditional. # The primary checkout itself must still be left on its own branch, never # stuck on a per-task worktree/branch from either concurrent attempt. assert repo.active_branch.name == "main" def test_workers_concurrent_merge_conflict_is_detected_and_retried( tmp_path: Path, monkeypatch ) -> None: """Two independent tasks, both editing the SAME file differently, dispatched concurrently via execute_plan (mirroring --workers), share one git_lock. Whichever one's merge runs second must hit a REAL git conflict (not a monkeypatched _finalize_task_branch, unlike test_queue.py's sequential unit test of this) and consume its one merge-conflict retry instead of silently clobbering the winner's change or raising uncaught.""" project = tmp_path / "project" repo = _init_repo(project, seed_filename="shared.txt") barrier = threading.Barrier(2) class FakeWorker: def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None: self.project_dir_str = str(project_dir) def execute_task(self, task): # Both branches/worktrees are already created (serialized by # git_lock, both from the same original tip) by this point -- # force both workers to be mid-flight before either one's # finalize/merge is attempted, so they genuinely diverge. barrier.wait(timeout=5) Path(self.project_dir_str, "shared.txt").write_text( f"changed by {task.id}\n", encoding="utf-8" ) return TaskStatus.PASSED, f"{task.id} completed", ["shared.txt"] monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True) ) plan = TaskPlan( project_name="workers-conflict-example", goal="Two tasks editing the same file concurrently", intent="implement", tasks=[ TaskNode(id="task-a", title="Task A", description="Edit shared.txt"), TaskNode(id="task-b", title="Task B", description="Edit shared.txt"), ], ) config = Config(projects_dir=tmp_path / "state") git_lock = threading.Lock() def _run(task_id: str) -> None: queue.execute_plan( plan, config, _FakeCortex(), project, "", "", isolation="worktree", only_task_id=task_id, git_lock=git_lock, ) threads = [threading.Thread(target=_run, args=(tid,)) for tid in ("task-a", "task-b")] for thread in threads: thread.start() for thread in threads: thread.join(timeout=15) assert not any(thread.is_alive() for thread in threads) statuses = {task.id: task.status for task in plan.tasks} # Exactly one task merged cleanly; the other hit a real conflict and # consumed its one merge-conflict retry (retry_count is still 0 on a # first attempt, so the reset status is PENDING, not RETRYING) instead of # silently clobbering the winner's change or crashing. assert sorted(status.value for status in statuses.values()) == sorted( status.value for status in (TaskStatus.PASSED, TaskStatus.PENDING) ) loser_id = next(task_id for task_id, status in statuses.items() if status is TaskStatus.PENDING) loser = next(task for task in plan.tasks if task.id == loser_id) assert loser.merge_conflict_retries_remaining == 0 assert not any(head.name.startswith("afk/") for head in repo.heads) def test_concurrent_sibling_completion_rolls_up_decomposed_parent_exactly_once( tmp_path: Path, monkeypatch ) -> None: """Two sibling subtasks of an already-decomposed parent, each finished via execute_plan in its own thread (mirroring --workers dispatch), must roll the parent up to PASSED with no corruption from the concurrent "are all my siblings passed" check racing itself.""" project = tmp_path / "project" _init_repo(project) barrier = threading.Barrier(2) class FakeWorker: def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None: self.project_dir_str = str(project_dir) def execute_task(self, task): filename = f"{task.id}.txt" Path(self.project_dir_str, filename).write_text("value = 1\n", encoding="utf-8") # Force both sibling threads to finish their worker step and reach # the finalize/rollup section at roughly the same moment. barrier.wait(timeout=5) return TaskStatus.PASSED, f"{task.id} completed", [filename] monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True) ) parent = TaskNode( id="parent", title="Parent", description="Already decomposed", status=TaskStatus.DECOMPOSED, subtask_ids=["parent-sub-1", "parent-sub-2"], ) sub1 = TaskNode( id="parent-sub-1", title="Sub 1", description="Part 1", parent_task_id="parent", decomposition_depth=1, ) sub2 = TaskNode( id="parent-sub-2", title="Sub 2", description="Part 2", parent_task_id="parent", decomposition_depth=1, ) plan = TaskPlan( project_name="rollup-example", goal="Roll up once both siblings pass concurrently", intent="implement", tasks=[parent, sub1, sub2], recovery=RecoverySettings(require_supervisor_parent_coherence=False), ) config = Config(projects_dir=tmp_path / "state") git_lock = threading.Lock() def _run(task_id: str) -> None: queue.execute_plan( plan, config, _FakeCortex(), project, "", "", isolation="worktree", only_task_id=task_id, git_lock=git_lock, ) threads = [ threading.Thread(target=_run, args=(tid,)) for tid in ("parent-sub-1", "parent-sub-2") ] for thread in threads: thread.start() for thread in threads: thread.join(timeout=15) assert not any(thread.is_alive() for thread in threads) assert plan.tasks[0].status is TaskStatus.PASSED # parent rolled up assert sub1.status is TaskStatus.PASSED assert sub2.status is TaskStatus.PASSED def test_workers_and_best_of_compose_via_shared_git_lock(tmp_path: Path, monkeypatch) -> None: """Two independent tasks, each dispatched via execute_best_of_n (n=2) in its own thread (mirroring `campaign work --workers 2 --best-of 2`), sharing one git_lock -- proving the two options' concurrency actually composes safely, which the hours-scale plan noted was an emergent, unverified property of both reusing the same lock contract.""" project = tmp_path / "project" repo = _init_repo(project) class FakeWorker: def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None: self.project_dir_str = str(project_dir) def execute_task(self, task): filename = f"{task.id}.txt" Path(self.project_dir_str, filename).write_text("value = 1\n", encoding="utf-8") return TaskStatus.PASSED, f"{task.id} completed", [filename] monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True) ) plan = TaskPlan( project_name="workers-best-of-example", goal="Two tasks, each best-of-2, dispatched concurrently", intent="implement", tasks=[ TaskNode(id="task-a", title="Task A", description="Do A"), TaskNode(id="task-b", title="Task B", description="Do B"), ], ) config = Config(projects_dir=tmp_path / "state") git_lock = threading.Lock() def _run(task_id: str) -> None: task = next(item for item in plan.tasks if item.id == task_id) queue.execute_best_of_n( task, plan, config, _FakeCortex(), project, "", "", n=2, git_lock=git_lock ) threads = [threading.Thread(target=_run, args=(tid,)) for tid in ("task-a", "task-b")] for thread in threads: thread.start() for thread in threads: thread.join(timeout=15) assert not any(thread.is_alive() for thread in threads) assert plan.tasks[0].status is TaskStatus.PASSED assert plan.tasks[1].status is TaskStatus.PASSED assert (project / "task-a.txt").read_text(encoding="utf-8") == "value = 1\n" assert (project / "task-b.txt").read_text(encoding="utf-8") == "value = 1\n" assert not any(head.name.startswith("afk/") for head in repo.heads) worktree_root = config.resolve_project_dir("workers-best-of-example") / "worktrees" assert not worktree_root.exists() or list(worktree_root.iterdir()) == []