From b6ecd8d7d9966475f7db52892ba5dbab31112ca8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 24 Oct 2026 14:18:39 -0400 Subject: [PATCH 1/7] Registry: compare a pull request's own commits from its fork point history_problems started every walk from the registry at base. On a pull_request event the base is the merge base with master, so once #560 landed, every open pull request branched before it reported each of its own commits as deleting the registry. Any pull request branched after it reported its commits too, as soon as master added an entry: each own commit lacks the entries master added since the fork. The walk now starts from the registry at the first listed commit's first parent, where the listed commits leave landed history: a pull request's fork point. At a merge whose other parent brings in landed history (an ancestor of base that the first parent lacks), the predecessor becomes that parent's registry, and the merge must extend it. A merge bringing in more than one line of landed history is reported. A git failure while reading parents or ancestry raises LookupError. On a push to the base branch the first listed commit's first parent is the before commit, as before. Tests: a pull request from before the registry, unmerged and after a master merge; one built on the registry while master grows; own commits after a master merge that rewrite, delete or drop a landed entry, and a merge that drops one; modify-then-restore on a pull request; a merge of unlanded history; two landed lines; injected git failures; and a property test over generated commit graphs that only the own commits whose registry removes or rewrites an entry of their predecessor are reported. Tiers: unit 18,271 (+17). Co-Authored-By: Claude Opus 5.5 --- .../track_b/holdout_registry.py | 95 +++++- tests/README-tiers.md | 4 +- tests/test_track_b_holdout_registry.py | 318 ++++++++++++++++++ tests/tier_counts.json | 2 +- 4 files changed, 403 insertions(+), 16 deletions(-) diff --git a/src/populace_dynamics/track_b/holdout_registry.py b/src/populace_dynamics/track_b/holdout_registry.py index fd2f7e8b..97a24b17 100644 --- a/src/populace_dynamics/track_b/holdout_registry.py +++ b/src/populace_dynamics/track_b/holdout_registry.py @@ -39,7 +39,9 @@ consecutive first-parent commits since it (each snapshot validated against its own commit's tree), and between a pull request's own commits, an entry's identity and units never change and its lists only - extend. A newly created registry is admitted against an empty one; + extend. A pull request's own commits are compared from its fork point, + and a merge that brings in landed history extends that history's + registry. A newly created registry is admitted against an empty one; - the registry stays incomplete until its completion record, B0.2's mechanical exposure inventory, exists. @@ -1178,6 +1180,44 @@ def _commit(repository: Path, ref: str) -> str | None: return found.stdout.strip() if found.returncode == 0 else None +def _parents(repository: Path, commit: str) -> list[str]: + """``commit``'s parents, first parent first. Raises ``LookupError`` + when git cannot list them.""" + found = _git(repository, "rev-list", "--parents", "-n", "1", commit) + listed = found.stdout.split() + if found.returncode != 0 or listed[:1] != [commit]: + raise LookupError(f"cannot list the parents of {str(commit)[:80]}") + return listed[1:] + + +def _is_ancestor(repository: Path, ancestor: str, descendant: str) -> bool: + """Whether ``ancestor`` is an ancestor of ``descendant`` (or the same + commit). Raises ``LookupError`` when git cannot answer.""" + found = _git( + repository, "merge-base", "--is-ancestor", ancestor, descendant + ) + if found.returncode not in (0, 1): + raise LookupError( + f"cannot tell whether {str(ancestor)[:80]} is an ancestor of " + f"{str(descendant)[:80]}" + ) + return found.returncode == 0 + + +def _landed_parents(repository: Path, commit: str, base: str) -> list[str]: + """The parents through which a merge ``commit`` brings in landed + history: each parent after the first that is an ancestor of ``base`` + and not already an ancestor of the first parent. Empty for a commit + that is not a merge.""" + parents = _parents(repository, commit) + return [ + parent + for parent in parents[1:] + if _is_ancestor(repository, parent, base) + and not _is_ancestor(repository, parent, parents[0]) + ] + + def _event() -> Mapping[str, Any]: """The GitHub event payload at ``GITHUB_EVENT_PATH``. Raises ``LookupError`` when it cannot be read or is not a JSON object.""" @@ -1289,12 +1329,24 @@ def history_problems( ``head``, so a run of commits cannot hide a change a later commit undoes. + The walk starts from the registry at the first listed commit's first + parent: where these commits leave landed history, which for a pull + request's own commits is its fork point, not ``base``. A pull request + branched before the registry existed, or before ``base`` changed it, + is so compared with the registry it was built on. A merge whose other + parent brings in landed history (an ancestor of ``base`` that its + first parent lacks) is compared with that parent's registry instead, + and must extend it; a merge bringing in more than one line of landed + history is reported. + With ``full``, each snapshot is validated against its own commit's tree. A snapshot that fails is reported and is not used as the next - one's predecessor. Each valid snapshot must append only to the last - valid one; a newly created registry is admitted against an empty + one's predecessor. Each valid snapshot must append only to its + predecessor: the last valid one, or the landed registry a merge + brings in. A newly created registry is admitted against an empty registry. Without ``full``, as for a pull request's own commits, only - the append-only rule is checked.""" + the append-only rule is checked. Raises ``LookupError`` when git + cannot list the commits, their parents or their ancestry.""" listed = _git( repository, "rev-list", @@ -1304,17 +1356,34 @@ def history_problems( ) if listed.returncode != 0: raise LookupError(f"cannot list commits from {base} to {head}") + commits = listed.stdout.split() problems: list[str] = [] - try: - previous = registry_at(repository, base) - except ValueError as error: - problems.append(f"{base[:12]}: {error}") - previous = None - if not isinstance(previous, Mapping): - previous = None - previous_commit = base - for commit in listed.stdout.split(): + + def landed_registry(commit: str) -> Mapping[str, Any] | None: + try: + found = registry_at(repository, commit) + except ValueError as error: + problems.append(f"{commit[:12]}: {error}") + return None + return found if isinstance(found, Mapping) else None + + previous_commit, previous = base, None + start = _parents(repository, commits[0])[:1] if commits else [base] + if start: + previous_commit = start[0] + previous = landed_registry(previous_commit) + for commit in commits: label = commit[:12] + landed = _landed_parents(repository, commit, base) + if len(landed) > 1: + problems.append( + f"{label}: a merge brings in more than one line of landed " + "history" + ) + continue + if landed: + previous_commit = landed[0] + previous = landed_registry(previous_commit) try: current = registry_at(repository, commit) except ValueError as error: diff --git a/tests/README-tiers.md b/tests/README-tiers.md index 52f601fc..611aa086 100644 --- a/tests/README-tiers.md +++ b/tests/README-tiers.md @@ -39,9 +39,9 @@ pytest --collect-only -q -m oracle_policyengine | tail -1 | Tier | Tests at HEAD | |---|---:| -| `unit` | 18,254 | +| `unit` | 18,271 | | `artifact` | 4,271 | | `integration_psid` | 1,450 | | `reproduction_legacy` | 520 | | `oracle_policyengine` | 308 | -| **Total** | **24,803** | +| **Total** | **24,820** | diff --git a/tests/test_track_b_holdout_registry.py b/tests/test_track_b_holdout_registry.py index 2deea18c..aaac2148 100644 --- a/tests/test_track_b_holdout_registry.py +++ b/tests/test_track_b_holdout_registry.py @@ -1307,6 +1307,324 @@ def test_a_run_of_commits_cannot_hide_a_change_it_undoes( assert registry.history_problems(repository, base, full=full, imports={}) +# A pull request's own commits, from its fork point ----------------------- + + +def branch(repository: Path, name: str) -> None: + git(repository, "checkout", "-q", "-b", name) + + +def switch(repository: Path, name: str) -> None: + git(repository, "checkout", "-q", name) + + +def merge_with(repository: Path, other: str, resolution) -> str: + """Merge ``other`` into the current branch, resolving the registry to + ``resolution`` (``None`` leaves no registry).""" + git( + repository, + "merge", + "-q", + "--no-ff", + "--no-commit", + "-s", + "ours", + other, + ) + path = repository / registry.REGISTRY + if resolution is not None: + write(repository, registry.REGISTRY, resolution) + elif path.exists(): + path.unlink() + return commit_all(repository, f"merge {other}") + + +def grown(document, *indices: int) -> dict: + """``document`` (or a new registry) with a lone candidate appended + for each index.""" + entries = [make_entry(index, [f"s_c:{2000 + index}"]) for index in indices] + if document is None: + return make_registry(entries) + document = copy.deepcopy(document) + document["entries"].extend(entries) + return document + + +def own_work(repository: Path, text: str) -> str: + write(repository, "notes.md", text) + return commit_all(repository, text) + + +def reported(problems: list[str]) -> set[str]: + """The commits, as 12-character labels, that ``problems`` name.""" + return {problem.split(": ", 1)[0].split("..")[-1] for problem in problems} + + +def head_of(repository: Path) -> str: + return git(repository, "rev-parse", "HEAD").strip() + + +@pytest.mark.parametrize("merged", [False, True]) +def test_a_pull_request_from_before_the_registry_passes( + tmp_path, no_ci_env, merged +): + """A pull request branched before the registry existed has own + commits without one. They are compared from the fork point, which + had none, not with the base, which has one; a master merge brings + the landed registry in unchanged.""" + repository = init_repository(tmp_path) + branch(repository, "pr") + own_work(repository, "one") + own_work(repository, "two") + switch(repository, "master") + commit_registry(repository, registered(["candidate"]), "registry lands") + landed = grown(registered(["candidate"]), 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + if merged: + merge_with(repository, "master", landed) + own_work(repository, "three") + problems = registry.history_problems( + repository, base, head_of(repository), full=False + ) + assert problems == [] + + +@pytest.mark.parametrize("merged", [False, True]) +def test_a_pull_request_passes_while_master_grows(tmp_path, no_ci_env, merged): + """A pull request that adds its own registration is compared with + the registry it was built on, not with a base that has since added + others; a master merge must keep the landed entries first.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + commit_registry(repository, grown(first, 5), "own registration") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + if merged: + merge_with(repository, "master", grown(landed, 5)) + own_work(repository, "after the merge") + problems = registry.history_problems( + repository, base, head_of(repository), full=False + ) + assert problems == [] + + +@pytest.mark.parametrize( + "change", ["rewrite", "delete", "drop_landed", "merge_drops_landed"] +) +def test_own_commits_after_a_master_merge_are_checked( + tmp_path, no_ci_env, change +): + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + own_work(repository, "own") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + if change == "merge_drops_landed": + bad = merge_with(repository, "master", first) + else: + merge_with(repository, "master", landed) + if change == "rewrite": + rewritten = copy.deepcopy(landed) + rewritten["entries"][0]["unit_keys"] = ["s_c:2199"] + bad = commit_registry(repository, rewritten, "rewrite") + elif change == "delete": + git(repository, "rm", "-q", registry.REGISTRY) + bad = commit_all(repository, "delete") + else: + bad = commit_registry(repository, first, "drop a landed entry") + commit_registry(repository, landed, "restore") + problems = registry.history_problems( + repository, base, head_of(repository), full=False + ) + assert reported(problems) == {bad[:12]} + + +@pytest.mark.parametrize("merged", [False, True]) +def test_a_pull_request_cannot_hide_a_change_it_undoes( + tmp_path, no_ci_env, merged +): + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + built_on = first + if merged: + merge_with(repository, "master", landed) + built_on = landed + changed = copy.deepcopy(built_on) + changed["entries"][0]["unit_keys"] = ["s_c:2199"] + bad = commit_registry(repository, changed, "change") + commit_registry(repository, built_on, "undo") + problems = registry.history_problems( + repository, base, head_of(repository), full=False + ) + assert reported(problems) == {bad[:12]} + + +@pytest.mark.parametrize("keeps_own_order", [True, False]) +def test_a_merge_of_unlanded_history_extends_its_own_predecessor( + tmp_path, no_ci_env, keeps_own_order +): + """Only landed history (an ancestor of the base) replaces a merge's + predecessor. Another unlanded branch is not trusted: the merge must + extend the pull request's own last registry.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + base = commit_registry(repository, first, "registry") + branch(repository, "side") + commit_registry(repository, grown(first, 7), "side registration") + switch(repository, "master") + branch(repository, "pr") + commit_registry(repository, grown(first, 5), "own registration") + resolution = grown(first, 5, 7) if keeps_own_order else grown(first, 7, 5) + merge = merge_with(repository, "side", resolution) + problems = registry.history_problems( + repository, base, head_of(repository), full=False + ) + assert reported(problems) == (set() if keeps_own_order else {merge[:12]}) + + +def test_a_merge_of_two_landed_lines_is_reported(tmp_path, no_ci_env): + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + own_work(repository, "own") + switch(repository, "master") + older = commit_registry(repository, grown(first, 1), "master grows") + base = commit_registry(repository, grown(first, 1, 2), "and again") + switch(repository, "pr") + tree = git(repository, "rev-parse", "HEAD^{tree}").strip() + octopus = git( + repository, + "commit-tree", + tree, + "-p", + "HEAD", + "-p", + older, + "-p", + base, + "-m", + "octopus", + ).strip() + git(repository, "update-ref", "refs/heads/pr", octopus) + problems = registry.history_problems(repository, base, octopus, full=False) + assert any("more than one line of landed history" in p for p in problems) + assert reported(problems) == {octopus[:12]} + + +@pytest.mark.parametrize( + "flag, code", + [("--parents", 128), ("--parents", 0), ("--is-ancestor", 128)], +) +def test_unreadable_parents_or_ancestry_raise( + tmp_path, no_ci_env, monkeypatch, flag, code +): + """A git failure while reading a commit's parents or ancestry raises + ``LookupError`` rather than choose a predecessor by default.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + own_work(repository, "own") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + merge_with(repository, "master", landed) + head = head_of(repository) + assert registry.history_problems(repository, base, head, full=False) == [] + real = registry._git + + def failing(repo, *args): + if flag in args: + return subprocess.CompletedProcess(args, code, "", "injected") + return real(repo, *args) + + monkeypatch.setattr(registry, "_git", failing) + with pytest.raises(LookupError): + registry.history_problems(repository, base, head, full=False) + + +PR_STEPS = st.lists( + st.sampled_from( + ["master", "own", "noop", "rewrite", "delete", "restore", "merge"] + ), + max_size=7, +) + + +@settings(max_examples=25, deadline=None) +@given(registered_first=st.booleans(), steps=PR_STEPS) +def test_only_commits_that_remove_or_rewrite_entries_are_reported( + tmp_path_factory, registered_first, steps +): + """Over generated graphs of master commits, own commits and master + merges, the pull request's own commits that are reported are exactly + those whose registry removes or rewrites an entry of its predecessor + (the last valid own registry, or the landed one a merge brings in).""" + repository = init_repository(tmp_path_factory.mktemp("graph")) + landed = registered(["candidate"]) if registered_first else None + if landed is not None: + commit_registry(repository, landed, "registry") + branch(repository, "pr") + valid, own, broken, behind, index = landed, [], False, False, 0 + expected = set() + for step in steps: + index += 1 + if step == "master": + switch(repository, "master") + landed = grown(landed, 100 + index) + commit_registry(repository, landed, "master grows") + switch(repository, "pr") + behind = True + continue + if step == "rewrite" and valid is not None and valid["entries"]: + rewritten = copy.deepcopy(valid) + rewritten["entries"][0]["unit_keys"] = ["s_c:2199"] + commit = commit_registry(repository, rewritten, "rewrite") + broken = True + elif step == "delete" and valid is not None: + git(repository, "rm", "-q", "--ignore-unmatch", registry.REGISTRY) + commit = commit_all(repository, "delete") + broken = True + elif step == "own": + valid = grown(valid, index) + own.append(index) + commit = commit_registry(repository, valid, "own registration") + broken = False + elif step == "restore" and valid is not None: + commit = commit_registry(repository, valid, "restore") + broken = False + elif step == "merge" and behind: + valid = grown(landed, *own) if landed is not None else valid + commit = merge_with(repository, "master", valid) + broken, behind = False, False + else: + commit = own_work(repository, f"note {index}") + if broken: + expected.add(commit[:12]) + switch(repository, "master") + base = head_of(repository) + head = git(repository, "rev-parse", "pr").strip() + problems = registry.history_problems(repository, base, head, full=False) + assert reported(problems) == expected + + def test_a_pull_request_head_is_read_from_its_event(tmp_path, monkeypatch): event = tmp_path / "event.json" sha = "a" * 40 diff --git a/tests/tier_counts.json b/tests/tier_counts.json index ea9b7fb1..f045f880 100644 --- a/tests/tier_counts.json +++ b/tests/tier_counts.json @@ -1,7 +1,7 @@ { "schema_version": 1, "counts": { - "unit": 18254, + "unit": 18271, "artifact": 4271, "integration_psid": 1450, "reproduction_legacy": 520, From ff29e5e76a83efaf334998a2f0623fd24068ec4f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 24 Oct 2026 16:17:20 -0400 Subject: [PATCH 2/7] Registry tests: cover three guards a targeted mutation run left untested Eleven targeted mutants of b6ecd8d7's new lines; eight were killed. These tests kill the other three. src/ is unchanged. - test_a_merge_of_contained_history_keeps_its_own_predecessor: a crafted merge of the fork point, already in its first parent, drops an entry a master merge brought in, and a later commit restores it. Without the guard that such a parent brings nothing in, the merge would be compared with the fork's older registry and pass. - test_a_first_commit_that_merges_unlanded_history_starts_at_the_fork: the walk starts from the first listed commit's first parent, so a rewrite carried by an unlanded branch that the first commit merges is reported at the merge. - test_an_unreadable_predecessor_is_reported: a non-JSON registry at the fork point or at a landed parent a merge brings in is reported under its commit. All 11 mutants are now killed. Tiers: unit 18,275 (+4). Co-Authored-By: Claude Opus 5.5 --- tests/README-tiers.md | 4 +- tests/test_track_b_holdout_registry.py | 93 ++++++++++++++++++++++++++ tests/tier_counts.json | 2 +- 3 files changed, 96 insertions(+), 3 deletions(-) diff --git a/tests/README-tiers.md b/tests/README-tiers.md index 611aa086..193a0f7d 100644 --- a/tests/README-tiers.md +++ b/tests/README-tiers.md @@ -39,9 +39,9 @@ pytest --collect-only -q -m oracle_policyengine | tail -1 | Tier | Tests at HEAD | |---|---:| -| `unit` | 18,271 | +| `unit` | 18,275 | | `artifact` | 4,271 | | `integration_psid` | 1,450 | | `reproduction_legacy` | 520 | | `oracle_policyengine` | 308 | -| **Total** | **24,820** | +| **Total** | **24,824** | diff --git a/tests/test_track_b_holdout_registry.py b/tests/test_track_b_holdout_registry.py index aaac2148..e2a1a1ce 100644 --- a/tests/test_track_b_holdout_registry.py +++ b/tests/test_track_b_holdout_registry.py @@ -1497,6 +1497,99 @@ def test_a_merge_of_unlanded_history_extends_its_own_predecessor( assert reported(problems) == (set() if keeps_own_order else {merge[:12]}) +def test_a_merge_of_contained_history_keeps_its_own_predecessor( + tmp_path, no_ci_env +): + """A merge whose other parent is landed but already in its first + parent brings nothing in, so it does not reset the predecessor to that + older registry. Otherwise a crafted merge of the fork point could drop + an entry a master merge brought in, and a later commit restore it, + unseen.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + fork = commit_registry(repository, first, "registry") + branch(repository, "pr") + own_work(repository, "own") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + merge_with(repository, "master", landed) + write(repository, registry.REGISTRY, first) + git(repository, "add", "-A") + tree = git(repository, "write-tree").strip() + crafted = git( + repository, + "commit-tree", + tree, + "-p", + "HEAD", + "-p", + fork, + "-m", + "merge the fork point again, dropping a landed entry", + ).strip() + git(repository, "reset", "-q", "--hard", crafted) + commit_registry(repository, landed, "restore") + problems = registry.history_problems( + repository, base, head_of(repository), full=False + ) + assert reported(problems) == {crafted[:12]} + + +def test_a_first_commit_that_merges_unlanded_history_starts_at_the_fork( + tmp_path, no_ci_env +): + """The walk starts from the first listed commit's first parent. When + that commit merges an unlanded branch, the branch's registry is not + the predecessor, so a rewrite the branch carries is reported at the + merge.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + base = commit_registry(repository, first, "registry") + branch(repository, "side") + rewritten = copy.deepcopy(first) + rewritten["entries"][0]["unit_keys"] = ["s_c:2199"] + commit_registry(repository, rewritten, "side rewrites an entry") + switch(repository, "master") + branch(repository, "pr") + merge = merge_with(repository, "side", rewritten) + problems = registry.history_problems( + repository, base, head_of(repository), full=False + ) + assert reported(problems) == {merge[:12]} + + +@pytest.mark.parametrize("where", ["fork", "landed_merge"]) +def test_an_unreadable_predecessor_is_reported(tmp_path, no_ci_env, where): + """A predecessor registry that is not JSON, at the fork point or at a + landed parent a merge brings in, is reported under its commit.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + if where == "fork": + write(repository, registry.REGISTRY, "not json") + unreadable = commit_all(repository, "an unreadable registry") + else: + commit_registry(repository, first, "registry") + branch(repository, "pr") + commit_registry(repository, first, "own registry") + switch(repository, "master") + if where == "landed_merge": + write(repository, registry.REGISTRY, "not json") + base = own_work(repository, "master moves on") + switch(repository, "pr") + if where == "landed_merge": + unreadable = base + merge_with(repository, "master", first) + problems = registry.history_problems( + repository, base, head_of(repository), full=False + ) + assert any( + p.startswith(f"{unreadable[:12]}: ") and "is not JSON" in p + for p in problems + ) + + def test_a_merge_of_two_landed_lines_is_reported(tmp_path, no_ci_env): repository = init_repository(tmp_path) first = registered(["candidate"]) diff --git a/tests/tier_counts.json b/tests/tier_counts.json index f045f880..a5d94610 100644 --- a/tests/tier_counts.json +++ b/tests/tier_counts.json @@ -1,7 +1,7 @@ { "schema_version": 1, "counts": { - "unit": 18271, + "unit": 18275, "artifact": 4271, "integration_psid": 1450, "reproduction_legacy": 520, From aa769ab7e5c1ed90ca0f64c7c74e97fef7f521fb Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 24 Oct 2026 17:19:25 -0400 Subject: [PATCH 3/7] Registry: keep both lines at a landed merge; pushes start at before Round-1 review fixes for #582. - A merge among a pull request's own commits that brings in landed history is compared with the union of its own predecessor and the landed parent's registry (_landed_union), not with the landed registry alone. A stale landed branch (another pull request's tip, which lacks master's later growth) can no longer drop an entry the pull request held, and a merge cannot drop the pull request's own registration or its additions to a landed entry. Entries and rules are ordered as the base registry lists them, then the pull request's, then the landed line's, so a landed branch whose own registry is [H001, H003] is merged in master's [H001, H002, H003] order. Fields that differ, and lists that each extend beyond the other, are reported at the merge. - The fork-point start and landed-merge handling apply only with the new pull_request=True, which the committed pull-request check passes. Push walks (pull_request=False) start at the event's before commit and chain first parents, exactly as on master, so a push whose before commit is not on the tip's first-parent line is still checked from it. - Tests: Sol's stale-branch, landed-order and push scenarios as regressions; own extensions kept, dropped and diverged; a dropped own entry; an octopus of a landed and a contained parent (one line); the first-commit start with an unlanded addition; the union's order, sources, rules and conflicts. The property test now generates multi-merge graphs with stale landed side branches (each merge step builds what it merges; 2/3 of examples have 3+ merges). - Tier counts: +16 unit tests (18,291 unit, 24,840 total). Co-Authored-By: Claude Opus 5.5 --- .../track_b/holdout_registry.py | 180 +++++-- tests/README-tiers.md | 4 +- tests/test_track_b_holdout_registry.py | 448 ++++++++++++++++-- ...test_track_b_holdout_registry_committed.py | 7 +- tests/tier_counts.json | 2 +- 5 files changed, 565 insertions(+), 76 deletions(-) diff --git a/src/populace_dynamics/track_b/holdout_registry.py b/src/populace_dynamics/track_b/holdout_registry.py index 97a24b17..9bda5a45 100644 --- a/src/populace_dynamics/track_b/holdout_registry.py +++ b/src/populace_dynamics/track_b/holdout_registry.py @@ -40,8 +40,9 @@ against its own commit's tree), and between a pull request's own commits, an entry's identity and units never change and its lists only extend. A pull request's own commits are compared from its fork point, - and a merge that brings in landed history extends that history's - registry. A newly created registry is admitted against an empty one; + and a merge among them that brings in landed history keeps every entry + of both lines. A newly created registry is admitted against an empty + one; - the registry stays incomplete until its completion record, B0.2's mechanical exposure inventory, exists. @@ -1218,6 +1219,113 @@ def _landed_parents(repository: Path, commit: str, base: str) -> list[str]: ] +def _union_ready(document: Any) -> bool: + """Whether ``document`` has the lists and mappings + :func:`_landed_union` combines.""" + return ( + isinstance(document, Mapping) + and isinstance(document.get("rules", []), list) + and isinstance(document.get("sources", {}), Mapping) + and isinstance(document.get("entries"), list) + and all( + isinstance(entry, Mapping) and isinstance(entry.get("id"), str) + for entry in document["entries"] + ) + ) + + +def _in_order(order: list, *groups: list) -> list: + """The keys in ``groups``, each once: those ``order`` lists, in its + order, then the rest in the order the groups give them.""" + present = set().union(*groups) + ranked = [key for key in dict.fromkeys(order) if key in present] + return list(dict.fromkeys([*ranked, *(key for g in groups for key in g)])) + + +def _landed_union( + previous: Any, incoming: Any, canonical: Any +) -> tuple[Any, list[str]]: + """The registry a merge that brings in landed history must extend. + + It holds every rule, source and entry of ``previous``, the pull + request's last valid registry, and of ``incoming``, the landed + parent's, each entry once with each list at the longer of its two + versions. Entries and rules that ``canonical``, the base's registry, + lists come first, in its order (the landed order; a landed side + branch's own registry need not follow it), then ``previous``'s others, + then ``incoming``'s. Also returns the conflicts that no merge could + resolve: a field that differs, or a list where neither version + extends the other. + + When either registry is missing, the other is returned. When either + lacks those lists and mappings, ``incoming`` is returned, as before + this union, for the append-only rule to report.""" + if previous is None or incoming is None: + return (incoming if previous is None else previous), [] + if not (_union_ready(previous) and _union_ready(incoming)): + return incoming, [] + conflicts: list[str] = [] + union = dict(incoming) + for key in ("schema", "status_values", "completion_record"): + if previous.get(key) != incoming.get(key): + conflicts.append(f"registry: {key} differs from the landed one") + sources = dict(incoming.get("sources", {})) + for source, declared in previous.get("sources", {}).items(): + if source in sources and sources[source] != declared: + conflicts.append( + f"source {source!r}: differs from the landed registry" + ) + sources.setdefault(source, declared) + union["sources"] = sources + if previous.get("complete") is True: + union["complete"] = True + order = canonical if _union_ready(canonical) else {} + + def text(rule: Any) -> str: + return json.dumps(rule, sort_keys=True) + + rules = { + text(rule): rule + for document in (incoming, previous) + for rule in document.get("rules", []) + } + union["rules"] = [ + rules[key] + for key in _in_order( + [text(rule) for rule in order.get("rules", [])], + [text(rule) for rule in previous.get("rules", [])], + [text(rule) for rule in incoming.get("rules", [])], + ) + ] + mine = {entry["id"]: entry for entry in previous["entries"]} + theirs = {entry["id"]: entry for entry in incoming["entries"]} + entries = [] + for name in _in_order( + [entry.get("id") for entry in order.get("entries", [])], + list(mine), + list(theirs), + ): + if name not in theirs or name not in mine: + entries.append(theirs.get(name, mine.get(name))) + continue + entry = dict(theirs[name]) + for key in IMMUTABLE: + if mine[name].get(key) != theirs[name].get(key): + conflicts.append(f"{name}: {key} differs from the landed one") + for key in EXTENDING: + ours, landed = mine[name].get(key, []), theirs[name].get(key, []) + if _extends(landed, ours): + entry[key] = ours + elif not _extends(ours, landed): + conflicts.append( + f"{name}: {key} and the landed {key} each extend " + "beyond the other" + ) + entries.append(entry) + union["entries"] = entries + return union, conflicts + + def _event() -> Mapping[str, Any]: """The GitHub event payload at ``GITHUB_EVENT_PATH``. Raises ``LookupError`` when it cannot be read or is not a JSON object.""" @@ -1322,6 +1430,7 @@ def history_problems( head: str = "HEAD", *, full: bool = True, + pull_request: bool = False, scored_runs: Mapping[str, tuple[str, str]] = SCORED_RUNS, imports: Mapping[str, Mapping[str, Any]] = HISTORICAL_IMPORTS, ) -> list[str]: @@ -1329,24 +1438,28 @@ def history_problems( ``head``, so a run of commits cannot hide a change a later commit undoes. - The walk starts from the registry at the first listed commit's first - parent: where these commits leave landed history, which for a pull - request's own commits is its fork point, not ``base``. A pull request - branched before the registry existed, or before ``base`` changed it, - is so compared with the registry it was built on. A merge whose other - parent brings in landed history (an ancestor of ``base`` that its - first parent lacks) is compared with that parent's registry instead, - and must extend it; a merge bringing in more than one line of landed - history is reported. + The walk starts from the registry at ``base``. With + ``pull_request``, for a pull request's own commits, it starts instead + from the registry at the first listed commit's first parent: the + pull request's fork point, where its commits leave landed history. A + pull request branched before the registry existed, or before + ``base`` changed it, is so compared with the registry it was built + on. A merge among those commits whose other parent brings in landed + history (an ancestor of ``base`` that its first parent lacks) is + compared with the union of its own predecessor and that parent's + registry (:func:`_landed_union`), so it keeps every entry either line + holds; a merge bringing in more than one line of landed history is + reported. Without ``pull_request``, as on a push, merges are not + treated apart, and nothing before ``base`` is trusted. With ``full``, each snapshot is validated against its own commit's tree. A snapshot that fails is reported and is not used as the next one's predecessor. Each valid snapshot must append only to its - predecessor: the last valid one, or the landed registry a merge - brings in. A newly created registry is admitted against an empty - registry. Without ``full``, as for a pull request's own commits, only - the append-only rule is checked. Raises ``LookupError`` when git - cannot list the commits, their parents or their ancestry.""" + predecessor: the last valid one, or the union a landed merge brings + in. A newly created registry is admitted against an empty registry. + Without ``full``, as for a pull request's own commits, only the + append-only rule is checked. Raises ``LookupError`` when git cannot + list the commits, their parents or their ancestry.""" listed = _git( repository, "rev-list", @@ -1367,14 +1480,24 @@ def landed_registry(commit: str) -> Mapping[str, Any] | None: return None return found if isinstance(found, Mapping) else None - previous_commit, previous = base, None - start = _parents(repository, commits[0])[:1] if commits else [base] + canonical = None + if pull_request: + try: + canonical = registry_at(repository, base) + except ValueError: + canonical = None + previous_label, previous = base[:12], None + start = [base] + if pull_request and commits: + start = _parents(repository, commits[0])[:1] if start: - previous_commit = start[0] - previous = landed_registry(previous_commit) + previous_label = start[0][:12] + previous = landed_registry(start[0]) for commit in commits: label = commit[:12] - landed = _landed_parents(repository, commit, base) + landed = ( + _landed_parents(repository, commit, base) if pull_request else [] + ) if len(landed) > 1: problems.append( f"{label}: a merge brings in more than one line of landed " @@ -1382,8 +1505,13 @@ def landed_registry(commit: str) -> Mapping[str, Any] | None: ) continue if landed: - previous_commit = landed[0] - previous = landed_registry(previous_commit) + previous, conflicts = _landed_union( + previous, landed_registry(landed[0]), canonical + ) + previous_label = f"{previous_label}+{landed[0][:12]}" + if conflicts: + problems.extend(f"{label}: {p}" for p in conflicts) + continue try: current = registry_at(repository, commit) except ValueError as error: @@ -1412,9 +1540,7 @@ def landed_registry(commit: str) -> Mapping[str, Any] | None: before = previous if previous is not None else empty_like(current) changes = append_only_problems(before, current) if changes: - problems.extend( - f"{previous_commit[:12]}..{label}: {p}" for p in changes - ) + problems.extend(f"{previous_label}..{label}: {p}" for p in changes) continue - previous_commit, previous = commit, current + previous_label, previous = label, current return problems diff --git a/tests/README-tiers.md b/tests/README-tiers.md index 193a0f7d..e2cf2709 100644 --- a/tests/README-tiers.md +++ b/tests/README-tiers.md @@ -39,9 +39,9 @@ pytest --collect-only -q -m oracle_policyengine | tail -1 | Tier | Tests at HEAD | |---|---:| -| `unit` | 18,275 | +| `unit` | 18,291 | | `artifact` | 4,271 | | `integration_psid` | 1,450 | | `reproduction_legacy` | 520 | | `oracle_policyengine` | 308 | -| **Total** | **24,824** | +| **Total** | **24,840** | diff --git a/tests/test_track_b_holdout_registry.py b/tests/test_track_b_holdout_registry.py index e2a1a1ce..ac1b8c29 100644 --- a/tests/test_track_b_holdout_registry.py +++ b/tests/test_track_b_holdout_registry.py @@ -19,7 +19,7 @@ from pathlib import Path import pytest -from hypothesis import given, settings +from hypothesis import event, given, settings, target from hypothesis import strategies as st from populace_dynamics.track_b import holdout_registry as registry @@ -1364,6 +1364,13 @@ def head_of(repository: Path) -> str: return git(repository, "rev-parse", "HEAD").strip() +def pr_problems(repository: Path, base: str, head: str) -> list[str]: + """The append-only problems in a pull request's own commits.""" + return registry.history_problems( + repository, base, head, full=False, pull_request=True + ) + + @pytest.mark.parametrize("merged", [False, True]) def test_a_pull_request_from_before_the_registry_passes( tmp_path, no_ci_env, merged @@ -1385,7 +1392,7 @@ def test_a_pull_request_from_before_the_registry_passes( merge_with(repository, "master", landed) own_work(repository, "three") problems = registry.history_problems( - repository, base, head_of(repository), full=False + repository, base, head_of(repository), full=False, pull_request=True ) assert problems == [] @@ -1408,7 +1415,7 @@ def test_a_pull_request_passes_while_master_grows(tmp_path, no_ci_env, merged): merge_with(repository, "master", grown(landed, 5)) own_work(repository, "after the merge") problems = registry.history_problems( - repository, base, head_of(repository), full=False + repository, base, head_of(repository), full=False, pull_request=True ) assert problems == [] @@ -1443,7 +1450,7 @@ def test_own_commits_after_a_master_merge_are_checked( bad = commit_registry(repository, first, "drop a landed entry") commit_registry(repository, landed, "restore") problems = registry.history_problems( - repository, base, head_of(repository), full=False + repository, base, head_of(repository), full=False, pull_request=True ) assert reported(problems) == {bad[:12]} @@ -1469,7 +1476,7 @@ def test_a_pull_request_cannot_hide_a_change_it_undoes( bad = commit_registry(repository, changed, "change") commit_registry(repository, built_on, "undo") problems = registry.history_problems( - repository, base, head_of(repository), full=False + repository, base, head_of(repository), full=False, pull_request=True ) assert reported(problems) == {bad[:12]} @@ -1492,7 +1499,7 @@ def test_a_merge_of_unlanded_history_extends_its_own_predecessor( resolution = grown(first, 5, 7) if keeps_own_order else grown(first, 7, 5) merge = merge_with(repository, "side", resolution) problems = registry.history_problems( - repository, base, head_of(repository), full=False + repository, base, head_of(repository), full=False, pull_request=True ) assert reported(problems) == (set() if keeps_own_order else {merge[:12]}) @@ -1532,32 +1539,39 @@ def test_a_merge_of_contained_history_keeps_its_own_predecessor( git(repository, "reset", "-q", "--hard", crafted) commit_registry(repository, landed, "restore") problems = registry.history_problems( - repository, base, head_of(repository), full=False + repository, base, head_of(repository), full=False, pull_request=True ) assert reported(problems) == {crafted[:12]} +@pytest.mark.parametrize("carried", ["rewrite", "addition"]) def test_a_first_commit_that_merges_unlanded_history_starts_at_the_fork( - tmp_path, no_ci_env + tmp_path, no_ci_env, carried ): """The walk starts from the first listed commit's first parent. When that commit merges an unlanded branch, the branch's registry is not - the predecessor, so a rewrite the branch carries is reported at the - merge.""" + the predecessor: a rewrite the branch carries is reported at the + merge, and an unlanded addition the merge leaves out is not.""" repository = init_repository(tmp_path) first = registered(["candidate"]) base = commit_registry(repository, first, "registry") branch(repository, "side") - rewritten = copy.deepcopy(first) - rewritten["entries"][0]["unit_keys"] = ["s_c:2199"] - commit_registry(repository, rewritten, "side rewrites an entry") + carried_registry = grown(first, 1) + if carried == "rewrite": + carried_registry = copy.deepcopy(first) + carried_registry["entries"][0]["unit_keys"] = ["s_c:2199"] + commit_registry(repository, carried_registry, f"side {carried}") switch(repository, "master") branch(repository, "pr") - merge = merge_with(repository, "side", rewritten) - problems = registry.history_problems( - repository, base, head_of(repository), full=False + merge = merge_with( + repository, + "side", + carried_registry if carried == "rewrite" else first, + ) + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == ( + {merge[:12]} if carried == "rewrite" else set() ) - assert reported(problems) == {merge[:12]} @pytest.mark.parametrize("where", ["fork", "landed_merge"]) @@ -1582,7 +1596,7 @@ def test_an_unreadable_predecessor_is_reported(tmp_path, no_ci_env, where): unreadable = base merge_with(repository, "master", first) problems = registry.history_problems( - repository, base, head_of(repository), full=False + repository, base, head_of(repository), full=False, pull_request=True ) assert any( p.startswith(f"{unreadable[:12]}: ") and "is not JSON" in p @@ -1615,11 +1629,255 @@ def test_a_merge_of_two_landed_lines_is_reported(tmp_path, no_ci_env): "octopus", ).strip() git(repository, "update-ref", "refs/heads/pr", octopus) - problems = registry.history_problems(repository, base, octopus, full=False) + problems = registry.history_problems( + repository, base, octopus, full=False, pull_request=True + ) assert any("more than one line of landed history" in p for p in problems) assert reported(problems) == {octopus[:12]} +def test_a_stale_landed_branch_cannot_drop_what_the_pull_request_holds( + tmp_path, no_ci_env +): + """Another pull request's branch, once landed, can carry an older + registry than this pull request's. A merge of it still keeps every + entry this pull request held: one resolved to the stale registry is + reported, though a later commit restores the entry it dropped.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "other") + own_work(repository, "the other pull request's work") + switch(repository, "master") + landed = grown(first, 1) + commit_registry(repository, landed, "master grows") + branch(repository, "pr") + own_work(repository, "own work, after the growth landed") + switch(repository, "master") + base = merge_with(repository, "other", landed) + switch(repository, "pr") + bad = merge_with(repository, "other", first) + commit_registry(repository, landed, "restore") + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == {bad[:12]} + + +@pytest.mark.parametrize("order", ["landed", "branch"]) +def test_a_landed_branch_is_merged_in_the_landed_order( + tmp_path, no_ci_env, order +): + """A landed branch's own registry need not follow master's order. One + that added H003 holds [H001, H003]; master, which landed H002 first, + holds [H001, H002, H003]. A pull request built on H002 that merges + that branch in master's order passes. Resolving to the branch's own + registry drops H002 and is reported, though a later master merge + restores it.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "other") + side = grown(first, 2) + commit_registry(repository, side, "the other pull request adds H003") + switch(repository, "master") + commit_registry(repository, grown(first, 1), "H002 lands") + branch(repository, "pr") + switch(repository, "master") + canonical = grown(first, 1, 2) + base = merge_with(repository, "other", canonical) + switch(repository, "pr") + merge = merge_with( + repository, "other", canonical if order == "landed" else side + ) + merge_with(repository, "master", canonical) + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == (set() if order == "landed" else {merge[:12]}) + + +@pytest.mark.parametrize("merge", ["keeps", "drops", "diverges"]) +def test_a_landed_merge_keeps_the_pull_requests_own_extensions( + tmp_path, no_ci_env, merge +): + """A landed merge keeps each list at the longer of its two versions, + so it cannot drop evidence the pull request added to a landed entry. + Where the pull request and master each extended that list + differently, no merge keeps both, and the merge is reported.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + extended = copy.deepcopy(first) + extended["entries"][0]["evidence"].append("own evidence") + commit_registry(repository, extended, "own evidence") + switch(repository, "master") + landed = copy.deepcopy(first) + if merge == "diverges": + landed["entries"][0]["evidence"].append("landed evidence") + landed = grown(landed, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + resolution = copy.deepcopy(landed) + if merge == "keeps": + resolution["entries"][0]["evidence"] = extended["entries"][0][ + "evidence" + ] + merged = merge_with(repository, "master", resolution) + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == (set() if merge == "keeps" else {merged[:12]}) + assert any("each extend beyond the other" in p for p in problems) == ( + merge == "diverges" + ) + + +def test_a_landed_merge_cannot_drop_the_pull_requests_own_entry( + tmp_path, no_ci_env +): + """A master merge that leaves out the pull request's own registration + is reported, though a later commit restores it.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + commit_registry(repository, grown(first, 5), "own registration") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + merge = merge_with(repository, "master", landed) + commit_registry(repository, grown(landed, 5), "restore") + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == {merge[:12]} + + +def test_an_octopus_of_a_landed_and_a_contained_parent_is_one_line( + tmp_path, no_ci_env +): + """A parent the first parent already has brings nothing in, so an + octopus of it and one landed parent brings in one line, and is + compared like any landed merge.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + fork = commit_registry(repository, first, "registry") + branch(repository, "pr") + own_work(repository, "own") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + + def octopus(document) -> str: + write(repository, registry.REGISTRY, document) + git(repository, "add", "-A") + tree = git(repository, "write-tree").strip() + return git( + repository, + "commit-tree", + tree, + "-p", + "HEAD", + "-p", + fork, + "-p", + base, + "-m", + "octopus", + ).strip() + + kept = octopus(landed) + dropped = octopus(first) + assert pr_problems(repository, base, kept) == [] + assert reported(pr_problems(repository, base, dropped)) == {dropped[:12]} + + +@pytest.mark.parametrize("change", ["delete", "rewrite"]) +def test_a_push_is_compared_from_its_before_commit( + tmp_path, no_ci_env, change +): + """A push is walked from its before commit, which need not lie on the + pushed tip's first-parent line: here an older branch merges a + descendant of it, changing the registry, and the next commit + restores it. The change is reported, as is the older branch's commit + without a registry; the fork-point start is for pull requests only.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + branch(repository, "pr") + older = own_work(repository, "older work") + switch(repository, "master") + before = commit_registry(repository, first, "registry lands") + own_work(repository, "a descendant of before") + switch(repository, "pr") + changed = None + if change == "rewrite": + changed = copy.deepcopy(first) + changed["entries"][0]["unit_keys"] = ["s_a:2199"] + bad = merge_with(repository, "master", changed) + commit_registry(repository, first, "restore") + head = head_of(repository) + first_parents = git(repository, "rev-list", "--first-parent", head) + assert before not in first_parents.split() + problems = registry.history_problems(repository, before, head, imports={}) + assert reported(problems) == {older[:12], bad[:12]} + + +def test_a_landed_union_orders_by_the_base_and_keeps_both_lines(): + """The union of the pull request's registry and a landed one: entries + and rules the base lists in its order, then the pull request's, then + the landed line's; sources from both; complete if either is.""" + first = registered(["candidate"]) + mine = grown(first, 1, 5) + mine["rules"].append("own rule") + mine["sources"]["s_own"] = {"family": "f3", "title": "own"} + theirs = grown(first, 2, 7) + theirs["rules"].append("landed rule") + theirs["complete"] = True + theirs["entries"][0]["history"].append({"status": "frozen"}) + canonical = grown(first, 1, 2) + canonical["rules"].append("landed rule") + union, conflicts = registry._landed_union(mine, theirs, canonical) + assert conflicts == [] + assert [e["id"] for e in union["entries"]] == [ + "H001", + "H002", + "H003", + "H006", + "H008", + ] + assert union["entries"][0]["history"] == theirs["entries"][0]["history"] + assert union["rules"] == [*first["rules"], "landed rule", "own rule"] + assert union["sources"] == {**theirs["sources"], **mine["sources"]} + assert union["complete"] is True + held = {entry["id"]: entry for entry in union["entries"]} + for document in (mine, theirs): + for entry in document["entries"]: + kept = held[entry["id"]] + assert all(kept[key] == entry[key] for key in registry.IMMUTABLE) + assert all( + kept[key][: len(entry[key])] == entry[key] + for key in registry.EXTENDING + ) + assert registry._landed_union(None, theirs, canonical) == (theirs, []) + assert registry._landed_union(mine, None, canonical) == (mine, []) + malformed = {"entries": [{}]} + assert registry._landed_union(malformed, theirs, None) == (theirs, []) + assert registry._landed_union(mine, malformed, None) == (malformed, []) + + +@pytest.mark.parametrize("field", ["schema", "source", "unit_keys", "history"]) +def test_a_landed_union_reports_what_no_merge_can_keep(field): + first = registered(["candidate"]) + mine, theirs = copy.deepcopy(first), copy.deepcopy(first) + if field == "schema": + theirs["schema"] = "another schema" + elif field == "source": + theirs["sources"]["s_a"] = {"family": "f9", "title": "changed"} + elif field == "unit_keys": + theirs["entries"][0]["unit_keys"] = ["s_a:2199"] + else: + mine["entries"][0]["history"].append({"status": "frozen"}) + theirs["entries"][0]["history"].append({"status": "withdrawn"}) + _, conflicts = registry._landed_union(mine, theirs, first) + assert len(conflicts) == 1 + + @pytest.mark.parametrize( "flag, code", [("--parents", 128), ("--parents", 0), ("--is-ancestor", 128)], @@ -1640,7 +1898,12 @@ def test_unreadable_parents_or_ancestry_raise( switch(repository, "pr") merge_with(repository, "master", landed) head = head_of(repository) - assert registry.history_problems(repository, base, head, full=False) == [] + assert ( + registry.history_problems( + repository, base, head, full=False, pull_request=True + ) + == [] + ) real = registry._git def failing(repo, *args): @@ -1650,42 +1913,115 @@ def failing(repo, *args): monkeypatch.setattr(registry, "_git", failing) with pytest.raises(LookupError): - registry.history_problems(repository, base, head, full=False) + registry.history_problems( + repository, base, head, full=False, pull_request=True + ) PR_STEPS = st.lists( st.sampled_from( - ["master", "own", "noop", "rewrite", "delete", "restore", "merge"] + [ + "master", + "own", + "noop", + "rewrite", + "delete", + "restore", + "fork_side", + "land_side", + "merge", + "merge_side", + "merge_side_raw", + ] ), - max_size=7, + max_size=10, ) -@settings(max_examples=25, deadline=None) +@settings(max_examples=30, deadline=None) @given(registered_first=st.booleans(), steps=PR_STEPS) def test_only_commits_that_remove_or_rewrite_entries_are_reported( tmp_path_factory, registered_first, steps ): - """Over generated graphs of master commits, own commits and master - merges, the pull request's own commits that are reported are exactly - those whose registry removes or rewrites an entry of its predecessor - (the last valid own registry, or the landed one a merge brings in).""" + """Over generated graphs of master commits, own commits, master + merges, and merges of other pull requests' branches after they land + (stale: they lack master's later growth, and, when forked before a + master merge, entries the pull request holds), the pull request's own + commits that are reported are exactly those whose registry removes, + reorders or rewrites an entry of its predecessor: the last valid own + registry, or, at a landed merge, every entry the pull request held + and the branch brings in, in master's order, then its own. + + Each merge step first makes what it merges: master grows when the + pull request is not behind it, and a branch is forked or landed when + none waits. Entries are tracked as indices (own ones, master's from + 100, other branches' from 200), so the expected registry is built + from master's order, independently of the module's comparison + code.""" repository = init_repository(tmp_path_factory.mktemp("graph")) - landed = registered(["candidate"]) if registered_first else None - if landed is not None: - commit_registry(repository, landed, "registry") + start = registered(["candidate"]) if registered_first else None + + def document(indices): + if start is None and not indices: + return None + return grown(start, *indices) + + if start is not None: + commit_registry(repository, start, "registry") branch(repository, "pr") - valid, own, broken, behind, index = landed, [], False, False, 0 - expected = set() - for step in steps: - index += 1 + master_order, known, own = [], set(), [] + pending, landed_sides = [], [] + valid, broken, behind = start, False, False + expected, merges = set(), 0 + + def resolved() -> list[int]: + return [index for index in master_order if index in known] + own + + def contained(name: str) -> bool: + found = subprocess.run( + ["git", "-C", str(repository), "merge-base", "--is-ancestor"] + + [name, "pr"], + capture_output=True, + ) + return found.returncode == 0 + + def grow_master(index: int) -> None: + switch(repository, "master") + master_order.append(100 + index) + commit_registry(repository, document(master_order), "grows") + switch(repository, "pr") + + def fork_side(index: int) -> None: + switch(repository, "master") + name = f"side{index}" + branch(repository, name) + indices = [*master_order, 200 + index] + commit_registry(repository, document(indices), "side adds") + pending.append((name, indices)) + switch(repository, "pr") + + def land_side() -> None: + name, indices = pending.pop(0) + switch(repository, "master") + master_order.append(indices[-1]) + merge_with(repository, name, document(master_order)) + landed_sides.append((name, indices)) + switch(repository, "pr") + + for index, step in enumerate(steps, start=1): + landed_sides = [s for s in landed_sides if not contained(s[0])] if step == "master": - switch(repository, "master") - landed = grown(landed, 100 + index) - commit_registry(repository, landed, "master grows") - switch(repository, "pr") + grow_master(index) behind = True continue + if step == "fork_side": + fork_side(index) + continue + if step == "land_side": + if pending: + land_side() + behind = True + continue if step == "rewrite" and valid is not None and valid["entries"]: rewritten = copy.deepcopy(valid) rewritten["entries"][0]["unit_keys"] = ["s_c:2199"] @@ -1696,26 +2032,48 @@ def test_only_commits_that_remove_or_rewrite_entries_are_reported( commit = commit_all(repository, "delete") broken = True elif step == "own": - valid = grown(valid, index) own.append(index) + valid = document(resolved()) commit = commit_registry(repository, valid, "own registration") broken = False elif step == "restore" and valid is not None: commit = commit_registry(repository, valid, "restore") broken = False - elif step == "merge" and behind: - valid = grown(landed, *own) if landed is not None else valid + elif step == "merge": + if not behind: + grow_master(index) + known = set(master_order) + valid = document(resolved()) commit = merge_with(repository, "master", valid) - broken, behind = False, False + broken, behind, merges = False, False, merges + 1 + elif step.startswith("merge_side"): + if not landed_sides: + if not pending: + fork_side(index) + grow_master(index) + land_side() + behind = True + name, indices = landed_sides.pop(0) + known |= set(indices) + valid = document(resolved()) + if step == "merge_side": + commit = merge_with(repository, name, valid) + broken = False + else: + raw = [*indices, *own] + commit = merge_with(repository, name, document(raw)) + broken = raw != resolved() + merges += 1 else: commit = own_work(repository, f"note {index}") if broken: expected.add(commit[:12]) + event(f"first-parent merges, up to 3: {min(merges, 3)}") + target(float(merges), label="first-parent merges") switch(repository, "master") base = head_of(repository) head = git(repository, "rev-parse", "pr").strip() - problems = registry.history_problems(repository, base, head, full=False) - assert reported(problems) == expected + assert reported(pr_problems(repository, base, head)) == expected def test_a_pull_request_head_is_read_from_its_event(tmp_path, monkeypatch): diff --git a/tests/test_track_b_holdout_registry_committed.py b/tests/test_track_b_holdout_registry_committed.py index a7e8b6e5..c802bea3 100644 --- a/tests/test_track_b_holdout_registry_committed.py +++ b/tests/test_track_b_holdout_registry_committed.py @@ -139,7 +139,12 @@ def test_a_pull_requests_own_commits_append_only(): "a merge commit; its endpoint is admitted against an empty " "registry above" ) - assert registry.history_problems(ROOT, base_commit, head, full=False) == [] + assert ( + registry.history_problems( + ROOT, base_commit, head, full=False, pull_request=True + ) + == [] + ) def test_every_first_parent_commit_since_the_base_appends_only(): diff --git a/tests/tier_counts.json b/tests/tier_counts.json index a5d94610..580509c5 100644 --- a/tests/tier_counts.json +++ b/tests/tier_counts.json @@ -1,7 +1,7 @@ { "schema_version": 1, "counts": { - "unit": 18275, + "unit": 18291, "artifact": 4271, "integration_psid": 1450, "reproduction_legacy": 520, From ac6dfe127566b5c67c2fef23241f07115407d931 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 24 Oct 2026 17:40:49 -0400 Subject: [PATCH 4/7] Registry tests: a push treats no merge apart; complete from either line Two tests that kill the survivors of the 22-mutant run on aa769ab7: - a push whose tip merges a side branch that master dropped an entry of is compared with its first-parent predecessor only, so treating landed merges apart on pushes is caught; - the landed union is complete when the pull request's own registry is, not only when the landed one is. Tiers: unit 18,293, total 24,842. Co-Authored-By: Claude Opus 5.5 --- tests/README-tiers.md | 4 +-- tests/test_track_b_holdout_registry.py | 37 ++++++++++++++++++++++++++ tests/tier_counts.json | 2 +- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/tests/README-tiers.md b/tests/README-tiers.md index e2cf2709..198d923b 100644 --- a/tests/README-tiers.md +++ b/tests/README-tiers.md @@ -39,9 +39,9 @@ pytest --collect-only -q -m oracle_policyengine | tail -1 | Tier | Tests at HEAD | |---|---:| -| `unit` | 18,291 | +| `unit` | 18,293 | | `artifact` | 4,271 | | `integration_psid` | 1,450 | | `reproduction_legacy` | 520 | | `oracle_policyengine` | 308 | -| **Total** | **24,840** | +| **Total** | **24,842** | diff --git a/tests/test_track_b_holdout_registry.py b/tests/test_track_b_holdout_registry.py index ac1b8c29..13a2d6de 100644 --- a/tests/test_track_b_holdout_registry.py +++ b/tests/test_track_b_holdout_registry.py @@ -1818,6 +1818,34 @@ def test_a_push_is_compared_from_its_before_commit( assert reported(problems) == {older[:12], bad[:12]} +def test_a_push_compares_a_merge_only_with_its_first_parent_line( + tmp_path, no_ci_env +): + """A push walk treats no merge apart. Here master dropped a side + branch's registration when it merged that branch, and an older + branch, pushed as master's new tip, merges the same side branch the + same way: the merge is compared with its first-parent predecessor, + which never held the side's entry, and is not reported. Only the + older branch's commit without a registry is.""" + repository = init_repository(tmp_path) + branch(repository, "pr") + older = own_work(repository, "older work") + switch(repository, "master") + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "side") + commit_registry(repository, grown(first, 2), "side adds H003") + switch(repository, "master") + merge_with(repository, "side", first) + before = own_work(repository, "master moves on") + switch(repository, "pr") + merge_with(repository, "side", first) + merge_with(repository, "master", first) + head = head_of(repository) + problems = registry.history_problems(repository, before, head, imports={}) + assert reported(problems) == {older[:12]} + + def test_a_landed_union_orders_by_the_base_and_keeps_both_lines(): """The union of the pull request's registry and a landed one: entries and rules the base lists in its order, then the pull request's, then @@ -1861,6 +1889,15 @@ def test_a_landed_union_orders_by_the_base_and_keeps_both_lines(): assert registry._landed_union(mine, malformed, None) == (malformed, []) +def test_a_landed_union_stays_complete_when_the_pull_request_is(): + """``complete`` is kept from either line, not only the landed one.""" + first = registered(["candidate"]) + mine, theirs = copy.deepcopy(first), copy.deepcopy(first) + mine["complete"] = True + union, conflicts = registry._landed_union(mine, theirs, first) + assert conflicts == [] and union["complete"] is True + + @pytest.mark.parametrize("field", ["schema", "source", "unit_keys", "history"]) def test_a_landed_union_reports_what_no_merge_can_keep(field): first = registered(["candidate"]) diff --git a/tests/tier_counts.json b/tests/tier_counts.json index 580509c5..74841e9f 100644 --- a/tests/tier_counts.json +++ b/tests/tier_counts.json @@ -1,7 +1,7 @@ { "schema_version": 1, "counts": { - "unit": 18291, + "unit": 18293, "artifact": 4271, "integration_psid": 1450, "reproduction_legacy": 520, From 3e587cca4e333554b91e047a58c7fe65353b4a8d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 24 Oct 2026 23:21:06 -0400 Subject: [PATCH 5/7] Registry: report a landed merge it cannot combine; count rule copies Round 2 of review at ac6dfe12 (the coordinator's Opus delta review and Sol) found the landed union failing open. When either line was not union-ready it returned the landed registry silently, and it keyed entries by id and rules by text, so an id or rule listed twice collapsed. Three histories could then hide a change to an own entry's units, and a dropped copy of a repeated rule went unreported. - _union_ready requires each entry id once, as validate does. A line that is not union-ready is reported at the merge, naming it. - Rules are counted in the union: each is keyed by its text and its occurrence, so every copy is kept and dropping one is a removal. validate is unchanged. - A landed merge may also extend the union in the pull request's own order, so a stacked pull request that merged its base request before it landed stays valid once it lands. The endpoint test still requires the base's order at the head. Tests cover the reviews' histories and each surviving mutant: every immutable and extending field as a conflict, malformed rules, counted rules, stacked and own-order merges, own entries reordered at a landed merge, an entry a landed merge adds, a conflicting merge's union as predecessor, and stale landed sides pinned as property examples. Co-Authored-By: Claude Opus 5.5 --- .../track_b/holdout_registry.py | 98 ++-- tests/test_track_b_holdout_registry.py | 419 +++++++++++++++++- 2 files changed, 480 insertions(+), 37 deletions(-) diff --git a/src/populace_dynamics/track_b/holdout_registry.py b/src/populace_dynamics/track_b/holdout_registry.py index 9bda5a45..b1efd6b2 100644 --- a/src/populace_dynamics/track_b/holdout_registry.py +++ b/src/populace_dynamics/track_b/holdout_registry.py @@ -1219,10 +1219,23 @@ def _landed_parents(repository: Path, commit: str, base: str) -> list[str]: ] +def _rule_keys(rules: list) -> list[tuple[str, int]]: + """A key for each of ``rules``: its JSON, keys sorted, and how many + equal rules come before it. So a rule listed twice has two keys, and + a union keeps both copies.""" + seen: dict[str, int] = {} + keys = [] + for rule in rules: + text = json.dumps(rule, sort_keys=True) + keys.append((text, seen.get(text, 0))) + seen[text] = seen.get(text, 0) + 1 + return keys + + def _union_ready(document: Any) -> bool: """Whether ``document`` has the lists and mappings - :func:`_landed_union` combines.""" - return ( + :func:`_landed_union` combines, with each entry id listed once.""" + if not ( isinstance(document, Mapping) and isinstance(document.get("rules", []), list) and isinstance(document.get("sources", {}), Mapping) @@ -1231,7 +1244,10 @@ def _union_ready(document: Any) -> bool: isinstance(entry, Mapping) and isinstance(entry.get("id"), str) for entry in document["entries"] ) - ) + ): + return False + ids = [entry["id"] for entry in document["entries"]] + return len(set(ids)) == len(ids) def _in_order(order: list, *groups: list) -> list: @@ -1249,21 +1265,39 @@ def _landed_union( It holds every rule, source and entry of ``previous``, the pull request's last valid registry, and of ``incoming``, the landed - parent's, each entry once with each list at the longer of its two - versions. Entries and rules that ``canonical``, the base's registry, + parent's: each entry once with each list at the longer of its two + versions, and each rule as often as either lists it, so dropping one + copy of a repeated rule is a removal. Entries and rules that + ``canonical``, the base's registry, lists come first, in its order (the landed order; a landed side branch's own registry need not follow it), then ``previous``'s others, - then ``incoming``'s. Also returns the conflicts that no merge could - resolve: a field that differs, or a list where neither version - extends the other. + then ``incoming``'s. With no ``canonical``, that is the pull request's + own order. Also returns the conflicts that no merge could resolve: a + field that differs, or a list where neither version extends the + other. When either registry is missing, the other is returned. When either - lacks those lists and mappings, ``incoming`` is returned, as before - this union, for the append-only rule to report.""" + repeats an entry id (as :func:`validate` also refuses), or lacks + those lists and mappings, no merge can be shown to keep all it holds: + ``incoming`` is returned, and that registry is reported as a + conflict.""" if previous is None or incoming is None: return (incoming if previous is None else previous), [] - if not (_union_ready(previous) and _union_ready(incoming)): - return incoming, [] + unready = [ + line + for line, document in ( + ("the pull request's", previous), + ("the landed", incoming), + ) + if not _union_ready(document) + ] + if unready: + return incoming, [ + f"registry: {line} registry cannot be combined at this merge: " + "it repeats an entry id, or its entries, rules or sources are " + "malformed" + for line in unready + ] conflicts: list[str] = [] union = dict(incoming) for key in ("schema", "status_values", "completion_record"): @@ -1280,21 +1314,21 @@ def _landed_union( if previous.get("complete") is True: union["complete"] = True order = canonical if _union_ready(canonical) else {} - - def text(rule: Any) -> str: - return json.dumps(rule, sort_keys=True) - rules = { - text(rule): rule + key: rule for document in (incoming, previous) - for rule in document.get("rules", []) + for key, rule in zip( + _rule_keys(document.get("rules", [])), + document.get("rules", []), + strict=True, + ) } union["rules"] = [ rules[key] for key in _in_order( - [text(rule) for rule in order.get("rules", [])], - [text(rule) for rule in previous.get("rules", [])], - [text(rule) for rule in incoming.get("rules", [])], + _rule_keys(order.get("rules", [])), + _rule_keys(previous.get("rules", [])), + _rule_keys(incoming.get("rules", [])), ) ] mine = {entry["id"]: entry for entry in previous["entries"]} @@ -1448,9 +1482,14 @@ def history_problems( history (an ancestor of ``base`` that its first parent lacks) is compared with the union of its own predecessor and that parent's registry (:func:`_landed_union`), so it keeps every entry either line - holds; a merge bringing in more than one line of landed history is - reported. Without ``pull_request``, as on a push, merges are not - treated apart, and nothing before ``base`` is trusted. + holds. It may list them in the base's order or in the pull request's + own: a stacked pull request that merged the request it builds on in + its own order, before that request landed, stays valid once it lands, + and the endpoint test still requires the base's order at the head. A + merge whose two lines cannot be combined, or that brings in more than + one line of landed history, is reported. Without ``pull_request``, as + on a push, merges are not treated apart, and nothing before ``base`` + is trusted. With ``full``, each snapshot is validated against its own commit's tree. A snapshot that fails is reported and is not used as the next @@ -1504,10 +1543,11 @@ def landed_registry(commit: str) -> Mapping[str, Any] | None: "history" ) continue + own_order = None if landed: - previous, conflicts = _landed_union( - previous, landed_registry(landed[0]), canonical - ) + incoming = landed_registry(landed[0]) + own_order, _ = _landed_union(previous, incoming, None) + previous, conflicts = _landed_union(previous, incoming, canonical) previous_label = f"{previous_label}+{landed[0][:12]}" if conflicts: problems.extend(f"{label}: {p}" for p in conflicts) @@ -1539,6 +1579,10 @@ def landed_registry(commit: str) -> Mapping[str, Any] | None: continue before = previous if previous is not None else empty_like(current) changes = append_only_problems(before, current) + if own_order is not None and not append_only_problems( + own_order, current + ): + changes = [] if changes: problems.extend(f"{previous_label}..{label}: {p}" for p in changes) continue diff --git a/tests/test_track_b_holdout_registry.py b/tests/test_track_b_holdout_registry.py index 13a2d6de..0ac15d2e 100644 --- a/tests/test_track_b_holdout_registry.py +++ b/tests/test_track_b_holdout_registry.py @@ -19,7 +19,7 @@ from pathlib import Path import pytest -from hypothesis import event, given, settings, target +from hypothesis import event, example, given, settings, target from hypothesis import strategies as st from populace_dynamics.track_b import holdout_registry as registry @@ -1748,6 +1748,271 @@ def test_a_landed_merge_cannot_drop_the_pull_requests_own_entry( assert reported(problems) == {merge[:12]} +@pytest.mark.parametrize("repeated", ["id", "rule"]) +def test_a_landed_merge_after_a_repeated_id_or_rule_is_reported( + tmp_path, no_ci_env, repeated +): + """An own commit lists H006 a second time with other units, or a rule + a second time. A master merge that keeps only the second H006 is + reported, though no later commit changes the registry: keyed by id, + the union cannot tell which H006 the pull request meant to keep. + One that keeps one copy of the rule is reported too: the union keeps + each copy, so dropping one is a removal.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + own = grown(first, 5) + commit_registry(repository, own, "own H006") + again = copy.deepcopy(own) + if repeated == "id": + second = make_entry(5, ["s_c:2155"]) + again["entries"].append(second) + else: + again["rules"].append(again["rules"][0]) + commit_registry(repository, again, f"own {repeated} again") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + resolution = copy.deepcopy(landed) + if repeated == "id": + resolution["entries"].append(second) + else: + resolution["entries"].append(own["entries"][-1]) + merge = merge_with(repository, "master", resolution) + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == {merge[:12]} + expected = ( + "cannot be combined" + if repeated == "id" + else "rules may only be appended" + ) + assert any(expected in p for p in problems) + + +@pytest.mark.parametrize("layout", ["inner", "trailing"]) +@pytest.mark.parametrize("merge", ["keeps", "drops_a_copy"]) +def test_a_landed_merge_keeps_each_copy_of_a_repeated_rule( + tmp_path, no_ci_env, layout, merge +): + """Validation lets a rule repeat, so the union counts its copies. A + master merge that keeps a registry listing rule one twice, as + [one, one, incomplete] or [one, incomplete, one], passes. One that + drops a copy is reported, though the next commit restores it.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + if layout == "inner": + first["rules"].insert(1, first["rules"][0]) + else: + first["rules"].append(first["rules"][0]) + assert validate(first) == [] + commit_registry(repository, first, "a registry with a repeated rule") + branch(repository, "pr") + own_work(repository, "own work") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + resolution = copy.deepcopy(landed) + if merge == "drops_a_copy": + del resolution["rules"][1 if layout == "inner" else -1] + merged = merge_with(repository, "master", resolution) + commit_registry(repository, landed, "restore") + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == (set() if merge == "keeps" else {merged[:12]}) + + +def test_a_landed_merge_after_an_own_registry_with_malformed_sources( + tmp_path, no_ci_env +): + """A pull request branched before the registry existed creates one + whose sources are a list, admitted against an empty registry. A + master merge resolved to master's registry drops its H006, and a + later commit adds H006 again with other units. The merge is + reported: the union cannot read what the pull request held.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + branch(repository, "pr") + own = grown(None, 5) + own["sources"] = [] + commit_registry(repository, own, "own registry, sources as a list") + switch(repository, "master") + base = commit_registry(repository, first, "the registry lands") + switch(repository, "pr") + merge = merge_with(repository, "master", first) + readded = grown(first, 5) + readded["entries"][-1]["unit_keys"] = ["s_c:2155"] + commit_registry(repository, readded, "own H006 again, other units") + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == {merge[:12]} + assert any("the pull request's registry cannot" in p for p in problems) + + +def test_a_merge_of_a_landed_tip_with_malformed_sources_is_reported( + tmp_path, no_ci_env +): + """Another pull request's tip lists its sources as a list; master + landed it with them fixed. A pull request that merges that tip and + drops its own H006, then adds H006 again with other units, is + reported at the merge.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "other") + broken = copy.deepcopy(first) + broken["sources"] = [] + commit_registry(repository, broken, "the other tip: sources as a list") + switch(repository, "master") + branch(repository, "pr") + commit_registry(repository, grown(first, 5), "own H006") + switch(repository, "master") + base = merge_with(repository, "other", first) + switch(repository, "pr") + merge = merge_with(repository, "other", first) + readded = grown(first, 5) + readded["entries"][-1]["unit_keys"] = ["s_c:2155"] + commit_registry(repository, readded, "own H006 again, other units") + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == {merge[:12]} + assert any("the landed registry cannot" in p for p in problems) + + +@pytest.mark.parametrize("order", ["own", "landed"]) +def test_a_stacked_pull_request_stays_valid_once_its_base_lands( + tmp_path, no_ci_env, order +): + """B, built on A, adds H006 and merges A's branch (which adds H003) + before A lands. While A is unlanded that merge must extend B's own + registry, so only B's order, [H001, H006, H003], passes. Once A + lands, the merge brings in landed history and passes in either order; + B's later master merge, in master's order, passes too.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "a") + commit_registry(repository, grown(first, 2), "A adds H003") + switch(repository, "master") + branch(repository, "b") + commit_registry(repository, grown(first, 5), "B adds H006") + stacked = merge_with( + repository, + "a", + grown(first, 5, 2) if order == "own" else grown(first, 2, 5), + ) + switch(repository, "master") + before = head_of(repository) + before_landing = pr_problems(repository, before, stacked) + assert reported(before_landing) == ( + set() if order == "own" else {stacked[:12]} + ) + base = merge_with(repository, "a", grown(first, 2)) + switch(repository, "b") + merge_with(repository, "master", grown(first, 2, 5)) + assert pr_problems(repository, base, head_of(repository)) == [] + + +@pytest.mark.parametrize("field", ["entries", "rules"]) +def test_a_landed_merge_in_the_pull_requests_own_order_waits_for_the_end( + tmp_path, no_ci_env, field +): + """A master merge that keeps the pull request's entries, or rules, + ahead of master's new ones passes the history check, which accepts + the pull request's own order at a landed merge. The endpoint test, + the head against the base, still reports it.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + own, landed = grown(first, 5), grown(first, 1) + if field == "rules": + own, landed = copy.deepcopy(first), copy.deepcopy(first) + own["rules"].append("own rule") + landed["rules"].append("master rule") + commit_registry(repository, own, "own addition") + switch(repository, "master") + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + own_first = grown(first, 5, 1) + if field == "rules": + own_first = copy.deepcopy(own) + own_first["rules"].append("master rule") + merge_with(repository, "master", own_first) + assert pr_problems(repository, base, head_of(repository)) == [] + head = registry.registry_at(repository, head_of(repository)) + assert registry.append_only_problems(landed, head) != [] + + +def test_a_landed_merge_cannot_reorder_the_pull_requests_own_entries( + tmp_path, no_ci_env +): + """The union orders the pull request's own entries as it held them, + after the base's. A master merge that swaps H006 and H007 is + reported, though the head still extends the base, so the endpoint + test alone would pass it.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + commit_registry(repository, grown(first, 5, 6), "own H006 and H007") + switch(repository, "master") + landed = grown(first, 2) + base = commit_registry(repository, landed, "master adds H003") + switch(repository, "pr") + swapped = grown(first, 2, 6, 5) + merge = merge_with(repository, "master", swapped) + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == {merge[:12]} + assert registry.append_only_problems(landed, swapped) == [] + + +def test_an_entry_a_landed_merge_adds_is_held_from_then_on( + tmp_path, no_ci_env +): + """A master merge whose resolution adds the pull request's own + registration becomes the next commit's predecessor, so a commit that + then drops that registration is reported.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + own_work(repository, "own") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + merge_with(repository, "master", grown(first, 1, 5)) + drop = commit_registry(repository, landed, "drops H006") + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == {drop[:12]} + + +def test_a_conflicting_landed_merge_leaves_the_union_as_predecessor( + tmp_path, no_ci_env +): + """A master merge whose two lines each extended H001's evidence is + reported, and, like any snapshot that fails, is not the next commit's + predecessor: the union is. So H006, which only that merge added, may + be dropped next without a second report.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + mine = copy.deepcopy(first) + mine["entries"][0]["evidence"].append("own evidence") + commit_registry(repository, mine, "own evidence") + switch(repository, "master") + landed = copy.deepcopy(first) + landed["entries"][0]["evidence"].append("landed evidence") + base = commit_registry(repository, landed, "master evidence") + switch(repository, "pr") + merge = merge_with(repository, "master", grown(landed, 5)) + commit_registry(repository, landed, "drops H006") + problems = pr_problems(repository, base, head_of(repository)) + assert reported(problems) == {merge[:12]} + assert len(problems) == 1 + + def test_an_octopus_of_a_landed_and_a_contained_parent_is_one_line( tmp_path, no_ci_env ): @@ -1885,8 +2150,103 @@ def test_a_landed_union_orders_by_the_base_and_keeps_both_lines(): assert registry._landed_union(None, theirs, canonical) == (theirs, []) assert registry._landed_union(mine, None, canonical) == (mine, []) malformed = {"entries": [{}]} - assert registry._landed_union(malformed, theirs, None) == (theirs, []) - assert registry._landed_union(mine, malformed, None) == (malformed, []) + union, conflicts = registry._landed_union(malformed, theirs, None) + assert union is theirs and len(conflicts) == 1 + assert "the pull request's registry" in conflicts[0] + union, conflicts = registry._landed_union(mine, malformed, None) + assert union is malformed and len(conflicts) == 1 + assert "the landed registry" in conflicts[0] + _, conflicts = registry._landed_union(malformed, malformed, None) + assert len(conflicts) == 2 + + +def test_a_landed_union_lists_rules_the_base_lacks_own_first(): + """Rules the base does not list follow its own, the pull request's + first, then the landed line's. With no base, the order is the pull + request's own: its rules, then the landed line's others.""" + first = registered(["candidate"]) + mine, theirs = copy.deepcopy(first), copy.deepcopy(first) + mine["rules"].append("own rule") + theirs["rules"].append("a landed rule the base lacks") + expected = [*first["rules"], "own rule", "a landed rule the base lacks"] + union, conflicts = registry._landed_union(mine, theirs, first) + assert conflicts == [] and union["rules"] == expected + canonical = copy.deepcopy(theirs) + union, _ = registry._landed_union(mine, theirs, canonical) + assert union["rules"] == [*theirs["rules"], "own rule"] + union, _ = registry._landed_union(mine, theirs, None) + assert union["rules"] == expected + + +def test_a_landed_union_keeps_each_copy_of_a_repeated_rule(): + """Rules are counted, not collapsed: the union lists each rule as + often as either line does, the base's copies in its order first.""" + first = registered(["candidate"]) + mine, theirs = copy.deepcopy(first), copy.deepcopy(first) + mine["rules"] += ["repeated", "repeated"] + theirs["rules"] += ["repeated", "landed"] + union, conflicts = registry._landed_union(mine, theirs, theirs) + assert conflicts == [] + assert union["rules"] == [ + *first["rules"], + "repeated", + "landed", + "repeated", + ] + union, _ = registry._landed_union(mine, theirs, None) + assert union["rules"] == [ + *first["rules"], + "repeated", + "repeated", + "landed", + ] + union, _ = registry._landed_union(theirs, mine, theirs) + assert union["rules"] == [ + *first["rules"], + "repeated", + "landed", + "repeated", + ] + assert registry._union_ready(mine) + + +@pytest.mark.parametrize("line", ["own", "landed"]) +@pytest.mark.parametrize( + "defect", + [ + "repeated_id", + "rules_not_a_list", + "sources_not_a_mapping", + "entry_id", + ], +) +def test_a_landed_union_reports_a_line_it_cannot_combine(line, defect): + """A line that lists an entry id twice, or whose entries, rules or + sources are malformed, cannot be shown to keep what it holds: keyed + by id, the union would keep one of two entries, and the append-only + rule reads sources that are not a mapping as none. So the union + reports that line rather than fall back on the other.""" + first = registered(["candidate"]) + mine, theirs = grown(first, 5), grown(first, 1) + broken = mine if line == "own" else theirs + if defect == "repeated_id": + again = copy.deepcopy(broken["entries"][-1]) + again["unit_keys"] = ["s_c:2155"] + broken["entries"].append(again) + elif defect == "rules_not_a_list": + broken["rules"] = "one rule, as text" + elif defect == "sources_not_a_mapping": + broken["sources"] = [] + else: + broken["entries"][-1]["id"] = 6 + assert not registry._union_ready(broken) + union, conflicts = registry._landed_union(mine, theirs, first) + assert union is theirs and len(conflicts) == 1 + named = "the pull request's" if line == "own" else "the landed" + assert conflicts[0].startswith(f"registry: {named} registry cannot") + for document in (mine, theirs, first): + if document is not broken: + assert registry._union_ready(document) def test_a_landed_union_stays_complete_when_the_pull_request_is(): @@ -1898,21 +2258,44 @@ def test_a_landed_union_stays_complete_when_the_pull_request_is(): assert conflicts == [] and union["complete"] is True -@pytest.mark.parametrize("field", ["schema", "source", "unit_keys", "history"]) +@pytest.mark.parametrize( + "field", + [ + "schema", + "status_values", + "completion_record", + "sources", + *(key for key in EXPECTED_IMMUTABLE if key != "id"), + *EXPECTED_EXTENDING, + ], +) def test_a_landed_union_reports_what_no_merge_can_keep(field): + """A top-level field or source that differs between the lines, an + entry field either line may not change, or an entry list each line + extended differently: no merge keeps both, so each is one conflict. + The fields come from this module's lists, not the module's.""" first = registered(["candidate"]) mine, theirs = copy.deepcopy(first), copy.deepcopy(first) if field == "schema": theirs["schema"] = "another schema" - elif field == "source": + elif field == "status_values": + theirs["status_values"] = {"candidate": "another reading"} + elif field == "completion_record": + theirs["completion_record"] = "docs/design/another_record.json" + elif field == "sources": theirs["sources"]["s_a"] = {"family": "f9", "title": "changed"} - elif field == "unit_keys": - theirs["entries"][0]["unit_keys"] = ["s_a:2199"] + elif field in EXPECTED_IMMUTABLE: + theirs["entries"][0][field] = f"another {field}" else: - mine["entries"][0]["history"].append({"status": "frozen"}) - theirs["entries"][0]["history"].append({"status": "withdrawn"}) + mine["entries"][0][field] = [*mine["entries"][0][field], "own item"] + theirs["entries"][0][field] = [ + *theirs["entries"][0][field], + "landed item", + ] _, conflicts = registry._landed_union(mine, theirs, first) assert len(conflicts) == 1 + if field in (*EXPECTED_IMMUTABLE, *EXPECTED_EXTENDING): + assert conflicts[0].startswith(f"H001: {field} ") @pytest.mark.parametrize( @@ -1977,6 +2360,18 @@ def failing(repo, *args): @settings(max_examples=30, deadline=None) @given(registered_first=st.booleans(), steps=PR_STEPS) +@example( + registered_first=True, + steps=["own", "fork_side", "merge", "land_side", "merge_side_raw"], +) +@example( + registered_first=True, + steps=["own", "fork_side", "merge", "land_side", "merge_side", "own"], +) +@example( + registered_first=False, + steps=["fork_side", "merge", "land_side", "merge_side_raw", "restore"], +) def test_only_commits_that_remove_or_rewrite_entries_are_reported( tmp_path_factory, registered_first, steps ): @@ -1987,7 +2382,11 @@ def test_only_commits_that_remove_or_rewrite_entries_are_reported( commits that are reported are exactly those whose registry removes, reorders or rewrites an entry of its predecessor: the last valid own registry, or, at a landed merge, every entry the pull request held - and the branch brings in, in master's order, then its own. + and the branch brings in, in master's order, then its own. (A landed + merge may also list the pull request's own entries first; no + generated merge does, so the oracle need not.) The examples pin a + merge of a stale landed branch, resolved to its own registry and + correctly, which the generator reaches rarely. Each merge step first makes what it merges: master grows when the pull request is not behind it, and a branch is forked or landed when From 14c68e4fa7bd703104bb9af954d46332ad11ab05 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 24 Oct 2026 23:36:39 -0400 Subject: [PATCH 6/7] Tests: recount the unit tier after round 3's registry tests The unit-tier collect at 3e587cca counts 18,330 unit and 24,879 in all: 37 more than at ac6dfe12, the registry module's new items. Co-Authored-By: Claude Opus 5.5 --- tests/README-tiers.md | 4 ++-- tests/tier_counts.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/README-tiers.md b/tests/README-tiers.md index 198d923b..0de07e34 100644 --- a/tests/README-tiers.md +++ b/tests/README-tiers.md @@ -39,9 +39,9 @@ pytest --collect-only -q -m oracle_policyengine | tail -1 | Tier | Tests at HEAD | |---|---:| -| `unit` | 18,293 | +| `unit` | 18,330 | | `artifact` | 4,271 | | `integration_psid` | 1,450 | | `reproduction_legacy` | 520 | | `oracle_policyengine` | 308 | -| **Total** | **24,842** | +| **Total** | **24,879** | diff --git a/tests/tier_counts.json b/tests/tier_counts.json index 74841e9f..e74bed0d 100644 --- a/tests/tier_counts.json +++ b/tests/tier_counts.json @@ -1,7 +1,7 @@ { "schema_version": 1, "counts": { - "unit": 18293, + "unit": 18330, "artifact": 4271, "integration_psid": 1450, "reproduction_legacy": 520, From 789978f9e19049fcd9619815e788b12a77f6aa23 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 25 Oct 2026 00:14:44 -0400 Subject: [PATCH 7/7] Registry tests: a landed merge after a failing own commit An own commit that fails is reported and is not a predecessor, so a master merge right after it is compared with the union of the last valid registry. No history test had a failing own commit just before a landed merge, so a walk that formed the union from the merge's first parent passed them all. Only the property test could catch it, and whether it does on every run is unconfirmed (the coordinator's round-3 reviewer found Sol's mutant for it surviving the targeted tests at 14c68e4f). The test pins both directions: after a rewrite of H001's units, a merge resolved to master's registry passes; after a commit that dropped H006, a merge without it is reported. Tiers: unit 18,332, total 24,881 (the registry module's 2 new items). Co-Authored-By: Claude Opus 5.5 --- tests/README-tiers.md | 4 ++-- tests/test_track_b_holdout_registry.py | 31 ++++++++++++++++++++++++++ tests/tier_counts.json | 2 +- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/tests/README-tiers.md b/tests/README-tiers.md index 0de07e34..0f5b3530 100644 --- a/tests/README-tiers.md +++ b/tests/README-tiers.md @@ -39,9 +39,9 @@ pytest --collect-only -q -m oracle_policyengine | tail -1 | Tier | Tests at HEAD | |---|---:| -| `unit` | 18,330 | +| `unit` | 18,332 | | `artifact` | 4,271 | | `integration_psid` | 1,450 | | `reproduction_legacy` | 520 | | `oracle_policyengine` | 308 | -| **Total** | **24,879** | +| **Total** | **24,881** | diff --git a/tests/test_track_b_holdout_registry.py b/tests/test_track_b_holdout_registry.py index 0ac15d2e..636e1110 100644 --- a/tests/test_track_b_holdout_registry.py +++ b/tests/test_track_b_holdout_registry.py @@ -2013,6 +2013,37 @@ def test_a_conflicting_landed_merge_leaves_the_union_as_predecessor( assert len(problems) == 1 +@pytest.mark.parametrize("change", ["rewrite", "drop"]) +def test_a_landed_merge_after_a_failing_own_commit_unions_the_last_valid( + tmp_path, no_ci_env, change +): + """An own commit that fails is reported and is not a predecessor, so + a master merge right after it is compared with the union of the last + valid registry, not of the failing one. A merge resolved to master's + registry after H001's units are rewritten passes, since the valid + H001 is master's. One that leaves out H006, after an own commit that + dropped it, is reported, since the valid registry held H006.""" + repository = init_repository(tmp_path) + first = registered(["candidate"]) + commit_registry(repository, first, "registry") + branch(repository, "pr") + if change == "rewrite": + failing = copy.deepcopy(first) + failing["entries"][0]["unit_keys"] = ["s_c:2199"] + else: + commit_registry(repository, grown(first, 5), "own H006") + failing = first + bad = commit_registry(repository, failing, f"{change} an own entry") + switch(repository, "master") + landed = grown(first, 1) + base = commit_registry(repository, landed, "master grows") + switch(repository, "pr") + merge = merge_with(repository, "master", landed) + problems = pr_problems(repository, base, head_of(repository)) + expected = {bad[:12]} | ({merge[:12]} if change == "drop" else set()) + assert reported(problems) == expected + + def test_an_octopus_of_a_landed_and_a_contained_parent_is_one_line( tmp_path, no_ci_env ): diff --git a/tests/tier_counts.json b/tests/tier_counts.json index e74bed0d..75ff348a 100644 --- a/tests/tier_counts.json +++ b/tests/tier_counts.json @@ -1,7 +1,7 @@ { "schema_version": 1, "counts": { - "unit": 18330, + "unit": 18332, "artifact": 4271, "integration_psid": 1450, "reproduction_legacy": 520,