/- Copyright (c) 2026 Andrew Noyes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. # Statement of minimality for a conflict range inference algorithm > **The closed form is minimal.** For every readable read/result pair `(r, res)`, > `closedForm r res` is a minimal sound conflict range. > > **Minimality is unique.** Any two minimal sound ranges for the same read and > result denote the same set of keys. It is a *statement* file, meant for review, not a proof. It contains: * the vocabulary --- keys, databases, selectors, reads, results, conflict ranges, soundness, and minimality * the closed form itself, in `## The closed form`, because the theorem is *about that function* * the headlines as the propositions `ClosedFormMinimal` and `MinimalUnique` There is no `theorem`, no `axiom`, no `sorry`, and the only import is Mathlib. ## Shape The closed form is a total, result-aware dispatch: ``` closedForm r res = if res.keys = [] then emptyValue r else if 1 ≤ r.begin.offset then closedFormPositive r res else if clampedNonpos r res then closedFormClamped r res else closedFormCrossed r res ``` `emptyValue` handles the empty result. `closedFormPositive` and `closedFormClamped` dispatch through `closedFormSplit` on whether the result is complete and, when it is not, on the direction. `closedFormCrossed` is the residual: nonempty, nonpositive-begin reads outside the clamped case, handled by a priority table over complete results and the two `more = true` cases (forward and reversed), split by `reverse`, `end_.offset ≤ 1` and a few capacity tests. Every leaf of the table is a literal half-open interval built from `begin.key`, `end_.key`, the reported head or last key, `keyAfter`, or `⊤`; there is no search and no oracle. That is the sense in which it is a *closed form*. The names below use "truncated" as shorthand for the `more = true` cases; a `more = true` result need only be a nonempty prefix, not a proper one. Many of the `Prop`-valued helpers below are `@[reducible]` so that `Decidable` synthesis can unfold them in `if` conditions; the `synthInstance.maxSize` bump before `closedFormCrossedComplete` is for the six-way clamp disjunction. The definitions are in dependency order, so the dispatcher comes last, right before the headline. -/ import Mathlib namespace Statement /-! ## Keys and databases -/ /-- A byte is an 8-bit value. -/ abbrev Byte := Fin 256 /-- A key is a list of bytes, ordered lexicographically. -/ abbrev Key := List Byte /-- A database is a list of keys, strictly increasing in the lexicographic order, hence duplicate-free. -/ structure DB where keys : List Key sorted : keys.SortedLT /-! ## Selectors -/ /-- A selector names a key position in `WithTop Key`, with an integer offset. The empty key anchors at the start of the key space and `⊤` anchors past every stored key. -/ structure Selector where key : WithTop Key offset : Int /-- The signed index a selector targets: the number of stored keys strictly below `selector.key` (none for the empty key, all of them for `⊤`), minus one, shifted by `selector.offset`. Offset `0` names the last stored key strictly below `selector.key`, which is index `-1` when there is none; offset `1` names the first stored key at or above it; offset `-1` names the key before that. -/ def Selector.anchor (db : DB) (s : Selector) : Int := (db.keys.countP (fun (k : Key) => decide ((↑k : WithTop Key) < s.key)) : Int) + s.offset - 1 /-- Resolve a selector against a database: target the anchor key, clamp negative indices to the empty key, and clamp indices past the end to `⊤`. Resolution never fails. -/ def resolve (db : DB) (s : Selector) : WithTop Key := if s.anchor db < 0 then ([] : Key) else match db.keys[(s.anchor db).toNat]? with | some k => k | none => ⊤ /-! ## Range reads and results -/ /-- A range read names `begin` and `end_` selectors and whether to traverse in reverse. -/ structure RangeRead where begin : Selector end_ : Selector reverse : Bool /-- The outcome of a range read: the keys produced and a `more` flag. In a compatible result, `more = false` means the keys are exactly the complete keys; `more = true` only means they form a nonempty prefix, so it does not assert that any key remains. -/ structure Result where keys : List Key more : Bool /-- The keys of `ks` lying in the half-open interval `[lo, hi)`, ascending. The bounds are in `WithTop Key`, so `⊤` naturally means "past the end". -/ def RangeRead.inRange (ks : List Key) (lo hi : WithTop Key) : List Key := ks.filter (fun k => decide (lo ≤ (k : WithTop Key) ∧ (k : WithTop Key) < hi)) /-- The complete keys of a range read: every stored key in the half-open interval `[resolve begin, resolve end_)`, reversed when the read is reversed. -/ def RangeRead.completeKeys (db : DB) (r : RangeRead) : List Key := let ks := inRange db.keys (resolve db r.begin) (resolve db r.end_) if r.reverse then ks.reverse else ks /-- A result is compatible with a range read when it is a valid response: a nonempty prefix of the complete keys with `more = true`, or exactly the complete keys with `more = false`. The prefix need not be proper, so `more = true` does not assert that any key remains; the nonemptiness requirement reflects that a truncated response reports at least one key. -/ def RangeRead.Compatible (db : DB) (r : RangeRead) (res : Result) : Prop := (res.more = true ∧ res.keys <+: completeKeys db r ∧ res.keys ≠ []) ∨ (res.more = false ∧ res.keys = completeKeys db r) /-- A read/result pair is realizable: some database is compatible with it. An inference sees only the read and the returned result, never the database contents, so readability --- not a particular database --- is the hypothesis of the headline theorem. -/ def Readable (r : RangeRead) (res : Result) : Prop := ∃ db, RangeRead.Compatible db r res /-! ## Conflict ranges -/ /-- A conflict range is a half-open interval of keys. Its lower end may be the empty key (an unbounded range from the bottom) and its upper end may be `⊤` (an unbounded range from the top). The endpoints need not be ordered: if `begin ≥ end_` the range contains no keys. -/ structure ConflictRange where begin : WithTop Key end_ : WithTop Key /-- A key falls in a conflict range when `begin ≤ k < end_`. -/ def ConflictRange.mem (cr : ConflictRange) (k : Key) : Prop := cr.begin ≤ (k : WithTop Key) ∧ (k : WithTop Key) < cr.end_ instance : Membership Key ConflictRange := ⟨ConflictRange.mem⟩ /-- The set of keys lying in a conflict range. -/ def ConflictRange.toSet (cr : ConflictRange) : Set Key := {k | k ∈ cr} /-- The keys of a database lying in a conflict range, ascending. -/ def ConflictRange.keys (cr : ConflictRange) (db : DB) : List Key := RangeRead.inRange db.keys cr.begin cr.end_ /-- A conflict range is a subrange of another when every key in the first also lies in the second. -/ def Subrange (cr' cr : ConflictRange) : Prop := ∀ k, k ∈ cr' → k ∈ cr /-- A conflict range is a proper subrange when it is a subrange and the reverse containment fails, i.e. the larger range contains a key the smaller does not. -/ def ProperSubrange (cr' cr : ConflictRange) : Prop := Subrange cr' cr ∧ ¬ Subrange cr cr' /-! ## Soundness and minimality -/ /-- Two databases agree on a conflict range when they store the same keys in it. -/ def AgreeOn (cr : ConflictRange) (db₁ db₂ : DB) : Prop := cr.keys db₁ = cr.keys db₂ /-- A conflict range is sound for a read and result when every pair of databases that agree on the range also agree on whether the result is compatible with the read. -/ def Sound (r : RangeRead) (res : Result) (cr : ConflictRange) : Prop := ∀ db₁ db₂, AgreeOn cr db₁ db₂ → (RangeRead.Compatible db₁ r res ↔ RangeRead.Compatible db₂ r res) /-- A conflict range is minimal when it is sound and no proper subrange of it is sound: every key in the range --- not merely every key stored in a particular database --- is needed. -/ def Minimal (r : RangeRead) (res : Result) (cr : ConflictRange) : Prop := Sound r res cr ∧ ∀ cr', ProperSubrange cr' cr → ¬ Sound r res cr' /-! ## The closed form -/ /-! ### Notation -/ /-- The empty key, as the bottom of `WithTop Key`. -/ abbrev bottom : WithTop Key := ↑([] : Key) /-- A conflict range from `begin` to `end_`. -/ abbrev range (begin end_ : WithTop Key) : ConflictRange := { begin := begin, end_ := end_ } /-- The first key of a result. -/ abbrev firstKey (res : Result) : Key := res.keys.headD [] /-- The last key of a result. -/ abbrev lastKey (res : Result) : Key := res.keys.getLastD [] /-- The first key of a result, as an ambient key. -/ abbrev first (res : Result) : WithTop Key := ↑(firstKey res) /-- The last key of a result, as an ambient key. -/ abbrev last (res : Result) : WithTop Key := ↑(lastKey res) /-- The same read with traversal forced forward. -/ abbrev forwardRead (r : RangeRead) : RangeRead := { r with reverse := false } /-- A complete result with the same keys in reverse order. -/ abbrev reversedResult (res : Result) : Result := { keys := res.keys.reverse, more := false } /-- The successor of `k`. -/ def keyAfter (k : Key) : Key := k ++ [0] /-- The successor of the first reported key, as an ambient key. -/ abbrev afterFirst (res : Result) : WithTop Key := ↑(keyAfter (firstKey res)) /-- The successor of the last reported key, as an ambient key. -/ abbrev afterLast (res : Result) : WithTop Key := ↑(keyAfter (lastKey res)) /-! ### Arithmetic helpers -/ /-- The nonpositive begin slack, `-begin.offset` as a natural. -/ def beginSlack (r : RangeRead) : ℕ := (0 - r.begin.offset).toNat /-- The offset datum `max (2 - oE) (oB - oE + 1)` as a natural number: the least end count `cE` compatible with the end anchor and with room for the begin anchor. Any feasible solution has `cE` at least this. -/ def cELo (oB oE : ℤ) : ℕ := max (2 - oE).toNat (oB - oE + 1).toNat /-- The least end count when the begin endpoint is `⊤`: only the end-anchor positivity `2 - oE ≤ cE` constrains it, since the begin count is then free. -/ def cEminP (_oB oE : ℤ) : ℕ := (2 - oE).toNat def canonicalRange (r : RangeRead) : ConflictRange := range r.begin.key r.end_.key /-- The number of key slots in `[b, e)` under the zero-padded prefix encoding: zero if `e ≤ b`, the length difference when `b` is a prefix of `e` followed only by zero bytes, and `⊤` otherwise. -/ def intervalCard (b e : WithTop Key) : ℕ∞ := match b, e with | none, _ => 0 | _, none => ⊤ | some b, some e => if e ≤ b then 0 else if b <+: e ∧ ((List.drop (List.length b) e).all fun c : Byte => c == 0) = true then ↑(List.length e - List.length b) else ⊤ /-- The capacity of the key gap `[end_.key, begin.key)`. -/ def clampCap (r : RangeRead) : ℕ∞ := intervalCard r.end_.key r.begin.key /-- The number `t` of reported keys at or above `end_.key`. -/ def residualT (r : RangeRead) (res : Result) : ℕ := List.countP (fun k : Key => decide (r.end_.key ≤ ↑k)) res.keys /-- The end offset `e = end.offset - 1`. -/ def residualE (r : RangeRead) : ℕ := (r.end_.offset - 1).toNat /-- The begin overshoot `b = begin.offset - 1`. -/ def residualB (r : RangeRead) : ℕ := (r.begin.offset - 1).toNat /-- The capacity deficit `d = max 0 (b - g)`, with `g : ℕ∞`; an infinite gap leaves nothing to fill. -/ def residualD (r : RangeRead) (g : ℕ∞) : ℕ := if g = ⊤ then 0 else residualB r - g.toNat /-- Reported keys strictly below `begin.key`. -/ def reportedBelowBegin (r : RangeRead) (res : Result) : ℕ := List.countP (fun k : Key => decide (↑k < r.begin.key)) res.keys /-- The slack beyond the reported keys below `begin.key`. -/ def clampSlack (r : RangeRead) (res : Result) : ℕ := beginSlack r + 1 - reportedBelowBegin r res /-- The upper endpoint of the clamp end-one cell. -/ def clampEndOneUpper (r : RangeRead) (res : Result) : WithTop Key := if ↑(clampSlack r res) ≤ clampCap r ∧ (↑(clampSlack r res) < clampCap r ∨ first res ≠ bottom) then r.begin.key else r.end_.key /-- The capacity of the key gap `[keyAfter last reported, begin.key)`. -/ def clampHighCap (r : RangeRead) (res : Result) : ℕ∞ := intervalCard (afterLast res) r.begin.key /-- The threshold for the clamping finite branch: `clampSlack`, plus one when `end_.key` is the empty key. -/ def clampHighThresh (r : RangeRead) (res : Result) : ℕ := clampSlack r res + if r.end_.key = bottom then 1 else 0 /-- The upper endpoint of the clamping finite branch of the crossed negative-begin complete high cell. -/ def clampHighU (r : RangeRead) (res : Result) : WithTop Key := if ↑(clampHighThresh r res) ≤ clampHighCap r res then r.begin.key else afterLast res /-- The buffer size `d = -end.offset`. -/ def clampNonposD (r : RangeRead) : ℕ := (0 - r.end_.offset).toNat /-- The capacity slack `C = beginSlack - reportedBelowBegin - clampNonposD` of the crossed negative-begin complete long clamp cell. -/ def clampLongC (r : RangeRead) (res : Result) : ℕ := beginSlack r - reportedBelowBegin r res - clampNonposD r /-- The upper endpoint of the crossed negative-begin complete long clamp cell. -/ def clampLongUpper (r : RangeRead) (res : Result) : WithTop Key := if clampCap r < ↑(clampLongC r res) ∨ clampCap r = ↑(clampLongC r res) ∧ first res = bottom then r.end_.key else r.begin.key @[reducible] def clampNonposBottom (r : RangeRead) (res : Result) : Prop := ↑(reportedBelowBegin r res) + (↑(clampNonposD r + 1) - intervalCard r.begin.key r.end_.key) ≤ ↑(beginSlack r) def leastReported (r : RangeRead) (res : Result) : Key := if r.reverse = true then lastKey res else firstKey res @[reducible] def clampedNonpos (r : RangeRead) (res : Result) : Prop := r.begin.offset ≤ 0 ∧ r.begin.key ≤ ↑(leastReported r res) @[reducible] def clampsToBottom (r : RangeRead) (res : Result) : Prop := r.begin.offset ≤ 0 ∧ r.begin.key ≤ first res /-- The begin count of the canonical no-pin witness: the least value within the difference cap `KBE` of the least end count `cELo`. -/ def noPinB (KBE : ℕ∞) (oB oE : ℤ) : ℕ := if KBE = ⊤ then 0 else max 0 (cELo oB oE - KBE.toNat) /-! ### Crossed complete cases -/ def closedFormNegCrossClampEndOne (r : RangeRead) (res : Result) : ConflictRange := range bottom (clampEndOneUpper r res) @[reducible] def negCrossClampEndOne (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ r.begin.offset < 0 ∧ res.more = false ∧ r.end_.offset = 1 ∧ first res < r.begin.key ∧ reportedBelowBegin r res ≤ beginSlack r @[reducible] def negCrossHeadBottom (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ r.begin.offset < 0 ∧ res.more = false ∧ r.end_.offset ≤ 0 ∧ r.begin.key ≤ r.end_.key ∧ first res = bottom @[reducible] def negCrossClampNonposInfinite (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ r.begin.offset < 0 ∧ res.more = false ∧ r.end_.offset ≤ 0 ∧ r.begin.key ≤ r.end_.key ∧ intervalCard r.begin.key r.end_.key = ⊤ ∧ first res < r.begin.key ∧ reportedBelowBegin r res ≤ beginSlack r @[reducible] def negCrossClampNonposLastGe (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ r.begin.offset < 0 ∧ res.more = false ∧ r.end_.offset ≤ 0 ∧ first res < r.begin.key ∧ r.begin.key ≤ last res ∧ reportedBelowBegin r res ≤ beginSlack r @[reducible] def negCrossClampNonposBottom (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ r.begin.offset < 0 ∧ res.more = false ∧ r.end_.offset ≤ 0 ∧ r.begin.key ≤ r.end_.key ∧ first res < r.begin.key ∧ clampNonposBottom r res @[reducible] def negCrossClampLongNonpos (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ r.begin.offset < 0 ∧ res.more = false ∧ r.end_.offset ≤ 0 ∧ first res < r.begin.key ∧ reportedBelowBegin r res ≤ beginSlack r ∧ clampNonposBottom r res ∧ r.end_.key < r.begin.key def closedFormNegCrossClampUnified (r : RangeRead) (res : Result) : ConflictRange := let end_ := if negCrossClampEndOne r res then clampEndOneUpper r res else if negCrossHeadBottom r res ∨ negCrossClampNonposInfinite r res ∨ negCrossClampNonposLastGe r res ∨ negCrossClampNonposBottom r res then r.end_.key else if negCrossClampLongNonpos r res then clampLongUpper r res else r.end_.key range bottom end_ def negCrossCompleteHighM (r : RangeRead) (res : Result) : WithTop Key := max r.begin.key (afterLast res) def negCrossHighD (r : RangeRead) (res : Result) : ℕ := residualE r - res.keys.length def negCrossHighGapCap (r : RangeRead) (res : Result) : ℕ∞ := intervalCard r.end_.key (first res) @[reducible] def negCrossHighUsesEnd (r : RangeRead) (res : Result) : Prop := ↑(negCrossHighD r res) < negCrossHighGapCap r res ∨ ↑(negCrossHighD r res) ≤ negCrossHighGapCap r res ∧ r.begin.key < ⊤ def closedFormNegCrossCompleteHigh (r : RangeRead) (res : Result) : ConflictRange := if reportedBelowBegin r res ≤ beginSlack r then if res.keys.length = residualE r then range bottom (clampHighU r res) else range bottom ⊤ else if res.keys.length = residualE r then range r.end_.key (negCrossCompleteHighM r res) else if negCrossHighUsesEnd r res then range r.end_.key ⊤ else range (first res) ⊤ @[reducible] def negCrossCompleteHigh (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ r.begin.offset < 0 ∧ res.more = false ∧ 2 ≤ r.end_.offset ∧ first res < r.begin.key ∧ r.end_.key < first res def closedFormDeficit (r : RangeRead) : ℕ := residualD r (intervalCard r.begin.key r.end_.key) def completeResidualReduced (r : RangeRead) (res : Result) : RangeRead := { r with end_ := { key := afterLast res, offset := r.end_.offset - ↑(residualT r res) } } def topOfLast (last : Key) : ConflictRange := range ↑last ⊤ def closedFormNegCrossOvershoot (r : RangeRead) (res : Result) : ConflictRange := if reportedBelowBegin r res ≤ beginSlack r then range bottom ⊤ else topOfLast (firstKey res) def closedFormNegCrossEndOne (r : RangeRead) (res : Result) : ConflictRange := range (first res) r.end_.key def closedFormNegCrossEndOneLong (r : RangeRead) (res : Result) : ConflictRange := range (first res) r.begin.key def closedFormNegCrossCompleteResidual (r : RangeRead) (res : Result) : ConflictRange := let r' := completeResidualReduced r res if 2 ≤ r'.end_.offset then closedFormNegCrossOvershoot r' res else if reportedBelowBegin r' res ≤ beginSlack r' then closedFormNegCrossClampEndOne r' res else if r.begin.key ≤ r'.end_.key then closedFormNegCrossEndOne r' res else closedFormNegCrossEndOneLong r' res def closedFormNegCrossCompleteHighResidual (r : RangeRead) (res : Result) : ConflictRange := if negCrossCompleteHigh r res then closedFormNegCrossCompleteHigh r res else closedFormNegCrossCompleteResidual r res def closedFormNegCrossNonclampUnified (r : RangeRead) (res : Result) : ConflictRange := range (first res) (max r.end_.key r.begin.key) def closedFormNegCrossTopUnified (r : RangeRead) (res : Result) : ConflictRange := let begin := if reportedBelowBegin r res ≤ beginSlack r then bottom else ↑(leastReported r res) range begin ⊤ /-! ### Crossed truncated cases -/ @[reducible] def negCrossTruncNonposGap (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = false ∧ r.begin.offset < 0 ∧ ↑(leastReported r res) < r.begin.key ∧ r.end_.offset ≤ 0 ∧ reportedBelowBegin r res ≤ beginSlack r ∧ last res < r.begin.key ∧ last res < r.end_.key ∧ r.end_.key < ⊤ ∧ (r.end_.key < r.begin.key ∨ intervalCard r.begin.key r.end_.key < ↑(clampNonposD r + 1)) @[reducible] def negCrossTruncNonposGapA2aBottom (r : RangeRead) (res : Result) : Prop := negCrossTruncNonposGap r res ∧ r.end_.key < r.begin.key ∧ clampNonposBottom r res @[reducible] def negCrossTruncNonposGapA2aBottomHigh (r : RangeRead) (res : Result) : Prop := negCrossTruncNonposGapA2aBottom r res ∧ ↑(beginSlack r + 1 + if first res = bottom then 1 else 0) ≤ ↑res.keys.length + intervalCard (afterLast res) r.begin.key def closedFormNegCrossTruncNonposGapA2aBottom (r : RangeRead) (res : Result) : ConflictRange := if negCrossTruncNonposGapA2aBottomHigh r res then range bottom r.begin.key else range bottom r.end_.key def closedFormNegCrossTruncRevBelowEnd (_r : RangeRead) (res : Result) : ConflictRange := topOfLast (lastKey res) def closedFormNegCrossTruncRevCrossedNonposLarge (r : RangeRead) (res : Result) : ConflictRange := range (last res) r.begin.key @[reducible] def finiteUnderCond (r : RangeRead) (res : Result) : Prop := ↑(reportedBelowBegin r res - 1) + intervalCard (afterFirst res) r.begin.key ≤ ↑(beginSlack r) def closedFormNegCrossTruncRevResidualFiniteUnder (r : RangeRead) (res : Result) : ConflictRange := let L := last res let U := if finiteUnderCond r res then afterFirst res else r.begin.key range L U @[reducible] def negCrossTruncRevResidualFiniteOver (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ 2 ≤ r.end_.offset ∧ r.end_.key < last res ∧ last res < r.begin.key ∧ residualT r res = residualE r def closedFormNegCrossTruncRevResidualFiniteUnified (r : RangeRead) (res : Result) : ConflictRange := let under := closedFormNegCrossTruncRevResidualFiniteUnder r res if negCrossTruncRevResidualFiniteOver r res then range r.end_.key under.end_ else under @[reducible] def sentinelLargeTight (r : RangeRead) (res : Result) : Prop := let L := last res residualE r = intervalCard r.end_.key L + ↑res.keys.length ∧ ↑res.keys.length + r.begin.offset = 1 def closedFormNegCrossTruncRevResidualTopLargeSentinel (r : RangeRead) (res : Result) : ConflictRange := let L := last res if sentinelLargeTight r res then range L ⊤ else range r.end_.key ⊤ @[reducible] def negCrossTruncRevResidualTopLarge (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ 2 ≤ r.end_.offset ∧ r.end_.key < last res ∧ residualT r res < residualE r ∧ ↑(residualE r) ≤ intervalCard r.end_.key (last res) + ↑res.keys.length @[reducible] def negCrossTruncRevResidualTopLargeSentinel (r : RangeRead) (res : Result) : Prop := negCrossTruncRevResidualTopLarge r res ∧ r.begin.key = ⊤ def closedFormNegCrossTruncRevResidualTopLargeUnified (r : RangeRead) (res : Result) : ConflictRange := if negCrossTruncRevResidualTopLargeSentinel r res then closedFormNegCrossTruncRevResidualTopLargeSentinel r res else range r.end_.key ⊤ def truncatedRangeRev (r : RangeRead) (last : Key) : ConflictRange := range ↑last r.end_.key def closedFormNegCrossTruncRevUnder (r : RangeRead) (res : Result) : ConflictRange := truncatedRangeRev r (lastKey res) def closedFormNegCrossTruncTopTopEq (_r : RangeRead) (res : Result) : ConflictRange := range (first res) ⊤ /-! ### Complete and offset-one cases -/ /-- Iterating the successor `keyAfter`. -/ def keyAfterN : ℕ → Key → Key | 0, k => k | n+1, k => keyAfter (keyAfterN n k) def closedFormReverseTruncatedZero (r : RangeRead) (res : Result) : ConflictRange := if r.end_.offset ≤ 1 then truncatedRangeRev r (lastKey res) else let L := last res if residualT r res = residualE r then range (min L r.end_.key) (afterFirst res) else match r.end_.key with | some E => if keyAfterN (residualE r - residualT r res - 1) E < lastKey res then range ↑E ⊤ else range L ⊤ | none => range L ⊤ def truncatedRange (r : RangeRead) (last : Key) : ConflictRange := range r.begin.key (↑(keyAfter last)) def truncatedForwardClosed (r : RangeRead) (res : Result) : ConflictRange := if intervalCard r.end_.key r.begin.key ≤ ↑(residualE r - res.keys.length) then truncatedRange r (lastKey res) else range r.end_.key (afterLast res) def gapOvershoot (r : RangeRead) (res : Result) : ℕ := residualE r - residualT r res /-- The complete-result rule, with `endKey` the reported endpoint in traversal order. -/ def completeClosedWith (endKey : WithTop Key) (r : RangeRead) (res : Result) : ConflictRange := let begin := if r.end_.key < r.begin.key ∧ ↑(gapOvershoot r res) ≤ intervalCard r.end_.key r.begin.key then r.end_.key else r.begin.key if r.end_.offset ≤ 1 then canonicalRange r else if residualT r res = residualE r then range begin endKey else range begin ⊤ def completeReversedClosed (r : RangeRead) (res : Result) : ConflictRange := completeClosedWith (afterFirst res) r res def completeForwardClosed (r : RangeRead) (res : Result) : ConflictRange := completeClosedWith (afterLast res) r res def completeClosed (r : RangeRead) (res : Result) : ConflictRange := if r.reverse = true then completeReversedClosed r res else completeForwardClosed r res def closedFormOffsetOneTruncated (r : RangeRead) (res : Result) : ConflictRange := if r.end_.offset ≤ 0 then canonicalRange r else truncatedRange r (lastKey res) def topRange (r : RangeRead) : ConflictRange := range r.begin.key ⊤ /-- The offset-one rule, with `endKey` the reported endpoint in traversal order. -/ def closedFormOffsetOneWith (endKey : Key) (r : RangeRead) (res : Result) : ConflictRange := if r.end_.offset ≤ 1 then canonicalRange r else if residualT r res = residualE r then truncatedRange r endKey else topRange r def closedFormOffsetOneRev (r : RangeRead) (res : Result) : ConflictRange := closedFormOffsetOneWith (firstKey res) r res def closedFormOffsetOne (r : RangeRead) (res : Result) : ConflictRange := closedFormOffsetOneWith (lastKey res) r res def closedFormOffsetOneAny (r : RangeRead) (res : Result) : ConflictRange := if r.reverse = true then closedFormOffsetOneRev r res else closedFormOffsetOne r res def closedFormOffsetOneUniversal (r : RangeRead) (res : Result) : ConflictRange := if res.more = true then if r.reverse = true then closedFormReverseTruncatedZero r res else closedFormOffsetOneTruncated r res else closedFormOffsetOneAny r res def closedFormOffsetOneTotal (r : RangeRead) (res : Result) : ConflictRange := if r.end_.key < r.begin.key then if res.more = true then if r.reverse = true then closedFormReverseTruncatedZero r res else truncatedForwardClosed r res else completeClosed r res else closedFormOffsetOneUniversal r res def nonposRevReduced (r : RangeRead) (res : Result) : RangeRead := { r with begin := { key := last res, offset := 1 } } def closedFormNonposRevTrunc (r : RangeRead) (res : Result) : ConflictRange := closedFormOffsetOneTotal (nonposRevReduced r res) res def closedFormZeroCrossEndOneLong (r : RangeRead) (res : Result) : ConflictRange := range (↑(leastReported r res)) r.begin.key /-! ### Zero-crossed cases -/ def closedFormZeroCrossEnd (r : RangeRead) (res : Result) : ConflictRange := range (↑(leastReported r res)) r.end_.key def crossedOvershootGeneral (r : RangeRead) (res : Result) : ℕ := residualE r - residualT r res - residualB r /-- The begin endpoint of a crossed range: `end_.key` when the crossed overshoot fits in the gap between the anchors, and `begin.key` otherwise. -/ def crossedBegin (r : RangeRead) (res : Result) : WithTop Key := if ↑(crossedOvershootGeneral r res) ≤ intervalCard r.end_.key r.begin.key then r.end_.key else r.begin.key def completeForwardCrossedGeneral (r : RangeRead) (res : Result) : ConflictRange := if r.end_.offset ≤ 1 then canonicalRange r else if residualT r res + residualB r = residualE r then range r.end_.key (afterLast res) else range (crossedBegin r res) ⊤ def zeroBeginAnchor (r : RangeRead) (res : Result) : RangeRead := { r with begin := { key := first res, offset := 1 } } def zeroCrossLongAnchor (r : RangeRead) (res : Result) : ConflictRange := if r.end_.key < first res then completeForwardCrossedGeneral (zeroBeginAnchor r res) res else closedFormOffsetOne (zeroBeginAnchor r res) res def closedFormZeroCrossLong (r : RangeRead) (res : Result) : ConflictRange := if r.begin.key = ⊤ then let H := first res let e := residualE r let t := residualT r res let g := intervalCard r.end_.key H range (if r.end_.key < H ∧ ↑e - ↑t < g then r.end_.key else H) ⊤ else let a := zeroCrossLongAnchor r res range a.begin (max a.end_ r.begin.key) def closedFormZeroCrossUnderEnd (r : RangeRead) (res : Result) : ConflictRange := closedFormOffsetOneTotal (zeroBeginAnchor r res) res def closedFormZeroCrossComplete (r : RangeRead) (res : Result) : ConflictRange := if r.end_.offset ≤ 0 then closedFormZeroCrossEnd r res else if r.end_.offset = 1 then if r.end_.key < r.begin.key then closedFormZeroCrossEndOneLong r res else closedFormZeroCrossEnd r res else if r.begin.key = ⊤ ∨ r.end_.key < r.begin.key then closedFormZeroCrossLong r res else closedFormZeroCrossUnderEnd r res def closedFormZeroCrossCompleteRev (r : RangeRead) (res : Result) : ConflictRange := closedFormZeroCrossComplete (forwardRead r) (reversedResult res) @[reducible] def zeroCrossUnderEnd (r : RangeRead) (res : Result) : Prop := r.begin.offset = 0 ∧ res.more = false ∧ r.reverse = false ∧ 2 ≤ r.end_.offset ∧ ↑(leastReported r res) < r.begin.key ∧ r.begin.key ≤ r.end_.key def closedFormZeroCrossResidual (r : RangeRead) (res : Result) : ConflictRange := if zeroCrossUnderEnd r res then closedFormZeroCrossUnderEnd r res else closedFormZeroCrossLong r res def closedFormZeroCrossTruncRevCrossed (r : RangeRead) (res : Result) : ConflictRange := closedFormZeroCrossCompleteRev r { res with more := false } /-! ### Empty result -/ /-- A read that returns no key for any database. This is the quantifier-free form of `∀ db, completeKeys db r = []`: a test on the two selectors and offsets alone. The outer test splits on whether `begin.key` is `⊤`. With `begin.key = ⊤` the inner test distinguishes `end_.key = ⊤` from a finite end; with `begin.key` finite the `end_.key = ⊤` case is `True` (so it is never always-empty) and the remaining branch is the finite-begin/finite-end case. The arithmetic in each branch is the corresponding capacity test. -/ abbrev AlwaysEmpty (r : RangeRead) : Prop := let gap := intervalCard r.begin.key r.end_.key let b := noPinB gap r.begin.offset r.end_.offset let e := cELo r.begin.offset r.end_.offset let cE := cEminP r.begin.offset r.end_.offset let underBegin := intervalCard bottom r.begin.key let underEnd := intervalCard bottom r.end_.key ¬ (if r.begin.key = ⊤ then if r.end_.key = ⊤ then r.begin.offset ≤ 0 ∧ r.begin.offset < r.end_.offset else r.begin.offset ≤ 0 ∧ r.begin.offset < r.end_.offset ∧ (cE : ℕ∞) ≤ underEnd else if r.end_.key = ⊤ then True else (b : ℕ∞) ≤ underBegin ∧ (e : ℕ∞) ≤ underEnd ∧ ((b - e : ℕ) : ℕ∞) ≤ intervalCard r.end_.key r.begin.key ∧ ((e - b : ℕ) : ℕ∞) ≤ intervalCard r.begin.key r.end_.key ∧ 0 < (e : ℤ) + r.end_.offset - 1 ∧ (b : ℤ) + r.begin.offset - 1 < (e : ℤ) + r.end_.offset - 1) def emptyRange (r : RangeRead) : ConflictRange := range r.begin.key r.begin.key def crossedRangeGeneral (r : RangeRead) : ConflictRange := if ↑(residualE r) - ↑(residualB r) ≤ intervalCard r.end_.key r.begin.key then range r.end_.key ⊤ else range r.begin.key ⊤ def emptyValue (r : RangeRead) : ConflictRange := if AlwaysEmpty r then emptyRange r else if r.begin.offset ≤ 0 then if 2 ≤ r.end_.offset then range bottom ⊤ else if r.begin.key ≤ r.end_.key then range bottom r.end_.key else if intervalCard r.end_.key r.begin.key < ↑(r.end_.offset - r.begin.offset).toNat then range bottom r.end_.key else range bottom (max r.begin.key r.end_.key) else if r.end_.offset ≤ 1 then canonicalRange r else if r.begin.key ≤ r.end_.key then topRange r else crossedRangeGeneral r /-! ### Complete and forward-truncated results -/ def closedFormBegin (r : RangeRead) (res : Result) : WithTop Key := if clampsToBottom r res then bottom else r.begin.key @[reducible] def closedFormFinite (r : RangeRead) (res : Result) : Prop := closedFormDeficit r + residualT r res = residualE r def closedFormCompleteForward (r : RangeRead) (res : Result) : ConflictRange := let begin := closedFormBegin r res if r.end_.offset ≤ 1 then range begin r.end_.key else if clampsToBottom r res ∨ r.begin.key ≤ r.end_.key then if residualT r res = residualE r then range begin (afterLast res) else if ∀ k ∈ res.keys, ↑k < r.end_.key then range begin ⊤ else if closedFormFinite r res then range begin (afterLast res) else range begin ⊤ else if closedFormFinite r res then range r.end_.key (afterLast res) else range (crossedBegin r res) ⊤ def normalizeCompleteResult (r : RangeRead) (res : Result) : Result := { keys := if r.reverse = true then res.keys.reverse else res.keys, more := false } def closedFormComplete (r : RangeRead) (res : Result) : ConflictRange := closedFormCompleteForward (forwardRead r) (normalizeCompleteResult r res) def closedFormForwardCapacity (r : RangeRead) (res : Result) : ℕ∞ := if clampsToBottom r res then 0 else intervalCard r.end_.key r.begin.key def closedFormForwardTruncated (r : RangeRead) (res : Result) : ConflictRange := let begin := closedFormBegin r res if r.end_.offset ≤ 0 then range begin r.end_.key else if closedFormForwardCapacity r res ≤ ↑(residualE r - res.keys.length - residualB r) then range begin (afterLast res) else range r.end_.key (afterLast res) def closedFormSplit (revRule : (RangeRead → Result → ConflictRange)) (r : RangeRead) (res : Result) : ConflictRange := if res.more = false then closedFormComplete r res else if r.reverse = false then closedFormForwardTruncated r res else revRule r res /-! ### Reversed truncation -/ def closedFormReverseCount (r : RangeRead) (res : Result) : ℕ := if r.end_.key < r.begin.key then res.keys.length else residualT r res @[reducible] def closedFormReverseFinite (r : RangeRead) (res : Result) : Prop := closedFormDeficit r + closedFormReverseCount r res = residualE r @[reducible] def closedFormCrossedRoom (r : RangeRead) (res : Result) : Prop := ↑(residualE r - res.keys.length) ≤ intervalCard r.end_.key (last res) def closedFormReverseTruncatedSkip (r : RangeRead) (res : Result) : ConflictRange := if r.end_.offset ≤ 1 then canonicalRange r else if ∀ k ∈ res.keys, ↑k < r.end_.key then topRange r else if closedFormReverseFinite r res then range (if r.end_.key < r.begin.key then r.end_.key else r.begin.key) (afterFirst res) else let begin := if r.end_.key < r.begin.key ∧ closedFormCrossedRoom r res then r.end_.key else r.begin.key range begin ⊤ def closedFormReverseTruncated (r : RangeRead) (res : Result) : ConflictRange := if residualB r = 0 then closedFormReverseTruncatedZero r res else closedFormReverseTruncatedSkip r res /-! ### Positive and clamped branches -/ def closedFormPositive (r : RangeRead) (res : Result) : ConflictRange := closedFormSplit closedFormReverseTruncated r res def closedFormClamped (r : RangeRead) (res : Result) : ConflictRange := closedFormSplit closedFormNonposRevTrunc r res /-! ### Crossed table -/ @[reducible] def overshoot (r : RangeRead) (res : Result) : Prop := 2 ≤ r.end_.offset ∧ ∀ k ∈ res.keys, ↑k < r.end_.key @[reducible] def zeroCrossOvershootComplete (r : RangeRead) (res : Result) : Prop := r.begin.offset = 0 ∧ res.more = false ∧ r.reverse = false ∧ overshoot r res ∧ ↑(leastReported r res) < r.begin.key @[reducible] def negCrossOvershoot (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ r.begin.offset < 0 ∧ res.more = false ∧ 2 ≤ r.end_.offset ∧ (∀ k ∈ res.keys, ↑k < r.end_.key) ∧ first res < r.begin.key @[reducible] def crossedCompleteOvershoot (r : RangeRead) (res : Result) : Prop := zeroCrossOvershootComplete r res ∨ negCrossOvershoot r res @[reducible] def crossedCompleteEndLeOne (r : RangeRead) (res : Result) : Prop := r.reverse = false ∧ res.more = false ∧ r.begin.offset ≤ 0 ∧ first res < r.begin.key ∧ (r.end_.offset = 1 ∧ beginSlack r < reportedBelowBegin r res ∨ r.end_.offset ≤ 0 ∧ ¬(reportedBelowBegin r res ≤ beginSlack r ∧ clampNonposBottom r res)) @[reducible] def zeroCrossLongTop (r : RangeRead) (res : Result) : Prop := r.begin.offset = 0 ∧ res.more = false ∧ r.reverse = false ∧ 2 ≤ r.end_.offset ∧ r.begin.key = ⊤ @[reducible] def zeroCrossLongFinite (r : RangeRead) (res : Result) : Prop := r.begin.offset = 0 ∧ res.more = false ∧ r.reverse = false ∧ 2 ≤ r.end_.offset ∧ r.begin.key ≠ ⊤ ∧ r.end_.key < r.begin.key ∧ ↑(leastReported r res) < r.begin.key @[reducible] def crossedCompleteBeginZero (r : RangeRead) (res : Result) : Prop := zeroCrossUnderEnd r res ∨ zeroCrossLongTop r res ∨ zeroCrossLongFinite r res @[reducible] def crossedCompleteClamp (r : RangeRead) (res : Result) : Prop := negCrossClampEndOne r res ∨ negCrossHeadBottom r res ∨ negCrossClampNonposInfinite r res ∨ negCrossClampNonposLastGe r res ∨ negCrossClampNonposBottom r res ∨ negCrossClampLongNonpos r res /- The six-way disjunction in `crossedCompleteClamp` exceeds the default instance-search budget. -/ set_option synthInstance.maxSize 10000 in def closedFormCrossedComplete (r : RangeRead) (res : Result) : ConflictRange := if crossedCompleteOvershoot r res then closedFormNegCrossTopUnified r res else if crossedCompleteEndLeOne r res then closedFormNegCrossNonclampUnified r res else if crossedCompleteBeginZero r res then closedFormZeroCrossResidual r res else if crossedCompleteClamp r res then closedFormNegCrossClampUnified r res else closedFormNegCrossCompleteHighResidual r res @[reducible] def zeroCrossTruncRevCrossed (r : RangeRead) (res : Result) : Prop := r.begin.offset = 0 ∧ r.reverse = true ∧ res.more = true ∧ ↑(leastReported r res) < r.begin.key @[reducible] def negCrossTruncRevUnder (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ last res < r.begin.key ∧ r.begin.key ≤ r.end_.key ∧ r.end_.offset ≤ 1 @[reducible] def negCrossTruncRevCrossedNonposSmall (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ last res < r.begin.key ∧ r.end_.key < r.begin.key ∧ r.end_.offset ≤ 0 ∧ intervalCard r.end_.key r.begin.key + ↑res.keys.length + ↑(1 - r.end_.offset).toNat ≤ ↑(beginSlack r) + 1 @[reducible] def negCrossTruncRevCrossedSmall (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ last res < r.begin.key ∧ r.end_.key < r.begin.key ∧ r.end_.offset = 1 ∧ intervalCard r.end_.key r.begin.key + ↑res.keys.length ≤ ↑(beginSlack r) + 1 @[reducible] def revTruncLeOneLow (r : RangeRead) (res : Result) : Prop := negCrossTruncRevUnder r res ∨ negCrossTruncRevCrossedNonposSmall r res ∨ negCrossTruncRevCrossedSmall r res @[reducible] def negCrossTruncRevBelowEnd (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ last res < r.begin.key ∧ 2 ≤ r.end_.offset ∧ ∀ k ∈ res.keys, ↑k < r.end_.key @[reducible] def negCrossTruncRevResidualRoom (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ 2 ≤ r.end_.offset ∧ (∃ k ∈ res.keys, r.end_.key ≤ ↑k) ∧ intervalCard r.end_.key (first res) + 2 ≤ ↑(residualE r) @[reducible] def negCrossTruncRevResidualTopCrossedSmallGap (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ 2 ≤ r.end_.offset ∧ r.end_.key < last res ∧ intervalCard r.end_.key (last res) + ↑res.keys.length < ↑(residualE r) @[reducible] def negCrossTruncRevResidualTopCrossed (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = true ∧ r.begin.offset < 0 ∧ 2 ≤ r.end_.offset ∧ last res ≤ r.end_.key ∧ residualT r res < residualE r @[reducible] def revTruncGeTwoTop (r : RangeRead) (res : Result) : Prop := negCrossTruncRevBelowEnd r res ∨ negCrossTruncRevResidualRoom r res ∨ negCrossTruncRevResidualTopCrossedSmallGap r res ∨ negCrossTruncRevResidualTopCrossed r res @[reducible] def negCrossTruncRevResidualTopLargeCrossed (r : RangeRead) (res : Result) : Prop := negCrossTruncRevResidualTopLarge r res ∧ last res < r.begin.key ∧ r.begin.key ≠ ⊤ @[reducible] def revTruncGeTwoLarge (r : RangeRead) (res : Result) : Prop := negCrossTruncRevResidualTopLargeCrossed r res ∨ negCrossTruncRevResidualTopLargeSentinel r res @[reducible] def negCrossTruncTopTop (r : RangeRead) (res : Result) : Prop := res.more = true ∧ r.reverse = false ∧ r.begin.offset < 0 ∧ r.begin.key = ⊤ ∧ r.end_.key = ⊤ ∧ r.end_.offset ≤ 0 @[reducible] def negCrossTruncTopTopEq (r : RangeRead) (res : Result) : Prop := negCrossTruncTopTop r res ∧ res.keys.length + (1 - r.end_.offset).toNat = beginSlack r + 1 def closedFormClampSlack (r : RangeRead) (res : Result) : ℕ := beginSlack r + 1 - res.keys.length + if first res = bottom then 1 else 0 @[reducible] def closedFormClampGapSmall (r : RangeRead) (res : Result) : Prop := intervalCard (last res) r.begin.key ≤ ↑(closedFormClampSlack r res) @[reducible] def closedFormClampGapExactSaturated (r : RangeRead) (res : Result) : Prop := first res ≠ bottom ∧ r.end_.key = bottom ∧ residualE r = res.keys.length ∧ intervalCard (afterLast res) r.begin.key = ↑(beginSlack r + 1 - res.keys.length) @[reducible] def closedFormClampGapLow (r : RangeRead) (res : Result) : Prop := closedFormClampGapSmall r res ∨ closedFormClampGapExactSaturated r res def closedFormClampUpper (r : RangeRead) (res : Result) : WithTop Key := if closedFormClampGapLow r res then (afterLast res) else r.begin.key @[reducible] def closedFormForwardSaturated (r : RangeRead) (res : Result) : Prop := 0 < residualE r ∧ r.end_.key < first res ∧ ↑(residualE r) < intervalCard r.end_.key (first res) + ↑res.keys.length def closedFormForwardTruncatedNonpos (r : RangeRead) (res : Result) : ConflictRange := if reportedBelowBegin r res ≤ beginSlack r then if r.end_.offset ≤ 0 then if r.end_.key < r.begin.key then if clampNonposBottom r res then if last res < r.end_.key then closedFormNegCrossTruncNonposGapA2aBottom r res else range bottom (clampLongUpper r res) else range (first res) r.begin.key else if negCrossTruncTopTopEq r res then closedFormNegCrossTruncTopTopEq r res else if clampNonposBottom r res then range bottom r.end_.key else range (first res) r.end_.key else range bottom (closedFormClampUpper r res) else if r.end_.offset ≤ 0 then range (first res) (max r.begin.key r.end_.key) else let begin := if closedFormForwardSaturated r res then r.end_.key else first res range begin (max r.begin.key (afterLast res)) def closedFormCrossed (r : RangeRead) (res : Result) : ConflictRange := if res.more = false then if r.reverse = false then closedFormCrossedComplete r res else closedFormCrossedComplete (forwardRead r) (reversedResult res) else if r.reverse = true then if zeroCrossTruncRevCrossed r res then closedFormZeroCrossTruncRevCrossed r res else if revTruncLeOneLow r res then closedFormNegCrossTruncRevUnder r res else if r.end_.offset ≤ 1 then closedFormNegCrossTruncRevCrossedNonposLarge r res else if revTruncGeTwoTop r res then closedFormNegCrossTruncRevBelowEnd r res else if revTruncGeTwoLarge r res then closedFormNegCrossTruncRevResidualTopLargeUnified r res else closedFormNegCrossTruncRevResidualFiniteUnified r res else closedFormForwardTruncatedNonpos r res /-! ### Dispatch -/ /-- The closed form. The empty result is handled first, so every branch below is reached only with `res.keys ≠ []`. -/ def closedForm (r : RangeRead) (res : Result) : ConflictRange := if res.keys = [] then emptyValue r else if 1 ≤ r.begin.offset then closedFormPositive r res else if clampedNonpos r res then closedFormClamped r res else closedFormCrossed r res /-! ## The headlines -/ /-- **The closed form is minimal.** For every readable read/result pair, `closedForm r res` is a minimal sound conflict range: it is sound, and no proper subrange of it is sound. -/ def ClosedFormMinimal : Prop := ∀ r res, Readable r res → Minimal r res (closedForm r res) /-- **Minimality is unique.** Any two minimal sound conflict ranges for the same read and result denote the same set of keys. This is a statement about `Minimal` alone, so it needs no readability hypothesis: minimality already carries soundness. Together with `ClosedFormMinimal` it says that `closedForm r res` is the minimal sound range up to its set of keys. The converse direction does not hold: unique *key sets* do not pin the endpoints, so an empty range is only determined up to `toSet` equality. That is why this statement is about `ConflictRange.toSet` rather than about equality of ranges. -/ def MinimalUnique : Prop := ∀ r res cr cr', Minimal r res cr → Minimal r res cr' → cr.toSet = cr'.toSet end Statement