#1023 Cloning pijul/pijul: one deletion takes 78 minutes since beta.24; three patches bring the replay of the whole history to 75 s

Opened by timostolz on Nov 3, 2026, 1:10 PM
Approve the patches, then land them on main with:
// timostolz on Nov 3, 2026, 1:10 PM

Summary

Cloning pijul/pijul has not been feasible for a while. With 1.0.0-beta.23, replaying the 970 changes before POBHKKNG… (“Use nixpkgs builtin Rust build tools”, 2023-11-26, deletes Cargo.nix, 4716 deleted edges) had not finished after 100 minutes. beta.24 fixed that quadratic case (as the comment on PROBE_BUDGET says) and brings those 970 changes to 53 s. The same change made the deletion in POBHKKNG… take 4668 s on the state right before it. pijul clone over SSH spends 22 minutes on that one change, fails after 26 min 39 s with Channel send error, and deletes the target directory. We have not verified why the connection fails; our guess is that the Nest closes the session while nobody reads from it during the long apply.

With the three patches attached, the replay takes 72 s for the 970 changes and 3 s for the deletion. Working copy and log are identical to unpatched beta.26.

pijul970 changes before (s)POBHKKNG… alone (s)pseudo-edges afterwards
1.0.0-beta.23> 6000 (stopped)––
1.0.0-beta.26534668not counted
+ fix.patch7426424 494
+ fix2.patch692110 229
+ fix3.patch72310 229

Root cause: the reduction of the entering × exiting reconnection in repair_zombies (new in beta.24) gives up on sets larger than PROBE_MAX_SET = 64 and writes the whole product into the graph. In a synthetic file with scattered edits over a few versions, that leaves 59 806 pseudo-edges where beta.23 leaves 400. Every later operation on the file walks them. The patches keep beta.24’s reduction and its intent; they replace the per-member probes with one walk per set, so the reduction never has to be skipped, and they make the two sweeps that beta.24 added run once per file instead of once per edge or per vertex.

A note on how this was done: the analysis, the patches and the proof below were produced with substantial help from an AI assistant (Claude). I verified the measurements, the test runs and the identical working copies myself, and I do not claim to know pijul’s theory. If any of this collides with an invariant you rely on, I would rather hear it than have the patches applied.

What stays guaranteed

beta.24’s reduction has one specification, visible in the fallback: for every dead vertex, every entering vertex must reach every exiting vertex through alive edges, either directly or through the pseudo-edges (bridges) the loop emits. The full product satisfies that trivially. All three patches keep exactly this guarantee. The only difference to the full product is fewer redundant bridges, and redundancy is what the existing code already accepts as harmless (comment on PROBE_BUDGET: “costs one redundant pseudo-edge and never costs correctness”).

Nothing here changes which real or deleted edges exist. The edge counts in the synthetic graphs are identical in every run except for the pseudo-edges.

The patches

All three are against pijul-core/src/apply.rs on main (workspace version 1.0.0-beta.24, last change 2026-10-20; the crates.io beta.26 has the same file) and apply in order. Each is useful on its own and measured on its own, so they can be taken in stages.

fix.patch: the two per-item sweeps run per source (small, no change of approach)

  1. clean_unjustified_pseudo_edges called pseudo_edge_justified(v, c) once per pseudo-edge, a fresh DFS from v through dead vertices. The patch runs that walk once per source v, collects everything it reaches (dead_reachable), and answers all of v’s pseudo-edges from the set. Same question, same answer.
  2. repair_zombies called alive_exits_through_dead once per dead vertex, an unbounded DFS. The patch memoizes the exits per dead vertex in an iterative post-order walk: the exits of a dead vertex are its alive children plus the exits of its dead children. The loop only adds edges between alive vertices, so the memo stays valid for the whole repair. On a cycle through dead vertices the memo returns None and the existing function handles that vertex.

Our first attempt ran the sweep only when a change brings vertices back to life. fuzz_unrecord_pseudo_only_vertex rejected that, because the sweep also removes pseudo-edges the change itself adds. The patch keeps the sweep’s scope.

Real case: 4668 s → 26 s. The pseudo-edge count is untouched (424 494 in the repository afterwards).

fix2.patch: one walk per set instead of one probe per member (the change of approach)

For each dead vertex, the maximal entering and the minimal exiting members are found by one breadth-first walk from all members at once:

  • Every vertex is visited once and labelled with the member whose walk reached it first (its owner).
  • Exiting set, forward over alive (non-DELETED, non-PARENT) edges: a member c met as a child of a vertex owned by s ≠ c is reached by s, so c is not minimal. The owner s is recorded as c’s witness.
  • Entering set, the mirror image backward over non-DELETED PARENT edges: a member p met as a parent of a vertex owned by s ≠ p reaches s, so p is not maximal.
  • The walk stops when all members but one are witnessed (the common case: a chain), or when its budget max(512, 8 × |set|) runs out. A walk that stops early witnesses less, which leaves redundant bridges and nothing else.

Why under-reporting is the only possible error: a member is witnessed only when a concrete alive path from another member to it has been walked (owner label plus one edge). Such a path is exactly what makes the bridge to that member redundant.

One case needs more, and the pairwise probes have the same gap: when members of a set reach each other (a cycle in the alive graph, which pijul allows as a cyclic conflict, see cyclic_conflict_resolution and cyclic_zombies), each is witnessed by another, all of them are dropped, and the dead vertex gets no bridge from or to that cycle at all. With reaches_any_within, two entering vertices on a cycle both answer “reaches another”, and maximal is empty. The patch therefore follows the witness chains before dropping: a chain that ends in an unwitnessed member is grounded (that member reaches everything on the chain transitively); a chain that closes on itself is a cycle, and one member of it is kept (restore_cycles). We could not produce an end-to-end failure from this gap on main: put_newedge and earlier repairs already place the bridges in the cases we tried. It may be masked by an invariant we do not see, so this is a question, not a bug report.

PROBE_MAX_SET and the two per-member probes (reaches_any_within, forward_reachable_within) are removed. PROBE_BUDGET = 512 stays as the lower bound of the walk’s budget. A budget factor of 2 instead of 8 changes almost nothing on the real case (19.7 s, 10 239 edges instead of 10 229), so the factor is a matter of taste.

Real case: 26 s → 21 s, pseudo-edges 424 494 → 10 229, working copy identical.

fix3.patch: the sweep in one pass, the reduction once per exit set (optimization, no approximation)

  1. clean_unjustified_pseudo_edges: all pseudo-edges of the sweep are collected first. Their targets are few, so each dead vertex gets a bitset over the targets (the targets among its children plus the bitsets of its dead children), computed in post-order once per dead vertex and memoized for the sweep. A source’s answer is the targets among its children plus the bitsets of its dead children: the same set dead_reachable built, restricted to the targets asked for. A cycle of dead vertices has no post-order; a source above one falls back to dead_reachable.
  2. repair_zombies keeps the result of the exiting walk per distinct exiting set (sorted vector as key) for one repair. The dead vertices of one region share their exits. The walk reads only the alive graph, and the bridges emitted in the same loop start at entering vertices, above the exits, so a stored result can only witness less than a fresh walk, never more.

Real case: 21 s → 6.6 s (sweep) → 3 s (memo). Pseudo-edges unchanged.

Proof of the approach (fix 2)

Reduction.lean (attached; Lean 4 with Mathlib, builds without sorry) states the argument of fix 2 independently of pijul’s graph, so it can be checked without trusting the code. The model is a transitive relation “reaches” on an abstract set, a witness assignment with the property the walks guarantee (every witness lies on a real alive path), and a kept set. Two theorems:

  • reduction_sound: if the kept set grounds every member (following witnesses ends in a kept member), then the alive graph plus the bridges between kept entering and kept exiting members makes every entering vertex reach every exiting one. That is the guarantee of the full product. It holds for any witness assignment with correct witnesses, hence for a walk that stops at any budget. It depends on no axioms.
  • all_grounded: on a finite set, keeping every unwitnessed member and one member of every cycle of witnesses grounds every member. This is the obligation of restore_cycles, and it shows why the cycle handling is needed: with nothing kept from a cycle, nothing on it is grounded.

What the proof does not cover: that the walks record correct witnesses (an owner label plus one traversed edge is a path by construction, but that is code), that restore_cycles establishes all_grounded’s hypothesis, and whether “every entering vertex reaches every exiting one” is the right specification for pijul. That last one is beta.24’s own design; the patches do not touch it. Fix 1 and fix 3 are not in the model: they compute the same relations as before in a different order.

Tests: fix2.patch adds three unit tests on hand-built alive graphs (reduction_tests): a chain keeps its ends; a cycle r1 ⇄ r2 with a member reached from it and an unrelated member keeps exactly one member of the cycle, on both the exiting and the entering side; and restore_cycles on a witness map with a cycle, a grounded chain and a chain into the cycle. The cycle tests fail if restore_cycles is replaced by “drop everything witnessed”. With all three patches, cargo test --release -p pijul-core on main passes 218 tests (4 ignored), including squash*, text_roundtrip and the fuzz tests for the sweep; the crates.io beta.26 package passes 169.

Measurements

Environment: Linux 7.2, AMD Ryzen 9 5950X, local SSD. pijul 1.0.0-beta.26 (Arch Linux package), main from the Nest, and 1.0.0-beta.23 from crates.io for comparison (its apply takes change files, not hashes, and does not output to the working copy, so the scripts run pijul reset outside the timing).

Real case: repro.sh

Needs a checkout of pijul/pijul. The script copies its change files into a fresh repository, applies the 970 changes before POBHKKNG… in channel order (pijul log --hash-only | tac), then times POBHKKNG… alone. Nothing is recorded, so no identity or SSH agent is needed.

bash repro.sh ~/src/pijul                       # pijul from PATH
bash repro.sh ~/src/pijul ./target/release/pijul

Results are in the table in the summary. All beta.26 builds leave the same working copy (diff -r --exclude=.pijul) and the same log (971 entries). Pseudo-edges were counted over the whole repository with pijul debug afterwards.

Synthetic case: delete_scaling.sh

Creates a file of N lines and records K versions of it. Each version changes every fourth line, shifted by one each time, like a generated file updated over the years. The script then deletes the file. In a fresh repository, it times applying the K versions and the deletion separately. It starts its own ssh-agent with a throwaway key. PIJUL=… chooses the binary, BY_PATH=1 is for beta.23.

PIJUL=/usr/bin/pijul bash delete_scaling.sh "400 5" "800 5" "400 20" "1600 5"

Applying the K versions (s):

pijulN=400, K=5N=800, K=5N=400, K=20N=1600, K=5
1.0.0-beta.232.924.932.3199.8
1.0.0-beta.266.874.0106.4–
beta.26 + fix.patch0.41.714.27.9

Applying the deletion: beta.23 takes 0.03 to 0.07 s for every size. beta.26 + fix.patch takes 25.6 s for N=1600, K=5.

Pseudo-edges: graph_compare.sh

Builds the state before the deletion with several binaries, counts the edges in pijul debug (plain, dashed = deleted, dotted = pseudo), then times the deletion. “pairwise” is the fix 2 binary with the previous probes switched back on.

N=800, K=5, plain and deleted edges are 1399 and 1400 in every row:

pijulpseudoK versions (s)deletion (s)
1.0.0-beta.2340025.10.0
1.0.0-beta.2659 80660.24.8
beta.26 + fix.patch59 8061.74.8
beta.26 + fix.patch, PROBE_MAX_SET = 10000067150.50.1
beta.26 + fix.patch + fix2.patch6711.10.1
beta.26 + all three6711.00.1

Counted after each version with beta.26: 0, 0, 200, 200, 200, 59 029, 59 806 pseudo-edges. With RUST_LOG=pijul_core::apply=debug, the jump is 59 028 lines of put_pseudo (reduced) and nothing else. The fourth row shows the trade-off the patches remove: without the size limit, the pairwise probes make the edits slow; with it, the graph keeps the product.

Other sizes, fix 2 against pairwise:

N / Kpseudo-edges fix 2pairwiseK versions fix 2 (s)pairwisedeletion fix 2 (s)pairwise
400 / 2039814 4774.710.30.01.0
1600 / 51 471240 3063.87.80.137.6

With fix 3, the K versions take 2.2 s (400/20) and 3.2 s (1600/5) at the same edge counts.

Where the remaining time goes

gdb stack samples on the real deletion with all three patches: 69 % of the 3 s in the exiting walk for the exit sets that are still distinct, including the Sanakirja lookups. We stopped here.

Open points

  1. The cycle gap in the pairwise probes (above): is it masked by an invariant, or a latent bug? We would appreciate a pointer either way.
  2. The budget factor 8 and the kept lower bound 512 are not load-bearing. If you prefer no budget at all, fix 3’s memo per exit set bounds the total work anyway.
  3. Fix 1 alone is a safe first step if the approach of fix 2 needs more scrutiny.
  4. We have not re-run the SSH clone against the Nest with the patched binary. The Channel send error is a separate question; with a 3 s apply it should not occur.

Attachments

The three patches are attached to this discussion as changes, in the order fix 1, fix 2, fix 3. The scripts (repro.sh, delete_scaling.sh, graph_compare.sh) and the proof (Reduction.lean) follow in the first reply.

timostolz
~ timostolz authored a change on Nov 3, 2026, 1:19 PM
· timostolz · on Nov 3, 2026, 1:18 PM
  • pijul-core/src/apply.rs
not landed on main yet
CLLRUUUTUUHOYQXVUOR4ICKUX3UM4BXND27PK2MFCZ2BBZ65HH7QC
timostolz
~ timostolz authored a change on Nov 3, 2026, 1:19 PM
· timostolz · on Nov 3, 2026, 1:18 PM
  • pijul-core/src/apply.rs
not landed on main yet
DFNOFD47YOYB4DR52LSGU5UAIHGFF4RVMUG3W52AMTIGRNZIDJDAC
timostolz
~ timostolz authored a change on Nov 3, 2026, 1:19 PM
· timostolz · on Nov 3, 2026, 1:18 PM
  • pijul-core/src/apply.rs
not landed on main yet
LBLGRCK7FP5EEQBCKWFYUY2C6X6OGNV6O7YMM6XHFNRIGLSJUHQAC
// timostolz on Nov 3, 2026, 1:24 PM

Scripts and proof referenced in the opening post. All three scripts were run on Linux with bash; repro.sh and graph_compare.sh need an existing checkout of pijul/pijul, delete_scaling.sh starts its own ssh-agent with a throwaway key. Reduction.lean builds in a fresh lake new proof math project (Lean 4 v4.36.0-rc2, Mathlib) with lake build; #print axioms Reduction.reduction_sound reports no axioms, all_grounded uses propext, Classical.choice and Quot.sound through Mathlib.

repro.sh

#!/usr/bin/env bash
# Times applying POBHKKNG… (2023, "Use nixpkgs builtin Rust build tools",
# deletes Cargo.nix) on the state of pijul/pijul right before it.
#
# Needs an existing checkout of pijul/pijul (channel main) that contains the
# change. Copies its change files into a fresh repository, applies the 970
# changes before POBHKKNG… in channel order, then times POBHKKNG… alone.
# Nothing is recorded, so no identity or SSH agent is needed.
#
# Usage: repro.sh PATH/TO/pijul-checkout [PIJUL_BINARY]
set -eu
SRC=$(cd "$1" && pwd)
P=${2:-pijul}
H=POBHKKNGVKC5M7ANC4I6BDU225AUP5IV5WPG63SDX3KYXRPC4PLAC
W=$(mktemp -d)
cd "$SRC"
"$P" log --hash-only | tac > "$W/order"
n=$(grep -n "^$H\$" "$W/order" | cut -d: -f1)
head -n $((n - 1)) "$W/order" > "$W/before"
"$P" init "$W/r" >/dev/null
cp -r "$SRC/.pijul/changes/"* "$W/r/.pijul/changes/"
cd "$W/r"
t0=$(date +%s)
"$P" apply $(cat "$W/before") >/dev/null
t1=$(date +%s)
echo "$(("$n" - 1)) changes before $H: $((t1 - t0)) s"
"$P" apply "$H" >/dev/null
t2=$(date +%s)
echo "$H alone: $((t2 - t1)) s"
echo "repository: $W/r"

delete_scaling.sh

#!/usr/bin/env bash
# How long does applying "delete a file" take, depending on the file's size
# (N lines) and how often it was rewritten completely before (K versions)?
# Mirrors POBHKKNG… in pijul's own history (deletes Cargo.nix, 4716 edges),
# on which `pijul clone` of pijul/pijul spends minutes.
# Usage: delete_scaling.sh "N K" ...   (default: a small grid)
# BY_PATH=1 applies change files instead of hashes (needed for beta.23).
set -u
export LC_ALL=C
P=${PIJUL:-/usr/bin/pijul}
W=$(mktemp -d "${TMPDIR:-/tmp}/pijul-scaling.XXXX")
unset SSH_AUTH_SOCK SSH_AGENT_PID
eval "$(ssh-agent -s)" >/dev/null
if [ -z "${SSH_AGENT_PID:-}" ] || ! kill -0 "$SSH_AGENT_PID" 2>/dev/null; then echo "no agent" >&2; exit 1; fi
trap 'ssh-agent -k >/dev/null 2>&1; echo "workdir: $W"' EXIT
trap 'exit 130' INT TERM
ssh-keygen -q -t ed25519 -N "" -C pijul-scaling -f "$W/key" && ssh-add -q "$W/key"
export HOME="$W" PIJUL_CONFIG_DIR="$W/cfg"; mkdir -p "$W/cfg"
"$P" identity new --no-link --display-name tester --email t@example.invalid tester >/dev/null 2>&1 || true

[ $# -eq 0 ] && set -- "200 5" "400 5" "800 5" "400 10" "400 20"
printf '%6s %4s %8s %10s %10s\n' N K edges "apply(s)" "rest(s)"
for nk in "$@"; do
    set -- $nk; N=$1; K=$2
    d="$W/r-$N-$K"; "$P" init "$d" >/dev/null; cd "$d"
    seq 1 "$N" | sed 's/^/line /' > big.txt; "$P" add big.txt >/dev/null
    "$P" record -a -m v0 >/dev/null
    for k in $(seq 1 "$K"); do
        # Scattered edits, like a generated file updated over the years:
        # every 4th line (shifted per version) changes.
        awk -v k="$k" '{ if ((NR + k) % 4 == 0) print "version " k " " $0; else print }' big.txt > big.new
        mv big.new big.txt; "$P" record -a -m "v$k" >/dev/null
    done
    rm big.txt; "$P" remove big.txt >/dev/null 2>&1; "$P" record -a -m delete >/dev/null
    del=$("$P" log --hash-only | sed -n 1p)
    edges=$("$P" change "$del" | tr ',' '\n' | grep -c -- '->')
    # Fresh repository: apply everything but the deletion, then the deletion.
    "$P" init "$d-fresh" >/dev/null; cp -r .pijul/changes/* "$d-fresh/.pijul/changes/"
    hashes=$("$P" log --hash-only | tac | sed '$d')
    if [ -n "${BY_PATH:-}" ]; then
        hashes=$(for h in $hashes; do echo ".pijul/changes/${h:0:2}/${h:2}.change"; done)
        del=".pijul/changes/${del:0:2}/${del:2}.change"
    fi
    cd "$d-fresh"
    t0=$(date +%s.%N); "$P" apply $hashes >/dev/null 2>&1 || echo "apply rest failed"; t1=$(date +%s.%N)
    # beta.23 does not output what it applies; the deletion then fails with
    # "Path not in repository". Not timed.
    t1r=$t1; if [ -n "${BY_PATH:-}" ]; then "$P" reset >/dev/null 2>&1; t1r=$(date +%s.%N); fi
    "$P" apply "$del" >/dev/null 2>&1 || echo "apply delete failed"; t2=$(date +%s.%N)
    printf '%6s %4s %8s %10.2f %10.2f\n' "$N" "$K" "$edges" "$(echo "$t2 - $t1r" | bc)" "$(echo "$t1 - $t0" | bc)"
done

graph_compare.sh

#!/usr/bin/env bash
# Builds the state before the deletion of a delete_scaling.sh repository with
# several pijul binaries, counts the edges of the resulting graph by kind
# (`pijul debug`), then times the deletion. Applies by change file path
# (beta.23 takes no bare hashes) and resets before the deletion (beta.23 does
# not output what it applies). Nothing is recorded.
# Usage: graph_compare.sh SOURCE_REPO NAME=BINARY...
set -u
export LC_ALL=C
SRC=$(cd "$1" && pwd); shift
W=$(mktemp -d "${TMPDIR:-/tmp}/pijul-graph.XXXX")
first=${1#*=}
hs=$(cd "$SRC" && HOME="$W" PIJUL_CONFIG_DIR="$W/cfg" "$first" log --hash-only | tac)
export HOME="$W" PIJUL_CONFIG_DIR="$W/cfg"; mkdir -p "$W/cfg"
del=$(echo "$hs" | tail -1)
path() { echo ".pijul/changes/${1:0:2}/${1:2}.change"; }
args=$(for h in $(echo "$hs" | sed '$d'); do path "$h"; done)
for nb in "$@"; do
    name=${nb%%=*}; B=${nb#*=}
    d="$W/$name"; "$B" init "$d" >/dev/null; cp -r "$SRC/.pijul/changes/"* "$d/.pijul/changes/"; cd "$d"
    t0=$(date +%s.%N); "$B" apply $args >/dev/null 2>&1; t1=$(date +%s.%N)
    "$B" debug > "$W/$name.dot" 2>/dev/null
    g() { grep forestgreen "$W/$name.dot" | grep "$@"; }
    printf '%-8s versions %6.1f s  child edges: plain %5d  deleted %5d  pseudo %5d\n' "$name" \
        "$(echo "$t1 - $t0" | bc)" "$(g -vc style=)" "$(g -c dashed)" "$(g -c dotted)"
    "$B" reset >/dev/null 2>&1
    t0=$(date +%s.%N); "$B" apply "$(path "$del")" >/dev/null 2>&1; rc=$?; t1=$(date +%s.%N)
    printf '%-8s deletion %6.1f s  rc=%d\n' "$name" "$(echo "$t1 - $t0" | bc)" "$rc"
done
echo "workdir: $W"

Reduction.lean

import Mathlib.Logic.Relation
import Mathlib.Data.Fintype.Card
import Mathlib.Data.Fintype.Option
import Mathlib.Data.Fintype.Pigeonhole

set_option linter.style.header false

/-!
# Soundness of the witness-based reduction in `repair_zombies`

Model of fix 2 for pijul-core `apply.rs` (`non_minimal_multi`,
`non_maximal_multi`, `restore_cycles`). The graph is abstracted away: all
that matters is a relation `R a b`, "`a` reaches `b` over alive edges", which
is transitive.

For one dead vertex, `repair_zombies` must make every entering vertex `l`
reach every exiting vertex `r`. Instead of a bridge `l → r` for every pair,
it drops members that are *witnessed*:

* exiting side: `wX m = some o` means the walk found an alive path from the
  member `o` to the member `m` (so `R o m`);
* entering side: `wE m = some o` means the walk found an alive path from the
  member `m` to the member `o` (so `R m o`).

A walk that stops early (budget) just witnesses less. `restore_cycles` then
keeps a set `K` of members: every unwitnessed member, and one member of every
cycle of witnesses. A member is *grounded* when following witnesses from it
ends in a kept member. Bridges are emitted between kept members only.

Theorems:

* `kept_reaches_exiting` / `entering_reaches_kept`: a grounded member is
  reached by (reaches) a kept member.
* `reduction_sound`: for grounded `l` and `r`, the alive graph plus the
  bridges `K_E × K_X` makes `l` reach `r`. This is the soundness of the
  approach, for *any* witness assignment with correct witnesses, and for any
  kept set that grounds everything.
* `all_grounded`: on a finite set, keeping every unwitnessed member and one
  member of every cycle grounds every member. This is what `restore_cycles`
  guarantees, and why its cycle handling is needed: without it (`C = ∅`), a
  cycle of witnesses grounds nobody.
-/

namespace Reduction

variable {α : Type*}

/-- `a` reaches `b` in zero or more steps. `R` is already transitive, so one
step or none is enough. -/
def Reach (R : α → α → Prop) (a b : α) : Prop := a = b ∨ R a b

theorem Reach.refl (R : α → α → Prop) (a : α) : Reach R a a := Or.inl rfl

theorem Reach.of_rel {R : α → α → Prop} {a b : α} (h : R a b) : Reach R a b := Or.inr h

theorem Reach.trans {R : α → α → Prop} [IsTrans α R] {a b c : α}
    (h₁ : Reach R a b) (h₂ : Reach R b c) : Reach R a c := by
  rcases h₁ with rfl | h₁
  · exact h₂
  · rcases h₂ with rfl | h₂
    · exact Or.inr h₁
    · exact Or.inr (IsTrans.trans _ _ _ h₁ h₂)

theorem Reach.mono {R R' : α → α → Prop} (h : ∀ a b, R a b → R' a b) {a b : α}
    (hab : Reach R a b) : Reach R' a b := by
  rcases hab with rfl | hab
  · exact Or.inl rfl
  · exact Or.inr (h _ _ hab)

/-- Following witnesses from `m` ends in a kept member. -/
inductive Grounded (w : α → Option α) (K : Set α) : α → Prop
  | kept {m : α} : m ∈ K → Grounded w K m
  | step {m o : α} : w m = some o → Grounded w K o → Grounded w K m

/-- Exiting side: witnesses reach the witnessed. A grounded member is reached
by a kept one, which therefore carries its bridge. -/
theorem kept_reaches_exiting {R : α → α → Prop} [IsTrans α R] {w : α → Option α} {K : Set α}
    (hw : ∀ m o, w m = some o → R o m) {m : α} (h : Grounded w K m) :
    ∃ k ∈ K, Reach R k m := by
  induction h with
  | kept hk => exact ⟨_, hk, Reach.refl R _⟩
  | step hwo _ ih =>
    obtain ⟨k, hk, hkm⟩ := ih
    exact ⟨k, hk, hkm.trans (Reach.of_rel (hw _ _ hwo))⟩

/-- Entering side: the witnessed reaches its witness. A grounded member reaches
a kept one. -/
theorem entering_reaches_kept {R : α → α → Prop} [IsTrans α R] {w : α → Option α} {K : Set α}
    (hw : ∀ m o, w m = some o → R m o) {m : α} (h : Grounded w K m) :
    ∃ k ∈ K, Reach R m k := by
  induction h with
  | kept hk => exact ⟨_, hk, Reach.refl R _⟩
  | step hwo _ ih =>
    obtain ⟨k, hk, hkm⟩ := ih
    exact ⟨k, hk, (Reach.of_rel (hw _ _ hwo)).trans hkm⟩

/-- Soundness of the approach. `R'` is the alive graph after the repair: it
contains `R` and a bridge from every kept entering member to every kept
exiting member. Then every grounded entering `l` reaches every grounded
exiting `r`, as the full product would have made it. -/
theorem reduction_sound {R R' : α → α → Prop} [IsTrans α R] [IsTrans α R']
    (hRR' : ∀ a b, R a b → R' a b)
    {wE wX : α → Option α} {KE KX : Set α}
    (hE : ∀ m o, wE m = some o → R m o) (hX : ∀ m o, wX m = some o → R o m)
    (hbridge : ∀ k ∈ KE, ∀ k' ∈ KX, R' k k')
    {l r : α} (gl : Grounded wE KE l) (gr : Grounded wX KX r) :
    Reach R' l r := by
  obtain ⟨k, hk, hlk⟩ := entering_reaches_kept hE gl
  obtain ⟨k', hk', hk'r⟩ := kept_reaches_exiting hX gr
  exact (hlk.mono hRR').trans ((Reach.of_rel (hbridge k hk k' hk')).trans (hk'r.mono hRR'))

/-! ## What `restore_cycles` must deliver

`iter w n m` follows witnesses `n` times. On a finite set, a chain either
runs into an unwitnessed member or repeats, and a repeated member lies on a
cycle. Keeping the unwitnessed members and one member of each cycle grounds
every member. -/

/-- Follow witnesses `n` times. -/
def iter (w : α → Option α) : ℕ → α → Option α
  | 0, m => some m
  | n + 1, m => (iter w n m).bind w

theorem iter_zero (w : α → Option α) (m : α) : iter w 0 m = some m := rfl

theorem iter_succ (w : α → Option α) (n : ℕ) (m : α) :
    iter w (n + 1) m = (iter w n m).bind w := rfl

theorem iter_add (w : α → Option α) (i d : ℕ) (m : α) :
    iter w (i + d) m = (iter w i m).bind (iter w d) := by
  induction d with
  | zero => cases iter w i m <;> rfl
  | succ d ih =>
    rw [← Nat.add_assoc, iter_succ, ih]
    cases iter w i m <;> rfl

/-- Grounded is preserved backwards along chains. -/
theorem grounded_of_iter {w : α → Option α} {K : Set α} {m x : α} {n : ℕ}
    (h : iter w n m = some x) (hx : Grounded w K x) : Grounded w K m := by
  induction n generalizing x with
  | zero => obtain rfl : m = x := Option.some.inj h; exact hx
  | succ n ih =>
    rw [iter_succ] at h
    cases hy : iter w n m with
    | none => simp [hy] at h
    | some y =>
      rw [hy] at h
      change w y = some x at h
      exact ih hy (Grounded.step h hx)

/-- A member on a cycle of witnesses. -/
def Cyclic (w : α → Option α) (x : α) : Prop := ∃ d, 0 < d ∧ iter w d x = some x

/-- If the chain from `m` breaks after `n` steps, then it ended at an
unwitnessed member, reachable from `m`. -/
theorem exists_unwitnessed_of_none {w : α → Option α} {m : α} {n : ℕ}
    (h : iter w n m = none) : ∃ i x, iter w i m = some x ∧ w x = none := by
  induction n with
  | zero => simp [iter_zero] at h
  | succ n ih =>
    rw [iter_succ] at h
    cases hy : iter w n m with
    | none => exact ih hy
    | some y =>
      rw [hy] at h
      change w y = none at h
      exact ⟨n, y, hy, h⟩

/-- `restore_cycles`: with every unwitnessed member kept and every cycle
met by a kept member, every member is grounded. -/
theorem all_grounded [Finite α] {w : α → Option α} {K : Set α}
    (hnone : ∀ m, w m = none → m ∈ K)
    (hcyc : ∀ x, Cyclic w x → ∃ n, ∃ k ∈ K, iter w n x = some k) (m : α) :
    Grounded w K m := by
  have := Fintype.ofFinite α
  -- The chain `iter w · m` on `card α + 2` indices cannot be injective into `Option α`.
  have hcard : Fintype.card (Option α) < Fintype.card (Fin (Fintype.card α + 2)) := by
    rw [Fintype.card_option, Fintype.card_fin]
    omega
  obtain ⟨i, j, hij, hiter⟩ :=
    Fintype.exists_ne_map_eq_of_card_lt (fun i : Fin (Fintype.card α + 2) => iter w i m) hcard
  -- Order the two indices.
  wlog hlt : (i : ℕ) < j generalizing i j
  · exact this j i hij.symm hiter.symm
      (lt_of_le_of_ne (not_lt.mp hlt) (fun h => hij (Fin.ext h.symm)))
  cases hx : iter w i m with
  | none =>
    obtain ⟨_, x, hx', hwx⟩ := exists_unwitnessed_of_none hx
    exact grounded_of_iter hx' (Grounded.kept (hnone x hwx))
  | some x =>
    -- `x` repeats after `j - i` steps: it is cyclic.
    have hcyc_x : Cyclic w x := by
      refine ⟨j - i, Nat.sub_pos_of_lt hlt, ?_⟩
      have := iter_add w i (j - i) m
      rw [Nat.add_sub_cancel' hlt.le, ← hiter, hx] at this
      exact this.symm
    obtain ⟨n, k, hk, hnk⟩ := hcyc x hcyc_x
    exact grounded_of_iter hx (grounded_of_iter hnk (Grounded.kept hk))

end Reduction