Files
roboco/tests/unit/services/test_git_worktree_routing_gaps.py
T
Renn F ce4d02b3c2 fix(gateway): bounded fail-open evidence assembly + PM decision transient-failure bypass
Evidence-assembly git legs (diff, changed-files, branch fetch, advisory
conventions run) ran unbounded inside claim_review / claim_doc_task /
claim_gate_review / evidence() / i_am_done's envelope build, so a slow
clone turned the whole verb into a silent 120s FlowVerbTimeout 504.
Each leg now runs through run_bounded_leg under a shared LegBudget
(evidence_assembly_timeout_seconds, 45s total): a timed-out leg — both
asyncio TimeoutError and git's own GitTimeoutError — degrades into an
evidence_gaps note on the envelope instead of hanging the verb, while
non-timeout git errors still propagate. The advisory conventions run
gets an inner-only timeout (conventions_validator_advisory_timeout_
seconds, 30s) threaded down to the subprocess so it is never orphaned
by an outer cancel; the fail-closed i_am_done/pr_pass conventions
gates keep their hardcoded 120s.

_ensure_pm_decision now reports a PmDecisionOutcome: a transient DB
failure recording the PM's decision journal (e.g. lock timeout under
load) no longer launders into a journal:decision gate rejection that
escalates and BLOCKS the task — the verb's own rationale satisfies the
gate with a structured warning, across all seven PM verbs.

Also: repo-wide ruff realignment to the lockfile-pinned ruff (8
format-only diffs, 14 UP038 isinstance conversions) that a transiently
newer venv ruff had masked.

Gate: 15474 passed, 459 skipped; ruff/mypy/xenon/vulture/bandit/
pip-audit/deptry/import-linter/foundation-check all green.
2026-07-31 13:56:19 +02:00

180 lines
6.3 KiB
Python

"""Rebase + conventions validator run in the per-task worktree, not the clone.
F123 gap: Phase B routed ``create_branch`` + ``commit`` to the worktree but
missed two cwd-dependent git ops that still resolved the clone root:
1. ``rebase_onto_base`` (called by ``sync_task_branch`` + ``rebase_pr_for_task``)
does ``git checkout <head>`` + ``git reset --hard origin/<head>`` in the
resolved workspace. Post-F123 the branch is checked out in the linked
worktree, so a ``checkout`` in the clone root is refused ("already checked
out at '<worktree>'") — the behind-base recovery loop + PM wedged-PR rebase
are dead on arrival.
2. ``conventions_check_for_task`` runs the validator with ``--root <clone
root>``; the validator reads ``(root/rel).read_bytes()`` — default-branch
content, not the dev's worktree changes. Newly-added files are absent from
the clone root → false pass; modified files are analyzed at stale content.
Both fix the same way: resolve the worktree via ``_worktree_for_task(clone_root,
task.id)`` + ``_ensure_worktree_for_commit`` and run the op there.
"""
from __future__ import annotations
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
from uuid import UUID, uuid4
import pytest
from roboco.services.forge import RepoRef
from roboco.services.git import GitService
def _service() -> GitService:
svc = GitService.__new__(GitService)
svc.log = MagicMock()
svc.session = MagicMock()
return svc
def _task(*, branch: str, task_id: UUID | None = None) -> MagicMock:
return MagicMock(
id=task_id or uuid4(),
project_id=uuid4(),
branch_name=branch,
assigned_to=uuid4(),
)
# --- rebase: sync_task_branch + rebase_pr_for_task route to the worktree ---
def _stub_rebase_common(svc: GitService, clone: Path) -> dict[str, list[Path]]:
object.__setattr__(
svc, "_project_for_task", AsyncMock(return_value=MagicMock(slug="roboco-api"))
)
object.__setattr__(
svc, "_resolve_workspace_agent_id", MagicMock(return_value=uuid4())
)
object.__setattr__(svc, "get_workspace", AsyncMock(return_value=clone))
object.__setattr__(
svc, "_get_project_token_or_raise", AsyncMock(return_value="tok")
)
object.__setattr__(svc, "_ensure_worktree_for_commit", AsyncMock())
cwds: list[Path] = []
async def _run_git(workspace: Path, args: list[str], **_kw: object) -> object:
cwds.append(Path(workspace))
if args[:1] == ["rev-list"]:
return MagicMock(stdout="0\n", returncode=0)
return MagicMock(stdout="", returncode=0)
object.__setattr__(svc, "_run_git", AsyncMock(side_effect=_run_git))
return {"cwds": cwds}
@pytest.mark.asyncio
async def test_sync_task_branch_rebases_in_worktree_not_clone() -> None:
svc = _service()
task_id = uuid4()
short = str(task_id)[:8]
clone = Path("/tmp/ws")
worktree = clone / ".worktrees" / short
task = _task(branch="feature/backend/abc12345", task_id=task_id)
state = _stub_rebase_common(svc, clone)
await svc.sync_task_branch(task, base_branch="master")
ensure = object.__getattribute__(svc, "_ensure_worktree_for_commit")
ensure.assert_awaited_once()
args = ensure.await_args.args
assert args[0] == clone, "ensure must target the clone root"
assert args[1] == worktree, (
f"ensure must target the worktree {worktree}; got {args[1]}"
)
assert args[2] == "feature/backend/abc12345"
assert state["cwds"], "rebase git ops must run"
assert all(c == worktree for c in state["cwds"]), (
f"all rebase git ops must run in the worktree {worktree}; got {state['cwds']}"
)
@pytest.mark.asyncio
async def test_rebase_pr_for_task_rebases_in_worktree_not_clone() -> None:
svc = _service()
task_id = uuid4()
short = str(task_id)[:8]
clone = Path("/tmp/ws")
worktree = clone / ".worktrees" / short
task = _task(branch="feature/backend/abc12345", task_id=task_id)
state = _stub_rebase_common(svc, clone)
object.__setattr__(
svc, "_parse_github_remote", MagicMock(return_value=RepoRef("owner", "repo"))
)
object.__setattr__(
svc,
"_get_pr_refs",
AsyncMock(return_value=("feature/backend/abc12345", "master")),
)
# rebase_pr_for_task loads the task from the DB by (pr_number, project_id).
session = MagicMock()
result = MagicMock()
result.scalar_one_or_none.return_value = task
session.execute = AsyncMock(return_value=result)
svc.session = session
await svc.rebase_pr_for_task(pr_number=42, project_id=uuid4())
ensure = object.__getattribute__(svc, "_ensure_worktree_for_commit")
ensure.assert_awaited_once()
assert ensure.await_args.args[1] == worktree
assert state["cwds"], "rebase git ops must run"
assert all(c == worktree for c in state["cwds"]), (
f"all rebase git ops must run in the worktree {worktree}; got {state['cwds']}"
)
# --- conventions: validator --root points at the worktree, not the clone ---
@pytest.mark.asyncio
async def test_conventions_check_runs_validator_in_worktree_not_clone() -> None:
svc = _service()
task_id = uuid4()
short = str(task_id)[:8]
clone = Path("/tmp/ws")
worktree = clone / ".worktrees" / short
task = _task(branch="feature/backend/abc12345", task_id=task_id)
object.__setattr__(svc, "_workspace_for_branch", AsyncMock(return_value=clone))
object.__setattr__(
svc, "list_changed_files", AsyncMock(return_value=["src/foo.py"])
)
object.__setattr__(svc, "_ensure_worktree_for_commit", AsyncMock())
captured: list[Path] = []
async def _capture_validator(
workspace: Path, _files: list[str], **_kwargs: object
) -> dict[str, object]:
captured.append(Path(workspace))
return {"findings": [], "could_not_run": False}
object.__setattr__(
svc, "_run_conventions_validator", AsyncMock(side_effect=_capture_validator)
)
await svc.conventions_check_for_task(actor_agent_id=uuid4(), task=task)
ensure = object.__getattribute__(svc, "_ensure_worktree_for_commit")
ensure.assert_awaited_once()
assert ensure.await_args.args[1] == worktree
assert captured, "validator must run"
assert captured[0] == worktree, (
f"validator --root must be the worktree {worktree}, not the clone root; "
f"got {captured[0]}"
)