Skip to content
Prev Previous commit
Next Next commit
fix: Record a merge only when it is on the default branch (review rou…
…nd 1)

Unit: merge-must-land-on-the-default-branch/1
  • Loading branch information
bwmatson committed Nov 17, 2026
commit 681bd0fe1d7d3f222ce578f3ae198caac7eb9e57
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ A standing cause names a situation that lasts until a state change passes anothe
`base_changed`, `upstream_went_back`, `usage`, `login`, `depth`, `toolchain`, `review_escalated_class`,
`review_escalated_disagreement`, `late_failure`, `needs_human`, `reviewer_hold`, `gated`, `restack_conflict`,
`restack_deferred`, `restack_handed_back`, `dirty_worktree`, `attached`, `host_unavailable`,
`network_unavailable`, `service_unavailable`, `environment`, `split_held`, `manual_step` and
`network_unavailable`, `service_unavailable`, `environment`, `split_held`, `manual_step`,
`too_big_for_tier` and `landed_off_default` (a pull request merged into a branch that is not the default branch).
An event cause names a transition that has happened and is over: `requeued`, `released`,
`adopted`, `merged`, `auto_landed`, `closed`, `retired`, `superseded` and `failed`. Recording an event cause ends a standing
Expand Down
1 change: 1 addition & 0 deletions src/agent_build_kit/cli/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -7079,6 +7079,7 @@ def dispatch_for(
that repo's turn. Also how a merge the poll has not reported yet is recorded."""
return build_dispatch(
store,
repos=inst.checkouts,
# A lane moves what the handlers hand it, and asks the guard before its resolver.
**build_stack_moves(
store,
Expand Down
84 changes: 57 additions & 27 deletions src/agent_build_kit/pipeline/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ def on_merged(
landing_path: Path | None = None,
merge_record: MergeRecord | None = None,
merge_commit: str | None = None,
landing: Landing | None = None,
landing: Callable[[], Landing | None] | None = None,
log: Log = print,
) -> bool:
"""Record the merge, move what was stacked on it, then clean up after it.
Expand All @@ -302,8 +302,9 @@ def on_merged(
unit already recorded merged changes nothing and returns True. `merge_commit` is the
commit the merge produced when the caller holds it (the merge's own answer, the listing's
snapshot), so the merge record does not ask the forge for it. `landing` says where the
merge went: one whose commit is not on the default branch is held (its base was a merged
unit's branch) or left settling with a note (its base was an open unit's branch).
merge went, asked only once a unit that is not yet merged is found: one whose commit is not
on the default branch is held (its base was a merged unit's branch) or left settling with a
note (its base was an open unit's branch).

False when the merged unit is itself being built — a rework someone
merged over — so the poller reports the merge again once it has finished.
Expand All @@ -316,21 +317,22 @@ def on_merged(
log(f"merged #{pr}: no unit recorded for it in {repo}, ignoring")
return True
note = ""
if landing is not None and not landing.on_default and merged.state != MERGED:
if landing.base == landing.default_branch:
log(f"merged #{pr}: {merged.id} not yet on {landing.default_branch}, will check again")
where = landing() if landing is not None and merged.state != MERGED else None
if where is not None and not where.on_default:
if where.base == where.default_branch:
log(f"merged #{pr}: {merged.id} not yet on {where.default_branch}, will check again")
return False
parent = next(
(
unit
for unit in store.all()
if unit.repo == merged.repo and unit.branch == landing.base and unit.id != merged.id
if unit.repo == merged.repo and unit.branch == where.base and unit.id != merged.id
),
None,
)
if parent is None or parent.state == MERGED:
return _hold_landed_off_default(store, merged, pr, landing, claim, resume, log)
note = f"merged into {landing.base}, which lands when {parent.id} does"
return _hold_landed_off_default(store, merged, pr, where, claim, resume, log)
note = f"merged into {where.base}, which lands when {parent.id} does"
if merged.state in (MERGED, SETTLING):
# The landing and the poller both report a merge, in either order: the
# second finds it recorded and moves, cleans and records nothing again.
Expand Down Expand Up @@ -386,15 +388,16 @@ def _hold_landed_off_default(
) -> bool:
"""Hold a unit whose pull request merged into a branch that is not the default branch: its
work is not on the default branch, so it is not recorded merged."""
note = (
f"#{pr} was merged into {landing.base}, not {landing.default_branch}: "
f"its commit is not on {landing.default_branch}"
)
try:
resume(merged, "merged", "", "")
# The hold goes to the unit's thread as a person's would: a merged event ends it.
taken = resume(merged, "hold", "", "")
with claim(merged):
note = (
f"#{pr} was merged into {landing.base}, not {landing.default_branch}: "
f"its commit is not on {landing.default_branch}"
)
store.set_state(merged.id, HELD, note=note, cause=Cause.LANDED_OFF_DEFAULT)
log(f"merged #{pr}: {merged.id} held — {note}")
log(f"merged #{pr}: {merged.id} held{' by its thread' if taken else ''} — {note}")
except BranchBusy as error:
return _deferred(f"merged #{pr}", merged, error, log)
return True
Expand All @@ -408,11 +411,14 @@ def on_settled(
claim: Claim = _unclaimed,
merge_record: MergeRecord | None = None,
merge_commit: str | None = None,
on_default: Callable[[StoredUnit], bool] | None = None,
log: Log = print,
) -> bool:
"""Every check of a settling unit's merged pull request has completed clean: the unit
becomes merged, with the tick that saw it settle. A unit not settling changes nothing.
`merge_commit` is the commit the listing's snapshot carries, if any."""
`merge_commit` is the commit the listing's snapshot carries, if any. `on_default` says
whether the unit's recorded commit is on the default branch: a unit whose commit is not
stays settling, with its note, until it is."""
unit = _find(store, repo, pr)
if unit is None or unit.state != SETTLING:
return True
Expand All @@ -421,6 +427,9 @@ def on_settled(
current = store.get(unit.id)
if current.state != SETTLING:
return True
if on_default is not None and not on_default(current):
log(f"settled #{pr}: {current.id} stays settling, its commit is not on the default")
return True
settle_merged(store, current, merge_record, merge_commit=merge_commit)
log(f"settled #{pr}: {current.id} merged, every check complete")
except BranchBusy as error:
Expand Down Expand Up @@ -1117,21 +1126,41 @@ def _commit_in_hand(event: dict[str, Any]) -> str | None:
return named or (pull.merge_commit if isinstance(pull, PullRequest) else None)


def _landing(repos: dict[str, Path] | None, repo: str, event: dict[str, Any]) -> Landing | None:
"""Where the event's merge went, when its commit and the repository's checkout are known."""
from agent_build_kit.config import active

def _landing(
repos: dict[str, Path] | None, repo: str, event: dict[str, Any]
) -> Callable[[], Landing | None] | None:
"""Where the event's merge went, asked for when needed (it fetches), and only when its
commit and the repository's checkout are known. The protection depends on the event
carrying the commit."""
pull = event.get("pull")
sha = _commit_in_hand(event)
if repos is None or repo not in repos or sha is None or not isinstance(pull, PullRequest):
return None
entry = active().repos.get(repo)
default = entry.default_branch if entry is not None else "main"
return Landing(
base=pull.base,
default_branch=default,
on_default=merged_on_default(repos[repo], sha, default),
)
checkout, base = repos[repo], pull.base

def where() -> Landing:
default = trunk_of(repo)
return Landing(
base=base,
default_branch=default,
on_default=merged_on_default(checkout, sha, default),
)

return where


def _unit_on_default(repos: dict[str, Path] | None) -> Callable[[StoredUnit], bool] | None:
"""Whether a unit's recorded merge commit is on its repo's default branch; a unit with no
recorded commit or no checkout is taken as being there, as nothing can say otherwise."""
if repos is None:
return None

def on_default(unit: StoredUnit) -> bool:
if not unit.merge_sha or unit.repo not in repos:
return True
return merged_on_default(repos[unit.repo], unit.merge_sha, trunk_of(unit.repo))

return on_default


def _with_merge(unit: StoredUnit, sha: str | None) -> tuple[Pull, ...]:
Expand Down Expand Up @@ -2765,6 +2794,7 @@ def dispatch(event: str, number: int, *, repo: str, **kwargs) -> bool:
claim=claim,
merge_record=merge_record,
merge_commit=_commit_in_hand(kwargs),
on_default=_unit_on_default(repos),
log=log,
)
if event == "late_check":
Expand Down
74 changes: 61 additions & 13 deletions tests/pipeline/test_merge_landing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import pytest

from agent_build_kit.cli import pipeline as cli
from agent_build_kit.forges.base import PullRequest
from agent_build_kit.pipeline import events
from agent_build_kit.pipeline.landing_check import merged_on_default
Expand All @@ -28,11 +29,11 @@
class Repos:
"""An origin and a clone with `main`, and a parent branch pushed beside it."""

def __init__(self, root: Path) -> None:
def __init__(self, root: Path, clone: Path | None = None) -> None:
self.origin = root / "origin.git"
self.origin.mkdir(parents=True)
git(self.origin, "init", "-q", "--bare", "-b", "main")
self.clone = init_repo(root / "clone")
self.clone = init_repo(clone or root / "clone")
git(self.clone, "remote", "add", "origin", str(self.origin))
commit(self.clone, "base")
git(self.clone, "push", "-q", "origin", "main")
Expand All @@ -58,9 +59,11 @@ def land_on_parent(self) -> str:


class World:
def __init__(self, tmp_path: Path, *, parent_state) -> None:
make_installation(tmp_path / "inst")
self.repos = Repos(tmp_path / "git")
def __init__(
self, tmp_path: Path, *, parent_state, resume=None, production: bool = False
) -> None:
inst = make_installation(tmp_path / "inst")
self.repos = Repos(tmp_path / "git", clone=inst.checkouts["app"])
self.store = UnitStore(tmp_path / "units.json")
self.store.upsert(
[
Expand All @@ -72,13 +75,17 @@ def __init__(self, tmp_path: Path, *, parent_state) -> None:
self.store.set_state(PARENT, parent_state, pr=1, branch=f"spec/{PARENT}")
self.store.set_state(CHILD, IN_REVIEW, pr=PR, branch=f"spec/{CHILD}")
self.log: list[str] = []
self.dispatch = events.build_dispatch(
self.store,
restack=lambda **k: None,
merge_record=lambda unit: (unit.merge_sha, None),
repos={"app": self.repos.clone},
log=self.log.append,
)
if production:
self.dispatch = cli.dispatch_for(inst, self.store)
else:
self.dispatch = events.build_dispatch(
self.store,
restack=lambda **k: None,
merge_record=lambda unit: (unit.merge_sha, None),
repos={"app": self.repos.clone},
**({"resume": resume} if resume else {}),
log=self.log.append,
)

def merged_into(self, base: str, sha: str | None):
pull = PullRequest(
Expand Down Expand Up @@ -184,7 +191,7 @@ def test_a_merge_into_an_open_units_branch_leaves_the_unit_settling_with_a_note(
assert PARENT in unit.note


def test_a_unit_with_no_merge_commit_stays_settling_until_it_is_known_off_default(
def test_a_unit_whose_listing_has_no_commit_stays_settling_until_a_report_carries_one(
merged_parent: World,
) -> None:
merged_parent.merged_into(f"spec/{PARENT}", None)
Expand All @@ -202,3 +209,44 @@ def test_the_dependents_of_a_held_unit_keep_waiting_for_it(merged_parent: World)

assert merged_parent.store.get(CHILD).state == HELD
assert merged_parent.waiting() == [CHILD]


def test_the_production_dispatch_holds_a_merge_into_a_merged_units_branch(
tmp_path: Path,
) -> None:
world = World(tmp_path, parent_state=MERGED, production=True)

world.merged_into(f"spec/{PARENT}", world.repos.land_on_parent())

unit = world.store.get(CHILD)
assert (unit.state, unit.cause) == (HELD, Cause.LANDED_OFF_DEFAULT)


def test_a_merge_into_a_merged_units_branch_reaches_the_unit_thread_as_a_hold(
tmp_path: Path,
) -> None:
delivered: list[str] = []

def resume(unit, kind, *rest) -> bool:
delivered.append(kind)
return True

world = World(tmp_path, parent_state=MERGED, resume=resume)

world.merged_into(f"spec/{PARENT}", world.repos.land_on_parent())

assert delivered == ["hold"]
assert world.store.get(CHILD).cause == Cause.LANDED_OFF_DEFAULT


def test_a_unit_merged_into_an_open_units_branch_stays_settling_when_its_checks_complete(
open_parent: World,
) -> None:
open_parent.merged_into(f"spec/{PARENT}", open_parent.repos.land_on_parent())

open_parent.dispatch("settled", PR, repo="app")

unit = open_parent.store.get(CHILD)
assert unit.state == SETTLING
assert "lands when" in unit.note
assert CHILD in open_parent.waiting()