Why Problems Are Hard

The Fibred Order of Difficulty

Also in فارسی · Short version: English · فارسی

The argument in brief.

Difficulty claims concern constraints on achieving specified ends under specified conditions. An encounter records the task, information, actions, admitted methods, environment, and resources. Its successful attainable region records the performance bounds under which the task can be achieved. A full performance region also records failures and approximations; it supports a difficulty claim only when the relevant success condition is retained.

The book's contribution is an audit of such claims. It separates finding a method from using one, a failure of knowledge from a missing physical path, and a change in the task from a change in its description. Information theory, control, abstraction, and complexity supply particular constraints. The fibred order organizes comparisons across different performance spaces after their semantic relation has been justified.

Chapter 9 adds mathematics of the book's own. Under its quantifier, one policy that must succeed in every admitted world, noisy reports are compared by the guarantees they permit. That order is strictly coarser than Blackwell's, the tests needed to decide it are known exactly, and deciding it is coNP-complete.

The philosophical commitment is to objective constraints within justified encounters. A constraint can depend on chosen ends without depending on what the solver believes is achievable. Calling such constraints dispositions is a further interpretation. Chapter 6 considers what that interpretation explains, what could bear a disposition, and why neither a proof nor an invariant alone identifies a metaphysical ground. Worked examples address omitted success, discovery cost, overlapping obstacles, disagreement about which encounter a practical decision requires, and a sensor upgrade that no guarantee can use.

Difficulty is often spoken of as though it were stored inside a problem. A conjecture is hard, a landscape is rugged, a system is complex. Yet the same calculation is routine with writable memory and impossible for a fixed finite machine that must retain an unbounded input. The same state is recoverable through one sensor and indistinguishable through another. The same target is reachable with one actuator and absent from the closure of another move set.

A common problem-object can remain while the encounter with it changes. If the success condition changes, even the task may have changed. For that reason this book predicates operational difficulty primarily of an encounter, not of a bare object. Schematically, write

\[ E=(Q,\mathsf{Succ},\Omega,\mathsf{Info},\mathsf{Act}, \mathsf{Prog},\mathsf{Perf}). \]

Here \(Q\) is the problem-object or instance family; \(\mathsf{Succ}\) declares success or loss; \(\Omega\) is the admitted environment and uncertainty class; \(\mathsf{Info}\) and \(\mathsf{Act}\) are the observation and action interfaces; \(\mathsf{Prog}\) fixes the admitted programs and machine model; and \(\mathsf{Perf}\) evaluates executions in an ordered performance space. This tuple is a checklist, not a universal datatype: its internal mathematics changes across theorem proving, control, estimation, and computation.

The framework uses information, action, and resources as three operational boundaries. Information governs which differences can enter a representation. Action governs which transformations and states are available. Resources govern which attainable performance can be realized in time, memory, communication, precision, or energy. Success and environment are separate parts of the encounter against which those boundaries are evaluated. The decomposition is useful but neither unique nor an exhaustive metaphysics. Communication, for example, can constrain both information and resources; institutions can constrain information, action, and resource access at once.

This does not make difficulty imaginary. A locked door does not open under a better description. A false conjecture does not become true for a weak prover. Noise can erase distinctions whether or not an observer understands why. Once an encounter has been specified, its attainable performance is a matter of fact. The specification itself, however, still owes justification. Choosing average instead of worst-case loss, treating preprocessing as free, admitting one environment family rather than another, or valuing time while ignoring energy can express purposes, conventions, and institutional or ethical priorities. The framework therefore separates two layers:

\[ \text{selection and justification of the encounter} \quad\longrightarrow\quad \text{objective consequences within it}. \]

Its central thesis is:

Operational difficulty is objective and relational. Once an encounter is specified, the performance bounds under which its success condition can be achieved are a matter of fact. Difficulty comparisons use that successful attainable structure, or a full performance structure that retains the relevant success criterion. Structural facts may explain or certify difficulty; normative and pragmatic considerations help select the encounter; justified transport or invariance licenses broader comparisons.

This operational thesis is not an exhaustive metaphysics of everything called hardness. A graph may have an intrinsic connectivity property, a theorem a proof-theoretic strength, and a space a topological obstruction. Such facts can cause or certify operational difficulty, sometimes uniformly across a large class of encounters. But the further claim that an object is hard remains elliptical until it says hard to accomplish what, with which access and actions, under which limits. The book rejects an unqualified hardness attributed to a bare problem, not intrinsic structure or context-independent truth. Chapter 6 examines a compatible metaphysical conjecture: hardness as modal resistance of a task situation, grounded in facts about its object, environment, interfaces, and resources. The formal encounter represents that situation. Its tuple notation does not establish that the situation possesses a disposition, and the dispositional interpretation remains open to argument.

The practical contribution is an eight-step audit for difficulty claims:

  1. Identify and individuate the encounter. State the raw specification, structural signature and its reduct, claim language, and transformations being treated as identity, equivalence, directed transport, or extension.
  2. State success. Declare the target, loss, tolerance, horizon, and quantifiers.
  3. Declare the environment. Fix the instance family, uncertainty, and admissible worlds.
  4. Expose the boundaries. State the information, action, program, and resource interfaces.
  5. Determine attainable performance. Compute, estimate, or bound the outcomes realizable under those declarations. For task difficulty, retain success explicitly; for discovery, charge the acquisition procedure.
  6. Justify cross-context alignment. Relate tasks, worlds, interfaces, and performance coordinates before transporting a claim.
  7. Search for stable content. Ask which equalities, orders, bounds, feasibility claims, or safety properties survive the admitted alignments.
  8. Separate specification from consequence. Do not let mathematical correctness stand in for empirical relevance or normative legitimacy.

The fibred order is the mathematical implementation of steps 5 to 7, not the philosophy by itself. Within one comparison context, encounters determine regions of the same declared kind: successful regions for task difficulty, or full regions for graded performance. Inclusion gives a partial comparison. Across contexts, performance maps reindex ambient specifications by preimage. But such a map is admitted only after an encounter-alignment argument relates the tasks and worlds it is supposed to compare. Reindexing realized classes then requires a further closure or realization theorem.

This division gives the construction one job. Ordinary Pareto analysis compares alternatives already expressed in one performance space; ordinary model-relative complexity fixes one machine and one family. Neither alone justifies a claim transported from simulator to hardware, from abstraction to execution, or from one success criterion to another. The framework separates semantic comparability, performance transport, and realizability transport.

The argument proceeds from representation and feedback, through robustness and fault, to reachability, abstraction, complexity, cross-context comparison, environments that react to being modeled, problem families whose nearby members stop being reliable guides, and noisy interfaces compared by the guarantees they permit. The mathematics is used locally. No universal scale or datatype is offered, and no machine-checked theorem is allowed to stand in for the philosophical, empirical, or normative argument that gives it a reading.

Chapter 1Representation is a state in a feedback loop

Description and operative state

A representation can be a sentence, diagram, coordinate system, probability distribution, learned feature vector, proof library, or physical mark. These objects differ too much for a single useful syntax. What matters here is a narrower role: an operative representation is whatever state carries selected consequences of past interaction into the next inference or action.

Let \(X\) be a task-relevant exogenous unknown and let \(Y_1,Y_2,\ldots\) be observations. The information theorem below does not cover a future target state that the actions themselves causally alter; such a problem needs a causal or directed-information formulation, in the sense introduced for feedback channels by Massey (1990). Put every random coin used by the estimator or sensing policy into a random tape \(W\), assumed independent of the pair \((X,Z_0)\), and write \(H_0=(Z_0,W)\). At round \(t\), write the maintained representation as

\[ Z_t=q_t(H_0,Y_1,\ldots,Y_t). \]

The map \(q_t\) is causal. It may describe an observer state, a posterior, a compressed transcript, or an external notebook included in the agent's extended state. An estimate is

\[ \widehat X_t=g_t(Z_t), \]

and an action can be chosen as \(A_t=\pi_t(H_0,Y_{<t})\). The random tape does not initially supply information about the unknown, but it must remain in the history. Once it selects sensing actions, discarding it from a conditional mutual-information expression can make the expression false.

This formulation separates representation quality from the amount of prose used to describe it. A large state can preserve irrelevant distinctions. A small sufficient statistic can preserve exactly those needed by one loss function. Compression is therefore task-relative: the same quotient can be exact for one decision and destructive for another.

There is already a preorder here before probability enters. A deterministic experiment \(o_f\) refines \(o_c\) when \(o_c=k\circ o_f\) for some post-processing map \(k\). Equality of fine reports then forces equality of coarse reports, so the fine compatibility class is smaller. Consequently, every action robust under the coarse report remains robust under the fine one. Mutual factorization preserves the compatibility classes and every robust action set. A two-state quotient can make the inclusion strict by merging states that require different actions. Distinct relabelings can occupy the same position, so antisymmetry requires identifying mutually factoring reports. This deterministic refinement preorder is the noiseless factorization case of Blackwell's comparison of statistical experiments: the coarse report is obtained by post-processing the fine report. Blackwell's theorem treats stochastic experiments and all decision problems; the elementary result here uses deterministic reports and declared robust-action sets. It is distinct from the Shannon data-processing inequality used below.

For noisy reports the book's own quantifier does not reproduce Blackwell's order. When one policy must succeed with a declared probability in every admitted world, noisy reports are compared by the guarantees they permit, and Chapter 9 shows that this comparison is strictly coarser than Blackwell's. The deterministic preorder above is unaffected: when either report is deterministic the two comparisons coincide.

Feedback cannot invent information

Because \(Z_t\) is constructed from the initial state and the transcript, the data-processing inequality in Shannon's information framework gives

\[ I(X;Z_t) \le I(X;H_0,Y_{1:t}) =I(X;H_0)+\sum_{k=1}^{t} I(X;Y_k\mid H_0,Y_{<k}) =I(X;Z_0)+\sum_{k=1}^{t} I(X;Y_k\mid H_0,Y_{<k}). \]

The equality is the chain rule. In an adaptive experiment, the distribution of \(Y_k\) can depend on earlier actions. The conditional information terms must therefore be evaluated under the actual policy, with its random tape in the conditioning set. Calling a sensor noisy is not enough to determine them. Actions generated from the recorded history do not create information about \(X\) by themselves.

For a fixed policy, suppose each round contributes at most \(C\) units of task-relevant information. To obtain a lower bound for an entire experiment class, the same bound must hold uniformly over every admissible adaptive policy. Assume that \(I_0\) and \(C\) are finite, and measure all information with one logarithm base. Then

\[ I(X;Z_t)\le I_0+tC, \qquad I_0=I(X;Z_0). \]

This caps what can enter the representation; an update rule may retain less.

To connect information with accuracy, fix a distortion \(d(x,\hat x)\) and use Shannon's fidelity-criterion formulation to define the rate-distortion function

\[ R_X(D)= \inf_{P_{\widehat X\mid X}:\,\mathbb E d(X,\widehat X)\le D} I(X;\widehat X). \]

For the real-valued subtraction and division below, also assume that \(R_X(D)\) is finite.

If \(\widehat X_t\) achieves expected distortion at most \(D\), its information about \(X\) is at least \(R_X(D)\). Since \(\widehat X_t\) is computed from \(Z_t\), another application of data processing gives

\[ R_X(D)\le I(X;\widehat X_t)\le I(X;Z_t). \]

For \(C>0\), any estimator meeting this expected-distortion criterion under the declared source law therefore obeys

\[ t\ge \left\lceil \frac{[R_X(D)-I_0]_+}{C} \right\rceil . \]

If the initial representation already contains enough information, this lower bound is zero. If \(C=0\) while \(R_X(D)>I_0\), the target accuracy is unattainable through that declared policy and feedback channel. If the bound on \(C\) is uniform over the admitted policy class, the impossibility is class-wide. The ceiling is not philosophical decoration: observations arrive in whole rounds.

A defensible application must justify the source distribution, distortion, initial information, experiment class, and uniform per-round bound.

A scalar Gaussian reconstruction

The simplest exact example makes the dependence on noise visible. Let a fixed scalar state have prior

\[ X\sim\mathcal N(m_0,P_0), \]

and let independent observations be

\[ Y_k=X+V_k, \qquad V_k\sim\mathcal N(0,R), \qquad P_0>0, R>0. \]

Gaussian conjugacy adds precision. After \(t\) observations the posterior variance is

\[ P_t=\left(P_0^{-1}+tR^{-1}\right)^{-1}. \]

For a positive target variance \(D\), the condition \(P_t\le D\) requires

\[ t\ge R\left(D^{-1}-P_0^{-1}\right). \]

The integer lower bound is the ceiling of the positive part. Increasing the measurement-noise variance \(R\) increases the number of observations needed for the same reduction in uncertainty. This is the clean core of the Kalman analogy: reconstruction speed is limited by the precision entering through feedback.

Observability is local geometry; detectability is dynamics

The scalar formula is not a theorem about a dynamic Kalman filter. For an LTI system \(\dot x=Ax,\ y=Cx\), the rank test comes from Kalman's control-system formulation: observability is tested by the vertical stack

\[ \mathcal O_L= \begin{bmatrix} C\\ CA\\ \vdots\\ CA^{n-1} \end{bmatrix}. \]

A smooth nonlinear system has no universal matrix with that finite form. For \(\dot x=f(x,u),\ y=h(x)\), let \(f_{\bar u}(x)=f(x,\bar u)\) for each constant admissible input. Let \(\mathcal G\) be the smallest real vector space that contains the output components and is closed under Lie differentiation by every \(f_{\bar u}\). Its observability codistribution is

\[ \mathcal O(x)= \operatorname{span}\{d\phi(x):\phi\in\mathcal G\} \subseteq T_x^*M. \]

For an autonomous system, this is the span of \(d(L_f^k h_j)(x)\). A coordinate matrix made from finitely many such covectors can be useful computationally, but there is no universal \(n-1\) truncation. Controlled systems can require mixed iterated Lie derivatives along all admitted system vector fields, not repeated derivatives along the drift alone.

The Hermann-Krener observability rank condition

\[ \dim\mathcal O(x_0)=\dim M \]

is sufficient for local weak observability at \(x_0\) over the declared common input experiments. Its scope matters: \(\dot x=0,\ y=x^3\) is observable although \(dh(0)=0\), and pointwise local observability does not by itself give a global result.

If the full codistribution has constant rank \(r<n\) on a neighborhood, its annihilator

\[ \mathcal N_x=\mathcal O(x)^\circ =\{v\in T_xM:\alpha(v)=0\text{ for every }\alpha\in\mathcal O(x)\} \]

is a smooth \((n-r)\)-dimensional involutive distribution. Frobenius integrates it into local connected leaves on which every function in \(\mathcal G\) is constant. When the observation algebra represents the admitted common-input experiments, points connected within such a leaf cannot be separated by those observation functions. This conclusion is local, and the leaves are generally curved sets rather than linear unobservable subspaces; Frobenius alone does not make a local leaf a global indistinguishability class. The neighborhood and constant-rank assumptions do the work; rank deficiency at one point supplies only a kernel of the differential test.

Observability asks whether output separates states. Detectability asks what happens to distinctions that output does not separate. One incremental form requires two forward-complete trajectories with the same admitted input and the same output history to satisfy

\[ d(x_a(t),x_b(t))\longrightarrow0. \]

In a regular observability decomposition, this is asymptotic convergence of hidden trajectories along each indistinguishability leaf. Bounded hidden trajectories may still remain separated. A fixed residual radius gives practical detectability, while

\[ \limsup_{t\to\infty}d(x_a(t),x_b(t)) \le\rho(\lVert\delta\rVert_\infty), \qquad \rho(0)=0, \]

gives a robust disturbance-dependent version. Detectability removes one obstruction to state reconstruction; observer construction, stabilization, a nonlinear separation principle, and safety remain separate problems.

Indistinguishability is task-relative

Information bounds concern degree. A complementary boundary concerns exact ambiguity. Fix an admissible experiment class. Two states are observationally equivalent when every experiment in that class produces the same law of finite observation histories. No computation on such a history can distinguish the states.

Exact recovery may still be unnecessary. If each state \(x\) admits a set \(A^*(x)\) of acceptable actions, an observation class \(E\) permits a robust choice exactly when

\[ \bigcap_{x\in E} A^*(x)\ne\varnothing. \]

The relevant representation need only preserve distinctions on which acceptable action sets conflict. This is why information must be called task-relevant. Bits about an irrelevant coordinate can be plentiful while a single decision-critical distinction remains absent.

The experiment class is part of the claim. Equivalence under all mathematical history-dependent policies can be finer than equivalence under experiments that a bounded agent can implement. Forgetting that quantifier turns an exact theorem into a claim about a different interface.

Chapter 2Robust reconstruction has a margin

Nominal convergence is not robustness

An observer can converge inside its design model and fail after a small change in the plant or sensor. Noise perturbs observations under a maintained law; mismatch changes the law itself. A fault enters the disturbance model through a declared class and magnitude.

Consider a nonlinear plant and a Luenberger-type observer written schematically as

\[ x_{t+1}=f_t(x_t,u_t)+w_t, \qquad y_t=h_t(x_t)+v_t, \]
\[ \widehat x_{t+1} =\widehat f_t(\widehat x_t,u_t) +K_t(\widehat x_t) \bigl(y_t-\widehat h_t(\widehat x_t)\bigr). \]

The plant's output geometry and convergence of this particular observer are two analyses. Suppose the second yields a scalar comparison inequality for the estimation error \(e_t\ge0\):

\[ e_{t+1}\le(q_0+\mu)e_t+\bar d. \]

Here \(q_0\ge0\) is a certified nominal contraction factor, \(\mu\ge0\) bounds the part of model mismatch that scales with current error, and \(\bar d\ge0\) bounds additive effects such as disturbances, sensor noise after observer gain, bias, and bounded fault. There is no universal metric that makes every model difference into this \(\mu\); the norm and derivation of the comparison inequality are the system-specific work.

Write \(q=q_0+\mu\). If \(0\le q<1\), iteration gives

\[ e_t\le q^t e_0 +\bar d\sum_{k=0}^{t-1}q^k =q^t\left(e_0-\frac{\bar d}{1-q}\right) +\frac{\bar d}{1-q}. \]

The certified ultimate tube has radius

\[ r_\infty=\frac{\bar d}{1-q_0-\mu}. \]

The two effects of mismatch are now separate. Multiplicative mismatch consumes the nominal contraction margin. Additive disturbance enlarges the upper bound that this comparison argument can certify. The certified tolerance is

\[ \mu<1-q_0. \]

The certificate is valid while this margin is positive; beyond it the comparison proof is silent. The radius \(r_\infty\) is an upper guarantee, not an accuracy floor. Establishing a floor requires a worst-case or minimax lower bound.

The same inequality gives an accuracy condition. To certify \(\limsup_{t\to\infty}e_t\le D\) for \(D>0\), it is sufficient that

\[ \bar d\le D(1-q_0-\mu). \]

Thus faster nominal contraction, mismatch tolerance, and final accuracy share one margin. They cannot be read independently from \(q_0\), \(\mu\), and \(\bar d\). If \(r_\infty<D<e_0\) and \(0<q<1\), the transient bound reaches \(D\) once the natural-number time satisfies

\[ t\ge \left\lceil \frac{\log\bigl((D-r_\infty)/(e_0-r_\infty)\bigr)}{\log q} \right\rceil . \]

If \(D\ge e_0\), time zero already satisfies the bound. The formula makes a familiar tradeoff explicit. Increasing observer gain can reduce a nominal contraction factor while amplifying measurement noise and therefore increasing \(\bar d\). Speed in the noiseless model need not improve the certified robust accuracy guarantee. The finite \(\bar d\) premise is a deterministic bounded-disturbance assumption. Gaussian noise is unbounded and needs a moment or high-probability reformulation.

Changing models and switching regimes

A family of plants \(\{f_\theta,h_\theta:\theta\in\Theta\}\) admits a uniform robust claim only when one common error metric or Lyapunov function gives the comparison inequality over the declared family. If the same bounds \(q<1\) and \(\bar d\) hold at every step, including every admitted switch, then the error tube survives arbitrary variation inside that family. Equal constants proved separately in mode-dependent metrics do not establish that claim. A switching theorem may instead need common Lyapunov data, dwell time, or reset bounds; these are standard alternatives in the switched-systems literature surveyed by Liberzon and Morse (1999).

Abrupt change can alter the observability codistribution or the stability of its hidden dynamics. Gain cannot recover a distinction absent from the output. An observer bank enlarges the hypothesis class while spending memory, computation, and identification effort. Any maximum divergence claim is therefore indexed by a chosen mismatch set and norm.

Accommodation, detection, and isolation

The separation of accommodation, detection, and isolation belongs to the model-based fault-diagnosis tradition reviewed by Venkatasubramanian et al. (2003). Accommodation means that the estimator or controller retains an accuracy or safety guarantee while the fault lies in an admissible class. The error tube above is an accommodation result when fault effects are included in \(\bar d\).

Detection asks whether a fault can be distinguished from ordinary uncertainty. Let a residual be

\[ r_t=y_t-\widehat h_t(\widehat x_t). \]

Suppose every healthy residual satisfies \(\lVert r_t^h\rVert\le\rho\), and a faulty residual has the additive form \(r_t^f=r_t^h+f\). Declare an alarm when \(\lVert r_t\rVert>\eta\). A threshold \(\eta\ge\rho\) avoids false alarms under that deterministic model. The reverse triangle inequality gives the worst-case sufficient condition

\[ \lVert f\rVert-\rho>\eta. \]

At the smallest threshold certified from this radius bound alone, \(\eta=\rho\), the familiar condition is

\[ \lVert f\rVert>2\rho. \]

This factor of two is the worst-case separation of the declared uncertainty tubes. Probabilistic false-alarm rates require a probability model.

Isolation asks which fault occurred. It requires the residual sets of candidate faults to be separated from one another, not merely from the healthy set. A fault may be detectable and still indistinguishable from another fault. If candidate \(i\) produces residuals in a closed ball of radius \(\rho\) around a signature \(f_i\), then \(\lVert f_i-f_j\rVert>2\rho\) makes the two candidate balls disjoint. The same geometry that governs task-relevant representation returns here: diagnosis is possible only when the observation interface preserves the distinctions the diagnosis is asked to make.

Robust reconstruction therefore has an informational boundary and a dynamical boundary. Observability determines which distinctions can enter the output, and information rate limits how quickly recoverable uncertainty can contract. Detectability asks whether the remaining ambiguity decays; stability margin limits how much mismatch and disturbance that contraction can tolerate. Neither boundary can be replaced by confidence reported from inside the maintained model.

Chapter 3Knowing does not create a path

Reachability is generated by actions

Reachability, invariance, and viability are distinct set-valued questions in control; Aubin's viability theory is a standard reference for their state-constrained forms. Here, let \(X\) be a state space and let each primitive action \(u\in U\) induce a transition \(F_u:X\to X\). The states reachable from \(x\) are

\[ \operatorname{Reach}_U(x) =\{F_{u_n}\circ\cdots\circ F_{u_1}(x):n\ge0,\ u_i\in U\}. \]

The empty composition includes \(x\). This set depends on the action boundary, not on how clearly the agent represents it. A complete map can settle whether a target is reachable and can shorten search, but it does not add an endpoint to the closure.

A derived action \(g\) also need not enlarge reachability. If

\[ g(x)\in\operatorname{Reach}_U(x) \quad\text{for every }x, \]

then treating \(g\) as one primitive step changes program length but not the reachable set. This condition is weaker than having one uniform finite macro for \(g\): the witnessing path may depend on \(x\), may have no common length bound, and may be noncomputable. A genuinely new actuator can enlarge reachability, but then the action boundary has changed.

Theorem proving supplies a sharp instance. Let the states be proof states over a fixed axiom and hypothesis context \(\Gamma\), let the primitive actions be the inference steps of the calculus, and let \(g\) be a lemma already provable from \(\Gamma\). Introducing \(g\) as one primitive step is a backed derived action: every use of \(g\) can be replaced by its derivation, so the set of provable goals does not change. What can change is cost. A goal whose direct derivation exceeds a search budget may fall inside the budget once \(g\) is a single step. Reachability preservation therefore does not imply preservation of finite-budget accessibility; the budgeted attainable regions of Chapter 5 are the coordinates that record what the lemma actually bought.

This separates epistemic and practical obstruction. A state can be perfectly known and unreachable. A state can be reachable while the agent lacks enough information to choose the path. The two failures can coexist, but neither explains the other.

Barrier depth is not search time

Reachability says that some path exists. It does not say what every path must cross. Let \(J:X\to\mathbb R\) be an objective, with larger values preferred, and let \(\gamma\) range over finite admissible paths from \(x\) to a goal set \(G\). Define the depth of a path relative to its starting value by

\[ \operatorname{depth}_J(\gamma) =\max_i [J(x)-J(\gamma_i)]_+, \]

and define the barrier

\[ B_J(x,G) =\inf_{\gamma:x\leadsto G}\operatorname{depth}_J(\gamma), \]

with value \(+\infty\) when there is no path.

A zero barrier means that paths can avoid a drop below the starting objective arbitrarily closely; under a witnessed monotone path it is exactly zero. A finite positive barrier means every path dips. An infinite barrier means no path exists. These are statements about the declared adjacency relation and objective.

Barrier depth records a bottleneck. Length, energy, escape probability, and search effort are separate coordinates: a zero-depth path may be extremely long, and a short path may have a deep dip.

The representation of a path can hide this distinction. An abstract edge may stand for a long concrete route. It preserves reachability if that route exists, but it preserves barrier depth only if the route satisfies an appropriate score bound. This is the point at which abstraction incurs a debt.

Chapter 4Behavior comes before its presentation

Systems as admitted trajectories

A differential equation, automaton, state-space realization, and input/output split are presentations of a system. In the behavioral approach of Willems (2007), the central object is instead a time domain \(T\), a declared signal space \(W\), and a set of admissible trajectories

\[ \Sigma=(T,W,\mathcal B), \qquad \mathcal B\subseteq W^T. \]

Equations matter insofar as they characterize \(\mathcal B\). Distinct internal models can present the same behavior at the declared signal boundary, even when one exposes a useful proof or algorithm that another hides. The equivalence is relative to the chosen variables, boundary, and trajectories.

When two components constrain the same signal universe, their behavioral interconnection is

\[ \mathcal B_1\parallel\mathcal B_2 =\mathcal B_1\cap\mathcal B_2. \]

If only some variables are shared, composition instead enforces compatibility over that interface, represented by a pullback or fibre product. Hiding a signal through \(\pi:W\to V\) takes the existential image

\[ \pi_*\mathcal B =\{\pi\circ w:w\in\mathcal B\}. \]

Interconnection removes trajectories; hiding identifies them. The operations do not generally commute:

\[ \pi_*(\mathcal B_1\cap\mathcal B_2) \subseteq \pi_*\mathcal B_1\cap\pi_*\mathcal B_2, \]

and the inclusion can be strict because the two projected memberships may use incompatible hidden witnesses. Two nonempty components can even have an empty interconnection. Composition therefore needs both compatibility and viability, not merely componentwise possibility.

An exact coordinate change transports a presentation while preserving the admitted behavior. An abstraction is many-to-one and can identify or introduce behavioral possibilities unless transfer conditions are proved. An extension adds a sensor, actuator, predicate, variable, oracle, or axiom and therefore changes the encounter.

The two directions of transfer

Simulation relations are a standard proof method for transferring behavior; forward and backward variants are treated systematically by Lynch and Vaandrager (1995), and their use for discrete abstractions of hybrid systems is surveyed by Alur, Henzinger, Lafferriere, and Pappas (2000). For the finite reachability setting here, let \(x\to_X x'\) and \(a\to_A a'\) be concrete and abstract step relations. Forward simulation requires

\[ x\to_X x' \quad\Longrightarrow\quad \phi(x)\to_A\phi(x'). \]

It maps every concrete path to an abstract path. With preservation of goals, it proves that concrete success implies abstract success. Its contrapositive can certify concrete impossibility from abstract impossibility.

Executing an abstract plan requires the reverse direction, expressed by a local step-lifting condition:

\[ \phi(x)\to_A a' \quad\Longrightarrow\quad \exists x',\ x\to_X x'\ \text{ and }\ \phi(x')=a'. \]

The quantifier starts from the current state \(x\), rather than a convenient representative of the same abstract cell. Induction then lifts a finite path one step at a time.

Goals need both directions as well. For concrete goal \(G_X\) and abstract goal \(G_A\), exact reachability transfer uses

\[ x\in G_X\quad\Longleftrightarrow\quad\phi(x)\in G_A. \]

Forward simulation, step lifting, and goal equivalence together give

\[ x\leadsto_X G_X \quad\Longleftrightarrow\quad \phi(x)\leadsto_A G_A. \]

Each premise has distinct work. Forward simulation gives sound abstract images of concrete behavior. Lifting prevents spurious abstract plans. Goal reflection prevents a non-goal concrete state from being declared successful only because its cell contains a goal.

These are strong reachability conditions. Approximate and probabilistic abstractions replace equality with error, value, kernel, or distributional bounds. Safety, cost, and barrier claims require corresponding bounds.

Local behavior and safety

Let \(\mathcal B(U)\) denote trajectories admitted on a region \(U\) of time. Restriction gives presheaf-like data. A sheaf of behaviors additionally requires compatible admitted local trajectories to have a unique admitted global glue. This use of sheaves for dynamical systems has a developed compositional treatment in Schultz, Spivak, and Vasilakopoulou (2020); the present manuscript uses only the elementary restriction-and-gluing distinction.

For a state predicate \(C\), define

\[ \operatorname{Safe}(C) =\{w:\forall t,\ C(w(t))\}. \]

Then the temporal safety claim is simply

\[ \mathcal B\models\Box C \quad\Longleftrightarrow\quad \mathcal B\subseteq\operatorname{Safe}(C). \]

For discrete deterministic dynamics, if \(\mathcal B_C\) consists exactly of the runs of \(F\) starting in \(C\), then

\[ \mathcal B_C\models\Box C \quad\Longleftrightarrow\quad F(C)\subseteq C. \]

Thus an all-time safety statement reduces to a one-step invariant for this declared behavior. A plant-controller interconnection is safe only when its closed behavior satisfies the inclusion. Nonblocking or viability remains a separate obligation: the empty behavior satisfies every universal safety claim vacuously.

Chapter 5Complexity and the fibred order

A bound needs a family and a machine

The dependence of a complexity measure on programs, encodings, and machines is classical; Blum's axiomatic treatment (1967) is an early general framework. An asymptotic resource bound concerns a family \(\{\mathcal I_n\}\), an encoding and size parameter \(n\), a machine or access model, a success or loss criterion, and a resource measure. Separately defined instance-level notions, including Kolmogorov and instance complexity, also exist. Time, workspace, queries, samples, communication, random bits, precision, and physical energy are not interchangeable until a conversion model is supplied.

The missing specifications matter. A one-pass stream and a rereadable array offer different information access. A random-access word machine and a Turing machine charge different primitive operations. Exact production and verification ask different questions. Worst-case, average-case, and smoothed analysis use different input quantifiers or distributions. A large search space by itself is not a lower bound under any of them.

Fix a model and let each admissible program \(p\) have a resource vector \(\operatorname{Res}_E(p)\) and a loss vector \(\operatorname{Loss}_E(p)\). The instance and environment quantifiers are built into these functions and into \(\mathsf{Succ}_E(p)\). For a robust task, success means that one program succeeds throughout the admitted environment class. One fortunate execution does not establish that guarantee. Take coordinates in the extended nonnegative reals, ordered componentwise, with smaller values preferred.

The full performance region is

\[ \mathsf{Ach}_{\mathrm{all}}(E) =\{(r,\ell):\exists p,\ \operatorname{Res}_E(p)\preceq r,\ \operatorname{Loss}_E(p)\preceq\ell\}. \]

The successful attainable region is

\[ \mathsf{Ach}_{\mathrm{succ}}(E) =\{(r,\ell):\exists p,\ \mathsf{Succ}_E(p)\ \land\ \operatorname{Res}_E(p)\preceq r\ \land\ \operatorname{Loss}_E(p)\preceq\ell\}. \]

Both are upward closed: meeting one pair of bounds implies meeting every looser pair. The success predicate remains fixed when the bounds are loosened. An unsuccessful program does not become a witness for the successful region merely because a generous loss bound would admit its performance.

The successful region is the default for difficulty of achieving the stated task. The full region supports comparisons of graded performance, including failure and approximation. They answer different questions. If success is completely encoded by downward-closed acceptable performance bounds \(G_E\), then a full region together with \(G_E\) also determines which acceptable bounds are attainable. More precisely,

\[ \mathsf{Ach}_{\mathrm{all}}(E)\cap G_E =\mathsf{Ach}_{\mathrm{succ}}(E)\cap G_E. \]

If a program meets a bound in \(G_E\), downward closure places its actual performance in \(G_E\) as well, so it succeeds. The reverse inclusion follows because every successful program is admitted. This equality concerns acceptable bounds; the successful region can also contain looser bounds outside \(G_E\). The success criterion must travel with that comparison. If performance omits a semantic requirement, it cannot recover success.

For example, suppose the task is to deliver a parcel to the authorized recipient. Two systems each have one admitted routine that uses one unit of time and reports zero damage. One delivers to the recipient; the other can deliver only to a different person. Their full time-and-damage regions are identical, \(\uparrow(1,0)\). Their successful regions are respectively \(\uparrow(1,0)\) and \(\varnothing\). Identifying these encounters in task difficulty would confuse omitted information with equivalence. Adding a delivery-correctness coordinate or retaining the success predicate prevents that mistake. This counterexample is a prose construction.

For either declared region, nondominated attainable points, when they exist, are Pareto-minimal. Implementation/resource spaces and Pareto antichains are already central to Censi's mathematical theory of co-design; the region construction is not claimed as new. Limiting tradeoffs need not be attained. More time may buy lower error, and more memory may replace recomputation. Information or action limits can prevent success at every finite budget.

For time and a distortion bound \(D\), the task-success slice is

\[ \tau_E(D)=\inf\{t:\exists p,\ \mathsf{Succ}_E(p)\ \land\ \operatorname{Time}_E(p)\le t\ \land\ \operatorname{Loss}_E(p)\le D\}. \]

Its value is \(+\infty\) when the set is empty. Approximation studies may instead ask for the full time/loss curve and make \(D\) the varying success threshold. Those thresholds define a family of tasks, not a silent alteration of one task. The information bound in Chapter 1 constrains an accuracy slice; the robust recurrence in Chapter 2 certifies an upper error bound without proving a matching lower bound. Reachability may exclude the success set altogether. Each result must be attached to the profile and quantifiers it actually concerns.

Feasibility and expense should remain distinguishable. An empty successful region means that no admitted program succeeds. A nonempty region may still contain no finite budget, or its cost infimum may be unattained. The region retains distinctions that a single extended-valued optimum can conceal.

Worked example: one robot, several encounters

Consider an autonomous warehouse robot that must leave a loading bay, choose one of two corridors, and reach a dock without collision. This is one task, but not yet one well-defined difficulty claim. We must say which layouts are admitted, what the robot senses, which motions it can execute, what uncertainty is allowed, and which costs count.

Start with two possible layouts, \(L\) and \(R\). In \(L\), the left corridor is blocked; in \(R\), the right corridor is blocked. A forward camera gives the same report at the fork in both layouts. Its observation class is therefore \(\{L,R\}\). If turning right is safe only in \(L\) and turning left is safe only in \(R\), the set of first turns safe for every compatible layout is

\[ \{\mathsf{right}\}\cap\{\mathsf{left}\}=\varnothing. \]

The obstacle has not made motion physically impossible. The current information boundary has made a certified first turn unavailable. A side looking lidar refines the report into the singleton classes \(\{L\}\) and \(\{R\}\), so each report has a robustly safe turn. This is the deterministic information preorder of Chapter 1 in operational form. If lidar is optional and all other interfaces stay fixed, every camera-only controller is still admissible; the attainable region can only expand. If a fire door closes both corridors, however, more sensing does not help. Unless the robot can open the door or take another route, the target lies outside its reachable set. That is an action boundary, not an information defect.

The sharp two-layout model is still too friendly. Let the estimated lateral position have error \(e_t\), let localization dynamics contract nominally by \(q_0<1\), let model mismatch contribute \(\mu\), and let bounded disturbance contribute \(d\). A certificate of the form

\[ |e_{t+1}|\le(q_0+\mu)|e_t|+d, \qquad q_0+\mu<1, \]

gives an ultimate localization tube. A path with smaller clearance lacks a robust certificate even when its nominal trajectory is collision-free. Performance must therefore record a bound under the declared uncertainty class. Better sensing may shrink the tube; the uncertainty quantifier remains.

The planner operates on a grid map rather than raw camera frames and motor currents. Let \(a:X_{\mathrm{hw}}\to X_{\mathrm{grid}}\) send hardware states to grid cells. Forward simulation,

\[ x\to_{\mathrm{hw}}x' \Longrightarrow a(x)\to_{\mathrm{grid}}a(x'), \]

shows that executed hardware paths have valid abstract images. Planning needs the other direction: each abstract step selected by the planner must lift from the current hardware state to an admissible hardware motion. A diagonal grid edge through a narrow aisle may fail this test because of turning radius, localization error, or acceleration limits. Goal reflection is separate again: an abstract cell labelled "dock" must contain only hardware states that meet the physical success condition, or the abstraction can report success too early. The useful abstraction theorem combines forward simulation, step lifting, and goal reflection for the declared planner interface.

Now put the alternatives in one hardware comparison context. Let lower values be better in

\[ P_{\mathrm{hw}} =\mathbb R_{\ge0}^{\,4} \quad\text{with coordinates}\quad (\text{time},\text{energy},\text{memory},\text{clearance loss}). \]

For the following calculation, take these illustrative values as each package's exact worst-case performance point in the declared model:

controller packagetime (s)energy (Wh)memory (MB)clearance loss (m)
camera planner with a slow inspection manoeuvre18780
lidar safety planner1210200
fast camera planner9680.12

The first camera controller spends time repositioning until its view separates the two layouts; this is why it can be safe despite the original ambiguous report. Each point generates a full performance region of looser bounds above it. For the fixed collision-free docking task, the fast camera package is excluded from the successful region because its clearance loss is positive. The two safe packages remain incomparable in time, energy, and memory. The lidar controller is faster than that camera controller but uses more energy and memory. The fast camera plan buys speed and energy at the price of a positive worst-case clearance violation. A weighting policy can compare all three only if graded clearance loss is admitted as a tradeoff. It cannot waive the original collision-free success condition without defining a different task. If lidar is a mandatory hardware package, its power and memory costs can make its attainable region cross the camera region. If it is merely an optional observation available to the same program class at no charged interface cost, the camera encounter's region is included in the lidar encounter's region because lidar can be ignored. The modelling choice changes the claim and must be stated.

Finally compare simulation with hardware. Let the simulator's nonnegative performance bounds be

\[ P_{\mathrm{sim}}=\mathbb R_{\ge0}^{\,3}, \qquad (s,n,z) =(\text{motion steps},\text{peak live planner nodes}, \text{normalized clearance loss}). \]

Alignment must first relate layouts, observations, executable moves, and dock success. A simulator that omits an admitted fire mode or offers an unexecutable move cannot be repaired by converting units. For the following calculation, assume this alignment and an exact calibration: one motion step costs two seconds, each live planner node occupies two MB, and clearance loss is normalized by 0.1 metre. These are illustrative model assumptions, not measured robot data. The performance map is

\[ u(t,e,m,c)=(t/2,m/2,10c). \]

Suppose the admitted simulator policy has attainable region

\[ A_{\mathrm{sim}}=\uparrow(6,10,0). \]

Its inverse image is exactly

\[ u^{-1}(A_{\mathrm{sim}}) =\{(t,e,m,c):t\ge12,\ m\ge20\}. \]

The missing energy condition is visible: \(u\) forgets energy. The hardware lidar policy in the table instead generates

\[ A_{\mathrm{lidar}}=\uparrow(12,10,20,0) \subsetneq u^{-1}(A_{\mathrm{sim}}). \]

For example, \((12,0,20,0)\) belongs to the inverse image but not to the hardware region. The simulator certificate accepts a zero-Wh bound that the hardware policy cannot meet. The formulas and strict inclusion are checked in the Lean companion.

Now declare a comparison family consisting of hardware encounters in which every successful docking run uses at least ten Wh, and use their successful attainable regions. No encounter in this family realizes the displayed preimage: every nonempty successful region excludes its zero-energy witness. This is a concrete failure of preimage closure. The family restriction is essential; it concerns the stipulated docking package, not all possible robots or the camera packages above. Nor is the conclusion obtained merely by showing that this one lidar policy fails to realize the preimage.

There are three different achievements here. Alignment relates the tasks and admitted worlds. Calibration makes performance bounds comparable. Realizability would supply an admitted encounter with exactly the translated region. The first two have been assumed for this calculation; the third fails in the declared hardware family.

Ordinary Pareto order already compares the three hardware packages. The fibred formulation adds a place to record the different simulator coordinates and the precise question whether their inverse-image specification is realizable. It earns its use here by exposing the energy constraint that a coordinate translation silently dropped, not by replacing the underlying control or optimization theories.

The fibred order of difficulty

A comparison context \(c\) fixes a common encounter schema: task, instance and environment quantifiers, uncertainty class, admissible programs, information and action interfaces, and resource and loss coordinates. It also fixes the success predicate and profile convention. Task difficulty uses successful regions; full regions compare graded performance and must carry the relevant success threshold when used to infer task feasibility. Its declared encounters instantiate that schema. Let \(P_c\) be the resulting ordered performance space. The ambient fibre is the powerset

\[ \mathcal R_c=\mathcal P(P_c), \]

ordered by inclusion. Let \(\operatorname{Enc}(c)\) be the declared encounters to be compared. Attainability is a map

\[ \mathsf{Ach}_c:\operatorname{Enc}(c)\longrightarrow\mathcal R_c \]

whose values are upward-closed regions of the chosen kind. In the task difficulty order below, set \(\mathsf{Ach}_c(E)=\mathsf{Ach}_{\mathrm{succ}}(E)\). Within this one context, define

\[ E_1\mathrel{\unrhd_c}E_2 \quad\Longleftrightarrow\quad \mathsf{Ach}_c(E_1)\subseteq\mathsf{Ach}_c(E_2), \]

and read \(E_1\unrhd_c E_2\) as "\(E_1\) is at least as hard as \(E_2\) for the stated success condition and recorded bounds." If full regions are chosen instead, the same algebra defines a graded-performance order; it does not license claims about unrecorded semantic success. The relation is reflexive and transitive, but it need not be antisymmetric on encounters. Two different plants, observation channels, or presentations can have exactly the same attainable region. Quotient by

\[ E_1\sim_c E_2 \quad\Longleftrightarrow\quad \mathsf{Ach}_c(E_1)=\mathsf{Ach}_c(E_2). \]

The quotient is order-isomorphic to the realized image:

\[ \operatorname{Enc}(c)/{\sim_c} \ \cong\ \operatorname{im}(\mathsf{Ach}_c) \ \subseteq\ \mathcal R_c. \]

This quotient is the realized subposet of the ambient fibre. The ambient powerset may contain unrealized regions, while the chosen performance coordinates intentionally forget other distinctions between systems.

The realized order is typically partial. Crossing Pareto frontiers witness incomparability, and an added scalarization can rank them differently.

To relate ambient fibres, choose a category \(\mathcal C\) of contexts. Its arrows are not arbitrary coordinate maps. An arrow \(f:c\to d\) is admitted only after its profile conventions have been matched and an encounter alignment has justified the relevant relation between problem or task, success predicates, environment families, observation and action interfaces, and resource conventions. The strength and direction of these components may differ: an implication of success is weaker than an equivalence, and forward simulation is weaker than executable lifting.

The formal region layer retains from this certificate a performance-point map \(u_f:P_c\to P_d\), compatible with identities and composition. It assumes the semantic licensing argument; it does not manufacture one. Preimage gives

\[ f^*:\mathcal R_d\longrightarrow\mathcal R_c, \qquad f^*(A)=u_f^{-1}(A). \]

It is monotone and strictly contravariant:

\[ (\operatorname{id}_c)^*=\operatorname{id}_{\mathcal R_c}, \qquad (g\circ f)^*=f^*\circ g^*. \]

Thus the ambient data form a strict contravariant indexed poset

\[ \mathcal R:\mathcal C^{\mathrm{op}}\longrightarrow\mathbf{Pos}. \]

Preimage always preserves inclusion. It reflects inclusion whenever \(u_f\) is surjective:

\[ f^*(A)\subseteq f^*(B) \Longrightarrow A\subseteq B. \]

A bijection of performance coordinates is sufficient for reflection and gives an order isomorphism between ambient fibres, but bijectivity is stronger than reflection needs.

Once semantic alignment and performance calibration have licensed \(f\), even without closure of realized regions it permits a heterogeneous comparison of two given encounters:

\[ E_c\mathrel{\unrhd_f}E_d \quad\Longleftrightarrow\quad \mathsf{Ach}_c(E_c) \subseteq u_f^{-1}\bigl(\mathsf{Ach}_d(E_d)\bigr). \]

This compares the pair without constructing a source encounter. Restricting \(f^*\) to realized subposets requires the additional preimage-closure condition:

\[ A\in\operatorname{im}(\mathsf{Ach}_d) \quad\Longrightarrow\quad u_f^{-1}(A)\in\operatorname{im}(\mathsf{Ach}_c). \]

One sufficient way to prove this closure and choose source representatives is an encounter transport \(T_f:\operatorname{Enc}(d)\to\operatorname{Enc}(c)\) satisfying

\[ \mathsf{Ach}_c(T_fE) =u_f^{-1}\bigl(\mathsf{Ach}_d(E)\bigr). \]

The Lean companion packages this stronger witness. Identity and composition then follow at the region level. Without preimage closure, reindexing remains an operation on ambient powersets.

This contravariant preimage must be separated from a lossy direct image. For a many-to-one map \(q:P_c\to P_d\), the covariant operation

\[ q_!:\mathcal R_c\longrightarrow\mathcal R_d, \qquad q_!(A)=\{q(x):x\in A\} \]

is monotone but can send distinct subsets to the same image and therefore fail to reflect inclusion. Noninjectivity causes that collapse; reflection by inverse image instead depends on surjectivity.

An empty successful region is preserved by preimage. A nonempty region can have empty preimage if the performance map never reaches it. A directional comparison therefore cannot silently reflect feasibility; reflecting it needs a suitable intersection or surjectivity argument as well as semantic alignment.

The formal contexts, performance maps, and reindexing laws are declared data, but their use carries layered proof obligations. Encounter alignment licenses semantic comparison; the performance map transports ambient specifications; preimage closure transports realized classes; and chosen encounter transport is stronger still. Together they yield a partial, context-indexed order rather than a global ranking.

Relation to neighboring orders

The ingredients above have substantial precedents. The proposed contribution is the encounter-audit protocol and its use of the fibred order to implement attainability, justified transport, and the search for stable claims. It is not a new theory of orders, fibrations, or Pareto frontiers.

frameworkobject being comparedrelation to this book
Blackwell orderstatistical experiments, ordered by decision performance or garblingthe deterministic observation preorder is a special case; for noisy reports, the guarantee order of Chapter 9 is strictly coarser
Medvedev and Weihrauch degreesmass problems or multivalued computational problems, ordered by uniform solution transformationsthey compare computational content; this book instead compares attainable resource/loss regions after an encounter is fixed
complexity measuresprograms and functions under a declared machine and measurethese supply coordinates and bounds inside one context
Pareto optimization and monotone co-designfeasible implementations, functionality, resources, and minimal antichainsthese supply the attainable-region geometry and already support compositional engineering tradeoffs
resource theoriesresources ordered by allowed conversion, often with a monoidal combination operationthis book has no general tensor or conversion calculus and does not replace those theories
indexed posets and fibrationscontext-indexed fibres with contravariant reindexingthe categorical machinery used here is standard

Blackwell (1953) compares experiments through the decision risks they support. Medvedev degrees and Weihrauch reducibility compare problems by uniform procedures that transform solutions or realizers. Those orders can distinguish computational content even when two encounters have the same resource/loss region. Conversely, two problems of the same Weihrauch degree can have different time, memory, energy, or robustness envelopes under a chosen machine and environment. The present order is therefore not a substitute for a reducibility degree.

The nearest engineering precedent is monotone co-design. Censi's framework already has functionality, implementation, and resource posets, feasibility relations, Pareto antichains, composition, and feedback; a subsequent extension treats uncertainty. It is more developed than this book's attainable-region construction as a design calculus. The narrower question asked here is what licenses comparison when the performance spaces or encounter interfaces themselves change. The answer separates an ambient inverse-image comparison from closure of the realized family under that inverse image. General resource theories order resources by allowed conversion and often add a monoidal combination; see Coecke, Fritz, and Spekkens (2016) and Fritz (2017). The book has no general tensor or conversion calculus and does not replace them either.

The same honesty applies to the categorical language. Contravariant reindexing, indexed posets, and their associated fibrations are standard; see Lawvere (1969), Bénabou (1985), and Jacobs (1999). Restricting an ambient indexed family to selected subfibres requires those subfibres to be stable under reindexing. Calling that requirement preimage closure makes the modelling debt visible but does not make the categorical fact new.

The defensible originality claim is consequently modest. The book combines: an encounter audit separating specification from consequence; attainable regions within each context; encounter alignment before cross-context comparison; and a distinction between ambient performance transport and transport of realized classes. The warehouse example carries those levels through one system. Whether this synthesis is useful can be tested by whether it catches invalid simulator-to-hardware, abstraction-to-execution, or model-to-plant transfers that a less explicit account leaves tacit, and by whether it identifies nontrivial claims stable across a justified comparison class. No claim of historical priority is made.

Finite envelopes and missing algorithms

Let \(E\) be a nonempty finite set of admissible programs and let \(V(p)\) be their value. A maximizer exists because the envelope is finite. If \(E\subseteq F\), the optimum over \(F\) cannot be worse. A strict gap can occur when an excluded program is better than every member of \(E\).

The optimum is internal to the declared envelope. Enlarging the envelope may improve value while making search more expensive; an infinite envelope may attain no optimum at all. The same distinction separates existence of a sufficient statistic or coordinate equivalence from its computable and efficient construction.

State counts are information-retention bounds

Finite-state lower bounds become meaningful when the interface is exact. Say a target machine is output-separated when, for every distinct pair \(s\ne t\), there exists a finite input word \(w\) after which their outputs differ. Any machine tracking it exactly needs an injective encoding of those states. Thus

\[ |S_{\mathrm{target}}|\le |S_{\mathrm{tracker}}|. \]

This is a capacity condition, not a theory of understanding. Equal state counts do not guarantee a tracking map, and a smaller quotient may preserve everything needed for one task.

The state-separation argument is the elementary core of the Myhill-Nerode tradition. The positional multiplication example in the formal companion is even more specific. For \(b\ge2\) and \(n>0\), a one-pass register machine reads two \(n\)-digit base-\(b\) operands, retains \(k\) registers with \(r\) values each, and emits the product only from its final register state. Fixing the second operand to one turns the task into delayed reproduction of the first. Distinct first operands must therefore end in distinct configurations:

\[ b^n\le r^k. \]

If all configurations fit into \(m\) bits, then \(n\le m\). The lower bound is about retaining an operand under a one-pass, final-output interface. It is not a lower bound on multiplication in standard complexity classes. Rereadable input, auxiliary storage, or incremental output changes the model and can invalidate the argument.

The conversion from states to bits is essential. A machine with \(2^s\) states has \(s\) bits of state capacity, not \(2^s\) bits. Exponential state counts and linear bit bounds are the same statement in different units.

Where cost is paid

Representations can move work across time. An index, abstraction hierarchy, compiled circuit, or proof library may be expensive to construct and cheap to query. A fair resource vector separates preprocessing from online cost and states whether the artifact is amortized across instances. Treating a problem-specific artifact as free advice changes the computational model.

The relocation is measurable only after the acquisition protocol has been declared. Counting the cost of using a supplied lemma while omitting the search that found it measures conditional proof cost, not end-to-end discovery cost. The formal proof-cost infimum below deliberately begins after a proof language, admitted-proof predicate, and cost function have been fixed. It does not manufacture a metric for discovering those choices.

A comparison may grant the same offline artifact to both agents, charge its construction once, or study nonuniform families with size-specific advice. Each convention defines a different attainable region.

Complexity theory earns objectivity not by removing models but by declaring them and proving invariance or simulation relations across a comparison class. The model dependence is controlled, not denied.

Worked example: finding a certificate costs more than checking it

Consider \(N\ge1\) labeled candidates, exactly one of which is marked. A deterministic search procedure initially knows only this promise. Its only access to the mark is an equality query on a chosen label, returning yes or no. Each query costs one unit; all other computation is free in this query model. Success requires submitting a label with its affirmative oracle response. Merely inferring the last remaining label is not an accepted certificate until it has been queried.

The task fixes one procedure before the marked label \(j\) is revealed. Let \(q(p,j)\) count its queries. Its robust discovery cost is

\[ Q_N=\inf_{p:\,\forall j,\ \mathsf{Succ}(p,j)}\ \max_{1\le j\le N}q(p,j). \]

Sequentially querying every label succeeds within \(N\) queries. Conversely, an oracle can answer no on the first \(N-1\) distinct labels queried. That history remains consistent with the promise, with the last unqueried label marked. A successful procedure must then query that label to obtain the required affirmative response. Repeated queries cannot improve this bound. Thus \(Q_N=N\).

Now supply the marked label as correct advice, but still require its oracle response as the certificate. One query suffices and is necessary. With the advice supplied, the certificate-acquisition cost is one for every \(N\). Without it, the worst-case discovery cost is \(N\). The successful regions in the query-budget coordinate are respectively \([1,\infty]\) and \([N,\infty]\).

The difference is epistemic and operational: the unknown label controls which query succeeds, and the information interface prevents learning it cheaply. Every instance has a short certificate, yet no one uninformed procedure can obtain the required certificate with fewer queries in the worst case. The fixed order of quantifiers prevents giving each instance its own secretly informed procedure. These bounds are proved here in prose, not in the Lean companion.

The example identifies a precise sense of discovery difficulty without equating it with certificate size. It does not model all mathematical insight. The candidate language, prior knowledge, and query interface were stipulated. Investigating how those are acquired requires an encounter whose procedures include that acquisition. Such a study must state its own starting resources; the present framework supplies no universal measure of creativity or felt effort.

Chapter 6Modal resistance and conditional objectivity

What the encounter represents

The operational framework asks what can be achieved under specified conditions. A metaphysics asks what makes those constraints obtain. The first question does not settle the second. A model can organize correct conditional inferences while leaving its interpretation open.

Three things should be distinguished. A task situation consists of a system or mathematical object considered in relation to an end and conditions of access and action. An encounter specification \(E\) represents those conditions, including the success predicate and charged resources. A performance region is a further representation that forgets distinctions outside its coordinates. Changing notation alters a specification without necessarily altering the situation. Changing a goal alters the task relation even if the physical system is untouched.

The end may be chosen while its attainability remains objective. Chess rules are instituted, but whether a position admits a legal mate does not depend on a player's confidence. A docking requirement is selected, but a robot's inability to reach the dock through its available actions is not abolished by disagreement. Objectivity here means independence from verdicts about the specified constraints. It does not require the task, rules, or resource conventions to exist independently of human purposes.

Accordingly, the minimal commitment is realism about the relevant constraints, where their application to an actual system is adequately supported. It is compatible with different views about laws, powers, and mathematical objects. The stronger phrase encounter-borne disposition will refer to a proposed property of the represented task situation, not to a causal power possessed by a tuple of symbols.

Admissibility, success, and counterfactual scope

Let \(\mathcal M(E)\) be the admitted realizations, let \(\mathcal S(E)\subseteq\mathcal M(E)\) be those satisfying the fixed success condition, and let \(\pi_E:\mathcal M(E)\to P_E\) record performance. Then

\[ \mathsf{Prof}_{\mathrm{all}}(E)=\pi_E[\mathcal M(E)], \qquad \mathsf{Prof}_{\mathrm{succ}}(E)=\pi_E[\mathcal S(E)]. \]

Their upward closures are the full and successful attainable regions of Chapter 5. The successful region is empty exactly when no realization satisfies the task. Full-profile equality cannot establish task equivalence when performance omits part of success, as the parcel example shows.

If success is completely determined by performance, an acceptable set \(G_E\subseteq P_E\) gives

\[ \mathcal S(E)=\pi_E^{-1}(G_E), \qquad \mathsf{Prof}_{\mathrm{succ}}(E) =\mathsf{Prof}_{\mathrm{all}}(E)\cap G_E. \]

This is an identity of exact profiles. Their upward closures consist of bounds, not necessarily actual performance points. The success predicate and its order properties must be retained when passing between the two.

The primary modality is encounter-relative admissibility: \(\Box_E\varphi\) means that \(\varphi\) holds throughout the realizations admitted by \(E\). It does not automatically express physical, technological, logical, or unrestricted metaphysical necessity. Formal admissibility follows the model's rules; physical possibility concerns the target system and its laws; technological availability concerns implementations that can presently be obtained. Their correspondence requires argument, and their domains need not even have the same objects before a representation map is supplied.

The level of realization matters too. For a robust task, a realization may be a policy whose cost summarizes all admitted environments. For an execution-level claim it may be a single run. A bound on every successful run is refuted by one faster successful run. A lower bound on every policy's worst-case cost is not: the faster run may be an easy instance of that policy. The quantifiers belong to the hardness claim, not to the word modal.

What a dispositional interpretation would add

The metaphysical conjecture is that a task situation has a disposition to constrain success, grounded in facts about its object, environment, interfaces, and resources. Modal resistance names that proposed disposition. A person's struggle is evidence to investigate; it is not what constitutes the constraint.

There is a reason to entertain the conjecture. An organized system can support the same constraint across many unperformed interactions. The robot's observation channel, for example, would still merge the two layouts if the experiment were repeated in either layout. Describing this as a capacity or incapacity locates the explanation in the organization of the situation and connects actual failures with unactualized alternatives. That makes the dispositional vocabulary potentially useful for explanation.

However, usefulness of that description does not establish an irreducible power. A rival account can accept the same physical organization, laws, and counterfactual constraints while treating the disposition as a derivative description. Another account can accept the conditional model without a realist interpretation of its unobserved possibilities. The attainable-region algebra does not decide between them. A defense of dispositional realism must explain why its account of those counterfactuals is preferable, rather than using their existence as a premise that already assumes powers.

This is the point of comparison with Mumford's account of dispositions and Vetter's account of potentiality. Vetter argues for explaining metaphysical modality through dispositions and potentialities. Here an admissibility class is specified first. Giving its constraints a dispositional interpretation does not reproduce that argument or establish the same direction of metaphysical explanation.

The application to mathematical tasks needs particular care. A restriction on formal proofs is an abstract consequence of a calculus and a task, even when no physical solver exists. The impossibility of satisfying \(0x=1\) over the reals does not by itself exhibit a causal power. One may extend dispositional language to abstract task relations, but must explain what this extension contributes beyond their mathematical constraints. The book leaves that metaphysical choice open.

Thus the proposed order of explanation is facts about the situation, its counterfactual constraints, and particular manifestations. Treating the middle level as a disposition is a conjecture about what sustains those constraints. The book defends the need to distinguish those levels, without claiming that the distinction establishes a separate entity at each level.

Explanatory grounds and overlapping obstacles

Grounding concerns what a fact obtains in virtue of. It is different from merely listing propositions from which the fact follows; Fine's discussion of ground motivates that distinction. A true but irrelevant premise can be added to a proof. A useful bound can also be derived through a mathematical surrogate that is not the best explanation of the target system's behavior.

The explanatory question must therefore name its target and contrast. Why is there no physically executable path? Why can no admitted policy guarantee safety despite paths existing? Why must finding a certificate consume many queries even though using it is cheap? These are different facts, and a feature explaining one need not explain the others.

Consider the two-layout robot again, with two independent restrictions. Its camera cannot distinguish the layouts. In addition, a common fire door is closed across both routes and cannot be opened. No probing, waiting for a change, or alternative route is admitted in this one-decision task. Define success as a single policy safely reaching the dock in either layout. Allow two interventions: replace the camera with a sensor that identifies the layout, or open the common door while leaving the corridor obstruction.

common doorobservationa path exists in each layoutone policy guarantees safe docking
closedambiguousnono
closedidentifies layoutnono
openambiguousyesno
openidentifies layoutyesyes

The closed door explains physical unreachability in the first two rows. In the third, each layout has a path, but the identical observation forces a deterministic policy to choose the same turn in both. That turn is blocked in one layout. This proves the separate information obstruction to a uniform safe policy. Both restrictions must be removed to restore the stipulated guarantee.

Improving the sensor while the door is closed changes no success verdict. That null result does not show the information restriction was irrelevant to the task's organization. The door masks the improvement at the chosen outcome level. Opening the door exposes the conditional contribution of the sensor. Conversely, the lack of a physical path in the baseline already suffices to explain failure; it would be misleading to insist that the sensor is also a necessary premise of that particular explanation.

An informative explanation therefore identifies the exact obstruction, derives it from the relevant organization, and checks the contrast for which the feature matters. Interventions can separate overlapping obstructions; they are not a universal definition of metaphysical grounding. Redundant obstacles need not each be a simple difference-maker at the baseline. The table is a prose analysis of the stipulated model, not an additional Lean theorem or a claim about measured robot behavior.

Across encounters, a structural property can support a uniform bound together with access and machine assumptions. Invariance establishes the scope of that result. Whether the property explains the bound still depends on the derivation and the competing explanatory accounts. A comparison class whose members all share the same restrictive interface cannot, by stability alone, locate the source in the bare object.

An oracle, cached lemma, or new primitive can overcome a constraint of an earlier encounter. This does not retrospectively make the earlier constraint unreal. If a transformation instead preserves the full task and its charged costs, the corresponding difficulty claim should survive. A reported gain then gives a reason to examine the claimed preservation or the accounting.

Identity, equivalence, and directed transport

Because difficulty is attributed to a specified task situation, relations between its encounter representations cannot be left to syntax. Yet there is no single context-free relation corresponding to the phrase “the same problem.” Relations between encounters must instead be classified by the structures and inferences they preserve.

Strict identity is literal equality \(E=E'\) of the specified encounter data. It supports formal substitution and machine bookkeeping, but is too fine-grained for every scientific use. Renaming an action symbol or changing coordinates can produce a different encoded tuple without producing a relevantly different encounter.

Structural signatures and reducts. A structural signature \(\Sigma\) names the encounter components, operations, relations, and laws relevant to a comparison. Its selection is part of the encounter-alignment certificate, not a conclusion extracted from the comparison. Write

\[ E|_\Sigma \]

for the \(\Sigma\)-reduct of \(E\): the structured encounter obtained by retaining exactly the data named by \(\Sigma\) and forgetting the rest. A reduct is typed forgetting, not a claim that omitted structure is unreal or causally idle.

Presentation equivalence is isomorphism of reducts:

\[ \boxed{ E\cong_\Sigma E' \quad\Longleftrightarrow\quad E|_\Sigma\cong E'|_\Sigma.} \]

A witness \(\alpha:E|_\Sigma\cong E'|_\Sigma\) consists of reversible component maps preserving every operation, relation, and law retained by the signature. The relevant environment, observation, action, transition, program, and performance diagrams commute only when those structures occur in \(\Sigma\).

If the realization and success structures belong to \(\Sigma\), the witness includes a bijection

\[ \widehat\alpha: \mathcal M(E|_\Sigma) \longrightarrow \mathcal M(E'|_\Sigma) \]

with

\[ m\in\mathcal S(E|_\Sigma) \quad\Longleftrightarrow\quad \widehat\alpha(m)\in\mathcal S(E'|_\Sigma). \]

If performance also belongs to \(\Sigma\), then for its declared coordinate isomorphism \(u_\alpha\),

\[ u_\alpha\circ\pi_{E|_\Sigma} = \pi_{E'|_\Sigma}\circ\widehat\alpha. \]

If realizations or performance do not belong to the signature, their full preservation is not silently imposed. This is the point of taking the reduct before asking for an isomorphism.

For a fixed signature, witnesses contain identities, inverses, and composites:

\[ \mathrm{id}_{E|_\Sigma}, \qquad \alpha^{-1}, \qquad \beta\circ\alpha. \]

They obey the usual identity and associativity laws. Thus the witnesses form a groupoid, and \(\cong_\Sigma\) is an equivalence relation on encounters whose \(\Sigma\)-reducts have the same structural type. An isometry is one witness when metric structure belongs to \(\Sigma\), not the universal definition. Graph isomorphism, diffeomorphism, dynamical conjugacy, or another reversible change can witness other signatures.

Claim-relative equivalence is indexed by an independently declared family of claim languages. Encounters may use different vocabularies, so write \(\Phi_E\) and \(\Phi_{E'}\). A witness of

\[ E\equiv_\Phi E' \]

contains licensed translations in both directions,

\[ T_\alpha:\Phi_E\longrightarrow\Phi_{E'}, \qquad T_{\bar\alpha}:\Phi_{E'}\longrightarrow\Phi_E, \]

such that claims are preserved and reflected:

\[ E\models\varphi \quad\Longleftrightarrow\quad E'\models T_\alpha(\varphi), \qquad \varphi\in\Phi_E, \]
\[ E'\models\psi \quad\Longleftrightarrow\quad E\models T_{\bar\alpha}(\psi), \qquad \psi\in\Phi_{E'}. \]

The translations are inverse up to semantic equivalence in the admitted claim semantics:

\[ T_{\bar\alpha}T_\alpha(\varphi)\simeq_E\varphi, \qquad T_\alpha T_{\bar\alpha}(\psi)\simeq_{E'}\psi. \]

Here \(\simeq_E\) means equality of truth conditions in the semantics declared for \(E\), not syntactic identity. Each translation must respect these semantic-equivalence relations, so it descends to the corresponding quotient claim language. When both encounters use literally the same claim language, the translations may be identities and the definition reduces to the simpler biconditional.

Claim-equivalence witnesses also support identity, reversal, and composition. Identity witnesses use identity translations. For composable witnesses \(\alpha:E\equiv_\Phi E'\) and \(\beta:E'\equiv_\Phi E''\), define

\[ T_{\beta\circ\alpha} = T_\beta\circ T_\alpha, \qquad T_{\overline{\beta\circ\alpha}} = T_{\bar\alpha}\circ T_{\bar\beta}. \]

The round-trip laws are preserved by composition. After translations are identified up to \(\simeq\), these witnesses form a groupoid; consequently the existence relation \(\equiv_\Phi\) is an equivalence relation at the chosen claim level. Coincidental agreement of the propositions currently tested is insufficient; the coherent translations belong to the witness.

Presentation equivalence yields claim-relative equivalence only when the chosen languages are invariant under reduct isomorphism and their translations are induced by the structural witness:

\[ E\cong_\Sigma E' \ \Longrightarrow\ E\equiv_\Phi E' \qquad \text{only for }\Phi\subseteq\operatorname{Inv}(\Sigma). \]

An extra memory bit may be irrelevant to reachability but visible to an exact memory-cost claim. Two sensors may be equivalent for robust action and inequivalent for state reconstruction. Extensionally equal success predicates may be presentationally interchangeable even when their syntax differs. Equal attainable regions provide performance equivalence, but can hide different causal mechanisms, realization spaces, or computational degrees.

Directed claim transport is asymmetric. A witness

\[ E\xrightarrow[\Phi]{\alpha}E' \]

contains a translation \(T_\alpha:\Phi_E\to\Phi_{E'}\) satisfying

\[ E\models\varphi \quad\Longrightarrow\quad E'\models T_\alpha(\varphi), \qquad \varphi\in\Phi_E, \]

without requiring reflection or an inverse. When the witness also maps realizations, it may additionally satisfy

\[ m\in\mathcal S(E) \quad\Longrightarrow\quad \widehat\alpha(m)\in\mathcal S(E'). \]

Directed witnesses have identity arrows and compose. If

\[ E\xrightarrow[\Phi]{\alpha}E' \xrightarrow[\Phi]{\beta}E'', \]

then

\[ E\xrightarrow[\Phi]{\beta\circ\alpha}E'', \qquad T_{\beta\circ\alpha} = T_\beta\circ T_\alpha, \]

with \(T_{\mathrm{id}_E}=\mathrm{id}_{\Phi_E}\) and associativity. They therefore form a category of encounters and licensed transports; only after discarding distinctions between parallel witnesses need this collapse to a preorder. Simulation, sound abstraction, embedding, refinement, reduction, and relaxation naturally live here.

Arrows in both directions do not by themselves give claim-relative or presentation equivalence. Claim equivalence additionally requires preservation, reflection, and coherent round trips in the chosen languages. Presentation equivalence additionally requires an isomorphism of the declared reducts.

Extension changes the admitted realization structure by adding, for example, an oracle, sensor, actuator, axiom, primitive, or resource. The old encounter may embed into the new one, but that embedding does not make the extension a presentation change.

The common mathematical notions are domain-specific witnesses rather than universal definitions:

witnesstypical preserved claimscommonly not preserved without more hypotheses
isomorphismincidence and exact structural claimsexternal metric or cost omitted from the signature
isometrydistance and path-length claimscomputational or causal organization
conjugacydynamical orbit structurephysical cost and robustness
homotopy equivalenceselected topological existence claimslength, barriers, conditioning, and timing
bisimulationselected behavioral or temporal claimsimplementation cost
simulationsound one-way behavioral claimslifting and reflection
relaxationfeasibility inclusion or objective boundsintegrality and executable solutions
reductionsolution or decision transportnative resource cost unless complexity is controlled

Continuous relaxation makes the direction visible. If \(X_{\mathrm{disc}}\subseteq X_{\mathrm{relax}}\) and the objective is compatible, then

\[ \inf_{x\in X_{\mathrm{relax}}}f(x) \le \inf_{x\in X_{\mathrm{disc}}}f(x). \]

The relaxation supplies a lower bound for minimization. It need not return an integral optimizer, executable path, or valid resource certificate. A minimum should not replace the infimum unless attainment has been proved.

Realizations must also remain distinct from their performance images. When the realizations are trajectories, write

\[ \Gamma_{\mathrm{succ}}(E) = \{\gamma:\gamma\text{ is admitted and successful}\}, \]

and only then define

\[ \mathsf{Prof}_{\mathrm{succ}}(E) = \pi_E[\Gamma_{\mathrm{succ}}(E)]. \]

The order of construction is

\[ \text{realizations} \longrightarrow \text{successful realizations} \longrightarrow \text{performance profiles} \longrightarrow \text{attainable regions}. \]

The individuation thesis is consequently:

Encounter individuation is preservation-relative: the relevant notion of sameness is determined by which independently specified structures or inferences must survive transformation. Strict identity is equality of specified data; presentation equivalence is isomorphism of a declared structural reduct; claim-relative equivalence is coherent bidirectional translation of a declared claim language; directed transport preserves selected inferences in one direction.

The formal implications should be read in two stages. Equality always induces the identity reduct isomorphism:

\[ E=E' \quad\Longrightarrow\quad E\cong_\Sigma E'. \]

When \(\Phi\subseteq\operatorname{Inv}(\Sigma)\) and the claim translations are induced by the reduct isomorphism,

\[ E\cong_\Sigma E' \quad\Longrightarrow\quad E\equiv_\Phi E' \quad\Longrightarrow\quad \left( \exists\alpha,\ E\xrightarrow[\Phi]{\alpha}E' \right) \ \text{and}\ \left( \exists\bar\alpha,\ E'\xrightarrow[\Phi]{\bar\alpha}E \right). \]

None of the converses holds in general. In particular, two directed arrows do not supply the coherent round trips required by \(\equiv_\Phi\). Nor may a difference be declared irrelevant after inspecting the desired conclusion: \(\Sigma\), \(\Phi\), their semantics, and the admitted transformations must be fixed and justified independently.

The architecture is therefore

\[ \boxed{ \text{raw encounter} \to E|_\Sigma \to \text{presentation equivalence} \to \Phi \to \text{claim equivalence or directed transport} \to \text{stability class} \to \text{demonstrated scope}.} \]

Specification before calculation

The framework separates the justification of an encounter from calculation inside it. Selecting a task, environment family, uncertainty model, success tolerance, program class, and charged resources can depend on scientific purposes, engineering priorities, conventions, institutions, and values. A declaration does not validate itself merely by being explicit.

Three questions should therefore remain visible:

Mathematics addresses the first directly and can support the second through validated models and measurements. It cannot infer the third from a type signature. Conditional objectivity concerns consequences within a specification. Warrant for applying them to a target requires evidence of adequacy; choosing which consequences matter requires reasons about the task. These are three separate achievements, rather than successive degrees of mathematical truth.

Within a fixed encounter, the resulting facts are not matters of opinion. The camera report at the fork merges \(L\) and \(R\); the closed fire door removes the dock from the reachable set; a controller either satisfies its certified time, energy, memory, and clearance bounds or it does not. Changing a sensor, actuator, uncertainty set, or charged resource creates a different encounter whose attainable region may change.

Worked example: two defensible specifications disagree

Suppose two controller packages have the following stipulated operating record. A fast package takes one minute in ordinary conditions and five minutes in a rare mode. A steady package takes two minutes in either mode. Both are collision-free and reach the dock. The rare mode has probability one in a hundred in the declared distribution. Energy and memory are equal for this comparison. These are illustrative assumptions, not measurements.

An encounter for routine throughput declares success to mean expected docking time at most 1.5 minutes. The fast package has expected time

\[ 0.99\cdot1+0.01\cdot5=1.04, \]

so it succeeds; the steady package's expected time is two, so it fails that task. An encounter for an emergency service instead requires docking within three minutes in every admitted mode. The steady package succeeds; the fast one fails because the rare mode takes five minutes. Both specifications can be mathematically coherent and empirically adequate descriptions of the same packages. They ask for different achievements.

The disagreement has several possible sources. Whether the rare mode occurs and how long each package takes are empirical questions. Whether one in a hundred is an appropriate probability for deployment is another empirical question, including uncertainty about that estimate. Whether an emergency service may trade a delayed individual delivery against faster average service is a question about the end and acceptable consequences. Averaging conventions are relevant only after those choices have been justified.

Suppose the actual commission requires a delivery within three minutes in every admitted mode. The average-time certificate does not answer that commission. This rejection follows from the success condition before either package's favorable result is inspected. If the commission instead concerns routine expected throughput, the average comparison is relevant, provided its distribution is supported. If the commission itself is disputed, more arithmetic cannot choose the end. Evidence about consequences and reasons offered by affected parties can inform that choice, but the present algebra does not supply an ethical ranking.

The audit has a limited but substantive role: it reveals whether apparently opposed difficulty verdicts concern one question or different questions, and locates the evidence or practical reasons needed to proceed. It can reject a mismatched certificate without pretending to settle every dispute about the proper task. This example is calculated and argued in prose.

Why the fibred order is needed

Inside the hardware context, ordinary Pareto order already performs the local comparison. It records the camera/lidar tradeoffs and leaves crossing frontiers incomparable. The fibred layer becomes useful when claims move between different performance spaces or encounter interfaces.

The obligations are staged:

\[ \text{encounter alignment} \Longrightarrow \text{licensed performance translation} \Longrightarrow \text{ambient region comparison} \Longrightarrow \text{realized-region transport, if proved}. \]

An alignment relates the tasks and admissible worlds. A performance map then translates specifications. Inverse image supports comparison of a given pair of aligned encounters, but does not produce a hardware encounter realizing every translated simulator region. Preimage closure proves transport of realized regions; an encounter map additionally supplies representatives.

Information theory, control, abstraction, and complexity determine particular constraints and attainable regions. The fibred order organizes how those results may be compared after semantic alignment has been justified. It does not decide whether the simulator represents the plant, whether a safety threshold is legitimate, or whether two tasks deserve comparison.

No unqualified master scale

The result is a partial order indexed by declared contexts, not an automatically privileged scalar. Crossing Pareto frontiers may remain incomparable, and scalarizations can rank them differently. This does not imply that context-independent facts are impossible. A claim of wider scope requires an argument covering that scope, such as transport across a justified comparison class. A local claim can already be objective; it need not become invariant under changes that alter its truth conditions.

The comparison class is itself declared. Requiring stability across coordinate changes is weaker than requiring stability across machine simulations, sensor substitutions, task translations, and environment enlargement. A claim is only as broad as the arrows along which it has been shown to survive.

What can survive context change

The individuation hierarchy supplies the transformation theory beneath stability. Reduct isomorphisms specify which changes count as presentation; coherent bidirectional translations specify which preserve and reflect a claim language; composable directed witnesses specify one-way inference. Their identity and composition laws allow stability to be tested along chains rather than only for isolated pairs. Exact equality is therefore only one form of invariant content. What survives an encounter alignment may instead be:

Let \(\mathcal A\) be a declared class of licensed encounter transformations. A claim is stable over \(\mathcal A\) when every relevant transformation transports it in the stated direction. Exact invariance may follow from presentation or claim-relative equivalence; directional stability may preserve only implications or bounds. Neither follows from a performance-coordinate map alone. The transformation class and claim language must be independently motivated: a trivial \(\Phi\) or a post hoc \(\mathcal A\) can manufacture uninformative invariance.

This yields increasing demonstrated scope, conditional on the premises:

\[ \boxed{ \text{local} \ \longrightarrow\ \text{transportable} \ \longrightarrow\ \text{stable over a declared comparison class}.} \]

The endpoint of the framework is therefore not that everything is contextual. It is a disciplined account of what individuates an encounter, what licenses transport, and what remains true when the encounter changes. Operational task difficulty compares successful attainable regions under the stated conditions; a full performance comparison must retain its success criterion. A relational hardness claim has broader demonstrated scope when it remains invariant, or directionally stable, under a justified class of transformations. This does not itself increase the evidence that the models describe reality: several models can preserve the same error. Scope, empirical warrant, and relevance to a decision must each be assessed. A correct local impossibility claim is not less objective because adding an actuator makes its conclusion false in a different encounter.

Chapter 7When the system reacts to the model

Reaction is not necessarily strategy

A model can fail because the world was unknown, because it changed, or because using the model helped change it. These explanations call for different tests. An unknown fixed parameter calls for identification. Time-dependent drift calls for tracking. Deployment feedback calls for a model of the response to the deployed policy.

Reaction need not involve an opponent. A controller can heat a sensor; a prediction can determine which observations will be collected; a scheduling rule can shift arrivals. Strategic response is the narrower case in which an agent selects behavior according to an objective. Adversarial response further specifies opposition to the solver's guarantee. Calling all three strategic would obscure the mechanism rather than explain it.

For a sequential encounter, let \(h_t\) be the history visible at time \(t\). A solver policy and an environment response jointly generate a trajectory:

\[ a_t=p(h_t), \qquad x_{t+1}=\alpha(h_t,a_t). \]

This timing lets the environment respond to the current action but not to an unobserved future action. Other timing and information conventions define different encounters. Randomized policies also require a declaration of which random choices the response observes.

If actions can change the transition rule itself, include the rule \(R_t\) in the state and write an augmented transition for \((x_t,R_t)\). Such an endogenous law still evolves under a specified higher-level rule. It does not license arbitrary changes to the encounter during an argument.

The uniform guarantee

Let \(\mathcal A\) be the admitted response class, and let \(L(p,\alpha)\) and \(C(p,\alpha)\) be the loss and resource cost of their joint execution. The robust full performance region in this chapter is

\[ \mathsf{Ach}_{\mathcal A} =\{(r,\ell):\exists p\in\mathsf{Prog},\ \forall\alpha\in\mathcal A,\ C(p,\alpha)\le r\ \land\ L(p,\alpha)\le\ell\}. \]

Here \(\mathsf{Ach}_{\mathcal A}\) records the full cost/loss curve. A fixed task additionally declares its acceptable loss and any semantic success requirements; use its successful region when comparing attainment of that task. One policy must meet both bounds against every admitted response. The weaker statement \(\forall\alpha\,\exists p\) permits a different policy after the response is known. Changing those quantifiers can turn a failed robust task into a collection of easy tasks without improving the original solver.

Holding programs, cost, and loss fixed, enlarging \(\mathcal A\) can only shrink this region. Merely replacing one known response law by another need not do so: it may change the best policy while leaving optimal performance unchanged. The following calculation separates these effects.

Worked example: a forecast changes its target

A deployed system announces a number \(\theta\in[0,1]\) and incurs absolute prediction loss \(\lvert\theta-y\rvert\). Each announcement costs one unit. There are two possible deterministic environments:

\[ F(\theta)=1, \qquad R(\theta)=1-\theta. \]

The first is frozen. The second mechanically reacts to the forecast. At the initial announcement \(\theta_0=0\), both produce the same observation \(y=1\). Fitting that observation gives \(\theta_1=1\). Its historical fitting error is zero. Deployed against \(R\), however, it produces \(y=0\) and error one. No agent chose to deceive it. The evidence failed to distinguish two response laws that agree at the data-collection policy.

Repeatedly replacing the forecast by the latest reactive observation gives

\[ \theta_{n+1}=1-\theta_n. \]

Starting at zero, this rule oscillates between zero and one. The fixed point \(\theta=1/2\) instead predicts its own reactive outcome perfectly. Thus the reactive encounter alone has the same optimal loss, zero, as the frozen encounter alone, although their optimal announcements differ.

Suppose the solver must commit to one announcement before learning which law applies. No further experiment is admitted in this one-round encounter. Its worst-case loss is

\[ W(\theta)=\max\{1-\theta,\lvert2\theta-1\rvert\}. \]

If \(W(\theta)\le\ell\), then \(1-\theta\le\ell\) and \(2\theta-1\le\ell\). Twice the first inequality plus the second yields \(1\le3\ell\). At \(\theta=2/3\), both losses equal \(1/3\), so

\[ \min_{0\le\theta\le1}W(\theta)=1/3. \]

The exact attainable regions are therefore

\[ \mathsf{Ach}_{\{F\}} =\{(r,\ell):r\ge1,\ \ell\ge0\}, \]
\[ \mathsf{Ach}_{\{F,R\}} =\{(r,\ell):r\ge1,\ \ell\ge1/3\}. \]

The second is strictly smaller. Reaction changed the required policy; uncertainty over the response class imposed the positive robust loss. Additional diagnostic announcements could identify the law here, but would change both the information interface and the resource accounting. The arithmetic, optimal bound, and both regions are machine checked.

This belongs to the setting studied as performative prediction: deployment can alter the data distribution. Perdomo, Zrnic, Mendler-Dünner, and Hardt (2020) distinguish performative optimality from stability under retraining. The displayed \(1/3\) bound is our elementary robust calculation over two response laws; it is not their convergence theorem. The oscillation also shows why a deployment fixed point and convergence of a chosen retraining procedure are different questions.

Counterfactual comparison against an adaptive environment

When the response depends on the solver's history, evaluating an alternative policy on the actual policy's frozen observations can misstate its performance. The alternative would have generated another history and therefore another response. A counterfactual policy comparison must rerun that interaction.

For cumulative loss \(L_T\), one possible comparison is

\[ L_T(p,\alpha) -\inf_{q\in\mathcal Q}L_T(q,\alpha), \]

where each term uses the trajectory jointly generated by its own policy and the same response rule \(\alpha\). The comparator class \(\mathcal Q\), information timing, and any randomization remain fixed. This is the concern addressed by policy regret in Arora, Dekel, and Tewari (2012). Their distinction from ordinary regret against an adaptive adversary is directly relevant; their guarantees also depend on restrictions on the adversary, such as bounded memory.

Learning itself can be limited by strategic opacity: two strategic response rules may agree on every interaction the learning protocol can perform but require different deployment policies. As in Chapter 1, the first question is whether the experiment class distinguishes the cases that matter to action. The forecast example exhibits the same information problem without strategy.

For deployment, the useful audit is short: which response laws were admitted, what did they observe, which policy generated the evidence, and does one implementable policy meet the promised bounds after deployment? A guarantee over a frozen dataset answers only part of that question. Once these declarations are supplied, the attainable-region comparison is the same one used elsewhere in the book.

Chapter 8When nearby problems stop being nearby

A failed recipe is not a lower bound

Nearby examples often suggest how to solve a target. The suggestion becomes a mathematical transfer claim only when a proof transformation is supplied and its side conditions and costs are checked. Division by a parameter, removal of an exceptional case, or relaxation of integrality can invalidate that transfer even when the resulting statements look nearly identical.

Three costs should be kept separate. Search cost is the work of locating a certificate. Certificate cost is a declared cost of constructing, executing, or checking a supplied certificate. Budget infeasibility means that no admitted certificate meets the bound. A search may fail while a cheap certificate exists. A changed search order can then help without extending the proof language. Conversely, adding an oracle or a stronger primitive changes which realizations are admitted or how they are charged. “Change the model” does not identify which of these happened.

The mathematical premises also remain distinct from a solver's expectations. A proof cannot violate the theorem's hypotheses to establish its conclusion. It can reject an expectation that the proof should use a particular coordinate system, resemble neighboring proofs, or proceed by a familiar decomposition. The formal question is whether that favored method was necessary, affordable, or merely the first one tried.

Cost profiles and available mechanisms

Fix a proof or certificate type, a predicate \(\operatorname{Proves}(p,P)\), and a cost \(C(p)\in\overline{\mathbb R}_+=[0,\infty]\). Write

\[ \kappa(P)=\inf_{p:\operatorname{Proves}(p,P)} C(p). \]

An empty admitted-proof set gives \(\kappa(P)=\infty\). Finite cost implies that a proof exists; the converse requires a finite-cost proof. An infimum need not be attained, so a budget at the infimum is not automatically feasible.

To compare costs even at infinity, use the extended cost gap

\[ g(a,b)=(a\mathbin{\dotminus}b)\vee(b\mathbin{\dotminus}a). \]

It is symmetric, vanishes exactly when \(a=b\), gives \(g(\infty,\infty)=0\), and gives \(g(a,\infty)=\infty\) for finite \(a\). For a declared proximity map \(d\), define the local variation

\[ \Delta_\varepsilon(P) =\sup_{Q:\,d(P,Q)\le\varepsilon} g\bigl(\kappa(Q),\kappa(P)\bigr). \]

This is monotone in \(\varepsilon\) and is zero exactly when every neighbor in the displayed set has the target's cost. The order laws need no metric axioms. Interpreting \(d\) as geometric distance requires those extra laws; interpreting it as useful mathematical similarity requires a modeling argument.

A selected proof label \(m(P)\) records what someone used, not what was available. To study availability, independently classify certificates by \(\operatorname{kind}(p)\) and define

\[ K_B(P)=\{k:\exists p,\ \operatorname{Proves}(p,P)\ \land\ C(p)\le B \ \land\ \operatorname{kind}(p)=k\}. \]

The set is empty exactly when no admitted certificate fits budget \(B\). Increasing the budget can only enlarge it. A selected label can change while the entire set stays fixed; therefore a change of label alone does not locate a boundary of possible methods.

For directed transport, a proof transformation \(\tau\) with kind map \(v\) must send every admitted source certificate within \(B\) to a target certificate within \(B'\), with \(\operatorname{kind}(\tau p)=v(\operatorname{kind}(p))\). Then

\[ v[K_B(P)]\subseteq K_{B'}(Q). \]

This is the proof-level counterpart of the performance transports in Chapter 5. Its soundness and cost assumptions expose what an analogy needs to supply.

The stability radius includes its supremum

Let \(m(P)\) be a declared mechanism summary and \(\sim\) a declared binary relation on summaries. One substantive choice is \(m(P)=K_B(P)\) with equality of sets. A selected-label summary instead studies stability of the selection. Define

\[ \operatorname{Stable}_P(r) \quad\Longleftrightarrow\quad \forall Q,\ d(P,Q)<r\Rightarrow m(Q)\sim m(P), \]
\[ R(P)=\sup\{r:\operatorname{Stable}_P(r)\}. \]

With extended nonnegative distances and this strict ball condition,

\[ \boxed{\operatorname{Stable}_P(r)\quad\Longleftrightarrow\quad r\le R(P).} \]

Here is why the endpoint is included. If \(d(P,Q)<R(P)\), the defining supremum contains some stable radius \(s>d(P,Q)\); otherwise \(d(P,Q)\) would be an upper bound. Stability at \(s\) supplies the required relation. Thus \(R(P)\) is itself stable, and downward closure gives the equivalence. This argument needs neither metric axioms nor equivalence laws on \(\sim\). Those laws are needed only for the interpretations that invoke them.

The stable radius includes its supremum, but its open ball excludes points whose distance equals that radius. At \(R(P)=\infty\), it also excludes points at infinite distance. Confusing these two endpoints produces an erroneous nonattainment warning; the corrected theorem is machine checked.

Worked example: a pivot fails while the problem stays easy

Consider the rational-parameter family

\[ t x+y=1,\qquad x=1,\qquad t\in\mathbb Q. \]

Its coefficient matrix has determinant \(-1\) for every \(t\). There is no singular system at zero: the solution is always \(x=1,\ y=1-t\). Now declare a deliberately small certificate language with two recipes. Recipe \(S\), substitution, uses that solution directly and charges one subtraction. Recipe \(E\), elimination with the first coefficient as pivot, requires \(t\ne0\) and calculates

\[ m=1/t,\quad u=-m,\quad v=1-m,\quad y=v/u,\quad x=(1-y)/t. \]

It charges six unit-cost arithmetic operations: three divisions, one negation, and two subtractions. This is a symbolic arithmetic model with exact rational input and checked side conditions; bit lengths and side-condition checking costs are outside the displayed construction-cost coordinate. Both recipes produce the required solution wherever admitted. Their algebraic soundness is proved in Lean over the reals and therefore applies to rational inputs too.

In this certificate language,

\[ \operatorname{Proves}(S,P_t)\text{ always},\qquad \operatorname{Proves}(E,P_t)\Longleftrightarrow t\ne0, \qquad C(S)=1,\ C(E)=6. \]

Consequently \(\kappa(P_t)=1\) for every \(t\), and \(\Delta_\varepsilon(P_t)=0\) for every neighborhood radius. No claim about the optimal bit complexity of unrestricted equation solving is being made. The certificate class and charged operations are what make this exact minimum a well-defined calculation.

At budget one the available set is \(K_1(P_t)=\{S\}\) everywhere. At budget six it is

\[ K_6(P_t)= \begin{cases} \{S,E\},&t\ne0,\\ \{S\},&t=0. \end{cases} \]

Use ordinary parameter distance \(d(P_t,P_s)=\lvert t-s\rvert\) and equality of available sets. At budget one, the stability radius is infinite. At budget six, the radius at a nonzero \(t\) is \(\lvert t\rvert\): every smaller distance avoids zero, while any larger-radius ball contains it. The radius at zero is zero, since nonzero rationals lie arbitrarily close. In particular, the ball of radius \(\lvert t\rvert\) is stable even though the point on its boundary has a different available set.

The chosen elimination recipe fails at zero, and even the availability set changes there. Yet the cheap substitution method survives and optimal cost never changes. A zero mechanism-stability radius is therefore compatible with constant attainable certificate cost. It can reveal the loss of an optional, inefficient method rather than any increase in operational difficulty.

Worked example: a genuine feasibility boundary

Contrast the scalar task

\[ Q_t:\quad\text{find }x\text{ such that }tx=1. \]

Here a certificate is a supplied exact value \(x\), admitted when \(tx=1\). Charge one multiplication for the arithmetic part of checking it; supplying the witness and checking exact equality are outside this coordinate. This is a verification-cost encounter, distinct from the construction-cost encounter above. For \(t\ne0\), the witness \(x=1/t\) is admitted. For \(t=0\), no value is admitted. Hence

\[ \kappa(Q_t)= \begin{cases} 1,&t\ne0,\\ \infty,&t=0. \end{cases} \]

Under ordinary parameter distance, \(\Delta_0(Q_0)=0\), while \(\Delta_\varepsilon(Q_0)=\infty\) for every positive \(\varepsilon\): the neighborhood contains a nonzero parameter with finite cost. This is an actual change of feasibility, not merely the failure of a pivot choice. The costs and the infinite gap between zero and each nonzero parameter are machine checked. The density argument giving the stated neighborhood supremum is the elementary argument in this paragraph.

Both examples contain a division that fails at zero. In the first, the determinant remains nonzero and another admitted recipe works. In the second, the equation itself loses every solution. Looking only at the failed division would miss precisely the distinction the framework is meant to expose.

What a perturbation experiment can establish

A useful experiment records the admitted certificate class and budgets, tests which methods survive, and computes or bounds the attainable cost. It then asks whether the change follows from the problem's structure, the interface, or the chosen method's side conditions. Failed attempts are observations to explain, not universal quantifiers over all admitted proofs.

An anti-model construction starts from a specified solver or model and constructs an instance that defeats it. The form \(\forall M\,\exists P\,\operatorname{Fails}(M,P)\) does not supply a fixed \(P\) defeating every model; swapping those quantifiers would invent a much stronger obstruction. Nor does locating a short certificate measure the cost of discovering its representation. That requires a search protocol and an additional resource coordinate.

The chapter's diagnostic can therefore be stated without a new hierarchy of hardness: declare proximity, distinguish selected from available methods, measure attainable cost, and prove the transport or failure being claimed. These are concrete uses of the encounter audit, not additional definitions of what makes all mathematics hard.

Chapter 9What a noisy report can guarantee

Chapter 1 compared deterministic reports. A fine report refines a coarse one when the coarse report can be computed from it, and every action robust under the coarse report stays robust under the fine one. For noisy reports the classical comparison is Blackwell's: one experiment is more informative than another when the second is a garbling, a randomized post-processing, of the first. That comparison evaluates a report by the expected payoffs it supports for every prior and every decision problem.

This book asks a different question of an interface. A task either succeeds or fails, one policy is chosen before the world is known, and the policy must succeed with a declared probability in every admitted world. This chapter shows that this quantifier induces its own order on noisy reports. The order is coarser than Blackwell's, the tests needed to decide it are known exactly, and deciding it is nevertheless harder.

Guaranteed success for a noisy report

Let \(W\) be a finite set of worlds. A noisy report, or experiment, is a matrix \(K\) whose row \(w\) is the distribution of signals in world \(w\). A task with binary success is described by its actions, each identified with the set of worlds in which it succeeds; write \(\mathcal S\) for this family of sets. A policy chooses, possibly at random, an action for each signal. Its guarantee is its smallest success probability over the worlds, and the value of the task under \(K\) is the best guarantee:

\[ V_K(\mathcal S)=\max_{p}\ \min_{w\in W}\ \sum_{o}K(o\mid w) \sum_{A\in\mathcal S,\ w\in A}p(A\mid o). \]

The minimax theorem expresses the same number through a least favorable distribution over worlds:

\[ V_K(\mathcal S)=\min_{\pi}\ \sum_{o}\ \max_{A\in\mathcal S}\ \sum_{w\in A}\pi(w)K(o\mid w). \]

The distribution \(\pi\) is not a belief held by the solver. It is a certificate: every policy's guarantee is at most the right-hand side for every \(\pi\), so a policy and a distribution with equal values settle the value exactly. Such a pair is a blame certificate. The policy shows a guarantee the report permits. The distribution shows that no policy using the report can exceed it. A deployed policy that falls short of the value is at fault; the remaining gap belongs to the report.

Write \(K\succeq_{\mathrm{WCS}}L\) when \(V_K(\mathcal S)\ge V_L(\mathcal S)\) for every task \(\mathcal S\): every guarantee available under \(L\) is available under \(K\). Garbling is sufficient for this. If \(L\) is obtained by passing the signal of \(K\) through a random channel, then any policy for \(L\), composed with that channel, is a policy for \(K\) with the same success in every world. The converse is where the two orders part.

A more informative report can guarantee nothing more

Take two worlds and two reports:

\[ K=\begin{pmatrix}2/3&1/3\\1/3&2/3\end{pmatrix}, \qquad L=\begin{pmatrix}1&0\\1/2&1/2\end{pmatrix}. \]

On two worlds only one task can distinguish reports: identify the world. Every other task either fails in some world under every report or succeeds everywhere under every report. For identification, \(K\) guarantees \(2/3\) by naming the world its signal suggests. \(L\) also guarantees \(2/3\). On its second signal it names the second world. On its first signal it names the first world with probability \(2/3\) and the second otherwise, so the first world succeeds with probability \(2/3\) and the second with probability \(1/2\cdot1/3+1/2=2/3\). The distributions \((1/2,1/2)\) and \((1/3,2/3)\) show that neither report can do better. The two reports therefore permit exactly the same guarantees.

Yet \(L\) is not a garbling of \(K\), while \(K\) is a garbling of \(L\). In Blackwell's sense \(L\) is strictly more informative. At an even prior it identifies the world with probability \(3/4\) rather than \(2/3\). No guarantee registers the difference.

With three worlds the separation becomes strict. The reports

\[ K=\begin{pmatrix}1&0\\1/4&3/4\\0&1\end{pmatrix}, \qquad L=\begin{pmatrix}1/4&3/4\\1&0\\1&0\end{pmatrix} \]

are incomparable in Blackwell's sense, yet \(K\) guarantees at least as much as \(L\) for every task and strictly more for 28 of the 127 tasks on three worlds. The largest gap occurs when the actions are two overlapping pairs of worlds. \(K\) then succeeds surely, while no policy under \(L\) guarantees more than \(4/5\).

The cause is binary success, not the worst-case quantifier. If a task may have arbitrary world-dependent payoffs and is still judged by its worst world, dominance again requires a garbling. That part is known in substance from work on maxmin valuation of experiments. The success-or-failure restriction removes the freedom to shift payoffs world by world, and the classical argument depends on that freedom.

For the audit this matters directly. Chapter 1's deterministic preorder is correct as it stands: when either report is deterministic, the guarantee order coincides with Blackwell's, and for two deterministic reports both reduce to refinement of partitions. Extending that preorder to noisy sensors by Blackwell's order would be a mistake for tasks that must succeed in every world. An upgrade in Blackwell's sense can leave every guarantee unchanged, and a report that is not an upgrade can still guarantee more.

Worked example: paying for information that a guarantee cannot use

A robot must choose between two corridors, one of which is blocked. Two sensors are offered. The first names the blocked corridor correctly with probability \(2/3\) in both layouts. The second is always right when the left corridor is blocked, but when the right corridor is blocked it answers at random. These are the reports \(K\) and \(L\) of the two-world example, with the first world meaning that the left corridor is blocked.

The second sensor is more informative in Blackwell's sense. When the layouts are equally likely, it leads the robot to the open corridor with probability \(3/4\), against \(2/3\) for the first sensor. If the commission is expected throughput, the second sensor is the better purchase. If the commission is a guarantee that one policy reaches the open corridor with probability at least \(q\) in each layout, the sensors are equivalent. Both permit exactly the guarantees up to \(2/3\), and paying for the second buys nothing.

As in Chapter 6's competing service specifications, the arithmetic is not in dispute. The success condition decides which calculation answers the question.

Which tests a comparison needs

A comparison of reports quantifies over all tasks, and many tasks are redundant. An action contained in another action can be deleted without lowering any guarantee. A task whose actions miss some world guarantees nothing, and a task with an action that succeeds in every world guarantees everything. What remains are the tasks in normal form: families of proper subsets of the worlds, none inside another, that together cover every world.

For three worlds there are eight such tasks: identify the world; separate one world from the other two, in three ways; choose between two overlapping pairs, in three ways; and exclude one world, using all three pairs. None of the eight can be omitted. For each there are two reports that are ordered one way on the other seven tasks and the other way on it.

From four worlds on, some tests are redundant, and the redundancy has a simple form. Suppose the worlds split into two groups and every action is a pair of choices, one inside each group, succeeding when the choice in the true world's group is right. A courier who must name one address in each of two districts is in this position. Whatever the other choice, success in the northern district depends only on the northern choice. The best guarantee for the combined task is then the smaller of the guarantees for its two parts, so a product task carries no information beyond its factors. In geometric terms its success polytope is a product.

Products are the only redundant tests. For a task in normal form, call a set of worlds a minimal failure when no single action covers it but every smaller set is covered by some action. A task is a product exactly when its minimal failures split into two groups that share no world. Every task whose minimal failures are connected is indispensable: for each such task there are two reports that are ordered correctly on every other task and incorrectly on it. The smallest complete test family, the least number of tasks whose guarantees decide the comparison of every pair of reports, is therefore known exactly.

worldstasks in normal formproductssmallest complete family
3808
41133110
56893656828
6778506118707783191

The counts grow at the scale of the Dedekind numbers, which count the antichains of subsets of the worlds and grow far faster than any exponential.

The construction behind the theorem is instructive. One report of the pair adds signals that are harmless for the target task, and for every task that covers at least what it covers, but costly for every other task. The comparison then becomes a question about the target's minimal failures alone. When those failures are connected, a spanning tree through them supplies a report at which the target's guarantee can be moved while every smaller family of failures lags behind.

For benchmarks this gives the precise form of an insufficient test suite. A suite of binary-success tasks is complete for comparing interfaces under guarantees only if it contains every task that is not a product, up to the normalization above. A short suite can certify that one interface fails to dominate another. It cannot certify dominance in general.

Deciding the comparison is hard

Blackwell's order is decided by a linear feasibility problem: search for a channel that turns one report into the other. The guarantee order is coarser, so one might expect it to be easier. It is not. Deciding whether one explicit report guarantees at least as much as another is coNP-complete: it is as hard as any problem whose negative answers have short, efficiently checkable certificates. This remains true when every probability is a fraction whose numerator and denominator are bounded by a polynomial in the number of worlds.

A failure of dominance has a short certificate: one task, a policy for one report, and a least favorable distribution for the other, with a strict gap between the two values. This is again a blame certificate. Dominance itself has no certificate of polynomial size unless NP equals coNP.

The hardness construction uses reports whose signals reveal edges of a graph. Each signal is possible in two worlds, the endpoints of an edge. The two reports share all edge signals and differ in one signal attached to a chosen vertex. The value of a task then depends on which edges it leaves uncovered, through the densest part of the uncovered graph. The one differing signal makes the difference positive exactly when the uncovered edges contain a clique of a prescribed size through the chosen vertex, and finding such a clique is a standard hard search problem. An earlier reduction, from subset sums on a star of worlds, needs large numbers; the clique reduction does not.

Two consequences matter for the audit. Unless P equals NP, the question whether replacing one interface by another ever hurts a task that must succeed in every world has no efficient general answer, even when the replacement changes a single signal. And, again unless P equals NP, the worst loss from such a replacement cannot be approximated efficiently to within an additive error of order \(n^{-5}\), where \(n\) is the number of worlds. For a fixed and small number of worlds, by contrast, the finite test family above decides the comparison with a fixed number of linear programs.

Graded guarantees

A guarantee is itself a threshold. Say that \(K\) matches \(L\) at level \(t\) when every task that \(L\) permits with success probability \(t\) in every world is also permitted at \(t\) under \(K\). Below \(t=1/|W|\) every report matches every other, because randomizing over one covering action per world already guarantees \(1/|W|\) for every task that covers the worlds. At \(t=1\) only supports matter: \(K\) matches \(L\) exactly when every signal of \(K\) is possible only within the set of worlds of some single signal of \(L\).

Between these ends the levels are not nested. An explicit pair on three worlds matches at every level up to \(1/2\), fails between \(1/2\) and \(9/10\), and matches again above \(9/10\). The guarantee order is the intersection of all the levels, and no fixed finite set of levels suffices for every pair.

What this chapter establishes

The results of this chapter are mathematics of the project, not restatements of the audit. Their evidence differs and is recorded separately.

The literature search behind this chapter found no earlier characterization of this order, of its smallest complete test families, or of its complexity. That search did not include MathSciNet or zbMATH, so no priority is claimed. Proofs, certificates, and referee reports are kept in the repository under book/research/.

Chapter 10What is machine checked

A formal layer covers Chapter 9. The module WorstCaseSuccess checks the certificate inequality for guaranteed success, that garbling implies dominance, the support characterization of sure success, and the two- and three-world examples with their non-garbling proofs. The module WorstCaseSuccessExtended checks monotonicity under enlarged actions, the reduction of a product task to its factors, the loss formula for signals possible in two worlds, and the arithmetic core and one exact certificate of the subset-sum reduction. The general theorems of Chapter 9, that product tasks are the only redundant tests and that the comparison is coNP-complete, are proved in prose and checked by exact certificates and independent referees. They are not claimed as Lean results.

The parcel counterexample, marked-candidate discovery bound, overlapping-obstacle table, and average-versus-deadline example are prose arguments. No Lean verification is claimed for them. The success profile convention specializes the existing region-order construction; the adequacy of an application's success representation remains an obligation.

The primary Lean companion checks the algebraic core with the repository-pinned Lean 4.33.0-rc1 toolchain and the Mathlib revision recorded in lake-manifest.json. Independent Aristotle jobs use an isolated Lean and Mathlib 4.28.0 project. The results used by the argument are summarized here.

part of the argumentchecked resultscope
information refinementfactorization shrinks compatibility classes and enlarges robust action sets; a quotient can lose a decision-critical distinctiondeterministic factorization
noisy interfacesthe certificate inequality for guarantees; garbling implies dominance; sure success depends only on supports; two-world equivalence without garbling; the three-world gap with non-garbling; product tasks reduce to their factors; the loss formula for two-world signals; the key inequality and one certificate of the subset-sum reductionfinite experiments and the explicit examples of Chapter 9; its general theorems are proved in prose
feedback and reconstructionscalar accumulation, scalar Gaussian variance algebra, robust recurrence tubes, switching bounds, and residual marginsexternal information budgets and noise models
actionfinite-horizon reachability, barrier witnesses, and backed shortcutsshortcuts backed by admitted transitions
behaviorinterconnection, hiding, safety, raw function gluing, an admissibility counterexample, and coordinate invariancedeclared trajectory spaces and interfaces
abstractionforward simulation, local step lifting, and goal reflection imply exact finite-path transferfinite reachability
finite memoryexact tracking needs enough separated states; one-pass final-output reproduction yields \(b^n\le r^k\)one-pass delayed output
resourcesfinite-envelope optima, monotonicity, and explicit external gapsfinite admitted envelopes
fibred orderattainable-region preorders, preimage reindexing, encounter transport, and failures of reflectioncontext maps after semantic alignment has been supplied
benchmark and proof-model stabilityselector-support bounds; extended proof-cost and variation laws; stability at the supremum radius; budget monotonicity and sound transport of available mechanismsfinite benchmarks and declared certificate, cost, proximity, and kind data
calculated examplesdeployment losses and exact robust regions; calibration preimage and strict inclusion; sound algebraic recipes, constant pivot cost, and the singular task's infinite cost gapthe explicit models in Chapters 5, 7, and 8

Decision-bearing benchmark support

For benchmark comparisons, one useful diagnostic is decision-bearing support. Let \(B\) be a nonempty finite benchmark, let \(A\) be its finite candidate type, and let \(Y_i(a)\) be the measured outcome of candidate \(a\). Define

\[ D=\{i\in B:\exists a,b\in A,\ Y_i(a)\ne Y_i(b)\}, \qquad \rho_{\mathrm{dec}}=\frac{|D|}{|B|}. \]

For any two selectors \(s,t\), every instance on which \(Y_i(s(i))\ne Y_i(t(i))\) lies in \(D\). Consequently the fraction of benchmark instances on which their measured outcomes differ is at most \(\rho_{\mathrm{dec}}\). This cardinality theorem does not bound an arbitrary weighted or unbounded evaluation metric. It says exactly that non-decision-bearing instances cannot distinguish two selectors by their measured candidate outcomes. A benchmark can therefore contain many labeled examples while containing few actual selection decisions. Any empirical estimate of \(\rho_{\mathrm{dec}}\) still owes its dataset, sampling rule, candidate construction, outcome protocol, and analysis code; kernel verification supplies none of those things.

What the new calculations add

ModelStability.lean proves that disagreements between selectors' measured outcomes occur only on decision-bearing benchmark instances. This is a finite, unweighted cardinality bound. The same module gives total extended proof costs, the gap and local-variation laws, stability at the supremum radius, budget monotonicity for available mechanisms, and their sound proof transport. Its label counterexample separates selected methods from available methods.

WorkedExamples.lean checks the forecast losses, the optimal robust loss of \(1/3\), both displayed deployment regions, the simulator preimage and its strict excess over the hardware region, the soundness of the two pivot recipes, their costs and availability conditions, and the singular equation's costs and infinite gap. It also checks a safety counterexample: a behavior containing all generated safe-start runs may contain other unsafe runs. That is why Chapter 4's equivalence uses exactly the generated behavior.

The available-set radius calculations for rational parameters and the density argument for the singular family's neighborhood supremum are proved in the prose, not separately encoded in this module. The elementary forecast example is formalized; a general theory of reactive strategies or performative learning is not. The structural signatures, coherent claim translations, and individuation hierarchy of Chapter 6 likewise remain mathematical prose.

All these results are imported by LeanTest/HardProblems.lean. The algebra checks the consequences of the stated models. It does not establish the robot's calibration empirically, justify a certificate cost as a model of human discovery, or prove the metaphysical attribution of a ground. Those are the specific remaining modeling obligations, rather than missing algebraic steps.

Six historical explorations survive only as collapsed Lean source disclosures in the formal companion, marked peripheral: the Grothendieck total category, closure operators, discrete and graded Stokes, group completion, and a twist obstruction. None of them is used by the main argument.

NotesNotes and sources

The book uses claim-level links where a named theorem or established framework enters the argument. The bibliography is selective rather than exhaustive, but it now distinguishes foundations, neighboring frameworks, and the manuscript's own elementary deductions.

The information chapter draws on Shannon's mutual information and rate-distortion theory, Blackwell's comparison of experiments, and Massey's directed information. The displayed feedback inequality is a chain-rule and data-processing consequence under the manuscript's explicit random-tape and policy assumptions; it is not quoted as a separate theorem from those papers.

Chapter 9 compares experiments in the tradition of Blackwell and of Torgersen's comparison of statistical experiments, under a different quantifier. That arbitrary payoffs restore Blackwell's order is known in substance from the maxmin literature, for instance Çelen and Li and Zhou. The guarantee order is also incomparable with Rosenthal's prior-free order and with the linear-Blackwell order, the second separation using an example of Bertschinger and Rauh. The hardness reductions use SUBSET-SUM and CLIQUE from Karp's list and the densest-subgraph linear program of Charikar. The chapter's theorems are the project's own; proofs, exact certificates, and independent referee reports are in the repository under book/research/.

The control chapter uses Kalman's linear rank test and the Hermann-Krener local weak-observability condition. The robust scalar recurrence and the \(2\rho\) residual-separation bounds are proved directly in the text. Their interpretation is situated against switched-system and model-based fault-diagnosis literature.

The behavioral and abstraction chapters use Willems's trajectory-based system view, simulation proof methods, viability theory, abstract interpretation in the sense of Cousot and Cousot (1977), state abstraction in the sense of Li, Walsh, and Littman (2006), and a minimal sheaf-gluing observation. Exact finite-path lifting in the manuscript is an elementary theorem under stronger hypotheses than most approximate, probabilistic, or temporal-logic abstraction results.

Chapter 6 distinguishes the task situation, its encounter specification, and its performance representation. It defends objective constraints relative to specified ends while presenting their interpretation as dispositions as a metaphysical conjecture. Mumford and Vetter motivate that interpretation; their theories are not consequences of the attainable-region construction. Fine motivates the distinction between grounding and entailment. The overlapping-obstacle example explains why a null intervention can conceal a restriction's conditional contribution without identifying intervention with metaphysical ground. The disputed service specification separates empirical questions from choices about ends and acceptable consequences.

The book also distinguishes certificate cost from discovery through a deterministic marked-candidate query model. The lower bound follows from an adversary answering no until the final candidate, together with the requirement of an affirmative response as the certificate. No claim about unrestricted mathematical creativity follows. These examples and the philosophical argument are given in prose. The signature and claim-translation framework is likewise prose; the earlier Lean results remain separately identified in Chapter 10.

Chapter 7 connects deployment feedback to performative prediction and adaptive comparison to policy regret. Its two-law calculation is an original elementary illustration, not an empirical model or a claim of priority for those frameworks. Chapter 8's algebraic families similarly test distinctions in the certificate model; they do not establish a new complexity lower bound.

Throughout, the book separates established ingredients from the proposal. Pareto regions, co-design, resource preorders, reducibility degrees, indexed posets, and fibrations are established theories. The manuscript proposes an encounter audit in which the fibred order implements attainable-region comparison, licensed transport, and the search for stable claims. It does not claim mathematical priority for the component constructions. Nor does it infer semantic encounter alignment from a performance map.

Appendix. Glossary

These definitions are local to Why Problems Are Hard.

Abstraction
A generally many-to-one map from a concrete domain to a simpler domain, chosen to preserve specified answers. Executable return requires step lifting and goal reflection.
Action boundary
The primitive transformations, constraints, and policy permissions through which states can change. Adding an actuator changes this boundary.
Anti-model construction
A problem generated from a declared solver or model class so as to defeat it. The quantifier order, every model admitting some defeating problem, distinguishes it from a fixed exceptional target.
Attainable region
An upward-closed set of resource and loss bounds achieved under a specified encounter. The full region includes every admitted realization; the successful region includes only realizations satisfying the fixed success condition. Task difficulty uses successful regions; a full-region comparison must retain the relevant success criterion before supporting a task-feasibility judgment.
Available mechanisms
The kinds of admitted certificates that fit a specified budget. Unlike a selected proof label, this set records every available method in the declared certificate class.
Barrier depth
The least, over admissible paths, of the greatest drop below the starting objective value. It is \(+\infty\) when no path exists.
Behavioral system
A time domain, signal space, and set of admitted trajectories. Interconnection enforces shared constraints; hiding removes selected signals.
Blame certificate
A policy and a least favorable distribution over worlds with equal values for one task and one report. The policy shows a guarantee the report permits; the distribution shows that no policy using the report can exceed it. A deployed policy below that value is at fault, and the remaining gap belongs to the report.
Claim-relative equivalence
Coherent translations in both directions preserve and reflect all propositions in the declared encounter-indexed claim languages, with round trips semantically equivalent to identity. Opposing directed transports alone do not establish it.
Comparison class
A declared collection of licensed encounter transformations across which a claim is intended to remain stable. Its independently justified relevance and breadth determine the demonstrated scope of an invariant. Empirical warrant requires separate evidence.
Complete test family
A family of tasks whose guarantees decide the comparison of every pair of reports. For guaranteed success the smallest complete family consists of the tasks in normal form that are not product tasks.
Contraction margin
For \(e_{t+1}\le(q_0+\mu)e_t+d\), the gap \(1-q_0-\mu\) that supports the geometric error certificate.
Coordinate change
An invertible relabeling transporting every structure named in a claim. Exact conjugacy preserves runs and reachability.
Data-processing inequality
Post-processing available data cannot increase its mutual information with an unknown.
Decision-bearing support
On a nonempty finite benchmark with a fixed finite candidate type, the fraction of instances at which some two candidate outcomes differ. It bounds the fraction of instances on which two selectors' measured outcomes can differ, not arbitrary evaluation metrics.
Detectability
Decay of state ambiguity left unresolved by the admitted output history. Practical and robust versions allow specified residual tubes.
Directed claim transport
A licensed one-way claim translation preserving selected inferences or successful realizations without requiring reflection or an inverse. Identity transports and coherent composition make such witnesses composable across encounter chains.
Discovery cost
The cost of a specified search or learning procedure obtaining a usable method or certificate from its declared initial information. It includes acquisition rather than merely use of a supplied artifact, with instance and environment quantifiers fixed in advance.
Distortion
A declared reconstruction loss \(d(x,\widehat x)\), often averaged under a source distribution.
Encounter
A specification of a task situation through its object, success, environment, information, actions, programs, and performance. The specification represents the situation; it is not itself a physical bearer of powers. Relevant equivalence depends on declared preservation.
Encounter alignment
A justification relating the tasks, success conditions, admissible worlds, interfaces, and resource conventions of two contexts. A performance-coordinate map is only one component and cannot establish semantic comparability by itself.
Endogenous law
A transition rule that is itself part of the state and can be changed by admitted actions, so that an action alters the semantics of later actions.
Error tube
A certified set containing estimation error under stated disturbance and mismatch bounds.
Experiment class
The passive and active procedures quantified over when comparing states or models.
Extended cost gap
For extended nonnegative costs, the supremum of the two truncated differences. It is symmetric, separates unequal costs, and assigns zero rather than an undefined expression to infinity versus infinity.
Extension
Addition of a sensor, actuator, predicate, state coordinate, oracle, axiom, primitive, or resource that changes the admitted realization structure. An embedding of the old encounter does not make the extension a presentation equivalence.
Fault tolerance
Accommodation retains a guarantee, detection separates fault from healthy uncertainty, and isolation distinguishes candidate faults.
Feedback capacity
A bound on task-relevant information entering through one feedback round under a specified policy and channel model.
Fibred order
Context-specific performance-region posets reindexed by preimage after encounter alignment has licensed the comparison. Ambient specifications transport through a performance map; realized classes additionally require preimage closure or encounter transport.
Forward simulation
A map sending each concrete step to a valid abstract step and therefore each concrete path to an abstract path.
Guarantee order
The comparison of noisy reports in which one report is at least as good as another when every task with binary success can be guaranteed at least as well in every world. It is coarser than Blackwell's garbling order, coincides with it when either report is deterministic, and is coNP-complete to decide.
Hardness ground
A fact about the problem-object, environment, interfaces, admitted realizations, resources, or their relations that helps explain an encounter's modal resistance. Grounds are not identical to the hardness they ground.
Information boundary
The observations, experiment class, prior state, and channel restrictions governing which distinctions enter a representation.
Invariant claim
An equality, order, bound, feasibility judgment, safety property, or other assertion proved stable over a declared comparison class. Stability may be exact or only directional.
Local step lifting
Realization of every offered abstract step from the concrete state actually reached. It lifts finite paths by induction.
Local variation
The supremum of the extended cost gap over a declared directed neighborhood of a target problem. It is relative to the chosen cost profile, proximity map, and radius.
Machine model
A specification of operations, input access, memory, randomness, and output timing used to state a complexity bound.
Mechanism stability
Persistence of a specified mechanism summary over a neighborhood. A summary may record a selected label or all budget-feasible kinds; these answer different questions. With the strict-ball definition, the supremum stable radius is itself stable. Availability can change while optimal cost stays constant.
Modal base
The realization class over which possibility, necessity, feasibility, or a lower bound is quantified. This book primarily uses encounter-relative admissibility; physical or metaphysical readings require additional justification.
Modal resistance
A proposed disposition of the represented task situation constraining success. The operational theory records its candidate counterfactual profile without establishing an irreducible disposition or treating every abstract impossibility as a causal power.
Model mismatch
Difference between the actual transition or observation law and the law used by an estimator.
Observability codistribution
The span of differentials of outputs and their admissible iterated Lie derivatives. Full rank gives the Hermann-Krener local sufficient condition.
Observational equivalence
Equality of all admitted finite observation laws from two states or models.
Operational difficulty
Comparison of successful attainable regions under a fixed task and resource convention. Full performance regions may support graded comparisons but cannot determine unrecorded semantic success. The relation is generally partial and its application requires justified encounter representations.
Operative representation
A causal state carrying selected consequences of past interaction into later inference or action.
Overlapping obstacles
Restrictions that separately obstruct success in appropriate contrasts and can conceal one another's effects. Removing one without changing the outcome does not establish its irrelevance.
Presentation equivalence
Isomorphism of two encounters' reducts to a fixed structural signature. Its witnesses have identity, inverse, and composition laws; they preserve only the structures retained by the signature.
Product task
A task whose worlds split into two groups so that each action is a pair of choices, one within each group. Its best guarantee is the smaller of the guarantees for its two parts, so it is redundant in every comparison of reports.
Proof cost
The infimum extended-nonnegative cost of the admitted proofs of a target. An empty admitted-proof type has cost infinity. The definition begins after the proof language and cost model have been chosen.
Rate-distortion function
The infimum mutual information required by a reconstruction channel to attain a declared expected distortion.
Reachability
Membership in the closure generated by finite admissible steps from a starting state.
Robust action
One action acceptable for every state in an observation equivalence class; equivalently, a member of the intersection of their acceptable-action sets.
Signature reduct
The encounter structure \(E|_\Sigma\) obtained by retaining exactly the components, operations, relations, and laws named by the structural signature \(\Sigma\).
State capacity
The number of internal configurations available to a finite machine, converted to bits by a logarithm.
Strategic opacity
Indistinguishability, under the learning interaction, of environment strategies that require different behavior under a relevant deployment interaction.
Structural hardness ground
A hardness ground located principally in a property of the problem-object, such as topology, graph width, dependency structure, or proof-theoretic strength. It requires encounter conditions to yield a hardness fact.
Structural signature
An independently declared selection of encounter components, operations, relations, and laws. It determines the reduct whose isomorphisms witness presentation equivalence and therefore the relevant standard of structural sameness.
Structurally grounded disposition
A proposed explanation of modal constraints in terms of object structure and encounter conditions. A stable bound establishes its declared scope; locating the ground additionally requires an argument connecting the structure to that bound.
Successful profile
The performance image of the successful admissible realizations. Its emptiness records impossibility under the modal base; its frontier records the costs and tradeoffs conditional on success.
Task situation
A system or mathematical object considered in relation to an end and conditions of access and action. An encounter specification represents this situation, and a performance region represents selected aspects of the specification.
Task-relevant information
Information that reduces uncertainty under the loss or decision being studied.

ReferencesSelected references

CompanionFormal companion

The self-contained Lean source is under LeanTest/HardProblems/, with LeanTest/HardProblems.lean as the import root. The repository pins Lean 4.33.0-rc1 and records the exact Mathlib revision in lake-manifest.json. Fetch that cache with lake exe cache get, then check the complete development with lake build.

The independent prover workspace under aristotle/ pins Lean and Mathlib 4.28.0. Install the optional CLI with uv tool install aristotlelib; a job can then be submitted with aristotle submit and --project-dir aristotle. No API credential is stored in this book or its generated HTML.

The HTML page presents the eight established proof groups used by the earlier argument first and labels six additional explorations as peripheral. All fourteen historical groups are included in full as collapsible Lean source. The HTML page retains the complete LeanTest/HardProblems/ModelStability.lean and LeanTest/HardProblems/WorkedExamples.lean modules and adds LeanTest/HardProblems/WorstCaseSuccess.lean and LeanTest/HardProblems/WorstCaseSuccessExtended.lean, all imported by the root. The book, glossary, and these eighteen source disclosures travel in one HTML file. Equation typesetting loads MathJax from a CDN; compiling the Lean development requires the pinned dependencies.

Collapsed Lean source

The proof groups used by the machine-checked chapter appear first. Groups marked peripheral are retained as formal experiments outside the narrative. Every declaration below is included in full.

deterministic information preorder, budgets, and scalar reconstruction (FeedbackBounds.lean, InformationBudget.lean, InformationOrder.lean, SystemsTheory.lean)run run run run

HardProblems.InformationOrder.Indist, HardProblems.InformationOrder.indist_equivalence, HardProblems.InformationOrder.ExperimentRefines, HardProblems.InformationOrder.experimentRefines_refl, HardProblems.InformationOrder.experimentRefines_trans, HardProblems.InformationOrder.ExperimentRefines.indist, HardProblems.InformationOrder.RobustActions, HardProblems.InformationOrder.ExperimentRefines.robustActions_mono, HardProblems.InformationOrder.indist_iff_of_mutual_refinement, HardProblems.InformationOrder.robustActions_eq_of_mutual_refinement, HardProblems.InformationOrder.quotient_strict_decision_loss, HardProblems.statistic_based_rule_fails', HardProblems.InformationBudget.accumulated_le_initial_add_rounds_mul, HardProblems.InformationBudget.required_excess_le_rounds_mul, HardProblems.InformationBudget.required_excess_div_capacity_le_rounds, HardProblems.InformationBudget.required_rounds_ceiling_le, HardProblems.ScalarGaussian.posteriorVariance, HardProblems.ScalarGaussian.posteriorVariance_pos, HardProblems.ScalarGaussian.target_accuracy_requires_observations, HardProblems.ScalarGaussian.target_accuracy_nontrivial_bound

-- LeanTest/HardProblems/InformationOrder.lean
/-- States are indistinguishable under an observation map when they produce
the same report. -/
def Indist {S : Type u} {O : Type v} (observe : S → O) (x y : S) : Prop :=
  observe x = observe y

-- LeanTest/HardProblems/InformationOrder.lean
/-- Equality of reports induces an equivalence relation on states. -/
theorem indist_equivalence {S : Type u} {O : Type v} (observe : S → O) :
    Equivalence (Indist observe) where
  refl _ := rfl
  symm h := h.symm
  trans hxy hyz := hxy.trans hyz

-- LeanTest/HardProblems/InformationOrder.lean
/-- `fine` refines `coarse` when the coarse report is obtained by deterministic
post-processing of the fine report. This orients the existing
`HardProblems.FactorsThrough` relation as an information preorder; it does not
introduce a second notion of factorization. -/
def ExperimentRefines {S : Type u} {F : Type v} {C : Type w}
    (fine : S → F) (coarse : S → C) : Prop :=
  FactorsThrough coarse fine

-- LeanTest/HardProblems/InformationOrder.lean
/-- Every experiment refines itself. -/
theorem experimentRefines_refl {S : Type u} {O : Type v}
    (observe : S → O) : ExperimentRefines observe observe := by
  exact ⟨id, by funext x; rfl⟩

-- LeanTest/HardProblems/InformationOrder.lean
/-- Deterministic experiment refinement is transitive. -/
theorem experimentRefines_trans {S : Type u} {A : Type v} {B : Type w}
    {C : Type z} {first : S → A} {second : S → B} {third : S → C}
    (h₁ : ExperimentRefines first second)
    (h₂ : ExperimentRefines second third) :
    ExperimentRefines first third := by
  rcases h₁ with ⟨post₁, rfl⟩
  rcases h₂ with ⟨post₂, rfl⟩
  exact ⟨post₂ ∘ post₁, by funext x; rfl⟩

-- LeanTest/HardProblems/InformationOrder.lean
/-- Refinement reverses inclusion of indistinguishability classes: equality of
fine reports forces equality of coarse reports. -/
theorem ExperimentRefines.indist {S : Type u} {F : Type v} {C : Type w}
    {fine : S → F} {coarse : S → C}
    (h : ExperimentRefines fine coarse) {x y : S}
    (hxy : Indist fine x y) : Indist coarse x y := by
  exact (show FactorsThrough coarse fine from h).eq_of_eq hxy

-- LeanTest/HardProblems/InformationOrder.lean
/-- Actions acceptable at every state compatible with the current report.
The acceptable-action predicate is part of the task, rather than part of the
observation alone. -/
def RobustActions {S : Type u} {O : Type v} {A : Type w}
    (observe : S → O) (Acceptable : S → A → Prop) (x : S) : Set A :=
  {a | ∀ y, Indist observe x y → Acceptable y a}

-- LeanTest/HardProblems/InformationOrder.lean
/-- A finer experiment weakly enlarges the set of robust acceptable actions.
The result is task-relevant but deterministic: it compares compatibility
classes, not probabilities or average information. -/
theorem ExperimentRefines.robustActions_mono
    {S : Type u} {F : Type v} {C : Type w} {A : Type z}
    {fine : S → F} {coarse : S → C}
    (h : ExperimentRefines fine coarse) (Acceptable : S → A → Prop) (x : S) :
    RobustActions coarse Acceptable x ⊆ RobustActions fine Acceptable x := by
  intro a ha y hxy
  exact ha y (h.indist hxy)

-- LeanTest/HardProblems/InformationOrder.lean
/-- Mutual deterministic factorization gives exactly the same induced
indistinguishability relation. The report types and report values themselves
need not be equal. -/
theorem indist_iff_of_mutual_refinement
    {S : Type u} {O₁ : Type v} {O₂ : Type w}
    {first : S → O₁} {second : S → O₂}
    (h₁₂ : ExperimentRefines first second)
    (h₂₁ : ExperimentRefines second first) (x y : S) :
    Indist first x y ↔ Indist second x y :=
  ⟨h₁₂.indist, h₂₁.indist⟩

-- LeanTest/HardProblems/InformationOrder.lean
/-- Mutual deterministic factorization preserves every robust action set for
every task predicate. -/
theorem robustActions_eq_of_mutual_refinement
    {S : Type u} {O₁ : Type v} {O₂ : Type w} {A : Type z}
    {first : S → O₁} {second : S → O₂}
    (h₁₂ : ExperimentRefines first second)
    (h₂₁ : ExperimentRefines second first)
    (Acceptable : S → A → Prop) (x : S) :
    RobustActions first Acceptable x = RobustActions second Acceptable x := by
  apply Set.Subset.antisymm
  · exact h₂₁.robustActions_mono Acceptable x
  · exact h₁₂.robustActions_mono Acceptable x

-- LeanTest/HardProblems/InformationOrder.lean
/-- A strict finite decision loss. The identity experiment separates the two
Bool states, while the quotient to `Unit` merges them. An action is acceptable
exactly when it names the true state. At state `false`, the fine report permits
the robust action `false`; the coarse report permits no robust action. -/
theorem quotient_strict_decision_loss :
    let fine : Bool → Bool := id
    let coarse : Bool → Unit := fun _ ↦ ()
    let Acceptable : Bool → Bool → Prop := fun state action ↦ state = action
    ExperimentRefines fine coarse ∧
      ¬ Indist fine false true ∧ Indist coarse false true ∧
      RobustActions coarse Acceptable false = ∅ ∧
      RobustActions fine Acceptable false = {false} ∧
      RobustActions coarse Acceptable false ⊂
        RobustActions fine Acceptable false := by
  dsimp
  refine ⟨⟨fun _ ↦ (), rfl⟩, by simp [Indist], by simp [Indist], ?_⟩
  have hCoarse : RobustActions (fun _ : Bool ↦ ())
      (fun state action : Bool ↦ state = action) false = ∅ := by
    ext action
    constructor
    · intro ha
      have hFalse := ha false (by rfl)
      have hTrue := ha true (by rfl)
      simp only [Set.mem_empty_iff_false]
      cases action <;> simp_all
    · simp
  have hFine : RobustActions id
      (fun state action : Bool ↦ state = action) false = {false} := by
    ext action
    simp [RobustActions, Indist]
  refine ⟨hCoarse, hFine, ?_⟩
  rw [hCoarse, hFine]
  exact Set.empty_ssubset.mpr (Set.singleton_nonempty false)

-- LeanTest/HardProblems/SystemsTheory.lean
/-- The statistic-factorization obstruction with an arbitrary statistic
codomain; nothing in the argument uses the real numbers. -/
theorem statistic_based_rule_fails' {Y : Type*} {m : S → Y} (Astar : S → Set A)
    {s s' : S} (hm : m s = m s') (hdisj : Disjoint (Astar s) (Astar s'))
    (α : Y → A) :
    α (m s) ∉ Astar s ∨ α (m s') ∉ Astar s' := by
  by_contra hc
  push Not at hc
  obtain ⟨h1, h2⟩ := hc
  rw [hm] at h1
  exact Set.disjoint_left.mp hdisj h1 h2

-- LeanTest/HardProblems/InformationBudget.lean
/-- An accumulated real-valued quantity with initial upper bound `I₀` and
one-round increment bounded above by `C` is at most `I₀ + n * C` after `n`
rounds.

No nonnegativity hypothesis is needed for this arithmetic statement.  An
information-theoretic application must separately establish that its chosen
quantities and bounds have the intended meaning. -/
theorem accumulated_le_initial_add_rounds_mul
    (accumulated : ℕ → ℝ) (I₀ C : ℝ)
    (hinitial : accumulated 0 ≤ I₀)
    (hstep : ∀ n, accumulated (n + 1) ≤ accumulated n + C) :
    ∀ n, accumulated n ≤ I₀ + (n : ℝ) * C := by
  intro n
  induction n with
  | zero => simpa using hinitial
  | succ n ih =>
      calc
        accumulated (n + 1) ≤ accumulated n + C := hstep n
        _ ≤ (I₀ + (n : ℝ) * C) + C := add_le_add_left ih C
        _ = I₀ + ((n + 1 : ℕ) : ℝ) * C := by
          push_cast
          ring

-- LeanTest/HardProblems/InformationBudget.lean
/-- If reaching the target requires at least `R` units of the accumulated
quantity, and the target has been reached at round `n`, then the required
amount above the initial budget is no larger than `n * C`.

This conclusion is conditional on `hrequired`: the lemma does not prove that a
distortion level really requires `R`, nor that the accumulated scalar is
mutual information. -/
theorem required_excess_le_rounds_mul
    (accumulated : ℕ → ℝ) (I₀ C R : ℝ) (n : ℕ)
    (hinitial : accumulated 0 ≤ I₀)
    (hstep : ∀ k, accumulated (k + 1) ≤ accumulated k + C)
    (hrequired : R ≤ accumulated n) :
    R - I₀ ≤ (n : ℝ) * C := by
  have hbudget :=
    accumulated_le_initial_add_rounds_mul accumulated I₀ C hinitial hstep n
  linarith

-- LeanTest/HardProblems/InformationBudget.lean
/-- With positive per-round capacity, the real-valued required excess divided
by that capacity is a lower bound on the number of rounds.

This is only division of the preceding scalar inequality.  In particular, it
does not identify `R` with a rate-distortion function or `C` with Shannon
capacity. -/
theorem required_excess_div_capacity_le_rounds
    (accumulated : ℕ → ℝ) (I₀ C R : ℝ) (n : ℕ)
    (hinitial : accumulated 0 ≤ I₀)
    (hstep : ∀ k, accumulated (k + 1) ≤ accumulated k + C)
    (hrequired : R ≤ accumulated n) (hC : 0 < C) :
    (R - I₀) / C ≤ (n : ℝ) := by
  apply (div_le_iff₀ hC).2
  exact required_excess_le_rounds_mul accumulated I₀ C R n
    hinitial hstep hrequired

-- LeanTest/HardProblems/InformationBudget.lean
/-- Since rounds are natural numbers, the natural ceiling of the real-valued
ratio is also a lower bound on the round count.

If `R ≤ I₀`, the ratio may be nonpositive and the ceiling is zero; the theorem
then correctly gives only the vacuous lower bound `0 ≤ n`. -/
theorem required_rounds_ceiling_le
    (accumulated : ℕ → ℝ) (I₀ C R : ℝ) (n : ℕ)
    (hinitial : accumulated 0 ≤ I₀)
    (hstep : ∀ k, accumulated (k + 1) ≤ accumulated k + C)
    (hrequired : R ≤ accumulated n) (hC : 0 < C) :
    Nat.ceil ((R - I₀) / C) ≤ n := by
  apply Nat.ceil_le.mpr
  exact required_excess_div_capacity_le_rounds accumulated I₀ C R n
    hinitial hstep hrequired hC

-- LeanTest/HardProblems/FeedbackBounds.lean
/-- Algebraic posterior variance for a scalar Gaussian prior of variance `P₀`
after `n` independent measurements with noise variance `R`.

This definition packages the standard conjugate-Gaussian calculation. It does
not itself prove that a physical measurement process is Gaussian, independent,
or correctly modeled. -/
noncomputable def posteriorVariance (P₀ R : ℝ) (n : ℕ) : ℝ :=
  1 / (1 / P₀ + (n : ℝ) / R)

-- LeanTest/HardProblems/FeedbackBounds.lean
/-- Positive prior and measurement variances give positive posterior variance. -/
theorem posteriorVariance_pos {P₀ R : ℝ} (hP₀ : 0 < P₀) (hR : 0 < R)
    (n : ℕ) : 0 < posteriorVariance P₀ R n := by
  unfold posteriorVariance
  positivity

-- LeanTest/HardProblems/FeedbackBounds.lean
/-- Reaching target variance `D` under the scalar posterior formula requires
at least `R * (1 / D - 1 / P₀)` measurements. The right side is real-valued;
an integer ceiling would be needed for a sharp natural-number statement.

This is an algebraic consequence of the displayed variance formula. It is not
a general Kalman-filter theorem and says nothing about model mismatch, process
noise, correlated measurements, or unobservable state directions. -/
theorem target_accuracy_requires_observations {P₀ R D : ℝ} {n : ℕ}
    (hP₀ : 0 < P₀) (hR : 0 < R) (hD : 0 < D)
    (hacc : posteriorVariance P₀ R n ≤ D) :
    R * (1 / D - 1 / P₀) ≤ (n : ℝ) := by
  have hden : 0 < 1 / P₀ + (n : ℝ) / R := by positivity
  have hcross : 1 ≤ D * (1 / P₀ + (n : ℝ) / R) := by
    exact (div_le_iff₀ hden).mp hacc
  have hprecision : 1 / D ≤ 1 / P₀ + (n : ℝ) / R := by
    apply (div_le_iff₀ hD).2
    nlinarith
  have hremaining : 1 / D - 1 / P₀ ≤ (n : ℝ) / R := by
    linarith
  simpa [mul_comm] using (le_div_iff₀ hR).mp hremaining

-- LeanTest/HardProblems/FeedbackBounds.lean
/-- If the target variance is strictly smaller than the prior variance, the
observation-count lower bound above is strictly positive rather than vacuous. -/
theorem target_accuracy_nontrivial_bound {P₀ R D : ℝ} {n : ℕ}
    (hP₀ : 0 < P₀) (hR : 0 < R) (hD : 0 < D) (hDlt : D < P₀)
    (hacc : posteriorVariance P₀ R n ≤ D) :
    0 < R * (1 / D - 1 / P₀) ∧
      R * (1 / D - 1 / P₀) ≤ (n : ℝ) := by
  constructor
  · exact mul_pos hR (sub_pos.mpr (one_div_lt_one_div_of_lt hD hDlt))
  · exact target_accuracy_requires_observations hP₀ hR hD hacc
robust recurrence, switching, and fault margins (FaultMargins.lean, FeedbackBounds.lean)run run

HardProblems.RobustFeedback.error_le_geometric_sum, HardProblems.RobustFeedback.error_le_tube_transient, HardProblems.RobustFeedback.error_le_tube, HardProblems.RobustFeedback.mismatch_le_margin_and_error_bound, HardProblems.FaultMargins.Alarm, HardProblems.FaultMargins.healthy_residual_not_alarm, HardProblems.FaultMargins.alarm_of_fault_norm_gt_threshold_add_radius, HardProblems.FaultMargins.alarm_of_fault_norm_gt_two_mul_radius, HardProblems.FaultMargins.faulted_residual_mem_closedBall, HardProblems.FaultMargins.closedBall_disjoint_of_norm_sub_gt_two_mul_radius, HardProblems.UniformSwitching.error_le_uniform_geometric_sum, HardProblems.UniformSwitching.error_le_uniform_tube_transient

-- LeanTest/HardProblems/FeedbackBounds.lean
/-- Iterating a scalar robust contraction gives a geometric finite-time bound.
The error need not be generated by any particular observer, but nonnegativity
of `q` is needed to propagate the upper inequality. -/
theorem error_le_geometric_sum (e : ℕ → ℝ) (q d : ℝ)
    (hq : 0 ≤ q) (hstep : ∀ n, e (n + 1) ≤ q * e n + d) (n : ℕ) :
    e n ≤ q ^ n * e 0 + d * ∑ k ∈ Finset.range n, q ^ k := by
  induction n with
  | zero => simp
  | succ n ih =>
      calc
        e (n + 1) ≤ q * e n + d := hstep n
        _ ≤ q * (q ^ n * e 0 + d * ∑ k ∈ Finset.range n, q ^ k) + d :=
          add_le_add (mul_le_mul_of_nonneg_left ih hq) le_rfl
        _ = q ^ (n + 1) * e 0 + d * ∑ k ∈ Finset.range (n + 1), q ^ k := by
          rw [geom_sum_succ]
          ring

-- LeanTest/HardProblems/FeedbackBounds.lean
/-- With a strict contraction, the geometric sum can be written using the
disturbance tube `d / (1 - q)`. This is a finite-time statement, not an
asymptotic optimality claim. -/
theorem error_le_tube_transient (e : ℕ → ℝ) (q d : ℝ)
    (hq0 : 0 ≤ q) (hq1 : q < 1)
    (hstep : ∀ n, e (n + 1) ≤ q * e n + d) (n : ℕ) :
    e n ≤ q ^ n * (e 0 - d / (1 - q)) + d / (1 - q) := by
  have hqne : q ≠ 1 := ne_of_lt hq1
  have hbound := error_le_geometric_sum e q d hq0 hstep n
  rw [geom_sum_eq hqne n] at hbound
  calc
    e n ≤ q ^ n * e 0 + d * ((q ^ n - 1) / (q - 1)) := hbound
    _ = q ^ n * (e 0 - d / (1 - q)) + d / (1 - q) := by
      field_simp [sub_ne_zero.mpr hqne, sub_ne_zero.mpr hqne.symm]
      ring

-- LeanTest/HardProblems/FeedbackBounds.lean
/-- The disturbance tube is forward invariant: if the initial error is below
`d / (1 - q)`, every later error remains below it. The assumption `0 ≤ d`
makes the displayed radius nonnegative; it is not needed merely for the upper
inequality but records its intended error-bound interpretation. -/
theorem error_le_tube (e : ℕ → ℝ) (q d : ℝ)
    (hq0 : 0 ≤ q) (hq1 : q < 1) (hd : 0 ≤ d)
    (hstep : ∀ n, e (n + 1) ≤ q * e n + d)
    (hinit : e 0 ≤ d / (1 - q)) (n : ℕ) :
    0 ≤ d / (1 - q) ∧ e n ≤ d / (1 - q) := by
  constructor
  · exact div_nonneg hd (sub_nonneg.mpr (le_of_lt hq1))
  · have hpow : 0 ≤ q ^ n := pow_nonneg hq0 n
    have htransient := error_le_tube_transient e q d hq0 hq1 hstep n
    have hdiff : e 0 - d / (1 - q) ≤ 0 := sub_nonpos.mpr hinit
    have hnonpos : q ^ n * (e 0 - d / (1 - q)) ≤ 0 :=
      mul_nonpos_of_nonneg_of_nonpos hpow hdiff
    linarith

-- LeanTest/HardProblems/FeedbackBounds.lean
/-- Writing the effective contraction factor as `q₀ + μ` makes the robustness
margin explicit. A certified mismatch `μ` must remain below `1 - q₀`; under
that hypothesis the same finite-time disturbance-tube bound applies.

The result does not say that `μ` is a universal metric on model difference.
An observer analysis must first justify that the actual mismatch contributes
at most `μ` to this scalar one-step estimate. -/
theorem mismatch_le_margin_and_error_bound (e : ℕ → ℝ) (q₀ μ d : ℝ)
    (hq₀ : 0 ≤ q₀) (hμ : 0 ≤ μ) (hmargin : q₀ + μ < 1)
    (hstep : ∀ n, e (n + 1) ≤ (q₀ + μ) * e n + d) (n : ℕ) :
    μ < 1 - q₀ ∧
      e n ≤ (q₀ + μ) ^ n * (e 0 - d / (1 - q₀ - μ)) +
        d / (1 - q₀ - μ) := by
  constructor
  · linarith
  · have hq : 0 ≤ q₀ + μ := add_nonneg hq₀ hμ
    simpa [sub_sub] using
      error_le_tube_transient e (q₀ + μ) d hq hmargin hstep n

-- LeanTest/HardProblems/FaultMargins.lean
/-- A strict deterministic threshold test on a residual. Equality with the
threshold does not raise an alarm. -/
def Alarm (η : ℝ) (residual : E) : Prop :=
  η < ‖residual‖

-- LeanTest/HardProblems/FaultMargins.lean
/-- A residual certified inside the healthy radius cannot cross a threshold
that is at least that radius. This is a pointwise deterministic statement, not
a probabilistic false-alarm guarantee. -/
theorem healthy_residual_not_alarm {healthy : E} {ρ η : ℝ}
    (hhealthy : ‖healthy‖ ≤ ρ) (hthreshold : ρ ≤ η) :
    ¬ Alarm η healthy := by
  exact not_lt_of_ge (hhealthy.trans hthreshold)

-- LeanTest/HardProblems/FaultMargins.lean
/-- Reverse-triangle geometry for an additive fault: if the fault norm exceeds
the threshold plus the healthy-radius allowance, every admitted healthy
residual forces an alarm. The condition is sufficient, not necessary. -/
theorem alarm_of_fault_norm_gt_threshold_add_radius
    {healthy fault : E} {ρ η : ℝ}
    (hhealthy : ‖healthy‖ ≤ ρ) (hfault : η + ρ < ‖fault‖) :
    Alarm η (healthy + fault) := by
  have hreverse : ‖fault‖ ≤ ‖healthy + fault‖ + ‖healthy‖ := by
    calc
      ‖fault‖ = ‖(healthy + fault) - healthy‖ := by
        congr 1
        abel
      _ ≤ ‖healthy + fault‖ + ‖healthy‖ := norm_sub_le _ _
  unfold Alarm
  linarith

-- LeanTest/HardProblems/FaultMargins.lean
/-- At the smallest threshold certified from the declared healthy-radius bound
alone, `η = ρ`, the familiar separation condition is
`2 * ρ < ‖fault‖`. It still asserts only guaranteed detection under that
deterministic radius. -/
theorem alarm_of_fault_norm_gt_two_mul_radius
    {healthy fault : E} {ρ : ℝ}
    (hhealthy : ‖healthy‖ ≤ ρ) (hfault : 2 * ρ < ‖fault‖) :
    Alarm ρ (healthy + fault) := by
  apply alarm_of_fault_norm_gt_threshold_add_radius hhealthy
  simpa [two_mul] using hfault

-- LeanTest/HardProblems/FaultMargins.lean
/-- An additive faulted residual lies in the closed residual ball centered at
its fault signature whenever the healthy component lies inside the declared
radius. -/
theorem faulted_residual_mem_closedBall {healthy fault : E} {ρ : ℝ}
    (hhealthy : ‖healthy‖ ≤ ρ) :
    healthy + fault ∈ Metric.closedBall fault ρ := by
  rw [Metric.mem_closedBall, dist_eq_norm]
  simpa [add_sub_cancel_right]

-- LeanTest/HardProblems/FaultMargins.lean
/-- Closed candidate residual balls of common radius are disjoint when their
fault centers are separated by more than twice that radius. This supplies a
deterministic isolation margin for these two declared candidates; it does not
show that the candidate list is exhaustive or statistically identifiable.
The explicit nonnegativity hypothesis rules out vacuous negative-radius
balls. -/
theorem closedBall_disjoint_of_norm_sub_gt_two_mul_radius
    {fault₁ fault₂ : E} {ρ : ℝ}
    (hρ : 0 ≤ ρ) (hseparated : 2 * ρ < ‖fault₁ - fault₂‖) :
    Disjoint (Metric.closedBall fault₁ ρ) (Metric.closedBall fault₂ ρ) := by
  rw [Set.disjoint_left]
  intro residual hmem₁ hmem₂
  have h₁ : dist fault₁ residual ≤ ρ := by
    simpa [dist_comm] using (Metric.mem_closedBall.mp hmem₁)
  have h₂ : dist residual fault₂ ≤ ρ :=
    Metric.mem_closedBall.mp hmem₂
  have htriangle : dist fault₁ fault₂ ≤ dist fault₁ residual + dist residual fault₂ :=
    dist_triangle _ _ _
  have h₁max : dist fault₁ residual ≤ max ρ 0 :=
    h₁.trans (le_max_left _ _)
  have h₂max : dist residual fault₂ ≤ max ρ 0 :=
    h₂.trans (le_max_left _ _)
  have hcentersMax : ‖fault₁ - fault₂‖ ≤ 2 * max ρ 0 := by
    rw [← dist_eq_norm]
    linarith
  have hcenters : ‖fault₁ - fault₂‖ ≤ 2 * ρ := by
    simpa [max_eq_left hρ] using hcentersMax
  linarith

-- LeanTest/HardProblems/FaultMargins.lean
/-- A scalar recurrence may switch its nonnegative contraction factor at every
step and still obey the constant geometric bound for a declared uniform upper
factor. Nonnegativity of the error is what permits replacing each active factor
by the uniform upper bound.

This extends the constant-factor recurrence in `RobustFeedback`; it does not
establish that a switched observer or plant satisfies the scalar hypotheses. -/
theorem error_le_uniform_geometric_sum
    (e q : ℕ → ℝ) (qMax d : ℝ)
    (hqMax : 0 ≤ qMax)
    (hq : ∀ n, 0 ≤ q n ∧ q n ≤ qMax)
    (he : ∀ n, 0 ≤ e n)
    (hstep : ∀ n, e (n + 1) ≤ q n * e n + d)
    (n : ℕ) :
    e n ≤ qMax ^ n * e 0 + d * ∑ k ∈ Finset.range n, qMax ^ k := by
  apply RobustFeedback.error_le_geometric_sum e qMax d hqMax
  intro k
  calc
    e (k + 1) ≤ q k * e k + d := hstep k
    _ ≤ qMax * e k + d :=
      add_le_add (mul_le_mul_of_nonneg_right (hq k).2 (he k)) le_rfl

-- LeanTest/HardProblems/FaultMargins.lean
/-- Under a strict uniform contraction bound, arbitrary switching obeys the
same closed-form disturbance-tube transient as the constant-factor recurrence.
The theorem gives an upper certificate under uniform scalar hypotheses; it
does not establish those hypotheses for a particular switched system. -/
theorem error_le_uniform_tube_transient
    (e q : ℕ → ℝ) (qMax d : ℝ)
    (hqMax0 : 0 ≤ qMax) (hqMax1 : qMax < 1)
    (hq : ∀ n, 0 ≤ q n ∧ q n ≤ qMax)
    (he : ∀ n, 0 ≤ e n)
    (hstep : ∀ n, e (n + 1) ≤ q n * e n + d)
    (n : ℕ) :
    e n ≤ qMax ^ n * (e 0 - d / (1 - qMax)) + d / (1 - qMax) := by
  apply RobustFeedback.error_le_tube_transient e qMax d hqMax0 hqMax1
  intro k
  calc
    e (k + 1) ≤ q k * e k + d := hstep k
    _ ≤ qMax * e k + d :=
      add_le_add (mul_le_mul_of_nonneg_right (hq k).2 (he k)) le_rfl
observational equivalence and robust action (Observability.lean, SystemsTheory.lean)run run

HardProblems.PassivelyDistinguishable, HardProblems.ProbeDistinguishable, HardProblems.passively_imp_probe, HardProblems.exists_probe_only_distinguishable, HardProblems.ObsEquiv, HardProblems.obsEquiv_equivalence, HardProblems.common_estimate_forces_pairwise_convergence, HardProblems.DecisionCritical, HardProblems.RobustAcceptable, HardProblems.robustSet_eq_iInter, HardProblems.RobustlyInfeasible, HardProblems.robustlyInfeasible_iff_iInter_eq_empty, HardProblems.DecisionCritical.no_robust_action

-- LeanTest/HardProblems/SystemsTheory.lean
/-- Two models are distinguishable from `s` under the constant action `a₀`
when their observation-history laws differ at some horizon. The type does not
assert that `a₀` is inert; that interpretation is supplied by an application. -/
def PassivelyDistinguishable (M₁ M₂ : POSystem S A O) (a₀ : A) (s : S) : Prop :=
  ∃ n, obsProcess M₁ (fun _ => PMF.pure a₀) n s [] ≠
        obsProcess M₂ (fun _ => PMF.pure a₀) n s []

-- LeanTest/HardProblems/SystemsTheory.lean
/-- Two models are probe distinguishable from `s` when some policy of the
declared function type separates their observation-history laws. -/
def ProbeDistinguishable (M₁ M₂ : POSystem S A O) (s : S) : Prop :=
  ∃ (π : List O → PMF A) (n : ℕ),
    obsProcess M₁ π n s [] ≠ obsProcess M₂ π n s []

-- LeanTest/HardProblems/SystemsTheory.lean
/-- A constant-action policy is a special case of an observation-dependent
policy. -/
theorem passively_imp_probe {M₁ M₂ : POSystem S A O} {a₀ : A} {s : S}
    (h : PassivelyDistinguishable M₁ M₂ a₀ s) : ProbeDistinguishable M₁ M₂ s :=
  let ⟨n, hn⟩ := h
  ⟨fun _ => PMF.pure a₀, n, hn⟩

-- LeanTest/HardProblems/SystemsTheory.lean
/-- There are two Boolean models whose laws agree under the constant action
`false` at every horizon but differ under the constant action `true`. In these
witness models, `false` is inert and `true` changes one model only. -/
theorem exists_probe_only_distinguishable :
    ∃ (M₁ M₂ : POSystem Bool Bool Bool) (s : Bool),
      ¬ PassivelyDistinguishable M₁ M₂ false s ∧ ProbeDistinguishable M₁ M₂ s := by
  refine ⟨flipModel, inertModel, false, ?_, ?_⟩
  · rintro ⟨n, hn⟩
    exact hn (obsProcess_congr_null flipModel inertModel false rfl
      (fun s => by simp [flipModel, inertModel]) n false [])
  · refine ⟨fun _ => PMF.pure true, 2, ?_⟩
    have h₁ : obsProcess flipModel (fun _ => PMF.pure true) 2 false [] =
        PMF.pure [false, true] := by
      simp [obsProcess, flipModel, PMF.pure_bind]
    have h₂ : obsProcess inertModel (fun _ => PMF.pure true) 2 false [] =
        PMF.pure [false, false] := by
      simp [obsProcess, inertModel, PMF.pure_bind]
    rw [h₁, h₂]
    intro hcontra
    have := congrArg (fun p => p [false, true]) hcontra
    simp [PMF.pure_apply] at this

-- LeanTest/HardProblems/Observability.lean
/-- Observational equivalence: no policy of the declared function type
distinguishes the two states at any finite horizon. -/
def ObsEquiv (M : POSystem S A O) (s s' : S) : Prop :=
  ∀ (π : List O → PMF A) (n : ℕ), obsProcess M π n s [] = obsProcess M π n s' []

-- LeanTest/HardProblems/Observability.lean
/-- Observational equivalence is an equivalence relation, as the notation
`≡` silently promises. -/
theorem obsEquiv_equivalence (M : POSystem S A O) : Equivalence (ObsEquiv M) where
  refl _ := fun _ _ => rfl
  symm h := fun π n => (h π n).symm
  trans h₁ h₂ := fun π n => (h₁ π n).trans (h₂ π n)

-- LeanTest/HardProblems/Observability.lean
/-- A necessary metric condition for asymptotic reconstruction: if the same
estimate converges to each of two state trajectories, their mutual distance
converges to zero. To turn this into a detectability theorem, a system-specific
argument must show that observationally indistinguishable trajectories really
feed the same estimate. -/
theorem common_estimate_forces_pairwise_convergence
    {X : Type*} [PseudoMetricSpace X] (x₁ x₂ xhat : ℕ → X)
    (h₁ : Tendsto (fun t => dist (x₁ t) (xhat t)) atTop (𝓝 0))
    (h₂ : Tendsto (fun t => dist (x₂ t) (xhat t)) atTop (𝓝 0)) :
    Tendsto (fun t => dist (x₁ t) (x₂ t)) atTop (𝓝 0) := by
  refine squeeze_zero (fun _ => dist_nonneg) (fun t => dist_triangle _ (xhat t) _) ?_
  have h₂' : Tendsto (fun t => dist (xhat t) (x₂ t)) atTop (𝓝 0) :=
    h₂.congr' (Eventually.of_forall fun t => dist_comm (x₂ t) (xhat t))
  simpa only [zero_add] using h₁.add h₂'

-- LeanTest/HardProblems/Observability.lean
/-- Decision-critical ambiguity: two observationally equivalent states whose
acceptable-action sets `A*_M` are disjoint. -/
def DecisionCritical (M : POSystem S A O) (Astar : S → Set A) (s s' : S) : Prop :=
  ObsEquiv M s s' ∧ Disjoint (Astar s) (Astar s')

-- LeanTest/HardProblems/Observability.lean
/-- An action is robust at `s` when it is acceptable in every state
observationally equivalent to `s`. -/
def RobustAcceptable (M : POSystem S A O) (Astar : S → Set A) (s : S) (a : A) : Prop :=
  ∀ s', ObsEquiv M s s' → a ∈ Astar s'

-- LeanTest/HardProblems/Observability.lean
/-- Robust actions are exactly the intersection of the acceptable sets over
the equivalence class of `s`. -/
theorem robustSet_eq_iInter (M : POSystem S A O) (Astar : S → Set A) (s : S) :
    {a | RobustAcceptable M Astar s a} = ⋂ s' ∈ {s' | ObsEquiv M s s'}, Astar s' := by
  ext a
  simp [RobustAcceptable]

-- LeanTest/HardProblems/Observability.lean
/-- Robust choice is infeasible when no action is acceptable throughout the
observational equivalence class. -/
def RobustlyInfeasible (M : POSystem S A O) (Astar : S → Set A) (s : S) : Prop :=
  ¬ ∃ a, RobustAcceptable M Astar s a

-- LeanTest/HardProblems/Observability.lean
/-- The exact criterion for robust infeasibility is emptiness of the total
intersection of acceptable-action sets over the observational class. Pairwise
disjointness is sufficient but not necessary for this intersection to be empty. -/
theorem robustlyInfeasible_iff_iInter_eq_empty
    (M : POSystem S A O) (Astar : S → Set A) (s : S) :
    RobustlyInfeasible M Astar s ↔
      ⋂ s' ∈ {s' | ObsEquiv M s s'}, Astar s' = ∅ := by
  rw [← robustSet_eq_iInter]
  change (¬ ({a | RobustAcceptable M Astar s a} : Set A).Nonempty) ↔ _
  exact Set.not_nonempty_iff_eq_empty

-- LeanTest/HardProblems/Observability.lean
/-- A disjoint observationally equivalent pair certifies that no robust action
exists at the first state. -/
theorem DecisionCritical.no_robust_action
    {M : POSystem S A O} {Astar : S → Set A} {s s' : S}
    (h : DecisionCritical M Astar s s') :
    ¬∃ a, RobustAcceptable M Astar s a := by
  rintro ⟨a, ha⟩
  have h₁ : a ∈ Astar s := ha s ((obsEquiv_equivalence M).refl s)
  have h₂ : a ∈ Astar s' := ha s' h.1
  exact Set.disjoint_left.mp h.2 h₁ h₂
reachability, barriers, and backed shortcuts (BoundedMachines.lean, Ruggedness.lean)run run

HardProblems.Reach, HardProblems.traj_mem_reach, HardProblems.Programmed, HardProblems.reach_insert_programmed, HardProblems.exists_new_effector_enlarges_reach, HardProblems.PathBetween, HardProblems.barrier, HardProblems.exists_dip_of_barrier_pos, HardProblems.barrier_eq_top_of_no_path, HardProblems.barrier_eq_zero_of_monotone_path, HardProblems.barrier_lt_iff, HardProblems.pathBetween_shortcut_nonempty_iff, HardProblems.barrier_shortcut_eq, HardProblems.exists_shortcut_hiding_valley

-- LeanTest/HardProblems/BoundedMachines.lean
/-- Finite-composition reachability: `y` is reachable from `x` by
applying effectors drawn from `G`. -/
inductive Reach (G : Set (X → X)) (x : X) : X → Prop
  | refl : Reach G x x
  | tail : ∀ {y z : X} {g : X → X}, Reach G x y → g ∈ G → z = g y → Reach G x z

-- LeanTest/HardProblems/BoundedMachines.lean
/-- Any admissible trajectory stays inside the reachable set: at each
step some effector in `G` was applied, chosen by an arbitrary policy,
and no choice rule ever escapes the orbit. -/
theorem traj_mem_reach (G : Set (X → X)) (σ : ℕ → X)
    (hstep : ∀ n, ∃ g ∈ G, σ (n + 1) = g (σ n)) (n : ℕ) :
    Reach G (σ 0) (σ n) := by
  induction n with
  | zero => exact Reach.refl
  | succ n ih =>
      obtain ⟨g, hg, heq⟩ := hstep n
      exact Reach.tail ih hg heq

-- LeanTest/HardProblems/BoundedMachines.lean
/-- Pointwise realizability over `G`: from every state, the image under `g` is
already reachable with `G`. The definition supplies neither a uniform generator
word nor a computable dispatcher for the witnessing paths. -/
def Programmed (G : Set (X → X)) (g : X → X) : Prop :=
  ∀ y : X, Reach G y (g y)

-- LeanTest/HardProblems/BoundedMachines.lean
/-- Inserting a pointwise realizable transformation as a primitive leaves every
reachability orbit unchanged. -/
theorem reach_insert_programmed (G : Set (X → X)) {g : X → X}
    (hg : Programmed G g) (x z : X) :
    Reach (insert g G) x z ↔ Reach G x z := by
  constructor
  · intro h
    induction h with
    | refl => exact Reach.refl
    | @tail y z f hy hmem heq ih =>
        rcases hmem with (rfl | hmem)
        · rw [heq]
          exact Reach.trans ih (hg y)
        · exact Reach.tail ih hmem heq
  · intro h
    induction h with
    | refl => exact Reach.refl
    | tail hy hmem heq ih =>
        exact Reach.tail ih (Set.mem_insert_of_mem g hmem) heq

-- LeanTest/HardProblems/BoundedMachines.lean
/-- A transformation outside the prior reachability closure can strictly
enlarge reach in an explicit two-state example. -/
theorem exists_new_effector_enlarges_reach :
    ∃ (G : Set (Bool → Bool)) (g : Bool → Bool) (x z : Bool),
      Reach (insert g G) x z ∧ ¬ Reach G x z := by
  refine ⟨∅, Bool.not, false, true, ?_, ?_⟩
  · exact Reach.tail Reach.refl (Set.mem_insert _ _) rfl
  · intro h
    cases h with
    | tail hy hmem heq => exact hmem.elim

-- LeanTest/HardProblems/Ruggedness.lean
/-- An admissible path in the configuration graph `Adj`, from `x` to `y`,
recorded as its list of visited configurations. -/
structure PathBetween (Adj : X → X → Prop) (x y : X) where
  points : List X
  head_eq : points.head? = some x
  last_eq : points.getLast? = some y
  admissible : points.IsChain Adj

-- LeanTest/HardProblems/Ruggedness.lean
/-- Barrier height from `x` to `y`: the infimum, over admissible paths, of the
deepest dip below `J x` along the path (dips measured in `ℝ≥0∞`, so paths
that never dip contribute `0`). Empty infimum is `⊤`: no path, infinite
barrier. -/
noncomputable def barrier (Adj : X → X → Prop) (J : X → ℝ) (x y : X) : ℝ≥0∞ :=
  ⨅ γ : PathBetween Adj x y, ⨆ z ∈ γ.points, ENNReal.ofReal (J x - J z)

-- LeanTest/HardProblems/Ruggedness.lean
/-- A positive barrier means every admissible route to `y` contains a
configuration strictly worse than the start. No hypothesis here says that `y`
is better than the start or that the dip occurs before first reaching `y`. -/
theorem exists_dip_of_barrier_pos {Adj : X → X → Prop} {J : X → ℝ} {x y : X}
    (h : 0 < barrier Adj J x y) (γ : PathBetween Adj x y) :
    ∃ z ∈ γ.points, J z < J x := by
  have hγ : 0 < ⨆ z ∈ γ.points, ENNReal.ofReal (J x - J z) :=
    lt_of_lt_of_le h (iInf_le _ γ)
  obtain ⟨z, hz⟩ := lt_iSup_iff.mp hγ
  obtain ⟨hmem, hpos⟩ := lt_iSup_iff.mp hz
  refine ⟨z, hmem, ?_⟩
  have := ENNReal.ofReal_pos.mp hpos
  linarith

-- LeanTest/HardProblems/Ruggedness.lean
/-- No admissible path at all makes the barrier infinite. -/
theorem barrier_eq_top_of_no_path {Adj : X → X → Prop} {J : X → ℝ} {x y : X}
    (h : IsEmpty (PathBetween Adj x y)) :
    barrier Adj J x y = ⊤ :=
  iInf_of_empty _

-- LeanTest/HardProblems/Ruggedness.lean
/-- If some admissible path never dips below the start value, the barrier
vanishes: the converse companion to `exists_dip_of_barrier_pos`. (Also
proved independently by Harmonic's Aristotle prover; see `aristotle/`.) -/
theorem barrier_eq_zero_of_monotone_path {Adj : X → X → Prop} {J : X → ℝ}
    {x y : X} (γ : PathBetween Adj x y) (hγ : ∀ z ∈ γ.points, J x ≤ J z) :
    barrier Adj J x y = 0 := by
  refine le_antisymm ?_ zero_le
  refine le_trans (iInf_le _ γ) ?_
  refine iSup_le fun z => iSup_le fun hz => ?_
  simp [ENNReal.ofReal_eq_zero, hγ z hz]

-- LeanTest/HardProblems/Ruggedness.lean
/-- The barrier sits strictly below `d` exactly when some admissible path
keeps every dip strictly below `d`. The backward direction uses the
finiteness of a path's point list: finitely many quantities each below `d`
have supremum below `d`. -/
theorem barrier_lt_iff {Adj : X → X → Prop} {J : X → ℝ} {x y : X}
    {d : ℝ≥0∞} :
    barrier Adj J x y < d ↔
      ∃ γ : PathBetween Adj x y, ∀ z ∈ γ.points,
        ENNReal.ofReal (J x - J z) < d := by
  constructor
  · intro h
    obtain ⟨γ, hγ⟩ := iInf_lt_iff.1 h
    exact ⟨γ, fun z hz =>
      lt_of_le_of_lt (le_biSup (fun z => ENNReal.ofReal (J x - J z)) hz) hγ⟩
  · rintro ⟨γ, hγ⟩
    have hx : x ∈ γ.points := List.mem_of_mem_head? γ.head_eq
    have hd : 0 < d := lt_of_le_of_lt zero_le (hγ x hx)
    exact lt_of_le_of_lt (iInf_le _ γ) (biSup_list_lt _ hd γ.points hγ)

-- LeanTest/HardProblems/Ruggedness.lean
/-- Reachability form: shortcuts backed by mere admissible paths do not
change what is reachable. -/
theorem pathBetween_shortcut_nonempty_iff {Adj S : X → X → Prop}
    (hback : ∀ u w, S u w → Nonempty (PathBetween Adj u w)) (x y : X) :
    Nonempty (PathBetween (fun a b => Adj a b ∨ S a b) x y) ↔
      Nonempty (PathBetween Adj x y) := by
  constructor
  · rintro ⟨γ⟩
    have hback' : ∀ u w, S u w → ∃ δ : PathBetween Adj u w,
        ∀ z ∈ δ.points, min ((fun _ : X => (0 : ℝ)) u) ((fun _ : X => (0 : ℝ)) w)
          ≤ (fun _ : X => (0 : ℝ)) z := by
      intro u w h
      obtain ⟨δ⟩ := hback u w h
      exact ⟨δ, fun _ _ => by simp⟩
    obtain ⟨γ', -⟩ := exists_splice hback' γ
    exact ⟨γ'⟩
  · rintro ⟨γ⟩
    exact ⟨γ.inl⟩

-- LeanTest/HardProblems/Ruggedness.lean
/-- Sufficient barrier certificate: shortcuts whose witnesses never dip below
the lower of their endpoints leave every barrier height unchanged. The theorem
does not claim that this certificate is necessary. -/
theorem barrier_shortcut_eq {Adj S : X → X → Prop} {J : X → ℝ}
    (hback : ∀ u w, S u w → ∃ γ : PathBetween Adj u w,
      ∀ z ∈ γ.points, min (J u) (J w) ≤ J z) (x y : X) :
    barrier (fun a b => Adj a b ∨ S a b) J x y = barrier Adj J x y := by
  refine le_antisymm (le_iInf fun γ => ?_) (le_iInf fun γ => ?_)
  · exact iInf_le_of_le γ.inl le_rfl
  · obtain ⟨γ', hγ'⟩ := exists_splice hback γ
    refine iInf_le_of_le γ' (iSup_le fun z => iSup_le fun hz => ?_)
    obtain ⟨p, hp, hple⟩ := hγ' z hz
    have key : ENNReal.ofReal (J x - J z) ≤ ENNReal.ofReal (J x - J p) :=
      ENNReal.ofReal_le_ofReal (by linarith)
    exact key.trans (le_biSup (fun p => ENNReal.ofReal (J x - J p)) hp)

-- LeanTest/HardProblems/Ruggedness.lean
/-- Mere `Nonempty` backing is insufficient for barrier preservation: a
shortcut can hide a valley. On the
two-step chain with a dip in the middle, admitting the backed shortcut
`0 → 2` drops the barrier from `ENNReal.ofReal 1` to `0`. This does not show
that the sufficient depth condition of `barrier_shortcut_eq` is necessary. -/
theorem exists_shortcut_hiding_valley :
    ∃ (Adj S : Fin 3 → Fin 3 → Prop) (J : Fin 3 → ℝ),
      (∀ u w, S u w → Nonempty (PathBetween Adj u w)) ∧
      ∃ x y : Fin 3,
        barrier (fun a b => Adj a b ∨ S a b) J x y < barrier Adj J x y := by
  refine ⟨hideAdj, hideS, hideJ, ?_, 0, 2, ?_⟩
  · intro u w huw
    obtain ⟨rfl, rfl⟩ : u = 0 ∧ w = 2 := huw
    refine ⟨⟨[0, 1, 2], rfl, rfl, ?_⟩⟩
    refine List.isChain_cons_cons.2 ⟨Or.inl ⟨rfl, rfl⟩, ?_⟩
    exact List.isChain_cons_cons.2 ⟨Or.inr ⟨rfl, rfl⟩, List.isChain_singleton _⟩
  · have hunion : barrier (fun a b => hideAdj a b ∨ hideS a b) hideJ 0 2 = 0 := by
      refine barrier_eq_zero_of_monotone_path ⟨[0, 2], rfl, rfl, ?_⟩ ?_
      · exact List.isChain_cons_cons.2 ⟨Or.inr ⟨rfl, rfl⟩, List.isChain_singleton _⟩
      · intro z hz
        have hz' : z = 0 ∨ z = 2 := by simpa using hz
        rcases hz' with rfl | rfl
        · exact le_rfl
        · rw [hideJ_zero, hideJ_two]
    have hlow : ENNReal.ofReal 1 ≤ barrier hideAdj hideJ 0 2 := by
      refine le_iInf fun γ => ?_
      have hmem : (1 : Fin 3) ∈ γ.points := one_mem_of_path γ
      have hval : ENNReal.ofReal 1 = ENNReal.ofReal (hideJ 0 - hideJ 1) := by
        rw [hideJ_zero, hideJ_one]; norm_num
      rw [hval]
      exact le_biSup (fun z => ENNReal.ofReal (hideJ 0 - hideJ z)) hmem
    rw [hunion]
    exact lt_of_lt_of_le (ENNReal.ofReal_pos.mpr one_pos) hlow
behavior, safety, and coordinate invariance (Behavioral.lean, Representation.lean)run run

HardProblems.Behavioral.Trajectory, HardProblems.Behavioral.Behavior, HardProblems.Behavioral.mapTrajectory, HardProblems.Behavioral.hide, HardProblems.Behavioral.interconnect, HardProblems.Behavioral.hide_interconnect_subset, HardProblems.Behavioral.hide_interconnect_strict_counterexample, HardProblems.Behavioral.hide_equiv_symm, HardProblems.Behavioral.IsSafe, HardProblems.Behavioral.IsViable, HardProblems.Behavioral.empty_behavior_safe, HardProblems.Behavioral.empty_behavior_not_viable, HardProblems.Behavioral.isSafe_mono, HardProblems.Behavioral.isSafe_hide_iff, HardProblems.Behavioral.isSafe_hide, HardProblems.Behavioral.IsRun, HardProblems.Behavioral.generatedBehavior, HardProblems.Behavioral.generatedBehavior_safe_of_invariant, HardProblems.Behavioral.generatedBehavior_safe_iff_invariant, HardProblems.Behavioral.restrict, HardProblems.Behavioral.Compatible, HardProblems.Behavioral.existsUnique_glue, HardProblems.Behavioral.admissible_glue_counterexample, HardProblems.Representation.run, HardProblems.CoordinateObservation.Indist, HardProblems.CoordinateObservation.run_conj, HardProblems.CoordinateObservation.indist_conj_iff, HardProblems.CoordinateReach.reachableSet, HardProblems.CoordinateReach.run_conj, HardProblems.CoordinateReach.image_reachableSet_conj, HardProblems.CoordinateBarrier.PathBetween, HardProblems.CoordinateBarrier.Relabel, HardProblems.CoordinateBarrier.PathBetween.map, HardProblems.CoordinateBarrier.PathBetween.relabel, HardProblems.CoordinateBarrier.PathBetween.unrelabel, HardProblems.CoordinateBarrier.pathDepth, HardProblems.CoordinateBarrier.barrier, HardProblems.CoordinateBarrier.pathDepth_relabel, HardProblems.CoordinateBarrier.pathDepth_unrelabel, HardProblems.CoordinateBarrier.path_nonempty_relabel_iff, HardProblems.CoordinateBarrier.barrier_relabel_eq

-- LeanTest/HardProblems/Behavioral.lean
/-- A complete signal trajectory on time domain `T`. -/
abbrev Trajectory (T : Type u) (W : Type v) := T → W

-- LeanTest/HardProblems/Behavioral.lean
/-- A behavior is the set of trajectories admitted by a system model. -/
abbrev Behavior (T : Type u) (W : Type v) := Set (Trajectory T W)

-- LeanTest/HardProblems/Behavioral.lean
/-- Apply a signal map pointwise to a trajectory. -/
def mapTrajectory {T : Type u} {W : Type v} {V : Type w}
    (f : W → V) (x : Trajectory T W) : Trajectory T V :=
  f ∘ x

-- LeanTest/HardProblems/Behavioral.lean
/-- Hide or relabel signal coordinates by taking the direct image of a
behavior under the pointwise signal map. -/
def hide {T : Type u} {W : Type v} {V : Type w}
    (f : W → V) (B : Behavior T W) : Behavior T V :=
  mapTrajectory f '' B

-- LeanTest/HardProblems/Behavioral.lean
/-- On one already aligned signal boundary, behavioral interconnection imposes
both component constraints. -/
def interconnect {T : Type u} {W : Type v}
    (B₁ B₂ : Behavior T W) : Behavior T W :=
  B₁ ∩ B₂

-- LeanTest/HardProblems/Behavioral.lean
/-- Hiding after interconnection is contained in interconnecting after hiding.
The reverse inclusion can fail because the two projected witnesses need not be
the same hidden trajectory. -/
theorem hide_interconnect_subset {T : Type u} {W : Type v} {V : Type w}
    (f : W → V) (B₁ B₂ : Behavior T W) :
    hide f (interconnect B₁ B₂) ⊆
      interconnect (hide f B₁) (hide f B₂) := by
  rintro _ ⟨x, ⟨hx₁, hx₂⟩, rfl⟩
  exact ⟨⟨x, hx₁, rfl⟩, ⟨x, hx₂, rfl⟩⟩

-- LeanTest/HardProblems/Behavioral.lean
/-- Explicit strictness witness: each component admits a different hidden Bool
trajectory with the same visible projection. The components are individually
viable, their interconnection is empty, but their visible projections have a
nonempty interconnection. -/
theorem hide_interconnect_strict_counterexample :
    let f : Bool × Bool → Bool := Prod.fst
    let x₀ : Trajectory Unit (Bool × Bool) := fun _ ↦ (false, false)
    let x₁ : Trajectory Unit (Bool × Bool) := fun _ ↦ (false, true)
    let B₀ : Behavior Unit (Bool × Bool) := {x₀}
    let B₁ : Behavior Unit (Bool × Bool) := {x₁}
    B₀.Nonempty ∧ B₁.Nonempty ∧ interconnect B₀ B₁ = ∅ ∧
      hide f (interconnect B₀ B₁) ⊂
        interconnect (hide f B₀) (hide f B₁) := by
  dsimp
  refine ⟨Set.singleton_nonempty _, Set.singleton_nonempty _, ?_⟩
  have hEmpty :
      interconnect ({fun _ : Unit ↦ (false, false)} :
        Behavior Unit (Bool × Bool)) {fun _ : Unit ↦ (false, true)} = ∅ := by
    apply Set.eq_empty_iff_forall_notMem.mpr
    rintro z ⟨hz₀, hz₁⟩
    rw [Set.mem_singleton_iff] at hz₀ hz₁
    have hEq : (fun _ : Unit ↦ (false, false)) =
        fun _ : Unit ↦ (false, true) := hz₀.symm.trans hz₁
    have := congrFun hEq ()
    simp at this
  refine ⟨hEmpty, ?_⟩
  refine Set.ssubset_iff_subset_ne.mpr
    ⟨hide_interconnect_subset _ _ _, ?_⟩
  intro hEq
  have hVisible : (fun _ : Unit ↦ false) ∈
      interconnect
        (hide Prod.fst ({fun _ : Unit ↦ (false, false)} :
          Behavior Unit (Bool × Bool)))
        (hide Prod.fst ({fun _ : Unit ↦ (false, true)} :
          Behavior Unit (Bool × Bool))) := by
    exact ⟨⟨_, rfl, rfl⟩, ⟨_, rfl, rfl⟩⟩
  have hImpossible : (fun _ : Unit ↦ false) ∈
      hide Prod.fst
        (interconnect ({fun _ : Unit ↦ (false, false)} :
          Behavior Unit (Bool × Bool)) {fun _ : Unit ↦ (false, true)}) := by
    rw [hEq]
    exact hVisible
  rw [hEmpty] at hImpossible
  rcases hImpossible with ⟨_, hmem, _⟩
  exact hmem

-- LeanTest/HardProblems/Behavioral.lean
/-- Exact relabeling by an equivalence loses no behavior. -/
theorem hide_equiv_symm {T : Type u} {W : Type v} {V : Type w}
    (e : W ≃ V) (B : Behavior T W) :
    hide e.symm (hide e B) = B := by
  ext x
  constructor
  · rintro ⟨_, ⟨z, hz, rfl⟩, hzx⟩
    have hzx' : z = x := by
      simpa [mapTrajectory, Function.comp_def] using hzx
    simpa [← hzx'] using hz
  · intro hx
    refine ⟨mapTrajectory e x, ⟨x, hx, rfl⟩, ?_⟩
    funext t
    simp [mapTrajectory, Function.comp_def]

-- LeanTest/HardProblems/Behavioral.lean
/-- A temporal safety predicate holds at every time on every admitted
trajectory. -/
def IsSafe {T : Type u} {W : Type v}
    (B : Behavior T W) (Safe : W → Prop) : Prop :=
  ∀ x ∈ B, ∀ t, Safe (x t)

-- LeanTest/HardProblems/Behavioral.lean
/-- A behavior is viable when it admits at least one trajectory. -/
def IsViable {T : Type u} {W : Type v} (B : Behavior T W) : Prop :=
  B.Nonempty

-- LeanTest/HardProblems/Behavioral.lean
/-- Universal safety is vacuous on the empty behavior. -/
theorem empty_behavior_safe {T : Type u} {W : Type v} {Safe : W → Prop} :
    IsSafe (∅ : Behavior T W) Safe := by
  simp [IsSafe]

-- LeanTest/HardProblems/Behavioral.lean
/-- The empty behavior is not viable. -/
theorem empty_behavior_not_viable {T : Type u} {W : Type v} :
    ¬ IsViable (∅ : Behavior T W) := by
  simp [IsViable]

-- LeanTest/HardProblems/Behavioral.lean
/-- Refining a behavior preserves every universal safety property. -/
theorem isSafe_mono {T : Type u} {W : Type v}
    {B B' : Behavior T W} {Safe : W → Prop}
    (hsub : B' ⊆ B) (h : IsSafe B Safe) : IsSafe B' Safe := by
  intro x hx t
  exact h x (hsub hx) t

-- LeanTest/HardProblems/Behavioral.lean
/-- Direct-image hiding has an exact safety semantics: a visible predicate
holds on every projected trajectory exactly when its pullback holds on every
original trajectory. This says nothing about predicates on discarded signal
coordinates. -/
theorem isSafe_hide_iff {T : Type u} {W : Type v} {V : Type w}
    (f : W → V) (B : Behavior T W) (SafeV : V → Prop) :
    IsSafe (hide f B) SafeV ↔ IsSafe B (SafeV ∘ f) := by
  constructor
  · intro h x hx t
    simpa [mapTrajectory, Function.comp_def] using
      h (mapTrajectory f x) ⟨x, hx, rfl⟩ t
  · rintro h _ ⟨x, hx, rfl⟩ t
    simpa [mapTrajectory, Function.comp_def] using h x hx t

-- LeanTest/HardProblems/Behavioral.lean
/-- Hiding preserves a safety property only when the signal map carries the
declared internal safe set into the external one. -/
theorem isSafe_hide {T : Type u} {W : Type v} {V : Type w}
    {B : Behavior T W} {SafeW : W → Prop} {SafeV : V → Prop}
    (f : W → V) (hB : IsSafe B SafeW)
    (hmap : ∀ w, SafeW w → SafeV (f w)) :
    IsSafe (hide f B) SafeV := by
  rintro _ ⟨x, hx, rfl⟩ t
  exact hmap (x t) (hB x hx t)

-- LeanTest/HardProblems/Behavioral.lean
/-- A discrete trajectory follows `step` at every successor time. -/
def IsRun {S : Type u} (step : S → S) (x : Trajectory ℕ S) : Prop :=
  ∀ n, x (n + 1) = step (x n)

-- LeanTest/HardProblems/Behavioral.lean
/-- All runs whose initial state lies in `Init`. -/
def generatedBehavior {S : Type u} (step : S → S) (Init : Set S) :
    Behavior ℕ S :=
  {x | x 0 ∈ Init ∧ IsRun step x}

-- LeanTest/HardProblems/Behavioral.lean
/-- Forward invariance gives all-time safety for every generated run. -/
theorem generatedBehavior_safe_of_invariant {S : Type u}
    {step : S → S} {Init Safe : Set S}
    (hInit : Init ⊆ Safe) (hInv : Set.MapsTo step Safe Safe) :
    IsSafe (generatedBehavior step Init) Safe := by
  rintro x ⟨hx₀, hrun⟩ n
  induction n with
  | zero => exact hInit hx₀
  | succ n ih =>
      rw [hrun n]
      exact hInv ih

-- LeanTest/HardProblems/Behavioral.lean
/-- For the behavior generated from every state in `Safe`, temporal safety is
equivalent to one-step forward invariance. -/
theorem generatedBehavior_safe_iff_invariant {S : Type u}
    (step : S → S) (Safe : Set S) :
    IsSafe (generatedBehavior step Safe) Safe ↔
      Set.MapsTo step Safe Safe := by
  constructor
  · intro h s hs
    let x : Trajectory ℕ S := fun n ↦ Nat.rec s (fun _ current ↦ step current) n
    have hrun : IsRun step x := by
      intro n
      simp [x]
    have hx : x ∈ generatedBehavior step Safe := by
      exact ⟨by simpa [x] using hs, hrun⟩
    have hs₁ := h x hx 1
    change x 1 ∈ Safe at hs₁
    simpa [x] using hs₁
  · intro hInv
    exact generatedBehavior_safe_of_invariant (by exact fun _ h ↦ h) hInv

-- LeanTest/HardProblems/Behavioral.lean
/-- Restrict a local trajectory from `I` to a smaller time domain `J`. -/
def restrict {T : Type u} {W : Type v} {I J : Set T}
    (hJI : J ⊆ I) (x : I → W) : J → W :=
  fun t ↦ x ⟨t.1, hJI t.2⟩

-- LeanTest/HardProblems/Behavioral.lean
/-- Two local trajectories agree wherever their time domains overlap. -/
def Compatible {T : Type u} {W : Type v} {I J : Set T}
    (x : I → W) (y : J → W) : Prop :=
  ∀ (t : T) (htI : t ∈ I) (htJ : t ∈ J),
    x ⟨t, htI⟩ = y ⟨t, htJ⟩

-- LeanTest/HardProblems/Behavioral.lean
/-- Compatible functions on two time domains have a unique global function on
their union with the prescribed restrictions. -/
theorem existsUnique_glue {T : Type u} {W : Type v} {I J : Set T}
    (x : I → W) (y : J → W) (hxy : Compatible x y) :
    ∃! z : ↥(I ∪ J) → W,
      restrict Set.subset_union_left z = x ∧
      restrict Set.subset_union_right z = y := by
  classical
  let z : ↥(I ∪ J) → W := fun t ↦
    if htI : (t : T) ∈ I then x ⟨t, htI⟩
    else y ⟨t, t.property.resolve_left htI⟩
  have hzI : restrict Set.subset_union_left z = x := by
    funext t
    simp [restrict, z]
  have hzJ : restrict Set.subset_union_right z = y := by
    funext t
    by_cases htI : (t : T) ∈ I
    · simpa [restrict, z, htI] using hxy t htI t.property
    · simp [restrict, z, htI]
  refine ⟨z, ⟨hzI, hzJ⟩, ?_⟩
  intro z' hz'
  funext t
  by_cases htI : (t : T) ∈ I
  · have h := congrFun hz'.1 (⟨t, htI⟩ : I)
    simpa [restrict, z, htI] using h
  · have htJ : (t : T) ∈ J := t.property.resolve_left htI
    have h := congrFun hz'.2 (⟨t, htJ⟩ : J)
    simpa [restrict, z, htI] using h

-- LeanTest/HardProblems/Behavioral.lean
/-- Raw compatible functions glue, but a nonempty declared set of admissible
global trajectories need not contain that glue. Thus arbitrary local/global
admissibility data do not acquire the sheaf property for free. -/
theorem admissible_glue_counterexample :
    let I : Set Bool := {false}
    let J : Set Bool := {true}
    let x : I → Bool := fun _ ↦ false
    let y : J → Bool := fun _ ↦ true
    let G : Set (↥(I ∪ J) → Bool) := {fun _ ↦ false}
    Compatible x y ∧ G.Nonempty ∧
      ¬ ∃ z ∈ G,
        restrict Set.subset_union_left z = x ∧
        restrict Set.subset_union_right z = y := by
  dsimp
  refine ⟨?_, Set.singleton_nonempty _, ?_⟩
  · intro t htI htJ
    rw [Set.mem_singleton_iff] at htI htJ
    exact Bool.noConfusion (htI.symm.trans htJ)
  · rintro ⟨z, hz, ⟨_, hzJ⟩⟩
    subst z
    have h := congrFun hzJ (⟨true, by simp⟩ : (↑({true} : Set Bool)))
    simp [restrict] at h

-- LeanTest/HardProblems/Representation.lean
/-- Drive deterministic dynamics with a finite input word, applying its
leftmost input first. -/
def run {U X : Type*} (step : U → X → X) : List U → X → X
  | [], x => x
  | u :: us, x => run step us (step u x)

-- LeanTest/HardProblems/Representation.lean
/-- Two states have identical outputs after every finite input word. -/
def Indist (step : U → X → X) (out : X → Y) (x x' : X) : Prop :=
  ∀ us : List U, out (run step us x) = out (run step us x')

-- LeanTest/HardProblems/Representation.lean
/-- A conjugating equivalence commutes with every finite run. -/
theorem run_conj (e : X ≃ X') {step : U → X → X}
    {step' : U → X' → X'}
    (hstep : ∀ u x, e (step u x) = step' u (e x)) (us : List U) (x : X) :
    e (run step us x) = run step' us (e x) := by
  induction us generalizing x with
  | nil => rfl
  | cons u us ih =>
    simp only [run]
    rw [ih, hstep]

-- LeanTest/HardProblems/Representation.lean
/-- Coordinate change preserves finite-word indistinguishability in both
directions when it conjugates transitions and preserves outputs. -/
theorem indist_conj_iff (e : X ≃ X') {step : U → X → X}
    {step' : U → X' → X'} {out : X → Y} {out' : X' → Y}
    (hstep : ∀ u x, e (step u x) = step' u (e x))
    (hout : ∀ x, out x = out' (e x)) (x y : X) :
    Indist step out x y ↔ Indist step' out' (e x) (e y) := by
  constructor
  · intro h us
    rw [← run_conj e hstep, ← run_conj e hstep]
    rw [← hout, ← hout]
    exact h us
  · intro h us
    rw [hout, hout]
    rw [run_conj e hstep, run_conj e hstep]
    exact h us

-- LeanTest/HardProblems/Representation.lean
/-- States reachable from `x` by some finite input word. -/
def reachableSet (step : U → X → X) (x : X) : Set X :=
  {z | ∃ us : List U, run step us x = z}

-- LeanTest/HardProblems/Representation.lean
/-- A conjugating equivalence commutes with every finite run. -/
theorem run_conj (e : X ≃ X') {step : U → X → X}
    {step' : U → X' → X'}
    (hstep : ∀ u x, e (step u x) = step' u (e x)) (us : List U) (x : X) :
    e (run step us x) = run step' us (e x) := by
  induction us generalizing x with
  | nil => rfl
  | cons u us ih =>
    simp only [run]
    calc
      e (run step us (step u x)) = run step' us (e (step u x)) := ih _
      _ = run step' us (step' u (e x)) := congrArg (run step' us) (hstep u x)

-- LeanTest/HardProblems/Representation.lean
/-- Coordinate change carries the concrete reachable set exactly onto the
reachable set in the conjugate coordinates. -/
theorem image_reachableSet_conj (e : X ≃ X') {step : U → X → X}
    {step' : U → X' → X'}
    (hstep : ∀ u x, e (step u x) = step' u (e x)) (x : X) :
    e '' reachableSet step x = reachableSet step' (e x) := by
  ext z
  constructor
  · rintro ⟨y, ⟨us, hus⟩, rfl⟩
    exact ⟨us, (run_conj e hstep us x).symm.trans (congrArg e hus)⟩
  · rintro ⟨us, hus⟩
    refine ⟨run step us x, ⟨us, rfl⟩, ?_⟩
    exact (run_conj e hstep us x).trans hus

-- LeanTest/HardProblems/Representation.lean
/-- A finite path including both endpoints. -/
structure PathBetween {X : Type u} (Adj : X → X → Prop) (x y : X) where
  points : List X
  head_eq : points.head? = some x
  last_eq : points.getLast? = some y
  admissible : points.IsChain Adj

-- LeanTest/HardProblems/Representation.lean
/-- Relabel a graph along a state-space equivalence. -/
def Relabel {X : Type u} {Y : Type v} (e : X ≃ Y)
    (Adj : X → X → Prop) : Y → Y → Prop :=
  fun a b => Adj (e.symm a) (e.symm b)

-- LeanTest/HardProblems/Representation.lean
/-- Map a path through any edge-preserving function. -/
def PathBetween.map {X : Type u} {Y : Type v}
    {Adj : X → X → Prop} {Adj' : Y → Y → Prop}
    (f : X → Y) (hstep : ∀ {a b}, Adj a b → Adj' (f a) (f b))
    {x y : X} (γ : PathBetween Adj x y) : PathBetween Adj' (f x) (f y) where
  points := γ.points.map f
  head_eq := by rw [List.head?_map, γ.head_eq]; rfl
  last_eq := by rw [List.getLast?_map, γ.last_eq]; rfl
  admissible := (List.isChain_map f).mpr
    (γ.admissible.imp fun _ _ h => hstep h)

-- LeanTest/HardProblems/Representation.lean
/-- Transport a path through a coordinate equivalence. -/
def PathBetween.relabel {X : Type u} {Y : Type v} {Adj : X → X → Prop}
    (e : X ≃ Y) {x y : X} (γ : PathBetween Adj x y) :
    PathBetween (Relabel e Adj) (e x) (e y) :=
  γ.map e (by intro a b h; simpa [Relabel] using h)

-- LeanTest/HardProblems/Representation.lean
/-- Return a transported path to the original coordinates. -/
def PathBetween.unrelabel {X : Type u} {Y : Type v} {Adj : X → X → Prop}
    (e : X ≃ Y) {x y : X}
    (γ : PathBetween (Relabel e Adj) (e x) (e y)) : PathBetween Adj x y := by
  simpa [Relabel] using
    γ.map e.symm (by intro a b h; simpa [Relabel] using h)

-- LeanTest/HardProblems/Representation.lean
/-- The deepest dip below the score of the starting vertex along one path. -/
noncomputable def pathDepth {X : Type u} {Adj : X → X → Prop}
    (J : X → ℝ) (x : X) {y : X} (γ : PathBetween Adj x y) : ℝ≥0∞ :=
  ⨆ z ∈ γ.points, ENNReal.ofReal (J x - J z)

-- LeanTest/HardProblems/Representation.lean
/-- The least path depth; the empty infimum is `⊤`. -/
noncomputable def barrier {X : Type u} (Adj : X → X → Prop)
    (J : X → ℝ) (x y : X) : ℝ≥0∞ :=
  ⨅ γ : PathBetween Adj x y, pathDepth J x γ

-- LeanTest/HardProblems/Representation.lean
/-- Relabeling a path and objective preserves that path's depth exactly. -/
theorem pathDepth_relabel {X : Type u} {Y : Type v}
    {Adj : X → X → Prop} (e : X ≃ Y) (J : X → ℝ)
    {x y : X} (γ : PathBetween Adj x y) :
    pathDepth (fun z => J (e.symm z)) (e x) (γ.relabel e) =
      pathDepth J x γ := by
  simp only [pathDepth, PathBetween.relabel, PathBetween.map,
    Equiv.symm_apply_apply]
  apply le_antisymm
  · refine iSup_le fun z => iSup_le fun hz => ?_
    obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hz
    simpa using
      (le_iSup_of_le a
        (le_iSup_of_le ha (le_refl (ENNReal.ofReal (J x - J a)))))
  · refine iSup_le fun a => iSup_le fun ha => ?_
    refine le_iSup_of_le (e a) (le_iSup_of_le ?_ ?_)
    · exact List.mem_map.mpr ⟨a, ha, rfl⟩
    · simp

-- LeanTest/HardProblems/Representation.lean
/-- Returning a relabeled path to the source coordinates also preserves its
depth exactly. -/
theorem pathDepth_unrelabel {X : Type u} {Y : Type v}
    {Adj : X → X → Prop} (e : X ≃ Y) (J : X → ℝ)
    {x y : X} (γ : PathBetween (Relabel e Adj) (e x) (e y)) :
    pathDepth J x (γ.unrelabel e) =
      pathDepth (fun z => J (e.symm z)) (e x) γ := by
  simp only [pathDepth, unrelabel_points, Equiv.symm_apply_apply]
  apply le_antisymm
  · refine iSup_le fun a => iSup_le fun ha => ?_
    obtain ⟨z, hz, rfl⟩ := List.mem_map.mp ha
    exact le_iSup_of_le z (le_iSup_of_le hz (le_refl _))
  · refine iSup_le fun z => iSup_le fun hz => ?_
    refine le_iSup_of_le (e.symm z) (le_iSup_of_le ?_ ?_)
    · exact List.mem_map.mpr ⟨z, hz, rfl⟩
    · rfl

-- LeanTest/HardProblems/Representation.lean
/-- Exact coordinate changes preserve the existence of a path. -/
theorem path_nonempty_relabel_iff {X : Type u} {Y : Type v}
    {Adj : X → X → Prop} (e : X ≃ Y) {x y : X} :
    Nonempty (PathBetween (Relabel e Adj) (e x) (e y)) ↔
      Nonempty (PathBetween Adj x y) := by
  constructor
  · rintro ⟨γ⟩
    exact ⟨γ.unrelabel e⟩
  · rintro ⟨γ⟩
    exact ⟨γ.relabel e⟩

-- LeanTest/HardProblems/Representation.lean
/-- Exact coordinate changes preserve every barrier height, including the
infinite value caused by unreachability. -/
theorem barrier_relabel_eq {X : Type u} {Y : Type v}
    (Adj : X → X → Prop) (e : X ≃ Y) (J : X → ℝ) (x y : X) :
    barrier (Relabel e Adj) (fun z => J (e.symm z)) (e x) (e y) =
      barrier Adj J x y := by
  apply le_antisymm
  · refine le_iInf fun γ => ?_
    exact iInf_le_of_le (γ.relabel e)
      (le_of_eq (pathDepth_relabel e J γ))
  · refine le_iInf fun γ => ?_
    exact iInf_le_of_le (γ.unrelabel e)
      (le_of_eq (pathDepth_unrelabel e J γ))
exact abstraction and path lifting (Representation.lean)run

HardProblems.SolutionTransfer.Reach, HardProblems.SolutionTransfer.Reach.map, HardProblems.SolutionTransfer.ReachTo, HardProblems.SolutionTransfer.ForwardSimulation, HardProblems.SolutionTransfer.StepLifting, HardProblems.SolutionTransfer.concrete_reach_maps, HardProblems.SolutionTransfer.lift_reach, HardProblems.SolutionTransfer.abstract_reach_lifts, HardProblems.SolutionTransfer.ExactAbstraction, HardProblems.SolutionTransfer.ExactAbstraction.reachTo_iff, HardProblems.SolutionTransfer.ExactAbstraction.comp, HardProblems.SolutionTransfer.forward_without_lifting_counterexample

-- LeanTest/HardProblems/Representation.lean
/-- Finite reflexive-transitive reachability generated by `Adj`. -/
inductive Reach {X : Type u} (Adj : X → X → Prop) (x : X) : X → Prop
  | refl : Reach Adj x x
  | tail {y z : X} : Reach Adj x y → Adj y z → Reach Adj x z

-- LeanTest/HardProblems/Representation.lean
/-- A map that preserves single steps preserves finite reachability. -/
theorem map {X : Type u} {Y : Type v} {Adj : X → X → Prop}
    {Adj' : Y → Y → Prop} {f : X → Y} {x y : X}
    (hstep : ∀ {a b}, Adj a b → Adj' (f a) (f b))
    (h : Reach Adj x y) : Reach Adj' (f x) (f y) := by
  induction h with
  | refl => exact Reach.refl
  | tail hxy hyz ih => exact Reach.tail ih (hstep hyz)

-- LeanTest/HardProblems/Representation.lean
/-- Some state in `G` is reachable from `x`. -/
def ReachTo {X : Type u} (Adj : X → X → Prop) (G : Set X) (x : X) : Prop :=
  ∃ y, Reach Adj x y ∧ y ∈ G

-- LeanTest/HardProblems/Representation.lean
/-- Every concrete step has a corresponding abstract step. -/
def ForwardSimulation {X : Type u} {Y : Type v} (f : X → Y)
    (Adj : X → X → Prop) (Adj' : Y → Y → Prop) : Prop :=
  ∀ {x y}, Adj x y → Adj' (f x) (f y)

-- LeanTest/HardProblems/Representation.lean
/-- Every abstract step offered at `f x` can be implemented from that actual
concrete representative `x`. This is stronger than requiring some member of
the fibre to implement the step. -/
def StepLifting {X : Type u} {Y : Type v} (f : X → Y)
    (Adj : X → X → Prop) (Adj' : Y → Y → Prop) : Prop :=
  ∀ (x : X) (y' : Y), Adj' (f x) y' →
    ∃ y : X, Adj x y ∧ f y = y'

-- LeanTest/HardProblems/Representation.lean
/-- Forward simulation sends a concrete solution to the image of its concrete
goal set. -/
theorem concrete_reach_maps {X : Type u} {Y : Type v}
    {Adj : X → X → Prop} {Adj' : Y → Y → Prop}
    {f : X → Y} {G : Set X} {x₀ : X}
    (hmap : ForwardSimulation f Adj Adj') :
    ReachTo Adj G x₀ → ReachTo Adj' (f '' G) (f x₀) := by
  rintro ⟨y, hxy, hyG⟩
  exact ⟨f y, Reach.map hmap hxy, ⟨y, hyG, rfl⟩⟩

-- LeanTest/HardProblems/Representation.lean
/-- Local step lifting extends to a lift of every finite abstract path, with
the endpoint lying in the required fibre. -/
theorem lift_reach {X : Type u} {Y : Type v}
    {Adj : X → X → Prop} {Adj' : Y → Y → Prop}
    {f : X → Y} (hlift : StepLifting f Adj Adj')
    {x : X} {y' : Y} (h : Reach Adj' (f x) y') :
    ∃ y : X, Reach Adj x y ∧ f y = y' := by
  induction h with
  | refl => exact ⟨x, Reach.refl, rfl⟩
  | @tail y' z' hxy hyz ih =>
      rcases ih with ⟨y, hxy', hy⟩
      rcases hlift y z' (hy ▸ hyz) with ⟨z, hyz', hz⟩
      exact ⟨z, Reach.tail hxy' hyz', hz⟩

-- LeanTest/HardProblems/Representation.lean
/-- An abstract solution descends when paths lift and abstract goal membership
reflects concrete success. -/
theorem abstract_reach_lifts {X : Type u} {Y : Type v}
    {Adj : X → X → Prop} {Adj' : Y → Y → Prop}
    {f : X → Y} {G : Set X} {G' : Set Y} {x₀ : X}
    (hlift : StepLifting f Adj Adj')
    (hreflect : ∀ x, f x ∈ G' → x ∈ G) :
    ReachTo Adj' G' (f x₀) → ReachTo Adj G x₀ := by
  rintro ⟨y', hxy, hyG⟩
  rcases lift_reach hlift hxy with ⟨y, hxy', hy⟩
  exact ⟨y, hxy', hreflect y (hy.symm ▸ hyG)⟩

-- LeanTest/HardProblems/Representation.lean
/-- The hypotheses for exact reachability transfer. -/
structure ExactAbstraction {X : Type u} {Y : Type v} (f : X → Y)
    (Adj : X → X → Prop) (Adj' : Y → Y → Prop)
    (G : Set X) (G' : Set Y) : Prop where
  mapStep : ForwardSimulation f Adj Adj'
  liftStep : StepLifting f Adj Adj'
  goalExact : ∀ x, x ∈ G ↔ f x ∈ G'

-- LeanTest/HardProblems/Representation.lean
/-- Under the exact hypotheses, concrete and abstract goal reachability agree. -/
theorem ExactAbstraction.reachTo_iff {X : Type u} {Y : Type v}
    {f : X → Y} {Adj : X → X → Prop} {Adj' : Y → Y → Prop}
    {G : Set X} {G' : Set Y} (h : ExactAbstraction f Adj Adj' G G') (x : X) :
    ReachTo Adj G x ↔ ReachTo Adj' G' (f x) := by
  constructor
  · rintro ⟨y, hxy, hyG⟩
    exact ⟨f y, Reach.map h.mapStep hxy, h.goalExact y |>.mp hyG⟩
  · exact abstract_reach_lifts h.liftStep (fun y => (h.goalExact y).mpr)

-- LeanTest/HardProblems/Representation.lean
/-- Exact abstractions compose. -/
theorem ExactAbstraction.comp {X : Type u} {Y : Type v} {Z : Type w}
    {f : X → Y} {g : Y → Z}
    {AdjX : X → X → Prop} {AdjY : Y → Y → Prop}
    {AdjZ : Z → Z → Prop} {GX : Set X} {GY : Set Y} {GZ : Set Z}
    (h₁ : ExactAbstraction f AdjX AdjY GX GY)
    (h₂ : ExactAbstraction g AdjY AdjZ GY GZ) :
    ExactAbstraction (g ∘ f) AdjX AdjZ GX GZ := by
  constructor
  · intro x y hxy
    exact h₂.mapStep (h₁.mapStep hxy)
  · intro x z hz
    rcases h₂.liftStep (f x) z hz with ⟨y, hxy, hy⟩
    rcases h₁.liftStep x y hxy with ⟨x', hxx', hx'⟩
    exact ⟨x', hxx', by simp only [Function.comp_apply, hx', hy]⟩
  · intro x
    exact (h₁.goalExact x).trans (h₂.goalExact (f x))

-- LeanTest/HardProblems/Representation.lean
/-- A forward simulation can have a reachable abstract goal with no concrete
representative. This explicit finite example isolates the missing lifting
condition. -/
theorem forward_without_lifting_counterexample :
    let f : Unit → Bool := fun _ => false
    let Adj : Unit → Unit → Prop := fun _ _ => False
    let Adj' : Bool → Bool → Prop := fun a b => a = false ∧ b = true
    ForwardSimulation f Adj Adj' ∧
      ReachTo Adj' ({true} : Set Bool) (f ()) ∧
      ¬ ReachTo Adj {x | f x = true} () := by
  dsimp
  constructor
  · intro x y h
    exact False.elim h
  constructor
  · exact ⟨true, Reach.tail Reach.refl ⟨rfl, rfl⟩, by simp⟩
  · rintro ⟨y, _, hy⟩
    simp at hy
finite memory and delayed output (BoundedMachines.lean, Positional.lean)run run

HardProblems.Machine, HardProblems.Machine.run, HardProblems.Machine.Separated, HardProblems.Tracks, HardProblems.Tracks.run_eq, HardProblems.Tracks.injective, HardProblems.card_le_of_tracks, HardProblems.card_eq_of_mutual_tracks, HardProblems.RegisterMachine, HardProblems.RegisterMachine.run, HardProblems.RegisterMachine.multiplicationInput, HardProblems.RegisterMachine.ComputesMultiplicationAt, HardProblems.RegisterMachine.finalState_injective, HardProblems.RegisterMachine.state_capacity_lower_bound, HardProblems.RegisterMachine.linear_bit_lower_bound, HardProblems.RegisterMachine.no_constant_register_budget

-- LeanTest/HardProblems/BoundedMachines.lean
/-- A deterministic machine with inputs `I`, outputs `O`, and state
space `S`: a step function and an output map. -/
structure Machine (I O S : Type*) where
  step : S → I → S
  out : S → O

-- LeanTest/HardProblems/BoundedMachines.lean
/-- Run a machine from state `s` on an input word `w`. -/
def Machine.run (M : Machine I O S) (s : S) (w : List I) : S :=
  w.foldl M.step s

-- LeanTest/HardProblems/BoundedMachines.lean
/-- A machine is output-separated when any two states that agree on the
outputs along every input word are equal. -/
def Machine.Separated (M : Machine I O S) : Prop :=
  ∀ s t : S, (∀ w : List I, M.out (M.run s w) = M.out (M.run t w)) → s = t

-- LeanTest/HardProblems/BoundedMachines.lean
/-- `f` tracks machine `B` inside machine `A`: the encoding intertwines
the dynamics and reproduces the outputs. This is what it means for `A`
to maintain a faithful copy of `B`. -/
structure Tracks (A : Machine I O S) (B : Machine I O T) (f : T → S) : Prop where
  step_eq : ∀ t i, f (B.step t i) = A.step (f t) i
  out_eq : ∀ t, A.out (f t) = B.out t

-- LeanTest/HardProblems/BoundedMachines.lean
/-- A tracking map intertwines whole runs, not just single steps. -/
theorem Tracks.run_eq {A : Machine I O S} {B : Machine I O T} {f : T → S}
    (h : Tracks A B f) (t : T) (w : List I) :
    f (B.run t w) = A.run (f t) w := by
  induction w generalizing t with
  | nil => rfl
  | cons i w ih =>
    simp [Machine.run]
    rw [← h.step_eq]
    exact ih (B.step t i)

-- LeanTest/HardProblems/BoundedMachines.lean
/-- Tracking an output-separated machine is injective: the tracker must
hold distinct internal states for distinct tracked states. -/
theorem Tracks.injective {A : Machine I O S} {B : Machine I O T} {f : T → S}
    (h : Tracks A B f) (hB : B.Separated) : Function.Injective f := by
  intro t₁ t₂ hft
  apply hB t₁ t₂
  intro w
  have eq1 : f (B.run t₁ w) = A.run (f t₁) w := h.run_eq t₁ w
  have eq2 : f (B.run t₂ w) = A.run (f t₂) w := h.run_eq t₂ w
  rw [← h.out_eq (B.run t₁ w), ← h.out_eq (B.run t₂ w), eq1, eq2, hft]

-- LeanTest/HardProblems/BoundedMachines.lean
/-- The pigeonhole bound: a finite machine can exactly track an
output-separated machine only if it has at least as many states. This is a
capacity bound for the stated exact tracking relation. -/
theorem card_le_of_tracks [Fintype S] [Fintype T]
    {A : Machine I O S} {B : Machine I O T} {f : T → S}
    (h : Tracks A B f) (hB : B.Separated) :
    Fintype.card T ≤ Fintype.card S := by
  exact Fintype.card_le_of_injective _ (Tracks.injective h hB)

-- LeanTest/HardProblems/BoundedMachines.lean
/-- Mutual exact tracking forces cardinality parity for finite
output-separated machines. It does not by itself give an isomorphism between
their transition systems. -/
theorem card_eq_of_mutual_tracks [Fintype S] [Fintype T]
    {A : Machine I O S} {B : Machine I O T} {f : T → S} {g : S → T}
    (hf : Tracks A B f) (hg : Tracks B A g)
    (hA : A.Separated) (hB : B.Separated) :
    Fintype.card S = Fintype.card T := by
  exact le_antisymm (card_le_of_tracks hg hA) (card_le_of_tracks hf hB)

-- LeanTest/HardProblems/Positional.lean
/-- A streaming machine with `k` finite-range registers. -/
structure RegisterMachine (base range k : ℕ) where
  init : Fin k → Fin range
  step : (Fin k → Fin range) → Fin base → (Fin k → Fin range)
  output : (Fin k → Fin range) → ℕ

-- LeanTest/HardProblems/Positional.lean
/-- Run a register machine over a finite input stream. -/
def run {base range k : ℕ} (M : RegisterMachine base range k) :
    List (Fin base) → (Fin k → Fin range) :=
  List.foldl M.step M.init

-- LeanTest/HardProblems/Positional.lean
/-- The fixed-width input stream for multiplying `x` and `y`. -/
def multiplicationInput (base n x y : ℕ) [NeZero base] : List (Fin base) :=
  fixedDigits base n x ++ fixedDigits base n y

-- LeanTest/HardProblems/Positional.lean
/-- The machine computes `n`-digit multiplication when its final-state output
is the product for every pair in the full fixed-width range `[0, base^n)`.
In particular, this quantifies over the actual transition-based execution; it
is not the mere existence of an unconstrained function on inputs. -/
def ComputesMultiplicationAt {base range k : ℕ} [NeZero base]
    (M : RegisterMachine base range k) (n : ℕ) : Prop :=
  ∀ x y, x < base ^ n → y < base ^ n →
    M.output (M.run (multiplicationInput base n x y)) = x * y

-- LeanTest/HardProblems/Positional.lean
/-- If a machine computes multiplication at width `n`, fixing the second
operand to one makes final configurations for distinct first operands distinct. -/
theorem finalState_injective {base range k n : ℕ} [NeZero base]
    (M : RegisterMachine base range k) (hbase : 2 ≤ base) (hn : 0 < n)
    (hM : M.ComputesMultiplicationAt n) :
    Function.Injective (fun x : Fin (base ^ n) =>
      M.run (multiplicationInput base n x 1)) := by
  intro x y hxy
  have h1 : (1 : ℕ) < base ^ n := one_lt_pow₀ (by omega) (by omega)
  have hx := hM x 1 x.is_lt h1
  have hy := hM y 1 y.is_lt h1
  simp only [mul_one] at hx hy
  simp only at hxy
  rw [hxy] at hx
  exact Fin.ext (hx.symm.trans hy)

-- LeanTest/HardProblems/Positional.lean
/-- The central configuration-count lower bound: a correct width-`n` machine
needs at least `base^n` different register configurations. -/
theorem state_capacity_lower_bound {base range k n : ℕ} [NeZero base]
    (M : RegisterMachine base range k) (hbase : 2 ≤ base) (hn : 0 < n)
    (hM : M.ComputesMultiplicationAt n) :
    base ^ n ≤ range ^ k := by
  have hinj := finalState_injective M hbase hn hM
  simpa using Fintype.card_le_of_injective _ hinj

-- LeanTest/HardProblems/Positional.lean
/-- Quantitative binary form.  If all register configurations can be encoded
in at most `bits` bits, correctness forces at least `n` bits. -/
theorem linear_bit_lower_bound {base range k n bits : ℕ} [NeZero base]
    (M : RegisterMachine base range k) (hbase : 2 ≤ base) (hn : 0 < n)
    (hM : M.ComputesMultiplicationAt n)
    (hbits : range ^ k ≤ 2 ^ bits) :
    n ≤ bits := by
  have h1 : base ^ n ≤ range ^ k := state_capacity_lower_bound M hbase hn hM
  have h2 : base ^ n ≤ 2 ^ bits := h1.trans hbits
  have h3 : 2 ^ n ≤ base ^ n := Nat.pow_le_pow_left hbase _
  have h4 : 2 ^ n ≤ 2 ^ bits := h3.trans h2
  exact (Nat.pow_le_pow_iff_right (by decide : 1 < 2)).mp h4

-- LeanTest/HardProblems/Positional.lean
/-- For every fixed finite register count and fixed finite value range, some
positive digit width cannot be handled under `ComputesMultiplicationAt`. Thus
no fixed finite configuration space satisfies this interface at every width. -/
theorem no_constant_register_budget (base range k : ℕ) (hbase : 2 ≤ base) :
    ∃ n > 0, ∀ M : RegisterMachine base range k,
      letI : NeZero base := ⟨by omega⟩
      ¬ M.ComputesMultiplicationAt n := by
  letI : NeZero base := ⟨by omega⟩
  have hbase1 : 1 < base := hbase
  by_cases hk : k = 0
  · exact ⟨1, by norm_num, fun M hM => by
      have hcap := state_capacity_lower_bound M hbase (by norm_num : 0 < 1) hM
      simp [hk] at hcap
      omega⟩
  · by_cases hr : range = 0
    · exact ⟨1, by norm_num, fun M hM => by
        have hcap := state_capacity_lower_bound M hbase (by norm_num : 0 < 1) hM
        simp [hr, hk] at hcap
        omega⟩
    · have hk0 : k ≠ 0 := hk
      have hpos : 0 < range ^ k := by positivity
      exact ⟨range ^ k, hpos, fun M hM => by
        have hcap := state_capacity_lower_bound M hbase hpos hM
        exact (Nat.lt_pow_self hbase1).not_ge hcap⟩
finite envelopes and context-indexed region orders (FibredOrder.lean, ResourceBounds.lean)run run

HardProblems.Envelope, HardProblems.exists_bounded_optimum, HardProblems.bounded_optimum_mono, HardProblems.exists_strict_envelope_gap, HardProblems.FibredOrder.SplitIndexedOrder, HardProblems.FibredOrder.SplitIndexedOrder.reindexHom, HardProblems.FibredOrder.SplitIndexedOrder.reindex_id_apply, HardProblems.FibredOrder.SplitIndexedOrder.reindex_comp_apply, HardProblems.FibredOrder.performanceRegions, HardProblems.FibredOrder.CompatibleEncounterRegions, HardProblems.FibredOrder.CompatibleEncounterRegions.RealizedRegion, HardProblems.FibredOrder.CompatibleEncounterRegions.instPartialOrderRealizedRegion, HardProblems.FibredOrder.CompatibleEncounterRegions.reindexRealized, HardProblems.FibredOrder.CompatibleEncounterRegions.reindexRealized_val, HardProblems.FibredOrder.CompatibleEncounterRegions.realizedRegionOrder, HardProblems.FibredOrder.CompatibleEncounterRegions.realizedRegionOrder_reindex_val, HardProblems.FibredOrder.ambient_preimage_can_be_unrealized, HardProblems.FibredOrder.EncounterLE, HardProblems.FibredOrder.encounterLE_refl, HardProblems.FibredOrder.encounterLE_trans, HardProblems.FibredOrder.encounterLE_antisymmetric_iff_injective, HardProblems.FibredOrder.constant_region_not_antisymmetric, HardProblems.FibredOrder.surjective_preimage_subset_iff, HardProblems.FibredOrder.equiv_preimage_subset_iff, HardProblems.FibredOrder.equiv_preimage_preserves_inclusion, HardProblems.FibredOrder.equiv_preimage_reflects_inclusion, HardProblems.FibredOrder.nonsurjective_preimage_not_order_reflecting, HardProblems.FibredOrder.noninjective_image_not_order_reflecting

-- LeanTest/HardProblems/ResourceBounds.lean
/-- A resource envelope specifies which programs are admitted and requires the
admitted set to be finite. -/
structure Envelope (P : Type*) where
  admits : P → Prop
  finite : Set.Finite {p | admits p}

-- LeanTest/HardProblems/ResourceBounds.lean
/-- A real-valued objective attains a maximum on any nonempty finite resource
envelope. This is an existence theorem, not an optimization procedure. -/
theorem exists_bounded_optimum {P : Type*} (E : Envelope P) (V : P → ℝ)
    (hne : ∃ p, E.admits p) :
    ∃ p, E.admits p ∧ ∀ q, E.admits q → V q ≤ V p := by
  obtain ⟨p, hp, hmax⟩ :=
    Set.exists_max_image {p | E.admits p} V E.finite hne
  exact ⟨p, hp, hmax⟩

-- LeanTest/HardProblems/ResourceBounds.lean
/-- If one finite envelope is included in another, the value of an optimum in
the larger envelope is at least that of an optimum in the smaller envelope. -/
theorem bounded_optimum_mono {P : Type*} (E F : Envelope P) (V : P → ℝ)
    (hEF : ∀ p, E.admits p → F.admits p)
    (p : P) (hp : E.admits p) (_hopt : ∀ q, E.admits q → V q ≤ V p)
    (q : P) (_hq : F.admits q) (hqopt : ∀ r, F.admits r → V r ≤ V q) :
    V p ≤ V q := by
  exact hqopt p (hEF p hp)

-- LeanTest/HardProblems/ResourceBounds.lean
/-- There is a nonempty finite envelope whose internal optimum is strictly
dominated by an excluded program. The witness's objective is unbounded, so the
statement deliberately does not claim that the excluded program is a global
optimum. -/
theorem exists_strict_envelope_gap :
    ∃ (E : Envelope ℕ) (V : ℕ → ℝ) (p : ℕ),
      E.admits p ∧ (∀ q, E.admits q → V q ≤ V p) ∧
      ∃ r, V p < V r := by
  use ⟨fun n => n = 0, by simp⟩
  use fun n => n
  use 0
  simp
  exact ⟨1, by norm_num⟩

-- LeanTest/HardProblems/FibredOrder.lean
/-- A strict contravariant family of partial orders over a category.

The pointwise identity and composition equations record a chosen splitting.
They are the only categorical coherence claimed in this file. -/
structure SplitIndexedOrder (C : Type u) [Category.{v} C] where
  /-- The carrier of the ordered fiber over a context. -/
  Fiber : C → Type w
  /-- The partial order in each fiber. -/
  fiberOrder : (c : C) → PartialOrder (Fiber c)
  /-- Contravariant transport along a context morphism. -/
  reindex : {c d : C} → (c ⟶ d) → Fiber d → Fiber c
  /-- Reindexing along an identity is the identity. -/
  reindex_id : ∀ (c : C) (x : Fiber c), reindex (𝟙 c) x = x
  /-- Reindexing reverses categorical composition. -/
  reindex_comp : ∀ {c d e : C} (f : c ⟶ d) (g : d ⟶ e)
    (x : Fiber e), reindex (f ≫ g) x = reindex f (reindex g x)
  /-- Every reindexing map is monotone in the fiber orders. -/
  reindex_mono : ∀ {c d : C} (f : c ⟶ d) {x y : Fiber d},
    (fiberOrder d).le x y → (fiberOrder c).le (reindex f x) (reindex f y)

-- LeanTest/HardProblems/FibredOrder.lean
/-- Reindexing as an order homomorphism. -/
def reindexHom (P : SplitIndexedOrder C) {c d : C} (f : c ⟶ d) :
    P.Fiber d →o P.Fiber c where
  toFun := P.reindex f
  monotone' := by
    intro x y hxy
    exact P.reindex_mono f hxy

-- LeanTest/HardProblems/FibredOrder.lean
@[simp]
theorem reindex_id_apply (P : SplitIndexedOrder C) (c : C) (x : P.Fiber c) :
    P.reindex (𝟙 c) x = x :=
  P.reindex_id c x

-- LeanTest/HardProblems/FibredOrder.lean
@[simp]
theorem reindex_comp_apply (P : SplitIndexedOrder C) {c d e : C}
    (f : c ⟶ d) (g : d ⟶ e) (x : P.Fiber e) :
    P.reindex (f ≫ g) x = P.reindex f (P.reindex g x) :=
  P.reindex_comp f g x

-- LeanTest/HardProblems/FibredOrder.lean
/-- The context-indexed partial order of all candidate performance regions
induced by a functor of performance-coordinate types. Context morphisms act
on points by `Perf.map`; candidate regions move in the opposite direction by
preimage. Realizability by an encounter or program is not part of this data. -/
def performanceRegions {C : Type u} [Category.{v} C] (Perf : C ⥤ Type w) :
    SplitIndexedOrder C where
  Fiber c := Set (Perf.obj c)
  fiberOrder _ := inferInstance
  reindex f A := Perf.map f ⁻¹' A
  reindex_id c A := by
    ext x
    simp
  reindex_comp f g A := by
    ext x
    simp
  reindex_mono := by
    intro c d f A B hAB
    exact Set.preimage_mono hAB

-- LeanTest/HardProblems/FibredOrder.lean
/-- Encounter data sufficient to make realized performance regions stable
under contravariant context change.

No identity or composition equation is imposed on `transport` at the level of
raw encounters. Only its observable effect on regions is stored. That exact
compatibility is enough to induce split reindexing after duplicate encounter
witnesses have been forgotten. -/
structure CompatibleEncounterRegions {C : Type u} [Category.{v} C]
    (Perf : C ⥤ Type w) where
  /-- The type of admitted encounters in each context. -/
  Encounter : C → Type e
  /-- The candidate region actually realized by an encounter. -/
  region : (c : C) → Encounter c → Set (Perf.obj c)
  /-- Contravariant transport of encounters along a context map. -/
  transport : {c d : C} → (c ⟶ d) → Encounter d → Encounter c
  /-- Transport realizes exactly the preimage of the target encounter's
  region. -/
  region_transport : ∀ {c d : C} (f : c ⟶ d) (E : Encounter d),
    region c (transport f E) = Perf.map f ⁻¹' region d E

-- LeanTest/HardProblems/FibredOrder.lean
/-- A region together with the proposition that some admitted encounter
realizes it. Different encounter witnesses with the same region determine the
same element of this subtype. -/
def RealizedRegion (D : CompatibleEncounterRegions Perf) (c : C) :=
  {A : Set (Perf.obj c) // ∃ E : D.Encounter c, D.region c E = A}

-- LeanTest/HardProblems/FibredOrder.lean
/-- Realized regions inherit the antisymmetric subset order from their
underlying sets; encounter witnesses do not participate in equality. -/
instance instPartialOrderRealizedRegion (D : CompatibleEncounterRegions Perf)
    (c : C) : PartialOrder (D.RealizedRegion c) :=
  PartialOrder.lift Subtype.val Subtype.val_injective

-- LeanTest/HardProblems/FibredOrder.lean
/-- Reindex a realized region by preimage. Compatibility supplies a transported
encounter witnessing that the resulting region is realized in the source
context. -/
def reindexRealized (D : CompatibleEncounterRegions Perf) {c d : C}
    (f : c ⟶ d) (A : D.RealizedRegion d) : D.RealizedRegion c :=
  ⟨Perf.map f ⁻¹' A.1, by
    rcases A.2 with ⟨E, hE⟩
    refine ⟨D.transport f E, ?_⟩
    rw [D.region_transport, hE]⟩

-- LeanTest/HardProblems/FibredOrder.lean
/-- The underlying set of a reindexed realized region is transparently the
ambient preimage. -/
@[simp]
theorem reindexRealized_val (D : CompatibleEncounterRegions Perf) {c d : C}
    (f : c ⟶ d) (A : D.RealizedRegion d) :
    (D.reindexRealized f A).1 = Perf.map f ⁻¹' A.1 :=
  rfl

-- LeanTest/HardProblems/FibredOrder.lean
/-- Realized regions form a split context-indexed partial order. The split laws
hold for region values; they do not assert coherent identity or composition
laws for the chosen raw encounter transports. -/
def realizedRegionOrder (D : CompatibleEncounterRegions Perf) :
    SplitIndexedOrder C where
  Fiber c := D.RealizedRegion c
  fiberOrder _ := inferInstance
  reindex := D.reindexRealized
  reindex_id c A := by
    apply Subtype.ext
    ext x
    simp [reindexRealized]
  reindex_comp f g A := by
    apply Subtype.ext
    ext x
    simp [reindexRealized]
  reindex_mono := by
    intro c d f A B hAB
    exact Set.preimage_mono hAB

-- LeanTest/HardProblems/FibredOrder.lean
/-- The reindexing stored in `realizedRegionOrder` has the same transparent
preimage value as `reindexRealized`. -/
@[simp]
theorem realizedRegionOrder_reindex_val
    (D : CompatibleEncounterRegions Perf) {c d : C}
    (f : c ⟶ d) (A : D.RealizedRegion d) :
    ((D.realizedRegionOrder).reindex f A).1 = Perf.map f ⁻¹' A.1 :=
  rfl

-- LeanTest/HardProblems/FibredOrder.lean
/-- Without compatible encounter transport, an ambient preimage need not be
among the regions declared realized in the source context. Both declared
families below are nonempty, yet the preimage of the realized target region is
not a realized source region. -/
theorem ambient_preimage_can_be_unrealized :
    let f : Unit → Bool := fun _ ↦ false
    let sourceRealized : Set (Set Unit) := {∅}
    let targetRegion : Set Bool := {false}
    let targetRealized : Set (Set Bool) := {targetRegion}
    sourceRealized.Nonempty ∧ targetRealized.Nonempty ∧
      targetRegion ∈ targetRealized ∧
      f ⁻¹' targetRegion ∉ sourceRealized := by
  simp

-- LeanTest/HardProblems/FibredOrder.lean
/-- Compare encounters by inclusion of their attainable regions. This is the
pullback of the fiber order along an encounter-to-region map. -/
def EncounterLE {E : Type u} {P : Type w} (region : E → Set P)
    (x y : E) : Prop :=
  region x ⊆ region y

-- LeanTest/HardProblems/FibredOrder.lean
/-- Region comparison pulled back to encounters is reflexive. -/
theorem encounterLE_refl {E : Type u} {P : Type w} (region : E → Set P)
    (x : E) : EncounterLE region x x :=
  Set.Subset.rfl

-- LeanTest/HardProblems/FibredOrder.lean
/-- Region comparison pulled back to encounters is transitive. -/
theorem encounterLE_trans {E : Type u} {P : Type w} (region : E → Set P)
    {x y z : E} (hxy : EncounterLE region x y)
    (hyz : EncounterLE region y z) : EncounterLE region x z :=
  hxy.trans hyz

-- LeanTest/HardProblems/FibredOrder.lean
/-- The pulled-back comparison is antisymmetric exactly when the
encounter-to-region map is injective. Without injectivity it is only a
preorder on encounters; quotienting encounters by equal regions restores a
partial order. -/
theorem encounterLE_antisymmetric_iff_injective {E : Type u} {P : Type w}
    (region : E → Set P) :
    (∀ ⦃x y : E⦄, EncounterLE region x y →
      EncounterLE region y x → x = y) ↔ Function.Injective region := by
  constructor
  · intro h x y hxy
    apply h
    · simp [EncounterLE, hxy]
    · simp [EncounterLE, hxy]
  · intro hinj x y hxy hyx
    exact hinj (Set.Subset.antisymm hxy hyx)

-- LeanTest/HardProblems/FibredOrder.lean
/-- Two distinct encounters assigned the same region witness the failure of
antisymmetry. The failure is in the encounter presentation, not in the subset
order on regions. -/
theorem constant_region_not_antisymmetric :
    let region : Bool → Set Unit := fun _ ↦ ∅
    EncounterLE region false true ∧ EncounterLE region true false ∧
      false ≠ true := by
  simp [EncounterLE]

-- LeanTest/HardProblems/FibredOrder.lean
/-- Preimage along a surjective point map preserves and reflects inclusion.
Bijectivity is therefore sufficient but not necessary for exact comparison
transport at the level of arbitrary candidate regions. -/
theorem surjective_preimage_subset_iff {X : Type u} {Y : Type w}
    (f : X → Y) (hf : Function.Surjective f) (A B : Set Y) :
    f ⁻¹' A ⊆ f ⁻¹' B ↔ A ⊆ B := by
  constructor
  · intro h y hy
    rcases hf y with ⟨x, rfl⟩
    exact h hy
  · exact Set.preimage_mono

-- LeanTest/HardProblems/FibredOrder.lean
/-- A bijective coordinate change preserves and reflects inclusion after
contravariant reindexing. Hence an exact relabeling neither creates nor erases
comparisons between candidate performance regions. -/
theorem equiv_preimage_subset_iff {X : Type u} {Y : Type w}
    (e : X ≃ Y) (A B : Set Y) :
    e ⁻¹' A ⊆ e ⁻¹' B ↔ A ⊆ B :=
  surjective_preimage_subset_iff e e.surjective A B

-- LeanTest/HardProblems/FibredOrder.lean
/-- The preservation direction of exact coordinate invariance. -/
theorem equiv_preimage_preserves_inclusion {X : Type u} {Y : Type w}
    (e : X ≃ Y) {A B : Set Y} (h : A ⊆ B) :
    e ⁻¹' A ⊆ e ⁻¹' B :=
  (equiv_preimage_subset_iff e A B).2 h

-- LeanTest/HardProblems/FibredOrder.lean
/-- The reflection direction of exact coordinate invariance. It depends on
surjectivity and is unavailable for a general non-surjective coordinate map. -/
theorem equiv_preimage_reflects_inclusion {X : Type u} {Y : Type w}
    (e : X ≃ Y) {A B : Set Y} (h : e ⁻¹' A ⊆ e ⁻¹' B) :
    A ⊆ B :=
  (equiv_preimage_subset_iff e A B).1 h

-- LeanTest/HardProblems/FibredOrder.lean
/-- Explicit failure of preimage order reflection for a non-surjective point
map. The injective constant map `Unit → Bool` misses `true`, so the whole Bool
region and `{false}` have equal preimages even though the former is not
contained in the latter. The issue here is failure of surjectivity, not
many-to-one collapse. -/
theorem nonsurjective_preimage_not_order_reflecting :
    let f : Unit → Bool := fun _ ↦ false
    let A : Set Bool := Set.univ
    let B : Set Bool := {false}
    ¬ Function.Surjective f ∧
      f ⁻¹' A = f ⁻¹' B ∧ f ⁻¹' A ⊆ f ⁻¹' B ∧ ¬ A ⊆ B := by
  dsimp
  constructor
  · intro hf
    rcases hf true with ⟨x, hx⟩
    simp at hx
  constructor
  · ext x
    simp
  constructor
  · intro x hx
    simp
  · intro h
    have : true ∈ ({false} : Set Bool) := h (Set.mem_univ true)
    simp at this

-- LeanTest/HardProblems/FibredOrder.lean
/-- Explicit failure of direct-image order reflection for a noninjective point
map. The constant map `Bool → Unit` merges `false` and `true`, so their
singleton regions have equal direct images although neither singleton is
contained in the other. This is the separate many-to-one failure mode. -/
theorem noninjective_image_not_order_reflecting :
    let f : Bool → Unit := fun _ ↦ ()
    let A : Set Bool := {false}
    let B : Set Bool := {true}
    ¬ Function.Injective f ∧
      f '' A = f '' B ∧ f '' A ⊆ f '' B ∧ ¬ A ⊆ B := by
  dsimp
  constructor
  · intro hf
    have h : false = true := hf rfl
    simp at h
  constructor
  · ext x
    simp
  constructor
  · intro x hx
    simp
  · intro h
    have : false ∈ ({true} : Set Bool) := h (by simp)
    simp at this
Peripheral formal experiment: the total category and its cartesian lifts (GrothendieckFibration.lean)run

HardProblems.FibredOrder.reindexFunctor, HardProblems.FibredOrder.toCatFunctor, HardProblems.FibredOrder.toCatPseudofunctor, HardProblems.FibredOrder.total, HardProblems.FibredOrder.projection, HardProblems.FibredOrder.totalObj, HardProblems.FibredOrder.cartesianLift, HardProblems.FibredOrder.cartesianLift_isStronglyCartesian, HardProblems.FibredOrder.projection_isFibered, HardProblems.FibredOrder.reindex_is_cartesian_lift, HardProblems.FibredOrder.fiberFunctor, HardProblems.FibredOrder.fiberFunctor_isEquivalence, HardProblems.FibredOrder.fiberEquiv

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- Reindexing along one arrow, regarded as a functor between thin categories. -/
def reindexFunctor (P : SplitIndexedOrder C) {c d : C} (f : c ⟶ d) :
    P.Fiber d ⥤ P.Fiber c where
  obj := P.reindex f
  map h := homOfLE (P.reindex_mono f h.le)

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- Package the indexed poset as a genuine contravariant functor into `Cat`. -/
def toCatFunctor (P : SplitIndexedOrder C) : Cᵒᵖ ⥤ Cat.{w, w} where
  obj c := Cat.of (P.Fiber c.unop)
  map f := (reindexFunctor P f.unop).toCatHom
  map_id c := by
    apply Cat.Hom.ext
    apply CategoryTheory.Functor.ext (fun x => P.reindex_id c.unop x)
  map_comp f g := by
    apply Cat.Hom.ext
    apply CategoryTheory.Functor.ext (fun x => P.reindex_comp g.unop f.unop x)

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The strict functor, promoted to the pseudofunctor expected by mathlib's
contravariant Grothendieck construction. -/
abbrev toCatPseudofunctor (P : SplitIndexedOrder C) :
    Pseudofunctor (LocallyDiscrete Cᵒᵖ) Cat.{w, w} :=
  (toCatFunctor P).toPseudoFunctor'

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The total category of the indexed order. -/
abbrev total (P : SplitIndexedOrder C) : Type _ :=
  Pseudofunctor.CoGrothendieck (toCatPseudofunctor P)

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- Projection of the total category to the original base. -/
abbrev projection (P : SplitIndexedOrder C) : total P ⥤ C :=
  Pseudofunctor.CoGrothendieck.forget (toCatPseudofunctor P)

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The total object represented by `x` in the fiber over `c`. -/
abbrev totalObj (P : SplitIndexedOrder C) (c : C) (x : P.Fiber c) : total P :=
  { base := c, fiber := x }

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The canonical arrow from the reindexed object to the original object. -/
def cartesianLift (P : SplitIndexedOrder C) {c d : C} (f : c ⟶ d) (x : P.Fiber d) :
    totalObj P c (P.reindex f x) ⟶ totalObj P d x where
  base := f
  fiber := 𝟙 _

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The canonical reindexing arrow is strongly cartesian. -/
theorem cartesianLift_isStronglyCartesian (P : SplitIndexedOrder C)
    {c d : C} (f : c ⟶ d) (x : P.Fiber d) :
    (projection P).IsStronglyCartesian f (cartesianLift P f x) := by
  change (projection P).IsStronglyCartesian f
    (Pseudofunctor.CoGrothendieck.cartesianLift (F := toCatPseudofunctor P) x f)
  exact Pseudofunctor.CoGrothendieck.isStronglyCartesian_homCartesianLift
    (F := toCatPseudofunctor P) x f

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The projection is a fibration over the original base category. -/
theorem projection_isFibered (P : SplitIndexedOrder C) :
    (projection P).IsFibered := by
  infer_instance

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The chosen transport is exactly the domain of the canonical cartesian lift,
and that lift satisfies mathlib's cartesian universal property. -/
theorem reindex_is_cartesian_lift (P : SplitIndexedOrder C)
    {c d : C} (f : c ⟶ d) (x : P.Fiber d) :
    (projection P).IsCartesian f (cartesianLift P f x) ∧
      Pseudofunctor.CoGrothendieck.domainCartesianLift
        (F := toCatPseudofunctor P) x f = totalObj P c (P.reindex f x) := by
  constructor
  · letI : (projection P).IsStronglyCartesian f (cartesianLift P f x) :=
      cartesianLift_isStronglyCartesian P f x
    exact Functor.IsStronglyCartesian.isCartesian_of_isStronglyCartesian
      (projection P) f (cartesianLift P f x)
  · rfl

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The original thin category maps to the standard fiber of the projection. -/
abbrev fiberFunctor (P : SplitIndexedOrder C) (c : C) :
    P.Fiber c ⥤ (projection P).Fiber c :=
  CategoryTheory.Functor.Fiber.inducedFunctor
    (Pseudofunctor.CoGrothendieck.comp_const (toCatPseudofunctor P) c)

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- The standard fiber category of the projection is equivalent to the original
partial order regarded as a thin category. -/
theorem fiberFunctor_isEquivalence (P : SplitIndexedOrder C) (c : C) :
    (fiberFunctor P c).IsEquivalence := by
  exact HasFibers.equiv c

-- LeanTest/HardProblems/GrothendieckFibration.lean
/-- Goal 4 in explicit categorical form. -/
noncomputable def fiberEquiv (P : SplitIndexedOrder C) (c : C) :
    P.Fiber c ≌ (projection P).Fiber c := by
  letI : (fiberFunctor P c).IsEquivalence := fiberFunctor_isEquivalence P c
  exact (fiberFunctor P c).asEquivalence
Peripheral formal experiment: boundaries as closure operators (BoundaryClosures.lean)run

HardProblems.ClosureUnification.reachSet, HardProblems.ClosureUnification.reachClosure, HardProblems.ClosureUnification.reachSet_insert_programmed, HardProblems.ClosureUnification.exists_strict_enlargement, HardProblems.ClosureUnification.indistSaturation, HardProblems.ClosureUnification.indistClosure, HardProblems.ClosureUnification.indistClosure_le_of_refines, HardProblems.ClosureUnification.behavioralClosure, HardProblems.ClosureUnification.hide_interconnect_subset_and_strict, HardProblems.ClosureUnification.ReindexCommutes, HardProblems.ClosureUnification.addFalseClosure, HardProblems.ClosureUnification.reindex_closure_need_not_commute, HardProblems.ClosureUnification.reachSet_insert_const_true_strict, HardProblems.ClosureUnification.reach_agrees, HardProblems.ClosureUnification.indist_agrees, HardProblems.ClosureUnification.hide_agrees, HardProblems.ClosureUnification.programmed_agrees, HardProblems.ClosureUnification.robustActions_agrees, HardProblems.ClosureUnification.interconnect_agrees

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The set of states reachable from a set of starting states. -/
def reachSet {X : Type u} (G : Set (X → X)) (S : Set X) : Set X :=
  {z | ∃ x ∈ S, Reach G x z}

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Goal 1. `reachSet G` is a closure operator on `Set X`. -/
def reachClosure {X : Type u} (G : Set (X → X)) : ClosureOperator (Set X) where
  toFun := reachSet G
  monotone' := by
    intro S T hST z hz
    rcases hz with ⟨x, hxS, hxz⟩
    exact ⟨x, hST hxS, hxz⟩
  le_closure' := by
    intro S x hx
    exact ⟨x, hx, .refl⟩
  idempotent' := by
    intro S
    apply Set.Subset.antisymm
    · rintro z ⟨y, ⟨x, hx, hxy⟩, hyz⟩
      exact ⟨x, hx, hxy.trans hyz⟩
    · rintro z hz
      exact ⟨z, hz, .refl⟩

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Goal 2. A programmed transformation adds no reachability. -/
theorem reachSet_insert_programmed {X : Type u} (G : Set (X → X))
    {g : X → X} (hg : Programmed G g) (S : Set X) :
    reachSet (insert g G) S = reachSet G S := by
  apply Set.Subset.antisymm
  · rintro z ⟨x, hx, hreach⟩
    exact ⟨x, hx, hreach.insert_programmed hg⟩
  · rintro z ⟨x, hx, hreach⟩
    exact ⟨x, hx, by
      induction hreach with
      | refl => exact .refl
      | tail hstep hmem hz ih => exact .tail ih (Set.mem_insert_of_mem _ hmem) hz⟩

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Goal 3. The concrete two-state system `Bool`, with no old primitives,
initial state `false`, and the new constant-`true` primitive, strictly enlarges
reachable closure. -/
theorem exists_strict_enlargement :
    ∃ (X : Type) (G : Set (X → X)) (g : X → X) (S : Set X),
      reachSet G S ⊂ reachSet (insert g G) S := by
  refine ⟨Bool, ∅, (fun _ => true), {false}, ?_⟩
  constructor
  · rintro z ⟨x, hx, hreach⟩
    exact ⟨x, hx, by
      induction hreach with
      | refl => exact .refl
      | tail hstep hmem hz => exact False.elim hmem⟩
  · intro hreverse
    have htrue : true ∈ reachSet (insert (fun _ : Bool => true) ∅) {false} :=
      ⟨false, by simp,
        Reach.tail (g := fun _ : Bool => true) Reach.refl (by simp) rfl⟩
    have hold : true ∈ reachSet (∅ : Set (Bool → Bool)) {false} := hreverse htrue
    rcases hold with ⟨x, hx, hreach⟩
    have hxfalse : x = false := by simpa using hx
    subst x
    have hempty : ∀ z : Bool, Reach (∅ : Set (Bool → Bool)) false z → z = false := by
      intro z hz
      induction hz with
      | refl => rfl
      | tail hstep hmem heq => exact False.elim hmem
    have : true = false := hempty true hreach
    cases this

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Saturation of states under equality of observations. -/
def indistSaturation {S : Type u} {O : Type v} (observe : S → O)
    (T : Set S) : Set S :=
  {y | ∃ x ∈ T, Indist observe x y}

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Goal 4. Saturation under observational indistinguishability is a closure
operator on `Set S`. -/
def indistClosure {S : Type u} {O : Type v} (observe : S → O) :
    ClosureOperator (Set S) where
  toFun := indistSaturation observe
  monotone' := by
    rintro A B h y ⟨x, hx, hxy⟩
    exact ⟨x, h hx, hxy⟩
  le_closure' := by
    intro A x hx
    exact ⟨x, hx, rfl⟩
  idempotent' := by
    intro A
    apply Set.Subset.antisymm
    · rintro y ⟨x, ⟨z, hz, hzx⟩, hxy⟩
      exact ⟨z, hz, hzx.trans hxy⟩
    · intro y hy
      exact ⟨y, hy, rfl⟩

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Goal 4'. If `coarse = k ∘ fine`, fine observational saturation is contained
in coarse observational saturation: a finer experiment separates at least as
many states. -/
theorem indistClosure_le_of_refines {S : Type u} {F : Type v} {Cc : Type w}
    (fine : S → F) (coarse : S → Cc) (k : F → Cc) (hk : coarse = k ∘ fine) :
    ∀ T : Set S, indistClosure fine T ⊆ indistClosure coarse T := by
  intro T y hy
  rcases hy with ⟨x, hx, hxy⟩
  refine ⟨x, hx, ?_⟩
  show coarse x = coarse y
  rw [hk]
  exact congrArg k hxy

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Pulling a hidden behavior back along the trajectory projection gives a
closure operator on behaviors. -/
def behavioralClosure {T : Type u} {W : Type v} {V : Type w} (f : W → V) :
    ClosureOperator (Behavior T W) where
  toFun B := {w | f ∘ w ∈ hide f B}
  monotone' := by
    rintro B C h w ⟨w', hw', heq⟩
    exact ⟨w', h hw', heq⟩
  le_closure' := by
    intro B w hw
    exact ⟨w, hw, rfl⟩
  idempotent' := by
    intro B
    apply Set.Subset.antisymm
    · rintro w ⟨w', ⟨w'', hw'', heq'⟩, heq⟩
      exact ⟨w'', hw'', heq'.trans heq⟩
    · intro w hw
      exact ⟨w, hw, rfl⟩

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Goal 5. Hiding after interconnection is always contained in interconnecting
after hiding. The displayed `Bool`/`Unit` example makes this inclusion strict,
so hiding is not a meet (lattice) homomorphism. -/
theorem hide_interconnect_subset_and_strict :
    (∀ {T W V : Type} (f : W → V) (B₁ B₂ : Behavior T W),
      hide f (interconnect B₁ B₂) ⊆ interconnect (hide f B₁) (hide f B₂)) ∧
    (let B₁ : Behavior Unit Bool := {w | w () = false}
     let B₂ : Behavior Unit Bool := {w | w () = true}
     hide (fun _ : Bool => ()) (interconnect B₁ B₂) ⊂
       interconnect (hide (fun _ : Bool => ()) B₁)
         (hide (fun _ : Bool => ()) B₂)) := by
  constructor
  · intro T W V f B₁ B₂ v hv
    rcases hv with ⟨w, ⟨hw₁, hw₂⟩, rfl⟩
    exact ⟨⟨w, hw₁, rfl⟩, ⟨w, hw₂, rfl⟩⟩
  · dsimp
    constructor
    · intro v hv
      rcases hv with ⟨w, ⟨hw₁, hw₂⟩, rfl⟩
      exact ⟨⟨w, hw₁, rfl⟩, ⟨w, hw₂, rfl⟩⟩
    · intro hreverse
      let v : Unit → Unit := fun _ => ()
      have hv : v ∈ interconnect
          (hide (fun _ : Bool => ()) {w : Unit → Bool | w () = false})
          (hide (fun _ : Bool => ()) {w : Unit → Bool | w () = true}) := by
        constructor
        · exact ⟨(fun _ => false), rfl, rfl⟩
        · exact ⟨(fun _ => true), rfl, rfl⟩
      have hv' := hreverse hv
      rcases hv' with ⟨w, ⟨hwf, hwt⟩, _⟩
      simp only [Set.mem_setOf_eq] at hwf hwt
      rw [hwf] at hwt
      contradiction

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- A reindexing order homomorphism commutes with two fiberwise closures when
the two possible composites agree pointwise. -/
def ReindexCommutes {P : Type u} {Q : Type v} [Preorder P] [Preorder Q]
    (r : Q →o P) (cQ : ClosureOperator Q) (cP : ClosureOperator P) : Prop :=
  ∀ x, r (cQ x) = cP (r x)

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The closure on `Set Bool` that adjoins `false`. -/
def addFalseClosure : ClosureOperator (Set Bool) where
  toFun S := S ∪ {false}
  monotone' := by
    intro A B h x hx
    exact hx.elim (fun hxA => Or.inl (h hxA)) Or.inr
  le_closure' := by
    intro A x hx
    exact Or.inl hx
  idempotent' := by
    intro A
    ext x
    simp only [Set.mem_union, Set.mem_singleton_iff]
    tauto

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- Reindexing by inverse image along the map `Unit → Bool` selecting `false`
does not commute with `addFalseClosure` and the identity closure on `Set Unit`.
Both carriers are nonempty, nontrivial finite posets. -/
theorem reindex_closure_need_not_commute :
    let r : Set Bool →o Set Unit :=
      { toFun := Set.preimage (fun _ : Unit => false)
        monotone' := by intro A B h; exact Set.preimage_mono h }
    ¬ ReindexCommutes r addFalseClosure (ClosureOperator.id (Set Unit)) := by
  intro r h
  have heq := h (∅ : Set Bool)
  have hunit : () ∈ r (addFalseClosure (∅ : Set Bool)) := Or.inr rfl
  rw [heq] at hunit
  exact hunit

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The strict enlargement of Goal 3, restated with its witness in the
statement rather than behind an existential: adjoining the constant-`true`
move to the empty move set strictly enlarges what is reachable from
`{false}`. -/
theorem reachSet_insert_const_true_strict :
    reachSet (∅ : Set (Bool → Bool)) {false} ⊂
      reachSet (insert (fun _ => true) (∅ : Set (Bool → Bool))) {false} := by
  constructor
  · rintro z ⟨x, hx, h⟩
    refine ⟨x, hx, ?_⟩
    induction h with
    | refl => exact Reach.refl
    | tail _ hg hz ih => exact Reach.tail ih (Set.mem_insert_of_mem _ hg) hz
  · intro hrev
    have htrue : true ∈
        reachSet (insert (fun _ => true) (∅ : Set (Bool → Bool))) {false} :=
      ⟨false, rfl, Reach.tail Reach.refl (Set.mem_insert _ _) rfl⟩
    rcases hrev htrue with ⟨x, hx, h⟩
    cases h with
    | refl => simp at hx
    | tail _ hg _ => simp at hg

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The local `Reach` is the project's `Reach`, definitionally. -/
theorem reach_agrees {X : Type u} (G : Set (X → X)) (x z : X) :
    ClosureUnification.Reach G x z ↔ HardProblems.Reach G x z := by
  constructor
  · intro h
    induction h with
    | refl => exact HardProblems.Reach.refl
    | tail hxy hg hz ih => exact HardProblems.Reach.tail ih hg hz
  · intro h
    induction h with
    | refl => exact ClosureUnification.Reach.refl
    | tail hxy hg hz ih => exact ClosureUnification.Reach.tail ih hg hz

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The local `Indist` is `InformationOrder.Indist`, definitionally. -/
theorem indist_agrees {S : Type u} {O : Type v} (observe : S → O) (x y : S) :
    ClosureUnification.Indist observe x y ↔
      InformationOrder.Indist observe x y :=
  Iff.rfl

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The local `hide` is `Behavioral.hide`, definitionally. -/
theorem hide_agrees {T : Type u} {W : Type v} {V : Type w}
    (f : W → V) (B : ClosureUnification.Behavior T W) :
    ClosureUnification.hide f B = Behavioral.hide f B := by
  rfl

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The local `Programmed` is the project's `Programmed`: both quantify the
respective `Reach`, and `reach_agrees` bridges those. -/
theorem programmed_agrees {X : Type u} (G : Set (X → X)) (g : X → X) :
    ClosureUnification.Programmed G g ↔ HardProblems.Programmed G g := by
  constructor
  · intro h y
    exact (reach_agrees G y (g y)).mp (h y)
  · intro h y
    exact (reach_agrees G y (g y)).mpr (h y)

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The local `RobustActions` is `InformationOrder.RobustActions`,
definitionally. -/
theorem robustActions_agrees {S : Type u} {O : Type v} {A : Type w}
    (observe : S → O) (Acceptable : S → A → Prop) (x : S) :
    ClosureUnification.RobustActions observe Acceptable x =
      InformationOrder.RobustActions observe Acceptable x :=
  rfl

-- LeanTest/HardProblems/BoundaryClosures.lean
/-- The local `interconnect` is `Behavioral.interconnect`, definitionally. -/
theorem interconnect_agrees {T : Type u} {W : Type v}
    (B₁ B₂ : ClosureUnification.Behavior T W) :
    ClosureUnification.interconnect B₁ B₂ = Behavioral.interconnect B₁ B₂ :=
  rfl
Peripheral formal experiment: discrete Stokes and coarse boundary transport (DiscreteStokes.lean)run

HardProblems.DiscreteStokes.DirectedComplex, HardProblems.DiscreteStokes.ComplexMap, HardProblems.DiscreteStokes.ZeroCochain, HardProblems.DiscreteStokes.OneCochain, HardProblems.DiscreteStokes.ZeroChain, HardProblems.DiscreteStokes.OneChain, HardProblems.DiscreteStokes.pair, HardProblems.DiscreteStokes.coboundary, HardProblems.DiscreteStokes.boundary, HardProblems.DiscreteStokes.pushForward, HardProblems.DiscreteStokes.discrete_stokes, HardProblems.DiscreteStokes.pair_coboundary_eq_zero_of_boundary_eq_zero, HardProblems.DiscreteStokes.coboundary_natural, HardProblems.DiscreteStokes.boundary_natural, HardProblems.DiscreteStokes.path_stokes

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- A directed one-dimensional cell complex. Parallel edges and loops are
allowed. -/
structure DirectedComplex where
  Vertex : Type u
  Edge : Type u
  source : Edge → Vertex
  target : Edge → Vertex

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- A map of directed complexes. It may identify vertices or edges, as a
coarse-graining does, but it must preserve incidence. -/
structure ComplexMap (K L : DirectedComplex) where
  onVertex : K.Vertex → L.Vertex
  onEdge : K.Edge → L.Edge
  map_source : ∀ e, onVertex (K.source e) = L.source (onEdge e)
  map_target : ∀ e, onVertex (K.target e) = L.target (onEdge e)

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Vertex observables: zero-cochains for the constant cellular sheaf. -/
abbrev ZeroCochain := K.Vertex → R

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Edge observables: one-cochains for the constant cellular sheaf. -/
abbrev OneCochain := K.Edge → R

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Finitely supported vertex flows: zero-chains for the constant cellular
cosheaf. -/
abbrev ZeroChain := K.Vertex →₀ R

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Finitely supported edge flows: one-chains for the constant cellular
cosheaf. -/
abbrev OneChain := K.Edge →₀ R

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Pair a cochain with a finitely supported chain. -/
def pair {X : Type*} (f : X → R) (c : X →₀ R) : R :=
  c.sum fun x a ↦ a * f x

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- The constant-sheaf coboundary of a vertex observable. -/
def coboundary (f : ZeroCochain K R) : OneCochain K R :=
  fun e ↦ f (K.target e) - f (K.source e)

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- The constant-cosheaf boundary of a finitely supported edge flow. -/
noncomputable def boundary (c : OneChain K R) : ZeroChain K R :=
  c.sum fun e a ↦
    Finsupp.single (K.target e) a - Finsupp.single (K.source e) a

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Aggregate a finitely supported chain along a possibly many-to-one map. -/
noncomputable def pushForward {X Y : Type*} (q : X → Y) (c : X →₀ R) : Y →₀ R :=
  Finsupp.mapDomain q c

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Discrete Stokes with constant coefficients: accumulated interior change
equals the observable evaluated on net boundary flow. -/
theorem discrete_stokes (f : ZeroCochain K R) (c : OneChain K R) :
    pair R (coboundary K R f) c = pair R f (boundary K R c) := by
  classical
  unfold pair boundary coboundary
  rw [Finsupp.sum_sum_index]
  · apply Finsupp.sum_congr
    intro e _
    rw [Finsupp.sum_sub_index (fun _ _ _ ↦ sub_mul _ _ _)]
    simp [mul_sub]
  · intro vertex
    simp
  · intro vertex a b
    simp [add_mul]

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- A flow with no exposed boundary pairs to zero with every exact local
change. This is the closed-cycle corollary of discrete Stokes. -/
theorem pair_coboundary_eq_zero_of_boundary_eq_zero
    (f : ZeroCochain K R) (c : OneChain K R)
    (hc : boundary K R c = 0) :
    pair R (coboundary K R f) c = 0 := by
  rw [discrete_stokes K R f c, hc]
  simp [pair]

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Pulling back a coarse observable and then taking its coboundary is the
same as taking the coarse coboundary and pulling it back to fine edges. -/
theorem coboundary_natural {L : DirectedComplex} (F : ComplexMap K L)
    (f : ZeroCochain L R) :
    coboundary K R (f ∘ F.onVertex) = coboundary L R f ∘ F.onEdge := by
  funext e
  simp [coboundary, F.map_source, F.map_target]

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- Net boundary flow commutes with incidence-preserving coarse-graining. -/
theorem boundary_natural {L : DirectedComplex} (F : ComplexMap K L)
    (c : OneChain K R) :
    pushForward R F.onVertex (boundary K R c) =
      boundary L R (pushForward R F.onEdge c) := by
  classical
  unfold pushForward boundary
  change (Finsupp.mapDomain.addMonoidHom F.onVertex)
      (c.sum fun e a ↦
        Finsupp.single (K.target e) a - Finsupp.single (K.source e) a) = _
  rw [map_finsuppSum (Finsupp.mapDomain.addMonoidHom F.onVertex) c,
    Finsupp.sum_mapDomain_index]
  · apply Finsupp.sum_congr
    intro e _
    simp [Finsupp.mapDomain_sub, F.map_source, F.map_target]
  · intro e
    simp
  · intro e a b
    simp [add_sub_add_comm]

-- LeanTest/HardProblems/DiscreteStokes.lean
/-- The path form of one-dimensional Stokes: exact local increments telescope
to the difference of the endpoint potentials. -/
theorem path_stokes (potential : K.Vertex → R) (x : ℕ → K.Vertex) (n : ℕ) :
    ∑ i ∈ Finset.range n,
        (potential (x (i + 1)) - potential (x i)) =
      potential (x n) - potential (x 0) := by
  induction n with
  | zero => simp
  | succ n ih =>
      rw [Finset.sum_range_succ, ih]
      ring
Peripheral formal experiment: higher-dimensional Stokes and boundary defects (HigherStokes.lean)run

HardProblems.HigherStokes.GradedComplex, HardProblems.HigherStokes.Cochain, HardProblems.HigherStokes.pair, HardProblems.HigherStokes.coboundary, HardProblems.HigherStokes.stokes, HardProblems.HigherStokes.surface_stokes_of_hodge_curl, HardProblems.HigherStokes.coboundary_coboundary, HardProblems.HigherStokes.IsCycle, HardProblems.HigherStokes.IsBoundary, HardProblems.HigherStokes.Homologous, HardProblems.HigherStokes.isCycle_of_isBoundary, HardProblems.HigherStokes.pair_coboundary_eq_zero_of_isCycle, HardProblems.HigherStokes.ChainMap, HardProblems.HigherStokes.pullback, HardProblems.HigherStokes.coboundary_natural, HardProblems.HigherStokes.ChainMap.map_isCycle, HardProblems.HigherStokes.ChainMap.map_isBoundary, HardProblems.HigherStokes.ChainMap.map_homologous, HardProblems.HigherStokes.boundaryDefect, HardProblems.HigherStokes.boundaryDefect_apply, HardProblems.HigherStokes.boundaryDefect_eq_zero_iff, HardProblems.HigherStokes.ChainMap.boundaryDefect_eq_zero, HardProblems.HigherStokes.boundary_image_eq_neg_defect_of_isCycle, HardProblems.HigherStokes.pair_boundaryDefect, HardProblems.HigherStokes.gradedPullback, HardProblems.HigherStokes.pairingDefect, HardProblems.HigherStokes.pairingDefect_gradedPullback_eq_zero, HardProblems.HigherStokes.coboundaryTransportDefect, HardProblems.HigherStokes.pair_coboundaryTransportDefect_gradedPullback, HardProblems.HigherStokes.taskDefect, HardProblems.HigherStokes.taskDefect_eq_neg_pairingDefect_add, HardProblems.HigherStokes.integerZeroComplex, HardProblems.HigherStokes.integerIdentityMap, HardProblems.HigherStokes.integerZeroObservationMap, HardProblems.HigherStokes.integerOneChain, HardProblems.HigherStokes.boundary_exact_but_pairing_defective, HardProblems.HigherStokes.pairing_exact_but_task_defective, HardProblems.HigherStokes.CellularComplex, HardProblems.HigherStokes.CellularComplex.toGradedComplex, HardProblems.HigherStokes.CellularComplex.incidence, HardProblems.HigherStokes.CellularComplex.boundary_incidence_eq_zero

-- LeanTest/HardProblems/HigherStokes.lean
/-- A nonnegatively graded chain complex, indexed so that `boundary k` maps
degree `k + 1` to degree `k`. -/
structure GradedComplex (R : Type v) [CommRing R] where
  Chain : ℕ → Type u
  [chainAddCommGroup : ∀ k, AddCommGroup (Chain k)]
  [chainModule : ∀ k, Module R (Chain k)]
  boundary : ∀ k, Chain (k + 1) →ₗ[R] Chain k
  boundary_boundary : ∀ k (c : Chain (k + 2)),
    boundary k (boundary (k + 1) c) = 0

-- LeanTest/HardProblems/HigherStokes.lean
/-- Degree-`k` cochains are linear observations on degree-`k` chains. -/
abbrev Cochain (K : GradedComplex R) (k : ℕ) := K.Chain k →ₗ[R] R

-- LeanTest/HardProblems/HigherStokes.lean
/-- Evaluation pairing between a cochain and a chain. -/
def pair (K : GradedComplex R) {k : ℕ} (φ : Cochain K k) (c : K.Chain k) : R :=
  φ c

-- LeanTest/HardProblems/HigherStokes.lean
/-- Coboundary is dual to boundary. -/
def coboundary (K : GradedComplex R) (k : ℕ) (φ : Cochain K k) :
    Cochain K (k + 1) :=
  φ.comp (K.boundary k)

-- LeanTest/HardProblems/HigherStokes.lean
/-- Higher-dimensional Stokes: accumulated coboundary on a chain equals the
original observation evaluated on the chain's exposed boundary. -/
theorem stokes (K : GradedComplex R) (k : ℕ) (φ : Cochain K k)
    (c : K.Chain (k + 1)) :
    pair K (coboundary K k φ) c = pair K φ (K.boundary k c) := by
  rfl

-- LeanTest/HardProblems/HigherStokes.lean
/-- Conditional circulation--flux form of Stokes.  In a geometric model one
may take `ωF` to be the one-form dual to a vector field and `starCurl` to be
the two-form obtained by applying the Hodge star to the one-form dual to its
curl.  Once the geometric identity `starCurl = coboundary K 1 ωF` is supplied,
the flux through a two-chain equals circulation around its boundary.

This theorem deliberately does not construct a metric, a Hodge star, or a
smooth curl operator. -/
theorem surface_stokes_of_hodge_curl (K : GradedComplex R)
    (ωF : Cochain K 1) (starCurl : Cochain K 2)
    (hcurl : starCurl = coboundary K 1 ωF) (surface : K.Chain 2) :
    pair K ωF (K.boundary 1 surface) = pair K starCurl surface := by
  rw [hcurl, stokes]

-- LeanTest/HardProblems/HigherStokes.lean
/-- The dual differential squares to zero because boundary squares to zero. -/
theorem coboundary_coboundary (K : GradedComplex R) (k : ℕ)
    (φ : Cochain K k) :
    coboundary K (k + 1) (coboundary K k φ) = 0 := by
  ext c
  change φ (K.boundary k (K.boundary (k + 1) c)) = 0
  rw [K.boundary_boundary]
  exact map_zero φ

-- LeanTest/HardProblems/HigherStokes.lean
/-- A positive-degree cycle is a chain with no exposed boundary. -/
def IsCycle (K : GradedComplex R) (k : ℕ) (c : K.Chain (k + 1)) : Prop :=
  K.boundary k c = 0

-- LeanTest/HardProblems/HigherStokes.lean
/-- A positive-degree boundary is the boundary of a chain one degree higher. -/
def IsBoundary (K : GradedComplex R) (k : ℕ) (c : K.Chain (k + 1)) : Prop :=
  ∃ b : K.Chain (k + 2), K.boundary (k + 1) b = c

-- LeanTest/HardProblems/HigherStokes.lean
/-- Two positive-degree chains are homologous when their difference is an
exposed boundary one degree higher. -/
def Homologous (K : GradedComplex R) (k : ℕ)
    (c d : K.Chain (k + 1)) : Prop :=
  ∃ b : K.Chain (k + 2), K.boundary (k + 1) b = c - d

-- LeanTest/HardProblems/HigherStokes.lean
/-- Every boundary is a cycle: the boundary of a boundary vanishes. -/
theorem isCycle_of_isBoundary (K : GradedComplex R) (k : ℕ)
    {c : K.Chain (k + 1)} (hc : IsBoundary K k c) : IsCycle K k c := by
  rcases hc with ⟨b, rfl⟩
  exact K.boundary_boundary k b

-- LeanTest/HardProblems/HigherStokes.lean
/-- Exact cochains vanish on cycles. -/
theorem pair_coboundary_eq_zero_of_isCycle (K : GradedComplex R) (k : ℕ)
    (φ : Cochain K k) {c : K.Chain (k + 1)} (hc : IsCycle K k c) :
    pair K (coboundary K k φ) c = 0 := by
  rw [stokes, hc]
  exact map_zero φ

-- LeanTest/HardProblems/HigherStokes.lean
/-- A degree-preserving coarse-graining is exact for boundary accounting when
it is a chain map.  Its components may identify or linearly aggregate cells. -/
structure ChainMap (K L : GradedComplex R) where
  map : ∀ k, K.Chain k →ₗ[R] L.Chain k
  commutes : ∀ k (c : K.Chain (k + 1)),
    map k (K.boundary k c) = L.boundary k (map (k + 1) c)

-- LeanTest/HardProblems/HigherStokes.lean
/-- Pull a coarse cochain back to the fine complex. -/
def pullback {K L : GradedComplex R} (F : ChainMap K L) (k : ℕ)
    (φ : Cochain L k) : Cochain K k :=
  φ.comp (F.map k)

-- LeanTest/HardProblems/HigherStokes.lean
/-- Pullback along a chain map commutes with coboundary in every degree. -/
theorem coboundary_natural {K L : GradedComplex R} (F : ChainMap K L)
    (k : ℕ) (φ : Cochain L k) :
    coboundary K k (pullback F k φ) =
      pullback F (k + 1) (coboundary L k φ) := by
  ext c
  change φ (F.map k (K.boundary k c)) =
    φ (L.boundary k (F.map (k + 1) c))
  rw [F.commutes]

-- LeanTest/HardProblems/HigherStokes.lean
/-- Exact coarse-graining sends cycles to cycles. -/
theorem ChainMap.map_isCycle {K L : GradedComplex R} (F : ChainMap K L)
    (k : ℕ) {c : K.Chain (k + 1)} (hc : IsCycle K k c) :
    IsCycle L k (F.map (k + 1) c) := by
  unfold IsCycle at hc ⊢
  rw [← F.commutes, hc]
  exact map_zero (F.map k)

-- LeanTest/HardProblems/HigherStokes.lean
/-- Exact coarse-graining sends boundaries to boundaries. -/
theorem ChainMap.map_isBoundary {K L : GradedComplex R} (F : ChainMap K L)
    (k : ℕ) {c : K.Chain (k + 1)} (hc : IsBoundary K k c) :
    IsBoundary L k (F.map (k + 1) c) := by
  rcases hc with ⟨b, rfl⟩
  exact ⟨F.map (k + 2) b, (F.commutes (k + 1) b).symm⟩

-- LeanTest/HardProblems/HigherStokes.lean
/-- Chain maps respect the boundary equivalence used to form homology. -/
theorem ChainMap.map_homologous {K L : GradedComplex R} (F : ChainMap K L)
    (k : ℕ) {c d : K.Chain (k + 1)} (hcd : Homologous K k c d) :
    Homologous L k (F.map (k + 1) c) (F.map (k + 1) d) := by
  rcases hcd with ⟨b, hb⟩
  refine ⟨F.map (k + 2) b, ?_⟩
  rw [← F.commutes, hb, map_sub]

-- LeanTest/HardProblems/HigherStokes.lean
/-- The degree-`k` boundary defect of an arbitrary graded linear
coarse-graining.  It is zero exactly when the boundary square commutes in that
degree. -/
def boundaryDefect {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k) (k : ℕ) :
    K.Chain (k + 1) →ₗ[R] L.Chain k :=
  (q k).comp (K.boundary k) - (L.boundary k).comp (q (k + 1))

-- LeanTest/HardProblems/HigherStokes.lean
theorem boundaryDefect_apply {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k) (k : ℕ)
    (c : K.Chain (k + 1)) :
    boundaryDefect q k c =
      q k (K.boundary k c) - L.boundary k (q (k + 1) c) := by
  rfl

-- LeanTest/HardProblems/HigherStokes.lean
/-- Vanishing defect is exactly the chain-map equation in one degree. -/
theorem boundaryDefect_eq_zero_iff {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k) (k : ℕ) :
    boundaryDefect q k = 0 ↔
      ∀ c : K.Chain (k + 1),
        q k (K.boundary k c) = L.boundary k (q (k + 1) c) := by
  constructor
  · intro h c
    have hc := LinearMap.congr_fun h c
    simpa [boundaryDefect, sub_eq_zero] using hc
  · intro h
    ext c
    simpa [boundaryDefect, sub_eq_zero] using h c

-- LeanTest/HardProblems/HigherStokes.lean
/-- A chain map has zero boundary defect in every degree. -/
theorem ChainMap.boundaryDefect_eq_zero {K L : GradedComplex R}
    (F : ChainMap K L) (k : ℕ) :
    boundaryDefect F.map k = 0 := by
  exact (boundaryDefect_eq_zero_iff F.map k).2 (F.commutes k)

-- LeanTest/HardProblems/HigherStokes.lean
/-- On a fine cycle, the defect is exactly the negative boundary charge that
appears after coarse-graining. -/
theorem boundary_image_eq_neg_defect_of_isCycle {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k) (k : ℕ)
    {c : K.Chain (k + 1)} (hc : IsCycle K k c) :
    L.boundary k (q (k + 1) c) = -boundaryDefect q k c := by
  rw [boundaryDefect_apply, hc, map_zero]
  simp

-- LeanTest/HardProblems/HigherStokes.lean
/-- Pairing an observable with the boundary defect gives exactly the mismatch
between fine-then-coarse and coarse-then-boundary accounting. -/
theorem pair_boundaryDefect {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k) (k : ℕ)
    (φ : Cochain L k) (c : K.Chain (k + 1)) :
    pair L φ (q k (K.boundary k c)) -
        pair K ((coboundary L k φ).comp (q (k + 1))) c =
      pair L φ (boundaryDefect q k c) := by
  change φ (q k (K.boundary k c)) -
      φ (L.boundary k (q (k + 1) c)) =
    φ (q k (K.boundary k c) - L.boundary k (q (k + 1) c))
  exact (map_sub φ _ _).symm

-- LeanTest/HardProblems/HigherStokes.lean
/-- The canonical transport of observations along an arbitrary graded chain
map.  This operation is available even when `q` has a nonzero boundary defect:
it is just precomposition degree by degree. -/
def gradedPullback {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k) :
    ∀ k, Cochain L k →ₗ[R] Cochain K k :=
  fun k =>
    { toFun := fun φ => φ.comp (q k)
      map_add' := by
        intro φ ψ
        ext c
        rfl
      map_smul' := by
        intro r φ
        ext c
        rfl }

-- LeanTest/HardProblems/HigherStokes.lean
/-- Failure of a declared observation transport to be dual to the declared
chain aggregation.  It is intentionally separate from `boundaryDefect`. -/
def pairingDefect {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k)
    (qObs : ∀ k, Cochain L k →ₗ[R] Cochain K k)
    (k : ℕ) (φ : Cochain L k) (c : K.Chain k) : R :=
  pair K (qObs k φ) c - pair L φ (q k c)

-- LeanTest/HardProblems/HigherStokes.lean
/-- Canonical pullback and chain aggregation are exactly adjoint, independently
of whether aggregation commutes with boundary. -/
@[simp] theorem pairingDefect_gradedPullback_eq_zero {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k)
    (k : ℕ) (φ : Cochain L k) (c : K.Chain k) :
    pairingDefect q (gradedPullback q) k φ c = 0 := by
  simp [pairingDefect, gradedPullback, pair]

-- LeanTest/HardProblems/HigherStokes.lean
/-- Failure of a declared observation transport to commute with coboundary. -/
def coboundaryTransportDefect {K L : GradedComplex R}
    (qObs : ∀ k, Cochain L k →ₗ[R] Cochain K k)
    (k : ℕ) (φ : Cochain L k) : Cochain K (k + 1) :=
  coboundary K k (qObs k φ) - qObs (k + 1) (coboundary L k φ)

-- LeanTest/HardProblems/HigherStokes.lean
/-- For canonical pullback, the coboundary-transport defect is precisely dual
to the boundary defect.  An arbitrary observation transport need not enjoy
this relation. -/
theorem pair_coboundaryTransportDefect_gradedPullback
    {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k)
    (k : ℕ) (φ : Cochain L k) (c : K.Chain (k + 1)) :
    pair K
        (coboundaryTransportDefect (gradedPullback q) k φ) c =
      pair L φ (boundaryDefect q k c) := by
  change φ (q k (K.boundary k c)) -
      φ (L.boundary k (q (k + 1) c)) =
    φ (q k (K.boundary k c) - L.boundary k (q (k + 1) c))
  exact (map_sub φ _ _).symm

-- LeanTest/HardProblems/HigherStokes.lean
/-- Failure of a declared task observable to be preserved by aggregation. -/
def taskDefect {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k) (k : ℕ)
    (JFine : Cochain K k) (JCoarse : Cochain L k) (c : K.Chain k) : R :=
  pair L JCoarse (q k c) - pair K JFine c

-- LeanTest/HardProblems/HigherStokes.lean
/-- Task mismatch decomposes into failure of pairing duality plus the mismatch
between the declared fine task and the transported coarse task. -/
theorem taskDefect_eq_neg_pairingDefect_add {K L : GradedComplex R}
    (q : ∀ k, K.Chain k →ₗ[R] L.Chain k)
    (qObs : ∀ k, Cochain L k →ₗ[R] Cochain K k)
    (k : ℕ) (JFine : Cochain K k) (JCoarse : Cochain L k)
    (c : K.Chain k) :
    taskDefect q k JFine JCoarse c =
      -pairingDefect q qObs k JCoarse c +
        pair K (qObs k JCoarse - JFine) c := by
  change JCoarse (q k c) - JFine c =
    -(qObs k JCoarse c - JCoarse (q k c)) +
      (qObs k JCoarse c - JFine c)
  abel

-- LeanTest/HardProblems/HigherStokes.lean
/-- A chain complex used to witness that the three defect notions are
logically independent.  Every chain group is `ℤ` and every boundary is zero. -/
def integerZeroComplex : GradedComplex ℤ where
  Chain _ := ℤ
  boundary _ := 0
  boundary_boundary := by simp

-- LeanTest/HardProblems/HigherStokes.lean
/-- Identity aggregation on `integerZeroComplex`. -/
def integerIdentityMap :
    ∀ k, integerZeroComplex.Chain k →ₗ[ℤ] integerZeroComplex.Chain k :=
  fun _ => LinearMap.id

-- LeanTest/HardProblems/HigherStokes.lean
/-- A deliberately wrong observation transport: it discards every cochain. -/
def integerZeroObservationMap :
    ∀ k, Cochain integerZeroComplex k →ₗ[ℤ] Cochain integerZeroComplex k :=
  fun _ => 0

-- LeanTest/HardProblems/HigherStokes.lean
/-- The unit chain in degree zero of `integerZeroComplex`. -/
def integerOneChain : integerZeroComplex.Chain 0 := by
  change ℤ
  exact 1

-- LeanTest/HardProblems/HigherStokes.lean
/-- Exact boundary transport does not force an independently declared
observation transport to preserve the pairing. -/
theorem boundary_exact_but_pairing_defective :
    (∀ k, boundaryDefect integerIdentityMap k = 0) ∧
      pairingDefect integerIdentityMap integerZeroObservationMap 0
        (LinearMap.id : ℤ →ₗ[ℤ] ℤ) integerOneChain ≠ 0 := by
  constructor
  · intro k
    apply (boundaryDefect_eq_zero_iff integerIdentityMap k).2
    intro c
    change (0 : ℤ) = 0
    rfl
  · change (-(1 : ℤ)) ≠ 0
    norm_num

-- LeanTest/HardProblems/HigherStokes.lean
/-- Even exact canonical pairing transport does not preserve a separately
declared task observable. -/
theorem pairing_exact_but_task_defective :
    (∀ (φ : Cochain integerZeroComplex 0)
        (c : integerZeroComplex.Chain 0),
      pairingDefect integerIdentityMap (gradedPullback integerIdentityMap)
        0 φ c = 0) ∧
      taskDefect integerIdentityMap 0 0
        (LinearMap.id : ℤ →ₗ[ℤ] ℤ) integerOneChain ≠ 0 := by
  constructor
  · intro φ c
    exact pairingDefect_gradedPullback_eq_zero integerIdentityMap 0 φ c
  · change (1 : ℤ) ≠ 0
    norm_num

-- LeanTest/HardProblems/HigherStokes.lean
/-- A free cellular chain complex with constant coefficients.  Each degree is
the free `R`-module on its cells; the supplied boundary maps encode oriented
incidence numbers. -/
structure CellularComplex (R : Type v) [CommRing R] where
  Cell : ℕ → Type u
  boundary : ∀ k, (Cell (k + 1) →₀ R) →ₗ[R] (Cell k →₀ R)
  boundary_boundary : ∀ k (c : Cell (k + 2) →₀ R),
    boundary k (boundary (k + 1) c) = 0

-- LeanTest/HardProblems/HigherStokes.lean
/-- Regard a constant-coefficient cellular complex as a graded chain complex. -/
noncomputable def CellularComplex.toGradedComplex
    (K : CellularComplex R) : GradedComplex R where
  Chain k := K.Cell k →₀ R
  boundary := K.boundary
  boundary_boundary := K.boundary_boundary

-- LeanTest/HardProblems/HigherStokes.lean
/-- The incidence column of a cell is its cellular boundary. -/
noncomputable def CellularComplex.incidence (K : CellularComplex R) (k : ℕ)
    (σ : K.Cell (k + 1)) : K.Cell k →₀ R :=
  K.boundary k (Finsupp.single σ 1)

-- LeanTest/HardProblems/HigherStokes.lean
/-- The incidence boundary of every cell is a cycle.  This is the cellular
column form of `boundary ∘ boundary = 0`. -/
theorem CellularComplex.boundary_incidence_eq_zero (K : CellularComplex R)
    (k : ℕ) (σ : K.Cell (k + 2)) :
    K.boundary k (K.incidence (k + 1) σ) = 0 := by
  exact K.boundary_boundary k (Finsupp.single σ 1)
Peripheral formal experiment: group completion forgets the order (KTheoryCollapse.lean)run

HardProblems.KTheoryCollapse.RegionMonoid, HardProblems.KTheoryCollapse.grothendieckGroup_subsingleton_of_idempotent, HardProblems.KTheoryCollapse.grothendieckGroup_regionMonoid_subsingleton, HardProblems.KTheoryCollapse.grothendieckGroup_of_eq_iff, HardProblems.KTheoryCollapse.toGrothendieckGroup_injective_of_cancel, HardProblems.KTheoryCollapse.concrete_regions_collapse, HardProblems.KTheoryCollapse.withTop_cost_top_add_image, HardProblems.KTheoryCollapse.saturating_costs_grothendieckAddGroup_subsingleton

-- LeanTest/HardProblems/KTheoryCollapse.lean
/-- Attainable-performance regions over a performance space `P`, composing by
union. -/
abbrev RegionMonoid (P : Type u) := Set P

-- LeanTest/HardProblems/KTheoryCollapse.lean
/-- Goal 1': the Grothendieck group of every commutative idempotent monoid is
trivial. -/
theorem grothendieckGroup_subsingleton_of_idempotent
    (M : Type u) [CommMonoid M] (hidem : ∀ a : M, a * a = a) :
    Subsingleton (GrothendieckGroup M) := by
  refine ⟨fun x y => ?_⟩
  -- We'll show all elements equal GrothendieckGroup.of 1
  suffices ∀ z : GrothendieckGroup M, z = GrothendieckGroup.of 1 by rw [this x, this y]
  intro z
  -- Use Quot.induction_on to work with representatives
  induction z using Quot.induction_on with
  | h p => 
    -- p : M × ⊤, need to show Quot.mk oreEqv p = 1
    let ⟨a, b⟩ := p
    -- Need to show Quot.mk oreEqv (a, b) = GrothendieckGroup.of 1
    -- First show GrothendieckGroup.of 1 = Quot.mk oreEqv (1, 1)
    have of_one_eq : GrothendieckGroup.of 1 = Quot.mk (OreLocalization.oreEqv ⊤ M) (1, 1) := by
      rfl
    rw [of_one_eq]
    -- Now use Quot.eq
    apply Quot.sound
    unfold OreLocalization.oreEqv
    -- Need ∃ u v, u • (1,1).1 = v • (a,b).1 ∧ u * (1,1).2 = v * (a,b).2
    -- i.e., ∃ u v, u = v * a ∧ u = v * b
    -- Take v = a * b, u = a * b
    refine ⟨⟨a * b, ?_⟩, a * b, ?_⟩
    · simp
    · constructor
      · -- ⟨a * ↑b, _⟩ • 1 = (a * ↑b) • a
        simp only [Submonoid.mk_smul, smul_eq_mul]
        rw [mul_one]
        conv_rhs => rw [mul_assoc, mul_comm, mul_assoc, hidem]
        rw [mul_comm]
      · -- ↑⟨a * ↑b, _⟩ * ↑(1,1).2 = a * ↑b * ↑(a,b).2
        simp [mul_one]
        rw [mul_assoc, hidem]

-- LeanTest/HardProblems/KTheoryCollapse.lean
/-- Goal 1: the Grothendieck group of the region monoid is trivial, for every
performance type `P` (including the empty type). -/
theorem grothendieckGroup_regionMonoid_subsingleton (P : Type u) :
    Subsingleton (GrothendieckGroup (RegionMonoid P)) := by
  apply grothendieckGroup_subsingleton_of_idempotent
  exact Set.union_self

-- LeanTest/HardProblems/KTheoryCollapse.lean
/-- Goal 2: canonical images are equal exactly when the two elements become
equal after multiplying by a common slack element. -/
theorem grothendieckGroup_of_eq_iff (M : Type u) [CommMonoid M] (a b : M) :
    GrothendieckGroup.of a = GrothendieckGroup.of b ↔
      ∃ c : M, a * c = b * c := by
  change Localization.mk a 1 = Localization.mk b 1 ↔ _
  rw [Localization.mk_eq_mk_iff, Localization.r_iff_exists]
  simp only [Submonoid.coe_one, one_mul]
  constructor
  · rintro ⟨c, hc⟩
    exact ⟨c, by simpa [mul_comm] using hc⟩
  · rintro ⟨c, hc⟩
    exact ⟨⟨c, Submonoid.mem_top c⟩, by simpa [mul_comm] using hc⟩

-- LeanTest/HardProblems/KTheoryCollapse.lean
/-- Goal 3: for a cancellative cost monoid, the canonical map is injective. -/
theorem toGrothendieckGroup_injective_of_cancel
    (M : Type u) [CancelCommMonoid M] :
    Function.Injective (GrothendieckGroup.of : M → GrothendieckGroup M) := by
  exact GrothendieckGroup.of_injective

-- LeanTest/HardProblems/KTheoryCollapse.lean
/-- Goal 4: the concrete regions `{true}` and `{false}` are distinct but have
the same image in the Grothendieck group. -/
theorem concrete_regions_collapse :
    ({true} : RegionMonoid Bool) ≠ {false} ∧
      GrothendieckGroup.of ({true} : RegionMonoid Bool) =
        GrothendieckGroup.of ({false} : RegionMonoid Bool) := by
  haveI : Subsingleton (GrothendieckGroup (RegionMonoid Bool)) :=
    grothendieckGroup_regionMonoid_subsingleton Bool
  refine ⟨?_, Subsingleton.elim _ _⟩
  simp [Set.eq_singleton_iff_unique_mem]

-- LeanTest/HardProblems/KTheoryCollapse.lean
/-- Goal 5a: adding any cost to the absorbing overflow value does not change
its canonical image. -/
theorem withTop_cost_top_add_image (a : WithTop ℕ) :
    GrothendieckAddGroup.of (⊤ + a) =
      GrothendieckAddGroup.of (⊤ : WithTop ℕ) := by
  simp

-- LeanTest/HardProblems/KTheoryCollapse.lean
/-- Goal 5: because `⊤` is absorbing, the entire Grothendieck group of
`WithTop ℕ` is trivial, not merely the part at or above the cap. -/
theorem saturating_costs_grothendieckAddGroup_subsingleton :
    Subsingleton (GrothendieckAddGroup (WithTop ℕ)) := by
  have hof : ∀ a : WithTop ℕ, GrothendieckAddGroup.of a = 0 := by
    intro a
    apply add_right_cancel (b := GrothendieckAddGroup.of (⊤ : WithTop ℕ))
    rw [← map_add]
    simp
  constructor
  intro x y
  suffices ∀ z : GrothendieckAddGroup (WithTop ℕ), z = 0 by rw [this x, this y]
  intro z
  induction z using AddLocalization.induction_on with
  | _ p =>
    have h : AddLocalization.mk p.1 p.2 +
        GrothendieckAddGroup.of (p.2 : WithTop ℕ) =
        GrothendieckAddGroup.of p.1 := by
      change AddLocalization.mk p.1 p.2 +
          AddLocalization.mk (p.2 : WithTop ℕ) 0 = AddLocalization.mk p.1 0
      rw [AddLocalization.mk_add, AddLocalization.mk_eq_mk_iff,
        AddLocalization.r_iff_exists]
      use 0
      simp [add_comm]
    rw [hof _, hof _] at h
    simpa using h
Peripheral formal experiment: no twist at the order level (TwistObstruction.lean)run

HardProblems.Twist.map_id_eq_of_thin_skeletal, HardProblems.Twist.map_comp_eq_of_thin_skeletal, HardProblems.Twist.mapComp_eqToIso_of_thin_skeletal, HardProblems.Twist.twoCocycle, HardProblems.Twist.twoCocycle_isCocycle, HardProblems.Twist.twoCocycle_not_coboundary, HardProblems.Twist.twistElementIso, HardProblems.Twist.twistNatIso, HardProblems.Twist.twistIdHom, HardProblems.Twist.twistComparison, HardProblems.Twist.twistedPseudofunctor, HardProblems.Twist.twistedPseudofunctor_mapComp, HardProblems.Twist.twist_is_essential, HardProblems.Twist.mapId_eqToIso_of_thin_skeletal, HardProblems.Twist.toCatPseudofunctor_fibre_thin, HardProblems.Twist.toCatPseudofunctor_fibre_skeletal, HardProblems.Twist.splitIndexedOrder_mapComp_eqToIso, HardProblems.Twist.splitIndexedOrder_mapId_eqToIso

-- LeanTest/HardProblems/TwistObstruction.lean
/-- Goal A1. If every value category of a pseudofunctor from a locally
discrete base is thin and skeletal, then the pseudofunctor preserves
identities on the nose: the underlying functor of `F.map (id)` equals the
identity functor. State with whatever locally-discrete encoding of the base
1-category `C` mathlib's `Pseudofunctor` needs. -/
theorem map_id_eq_of_thin_skeletal
    (F : Pseudofunctor (LocallyDiscrete C) Cat.{w, w})
    (hthin : ∀ c : C, Quiver.IsThin (F.obj ⟨c⟩))
    (hskel : ∀ c : C, Skeletal (F.obj ⟨c⟩)) (c : C) :
    F.map (𝟙 ⟨c⟩) = 𝟙 (F.obj ⟨c⟩) := by
  letI := hthin c
  apply Cat.Hom.ext
  exact Functor.eq_of_iso (hskel c) (Cat.Hom.toNatIso (F.mapId ⟨c⟩))

-- LeanTest/HardProblems/TwistObstruction.lean
/-- Goal A2. Same hypotheses: composition is preserved on the nose. -/
theorem map_comp_eq_of_thin_skeletal
    (F : Pseudofunctor (LocallyDiscrete C) Cat.{w, w})
    (hthin : ∀ c : C, Quiver.IsThin (F.obj ⟨c⟩))
    (hskel : ∀ c : C, Skeletal (F.obj ⟨c⟩))
    {a b c : C} (f : a ⟶ b) (g : b ⟶ c) :
    F.map (⟨f⟩ ≫ ⟨g⟩ : (⟨a⟩ : LocallyDiscrete C) ⟶ ⟨c⟩) =
      F.map ⟨f⟩ ≫ F.map ⟨g⟩ := by
  letI := hthin c
  apply Cat.Hom.ext
  exact Functor.eq_of_iso (hskel c) (Cat.Hom.toNatIso (F.mapComp ⟨f⟩ ⟨g⟩))

-- LeanTest/HardProblems/TwistObstruction.lean
/-- Goal A3. The comparison isomorphisms themselves are the identity
2-cells modulo the equalities above: each `mapComp` component is an
`eqToIso`. State the cleanest correct version; if a different phrasing of
"the comparison data is trivial" is more natural in mathlib's API, prove
that and rename. -/
theorem mapComp_eqToIso_of_thin_skeletal
    (F : Pseudofunctor (LocallyDiscrete C) Cat.{w, w})
    (hthin : ∀ c : C, Quiver.IsThin (F.obj ⟨c⟩))
    (hskel : ∀ c : C, Skeletal (F.obj ⟨c⟩))
    {a b c : C} (f : a ⟶ b) (g : b ⟶ c) :
    F.mapComp ⟨f⟩ ⟨g⟩ =
      eqToIso (map_comp_eq_of_thin_skeletal F hthin hskel f g) := by
  ext X
  have thin := hthin c
  exact Subsingleton.elim _ _

-- LeanTest/HardProblems/TwistObstruction.lean
/-- The cup-product 2-cocycle on `ZMod 2`: `c h h' = h * h'`. Its class
generates the degree-2 cohomology of Z/2 with Z/2 coefficients, and is the
obstruction separating the two extensions of Z/2 by Z/2. -/
def twoCocycle (h h' : ZMod 2) : ZMod 2 := h * h'

-- LeanTest/HardProblems/TwistObstruction.lean
/-- Goal B1. The cocycle identity, with trivial action:
`c(h',h'') - c(h+h',h'') + c(h,h'+h'') - c(h,h') = 0`. -/
theorem twoCocycle_isCocycle (h h' h'' : ZMod 2) :
    twoCocycle h' h'' - twoCocycle (h + h') h''
      + twoCocycle h (h' + h'') - twoCocycle h h' = 0 := by
  simp only [twoCocycle]
  ring

-- LeanTest/HardProblems/TwistObstruction.lean
/-- Goal B2. Not a coboundary: no 1-cochain `φ` has
`c(h,h') = φ h' - φ (h+h') + φ h` everywhere. This is the precise sense in
which the comparison data below cannot be normalized away. -/
theorem twoCocycle_not_coboundary :
    ¬ ∃ φ : ZMod 2 → ZMod 2,
      ∀ h h', twoCocycle h h' = φ h' - φ (h + h') + φ h := by
  decide

-- LeanTest/HardProblems/TwistObstruction.lean
def twistElementIso (x : ZMod 2) :
    (SingleObj.star TwistGroup : TwistFibre) ≅ SingleObj.star TwistGroup :=
  Iso.mk (Multiplicative.ofAdd x) (Multiplicative.ofAdd (-x))
    (by change -x + x = 0; exact neg_add_cancel x)
    (by change x + -x = 0; exact add_neg_cancel x)

-- LeanTest/HardProblems/TwistObstruction.lean
def twistNatIso (x : ZMod 2) : 𝟭 TwistFibre ≅ 𝟭 TwistFibre :=
  NatIso.ofComponents (fun _ => twistElementIso x) (by
    intro X Y f
    cases X
    cases Y
    first
      | exact mul_comm f (Multiplicative.ofAdd x)
      | exact mul_comm (Multiplicative.ofAdd x) f)

-- LeanTest/HardProblems/TwistObstruction.lean
def twistIdHom : (Cat.of TwistFibre) ⟶ Cat.of TwistFibre :=
  (𝟭 TwistFibre).toCatHom

-- LeanTest/HardProblems/TwistObstruction.lean
/-- The comparison 2-isomorphism whose distinguished component is literally
`twoCocycle h h'`.  The right-unitor only reconciles the wrapper used by
`Cat` for the composite of two identity functors. -/
def twistComparison (h h' : ZMod 2) :
    twistIdHom ≅ twistIdHom ≫ twistIdHom :=
  Cat.Hom.isoMk
    (twistNatIso (twoCocycle h h') ≪≫ (Functor.rightUnitor (𝟭 TwistFibre)).symm)

-- LeanTest/HardProblems/TwistObstruction.lean
noncomputable def twistedPseudofunctor :
    Pseudofunctor (LocallyDiscrete TwistBase) Cat :=
  LocallyDiscrete.mkPseudofunctor
    (fun _ => Cat.of TwistFibre)
    (fun _ => twistIdHom)
    (fun _ => Cat.Hom.isoMk (Iso.refl _))
    (fun f g => by
      cases ‹TwistBase›
      cases ‹TwistBase›
      cases ‹TwistBase›
      change TwistGroup at f g
      exact twistComparison (Multiplicative.toAdd f) (Multiplicative.toAdd g))
    (by
      intros b₀ b₁ b₂ b₃ f g h
      cases b₀; cases b₁; cases b₂; cases b₃
      show _
      simp only [Cat.of]
      show _
      change Multiplicative (ZMod 2) at f g h
      have hc := twoCocycle_isCocycle
        (Multiplicative.toAdd f) (Multiplicative.toAdd g) (Multiplicative.toAdd h)
      fin_cases f <;> fin_cases g <;> fin_cases h <;> simp_all [twistComparison, twistNatIso,
        twistElementIso, NatIso.ofComponents, Functor.rightUnitor, Bicategory.associator] <;>
        ext <;> simp_all [twistIdHom, twoCocycle] <;> norm_cast
      all_goals rename_i X
      all_goals cases X
      all_goals change (_ : TwistGroup) = _
      all_goals rfl)
    (by
      intros b₀ b₁ f
      cases b₀; cases b₁
      change Multiplicative (ZMod 2) at f
      fin_cases f <;> simp_all [twistComparison, twistNatIso,
        twistElementIso, NatIso.ofComponents] <;>
        ext <;> simp_all [twistIdHom, twoCocycle] <;> norm_cast)
    (by
      intros b₀ b₁ f
      cases b₀; cases b₁
      change Multiplicative (ZMod 2) at f
      fin_cases f <;> simp_all [twistComparison, twistNatIso,
        twistElementIso, NatIso.ofComponents, Functor.rightUnitor] <;>
        ext <;> simp_all [twistIdHom, twoCocycle] <;> norm_cast)

-- LeanTest/HardProblems/TwistObstruction.lean
/-- The comparison of `twistedPseudofunctor` is the cocycle comparison by
construction. -/
theorem twistedPseudofunctor_mapComp (h h' : TwistGroup) :
    twistedPseudofunctor.mapComp
        (⟨h⟩ : (⟨SingleObj.star TwistGroup⟩ : LocallyDiscrete TwistBase) ⟶ ⟨SingleObj.star TwistGroup⟩)
        (⟨h'⟩ : (⟨SingleObj.star TwistGroup⟩ : LocallyDiscrete TwistBase) ⟶ ⟨SingleObj.star TwistGroup⟩) =
      twistComparison (Multiplicative.toAdd h) (Multiplicative.toAdd h') := by
  rfl

-- LeanTest/HardProblems/TwistObstruction.lean
/-- Goal B4. No re-choice of comparison components has coboundary equal to
(the negative of, equivalently in `ZMod 2`, equal to) the coefficients of the
actual comparison cells of `twistedPseudofunctor`. -/
theorem twist_is_essential :
    (∀ h h' : TwistGroup,
      twistedPseudofunctor.mapComp
          (⟨h⟩ : (⟨SingleObj.star TwistGroup⟩ : LocallyDiscrete TwistBase) ⟶
            ⟨SingleObj.star TwistGroup⟩)
          (⟨h'⟩ : (⟨SingleObj.star TwistGroup⟩ : LocallyDiscrete TwistBase) ⟶
            ⟨SingleObj.star TwistGroup⟩) =
        twistComparison (Multiplicative.toAdd h) (Multiplicative.toAdd h')) ∧
    ¬ ∃ φ : ZMod 2 → ZMod 2,
      ∀ h h', twoCocycle h h' = φ h' - φ (h + h') + φ h := by
  exact ⟨twistedPseudofunctor_mapComp, twoCocycle_not_coboundary⟩

-- LeanTest/HardProblems/TwistObstruction.lean
/-- The identity comparison is also equality-induced, completing the pair:
with thin skeletal values, both comparison isomorphisms of a pseudofunctor
are `eqToIso`, which is the full content of "strict on the nose". -/
theorem mapId_eqToIso_of_thin_skeletal
    (F : Pseudofunctor (LocallyDiscrete C) Cat.{w, w})
    (hthin : ∀ c : C, Quiver.IsThin (F.obj ⟨c⟩))
    (hskel : ∀ c : C, Skeletal (F.obj ⟨c⟩)) (c : C) :
    F.mapId ⟨c⟩ = eqToIso (map_id_eq_of_thin_skeletal F hthin hskel c) := by
  ext X
  have thin := hthin c
  exact Subsingleton.elim _ _

-- LeanTest/HardProblems/TwistObstruction.lean
/-- Fibres of the book's indexed order are thin: their homs are proofs. -/
theorem toCatPseudofunctor_fibre_thin (P : SplitIndexedOrder.{v, u, w} C)
    (c : Cᵒᵖ) : Quiver.IsThin ((toCatPseudofunctor P).obj ⟨c⟩) := by
  show Quiver.IsThin (P.Fiber c.unop)
  intro X Y
  exact ⟨fun f g => Subsingleton.elim f g⟩

-- LeanTest/HardProblems/TwistObstruction.lean
/-- Fibres of the book's indexed order are skeletal: an isomorphism gives
inequalities both ways, and antisymmetry finishes. -/
theorem toCatPseudofunctor_fibre_skeletal (P : SplitIndexedOrder.{v, u, w} C)
    (c : Cᵒᵖ) : Skeletal ((toCatPseudofunctor P).obj ⟨c⟩) := by
  show Skeletal (P.Fiber c.unop)
  rintro X Y ⟨i⟩
  exact le_antisymm (leOfHom i.hom) (leOfHom i.inv)

-- LeanTest/HardProblems/TwistObstruction.lean
/-- The splitting of the book's indexed order was forced: its composition
comparison is equality-induced. -/
theorem splitIndexedOrder_mapComp_eqToIso (P : SplitIndexedOrder.{v, u, w} C)
    {a b c : Cᵒᵖ} (f : a ⟶ b) (g : b ⟶ c) :
    (toCatPseudofunctor P).mapComp ⟨f⟩ ⟨g⟩ =
      eqToIso (map_comp_eq_of_thin_skeletal (toCatPseudofunctor P)
        (toCatPseudofunctor_fibre_thin P) (toCatPseudofunctor_fibre_skeletal P)
        f g) :=
  mapComp_eqToIso_of_thin_skeletal (toCatPseudofunctor P)
    (toCatPseudofunctor_fibre_thin P) (toCatPseudofunctor_fibre_skeletal P) f g

-- LeanTest/HardProblems/TwistObstruction.lean
/-- And its identity comparison likewise. -/
theorem splitIndexedOrder_mapId_eqToIso (P : SplitIndexedOrder.{v, u, w} C)
    (c : Cᵒᵖ) :
    (toCatPseudofunctor P).mapId ⟨c⟩ =
      eqToIso (map_id_eq_of_thin_skeletal (toCatPseudofunctor P)
        (toCatPseudofunctor_fibre_thin P) (toCatPseudofunctor_fibre_skeletal P)
        c) :=
  mapId_eqToIso_of_thin_skeletal (toCatPseudofunctor P)
    (toCatPseudofunctor_fibre_thin P) (toCatPseudofunctor_fibre_skeletal P) c
Additional formal layer: ModelStability.lean

LeanTest/HardProblems/ModelStability.lean

import Mathlib

/-!
# Decision-bearing support and proof-model stability

This module formalizes two diagnostics used by the book.

First, decision-bearing support is a finite benchmark statement: the instances
on which two selectors can produce different measured outcomes are contained
in the instances on which some pair of candidate outcomes differs.

Second, proof costs take values in `ℝ≥0∞`. The infimum over an empty proof
type is therefore `∞`, so unprovable problems are handled without a partial
definition. A symmetric gap built from truncated subtraction avoids the
undefined informal expression `∞ - ∞`. Local cost variation and mechanism
stability radii are then well-defined even at infinite proof cost.

The open-ball radius is itself stable. Available mechanisms are defined from
admitted proofs and budgets, so a change in a selected proof label can be
distinguished from the loss of an available method.
-/

namespace HardProblems

namespace DecisionBearing

variable {Instance Candidate Outcome : Type*}

/-- An instance is decision-bearing when at least two candidates have
different measured outcomes. -/
def IsDecisionBearing (outcome : Instance → Candidate → Outcome)
    (i : Instance) : Prop :=
  ∃ a b, outcome i a ≠ outcome i b

instance instDecidableIsDecisionBearing [Fintype Candidate] [DecidableEq Outcome]
    (outcome : Instance → Candidate → Outcome) (i : Instance) :
    Decidable (IsDecisionBearing outcome i) := by
  unfold IsDecisionBearing
  infer_instance

/-- If two selectors produce different outcomes on an instance, that instance
is decision-bearing. -/
theorem isDecisionBearing_of_selector_disagreement
    (outcome : Instance → Candidate → Outcome)
    (select₁ select₂ : Instance → Candidate) (i : Instance)
    (h : outcome i (select₁ i) ≠ outcome i (select₂ i)) :
    IsDecisionBearing outcome i := by
  exact ⟨select₁ i, select₂ i, h⟩

/-- On a non-decision-bearing instance every pair of selectors receives the
same measured outcome. -/
theorem selector_outcomes_eq_of_not_isDecisionBearing
    (outcome : Instance → Candidate → Outcome)
    (select₁ select₂ : Instance → Candidate) (i : Instance)
    (h : ¬ IsDecisionBearing outcome i) :
    outcome i (select₁ i) = outcome i (select₂ i) := by
  by_contra hne
  exact h ⟨select₁ i, select₂ i, hne⟩

/-- For every finite benchmark, the number of instances on which two
selectors obtain different measured outcomes is at most the number of
decision-bearing instances. This is the precise cardinality statement behind
the decision-bearing-support diagnostic; it does not bound an arbitrary
weighted or unbounded evaluation metric. -/
theorem selector_disagreement_card_le_decisionBearing_card
    [Fintype Candidate] [DecidableEq Outcome]
    (outcome : Instance → Candidate → Outcome)
    (select₁ select₂ : Instance → Candidate)
    (benchmark : Finset Instance) :
    (benchmark.filter fun i => outcome i (select₁ i) ≠ outcome i (select₂ i)).card ≤
      (benchmark.filter fun i => IsDecisionBearing outcome i).card := by
  classical
  apply Finset.card_le_card
  intro i hi
  simp only [Finset.mem_filter] at hi ⊢
  exact ⟨hi.1, isDecisionBearing_of_selector_disagreement outcome select₁ select₂ i hi.2⟩

end DecisionBearing

namespace ModelStability

open scoped ENNReal

variable {Problem Proof Mechanism : Type*}

/-- The least cost of an admitted proof. The codomain is extended
nonnegative real numbers, and the infimum of the empty proof subtype is `∞`. -/
noncomputable def proofCost (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    (problem : Problem) : ℝ≥0∞ :=
  ⨅ proof : {proof // Proves proof problem}, cost proof.1

/-- A problem with no admitted proof has infinite proof cost. -/
theorem proofCost_eq_top_of_no_proof
    (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    (problem : Problem) (h : ¬ ∃ proof, Proves proof problem) :
    proofCost Proves cost problem = ⊤ := by
  letI : IsEmpty {proof // Proves proof problem} :=
    ⟨fun proof => h ⟨proof.1, proof.2⟩⟩
  rw [proofCost]
  exact iInf_of_empty (fun proof : {proof // Proves proof problem} => cost proof.1)

/-- Every admitted proof gives an upper bound on the problem's proof cost. -/
theorem proofCost_le
    (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    {problem : Problem} {proof : Proof} (h : Proves proof problem) :
    proofCost Proves cost problem ≤ cost proof := by
  exact iInf_le_of_le ⟨proof, h⟩ le_rfl

/-- A uniform lower bound on all admitted proofs is a lower bound on proof
cost. The statement also holds vacuously for an unprovable problem. -/
theorem le_proofCost
    (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    {problem : Problem} {bound : ℝ≥0∞}
    (h : ∀ proof, Proves proof problem → bound ≤ cost proof) :
    bound ≤ proofCost Proves cost problem := by
  refine le_iInf fun proof => ?_
  exact h proof.1 proof.2

/-- A proof attaining the common lower bound realizes the proof cost exactly. -/
theorem proofCost_eq_of_isMin
    (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    {problem : Problem} {proof : Proof} (hproof : Proves proof problem)
    (hmin : ∀ other, Proves other problem → cost proof ≤ cost other) :
    proofCost Proves cost problem = cost proof := by
  apply le_antisymm (proofCost_le Proves cost hproof)
  exact le_proofCost Proves cost hmin

/-- Finite proof cost certifies existence of an admitted proof. -/
theorem exists_proof_of_proofCost_lt_top
    (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    {problem : Problem} (h : proofCost Proves cost problem < ⊤) :
    ∃ proof, Proves proof problem := by
  by_contra hnone
  rw [proofCost_eq_top_of_no_proof Proves cost problem hnone] at h
  exact (lt_irrefl ⊤ h)

/-- A symmetric gap on extended nonnegative costs. Truncated subtraction makes
the gap of `∞` with itself zero while retaining an infinite gap between a
finite cost and `∞`. -/
def costGap (a b : ℝ≥0∞) : ℝ≥0∞ :=
  (a - b) ⊔ (b - a)

@[simp]
theorem costGap_self (a : ℝ≥0∞) : costGap a a = 0 := by
  simp [costGap]

theorem costGap_comm (a b : ℝ≥0∞) : costGap a b = costGap b a := by
  simp [costGap, sup_comm]

/-- The extended cost gap vanishes exactly when its arguments agree. -/
@[simp]
theorem costGap_eq_zero_iff (a b : ℝ≥0∞) : costGap a b = 0 ↔ a = b := by
  constructor
  · intro h
    have hab0 : a - b = 0 := by
      apply bot_unique
      exact le_trans le_sup_left (le_of_eq h)
    have hba0 : b - a = 0 := by
      apply bot_unique
      exact le_trans le_sup_right (le_of_eq h)
    exact le_antisymm (tsub_eq_zero_iff_le.mp hab0) (tsub_eq_zero_iff_le.mp hba0)
  · rintro rfl
    exact costGap_self a

@[simp]
theorem costGap_top_top : costGap (⊤ : ℝ≥0∞) ⊤ = 0 := by
  exact costGap_self ⊤

/-- A finite extended cost has infinite gap from an infinite cost. -/
@[simp]
theorem costGap_top_of_ne_top (a : ℝ≥0∞) (ha : a ≠ ⊤) :
    costGap a ⊤ = ⊤ := by
  simp [costGap, ha]

/-- Local variation of a cost profile in a declared directed neighborhood.
The codomain and `costGap` keep this total when costs are infinite. -/
noncomputable def localVariation (costProfile : Problem → ℝ≥0∞)
    (distance : Problem → Problem → ℝ≥0∞) (ε : ℝ≥0∞)
    (problem : Problem) : ℝ≥0∞ :=
  ⨆ neighbor : Problem, ⨆ (_h : distance problem neighbor ≤ ε),
    costGap (costProfile neighbor) (costProfile problem)

/-- Every neighbor's cost gap is bounded by the local variation. -/
theorem costGap_le_localVariation
    (costProfile : Problem → ℝ≥0∞)
    (distance : Problem → Problem → ℝ≥0∞) {ε : ℝ≥0∞}
    {problem neighbor : Problem} (h : distance problem neighbor ≤ ε) :
    costGap (costProfile neighbor) (costProfile problem) ≤
      localVariation costProfile distance ε problem := by
  exact le_iSup_of_le neighbor (le_iSup_of_le h le_rfl)

/-- Enlarging the neighborhood cannot decrease local variation. -/
theorem localVariation_mono
    (costProfile : Problem → ℝ≥0∞)
    (distance : Problem → Problem → ℝ≥0∞) {problem : Problem}
    {ε₁ ε₂ : ℝ≥0∞} (hε : ε₁ ≤ ε₂) :
    localVariation costProfile distance ε₁ problem ≤
      localVariation costProfile distance ε₂ problem := by
  refine iSup_le fun neighbor => iSup_le fun hneighbor => ?_
  exact costGap_le_localVariation costProfile distance (hneighbor.trans hε)

/-- If the cost profile is constant throughout a neighborhood, its local
variation is zero. -/
theorem localVariation_eq_zero_of_constant
    (costProfile : Problem → ℝ≥0∞)
    (distance : Problem → Problem → ℝ≥0∞) (ε : ℝ≥0∞)
    (problem : Problem)
    (h : ∀ neighbor, distance problem neighbor ≤ ε →
      costProfile neighbor = costProfile problem) :
    localVariation costProfile distance ε problem = 0 := by
  apply bot_unique
  refine iSup_le fun neighbor => iSup_le fun hneighbor => ?_
  simp [h neighbor hneighbor]

/-- Conversely, zero local variation forces equality of proof costs at every
declared neighbor. -/
theorem cost_eq_of_localVariation_eq_zero
    (costProfile : Problem → ℝ≥0∞)
    (distance : Problem → Problem → ℝ≥0∞) {ε : ℝ≥0∞}
    {problem neighbor : Problem} (hneighbor : distance problem neighbor ≤ ε)
    (hzero : localVariation costProfile distance ε problem = 0) :
    costProfile neighbor = costProfile problem := by
  apply (costGap_eq_zero_iff _ _).mp
  apply bot_unique
  exact (costGap_le_localVariation costProfile distance hneighbor).trans (le_of_eq hzero)

/-- A proof mechanism is stable at radius `r` when every problem strictly
inside that directed ball has an equivalent mechanism. -/
def StableAtRadius (mechanism : Problem → Mechanism)
    (sameMechanism : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem)
    (r : ℝ≥0∞) : Prop :=
  ∀ neighbor, distance problem neighbor < r →
    sameMechanism (mechanism neighbor) (mechanism problem)

/-- Radius zero is always stable because no extended nonnegative distance is
strictly below zero. -/
@[simp]
theorem stableAtRadius_zero
    (mechanism : Problem → Mechanism)
    (sameMechanism : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem) :
    StableAtRadius mechanism sameMechanism distance problem 0 := by
  intro neighbor hneighbor
  exact (not_lt_of_ge bot_le hneighbor).elim

/-- Stability is downward closed in the radius. -/
theorem StableAtRadius.mono
    (mechanism : Problem → Mechanism)
    (sameMechanism : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem)
    {r s : ℝ≥0∞} (hr : StableAtRadius mechanism sameMechanism distance problem r)
    (hsr : s ≤ r) :
    StableAtRadius mechanism sameMechanism distance problem s := by
  intro neighbor hneighbor
  exact hr neighbor (hneighbor.trans_le hsr)

/-- The mechanism-stability radius is the supremum of all stable radii.
The strict ball condition makes this supremum stable, as proved below. -/
noncomputable def mechanismRadius (mechanism : Problem → Mechanism)
    (sameMechanism : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem) : ℝ≥0∞ :=
  ⨆ r : ℝ≥0∞, ⨆ (_h : StableAtRadius mechanism sameMechanism distance problem r), r

/-- Every stable radius is bounded by the mechanism-stability radius. -/
theorem le_mechanismRadius
    (mechanism : Problem → Mechanism)
    (sameMechanism : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem)
    {r : ℝ≥0∞} (hr : StableAtRadius mechanism sameMechanism distance problem r) :
    r ≤ mechanismRadius mechanism sameMechanism distance problem := by
  exact le_iSup_of_le r (le_iSup_of_le hr le_rfl)

/-- Every point strictly below the supremum lies inside a stable ball.
No metric axioms or laws on the mechanism relation are needed. -/
theorem stableAtRadius_mechanismRadius
    (mechanism : Problem → Mechanism)
    (sameMechanism : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem) :
    StableAtRadius mechanism sameMechanism distance problem
      (mechanismRadius mechanism sameMechanism distance problem) := by
  intro neighbor hneighbor
  unfold mechanismRadius at hneighbor
  obtain ⟨r, hr⟩ := lt_iSup_iff.mp hneighbor
  obtain ⟨hstable, hlt⟩ := lt_iSup_iff.mp hr
  exact hstable neighbor hlt

/-- Stable radii form the closed initial interval ending at the radius. -/
theorem stableAtRadius_iff_le_mechanismRadius
    (mechanism : Problem → Mechanism)
    (sameMechanism : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem)
    (r : ℝ≥0∞) :
    StableAtRadius mechanism sameMechanism distance problem r ↔
      r ≤ mechanismRadius mechanism sameMechanism distance problem := by
  constructor
  · exact le_mechanismRadius mechanism sameMechanism distance problem
  · intro hr
    exact StableAtRadius.mono mechanism sameMechanism distance problem
      (stableAtRadius_mechanismRadius mechanism sameMechanism distance problem) hr

/-- Any radius strictly above the supremum is not stable. -/
theorem not_stableAtRadius_of_mechanismRadius_lt
    (mechanism : Problem → Mechanism)
    (sameMechanism : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem)
    {r : ℝ≥0∞}
    (h : mechanismRadius mechanism sameMechanism distance problem < r) :
    ¬ StableAtRadius mechanism sameMechanism distance problem r := by
  intro hr
  exact (not_le_of_gt h) (le_mechanismRadius mechanism sameMechanism distance problem hr)

/-- Weakening the mechanism-equivalence requirement cannot decrease the
stability radius. -/
theorem mechanismRadius_mono_relation
    (mechanism : Problem → Mechanism)
    (same₁ same₂ : Mechanism → Mechanism → Prop)
    (distance : Problem → Problem → ℝ≥0∞) (problem : Problem)
    (hrel : ∀ a b, same₁ a b → same₂ a b) :
    mechanismRadius mechanism same₁ distance problem ≤
      mechanismRadius mechanism same₂ distance problem := by
  refine iSup_le fun r => iSup_le fun hr => ?_
  apply le_mechanismRadius mechanism same₂ distance problem
  intro neighbor hneighbor
  exact hrel _ _ (hr neighbor hneighbor)

/-! ## Mechanisms available from admitted proofs -/

/-- A mechanism is available when an admitted proof of that kind fits the
budget. This definition does not require selecting a proof for every problem. -/
def availableMechanisms (Proves : Proof → Problem → Prop)
    (cost : Proof → ℝ≥0∞) (kind : Proof → Mechanism)
    (budget : ℝ≥0∞) (problem : Problem) : Set Mechanism :=
  {k | ∃ p, Proves p problem ∧ cost p ≤ budget ∧ kind p = k}

theorem availableMechanisms_mono_budget
    (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    (kind : Proof → Mechanism) {b B : ℝ≥0∞} (hb : b ≤ B)
    (problem : Problem) :
    availableMechanisms Proves cost kind b problem ⊆
      availableMechanisms Proves cost kind B problem := by
  rintro k ⟨p, hp, hc, hk⟩
  exact ⟨p, hp, hc.trans hb, hk⟩

theorem availableMechanisms_nonempty_iff
    (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    (kind : Proof → Mechanism) (budget : ℝ≥0∞) (problem : Problem) :
    (availableMechanisms Proves cost kind budget problem).Nonempty ↔
      ∃ p, Proves p problem ∧ cost p ≤ budget := by
  constructor
  · rintro ⟨_, p, hp, hc, _⟩
    exact ⟨p, hp, hc⟩
  · rintro ⟨p, hp, hc⟩
    exact ⟨kind p, p, hp, hc, rfl⟩

/-- A sound proof transformation with a cost allowance transports available
mechanisms. Merely changing the selected label supplies no such witness. -/
theorem availableMechanisms_transport
    (Proves : Proof → Problem → Prop) (cost : Proof → ℝ≥0∞)
    (kind : Proof → Mechanism) (transform : Proof → Proof)
    (translateKind : Mechanism → Mechanism)
    {source target : Problem} {b B : ℝ≥0∞}
    (hsound : ∀ p, Proves p source → cost p ≤ b → Proves (transform p) target)
    (hcost : ∀ p, Proves p source → cost p ≤ b → cost (transform p) ≤ B)
    (hkind : ∀ p, kind (transform p) = translateKind (kind p)) :
    translateKind '' availableMechanisms Proves cost kind b source ⊆
      availableMechanisms Proves cost kind B target := by
  rintro _ ⟨k, ⟨p, hp, hc, hk⟩, rfl⟩
  refine ⟨transform p, hsound p hp hc, hcost p hp hc, ?_⟩
  rw [hkind, hk]

/-- Different selected labels can coexist with identical availability sets. -/
theorem selected_labels_can_differ_without_availability_change :
    let proves : Bool → Bool → Prop := fun _ _ => True
    let cost : Bool → ℝ≥0∞ := fun _ => 1
    let kind : Bool → Bool := id
    (false : Bool) ≠ true ∧
      availableMechanisms proves cost kind 1 false =
        availableMechanisms proves cost kind 1 true := by
  exact ⟨Bool.false_ne_true, rfl⟩

end ModelStability

end HardProblems
Additional formal layer: WorkedExamples.lean

LeanTest/HardProblems/WorkedExamples.lean

import LeanTest.HardProblems.ModelStability
import LeanTest.HardProblems.Behavioral

/-!
# Calculated examples

Deployment loss, a calibration preimage, and two elementary algebraic
certificate families. Cost claims refer only to the declared certificate
languages; the algebraic soundness of the certificates is proved separately.
-/

namespace HardProblems.WorkedExamples

open scoped ENNReal NNReal
open ModelStability

namespace Deployment

def frozenLoss (θ : ℝ) : ℝ := |θ - 1|
def feedbackLoss (θ : ℝ) : ℝ := |θ - (1 - θ)|
def worstLoss (θ : ℝ) : ℝ := max (frozenLoss θ) (feedbackLoss θ)

theorem fitted_model_fails_after_deployment :
    frozenLoss 1 = 0 ∧ feedbackLoss 1 = 1 := by
  norm_num [frozenLoss, feedbackLoss]

theorem feedback_fixed_point : feedbackLoss (1 / 2) = 0 := by
  norm_num [feedbackLoss]

theorem worstLoss_lower_bound (θ : ℝ) : (1 : ℝ) / 3 ≤ worstLoss θ := by
  have h₁ : -(θ - 1) ≤ worstLoss θ :=
    (neg_le_abs _).trans (le_max_left _ _)
  have h₂ : θ - (1 - θ) ≤ worstLoss θ :=
    (le_abs_self _).trans (le_max_right _ _)
  linarith

theorem worstLoss_at_two_thirds : worstLoss (2 / 3) = (1 : ℝ) / 3 := by
  norm_num [worstLoss, frozenLoss, feedbackLoss]

theorem robust_region (r ℓ : ℝ) :
    (∃ θ : ℝ, 0 ≤ θ ∧ θ ≤ 1 ∧ 1 ≤ r ∧ worstLoss θ ≤ ℓ) ↔
      1 ≤ r ∧ (1 : ℝ) / 3 ≤ ℓ := by
  constructor
  · rintro ⟨θ, _, _, hr, hℓ⟩
    exact ⟨hr, (worstLoss_lower_bound θ).trans hℓ⟩
  · rintro ⟨hr, hℓ⟩
    refine ⟨2 / 3, by norm_num, by norm_num, hr, ?_⟩
    rwa [worstLoss_at_two_thirds]

theorem frozen_region (r ℓ : ℝ) :
    (∃ θ : ℝ, 0 ≤ θ ∧ θ ≤ 1 ∧ 1 ≤ r ∧ frozenLoss θ ≤ ℓ) ↔
      1 ≤ r ∧ 0 ≤ ℓ := by
  constructor
  · rintro ⟨θ, _, _, hr, hℓ⟩
    exact ⟨hr, (abs_nonneg _).trans hℓ⟩
  · rintro ⟨hr, hℓ⟩
    refine ⟨1, by norm_num, le_rfl, hr, ?_⟩
    simpa [frozenLoss] using hℓ

end Deployment

namespace Calibration

abbrev Hardware := ℝ≥0 × ℝ≥0 × ℝ≥0 × ℝ≥0
abbrev Simulator := ℝ≥0 × ℝ≥0 × ℝ≥0

noncomputable def translate (p : Hardware) : Simulator :=
  (p.1 / 2, p.2.2.1 / 2, p.2.2.2 * 10)
def simulatorRegion : Set Simulator := {p | 6 ≤ p.1 ∧ 10 ≤ p.2.1}
def hardwareRegion : Set Hardware := {p | 12 ≤ p.1 ∧ 10 ≤ p.2.1 ∧ 20 ≤ p.2.2.1}

theorem preimage_formula (p : Hardware) :
    p ∈ translate ⁻¹' simulatorRegion ↔ 12 ≤ p.1 ∧ 20 ≤ p.2.2.1 := by
  simp only [Set.mem_preimage, simulatorRegion, Set.mem_ofPred_eq, translate]
  constructor <;> rintro ⟨h₁, h₂⟩ <;> constructor <;> linarith

theorem preimage_strictly_exceeds_hardware :
    hardwareRegion ⊂ translate ⁻¹' simulatorRegion := by
  refine Set.ssubset_iff_subset_ne.mpr ⟨?_, ?_⟩
  · intro p hp
    exact (preimage_formula p).mpr ⟨hp.1, hp.2.2⟩
  · intro heq
    have hmem : (12, 0, 20, 0) ∈ translate ⁻¹' simulatorRegion := by
      rw [preimage_formula]
      norm_num
    rw [← heq] at hmem
    norm_num [hardwareRegion] at hmem

end Calibration

namespace Pivot

inductive Recipe where
  | substitution
  | elimination
  deriving DecidableEq

def Proves : Recipe → ℝ → Prop
  | .substitution, _ => True
  | .elimination, t => t ≠ 0

def cost : Recipe → ℝ≥0∞
  | .substitution => 1
  | .elimination => 6

theorem substitution_sound (t : ℝ) :
    t * 1 + (1 - t) = 1 ∧ (1 : ℝ) = 1 := by
  constructor <;> ring

theorem elimination_sound (t : ℝ) (ht : t ≠ 0) :
    let m := 1 / t
    let u := -m
    let v := 1 - m
    let y := v / u
    let x := (1 - y) / t
    t * x + y = 1 ∧ x = 1 := by
  dsimp
  constructor <;> field_simp <;> ring

theorem proofCost_constant (t : ℝ) : proofCost Proves cost t = 1 := by
  apply proofCost_eq_of_isMin Proves cost (proof := Recipe.substitution) trivial
  intro other _
  cases other <;> norm_num [cost]

theorem substitution_available (t : ℝ) (B : ℝ≥0∞) :
    Recipe.substitution ∈ availableMechanisms Proves cost id B t ↔ 1 ≤ B := by
  simp [availableMechanisms, Proves, cost]

theorem elimination_available (t : ℝ) (B : ℝ≥0∞) :
    Recipe.elimination ∈ availableMechanisms Proves cost id B t ↔ t ≠ 0 ∧ 6 ≤ B := by
  simp [availableMechanisms, Proves, cost]

theorem cost_variation_zero (distance : ℝ → ℝ → ℝ≥0∞)
    (ε : ℝ≥0∞) (t : ℝ) :
    localVariation (proofCost Proves cost) distance ε t = 0 := by
  apply localVariation_eq_zero_of_constant
  intro s _
  rw [proofCost_constant, proofCost_constant]

end Pivot

namespace Singular

def Proves (x t : ℝ) : Prop := t * x = 1
def cost (_x : ℝ) : ℝ≥0∞ := 1

theorem proofCost_nonzero (t : ℝ) (ht : t ≠ 0) :
    proofCost Proves cost t = 1 := by
  apply proofCost_eq_of_isMin Proves cost (proof := t⁻¹)
  · exact mul_inv_cancel₀ ht
  · intro _ _
    exact le_rfl

theorem proofCost_zero : proofCost Proves cost 0 = ⊤ := by
  apply proofCost_eq_top_of_no_proof
  simp [Proves]

theorem infinite_gap_at_zero (t : ℝ) (ht : t ≠ 0) :
    costGap (proofCost Proves cost t) (proofCost Proves cost 0) = ⊤ := by
  rw [proofCost_nonzero t ht, proofCost_zero]
  exact costGap_top_of_ne_top 1 (by simp)

end Singular

/-- The safety equivalence cannot use a strict superset of generated runs. -/
theorem safety_needs_exact_generated_behavior :
    let step : Bool → Bool := id
    let safe : Set Bool := {false}
    let behavior : Behavioral.Behavior ℕ Bool := Set.univ
    Behavioral.generatedBehavior step safe ⊆ behavior ∧
      Set.MapsTo step safe safe ∧ ¬ Behavioral.IsSafe behavior safe := by
  dsimp
  refine ⟨Set.subset_univ _, (fun _ h => h), ?_⟩
  intro hsafe
  have hfalse := hsafe (fun _ => true) (Set.mem_univ _) 0
  change true = false at hfalse
  cases hfalse

end HardProblems.WorkedExamples
Additional formal layer: WorstCaseSuccess.lean

LeanTest/HardProblems/WorstCaseSuccess.lean

import Mathlib

/-!
# Worst-case success: a machine-checked certificate layer

This module is part of the book companion. It began as
a standalone research artifact for the "Operational Hardness" programme
(`book/research/hard-problems-research-direction.md`,
`book/research/hardness-project-record.md`) and is Milestone 3 of that
programme's Track 1: a Lean formalization of the core object of worst-case
success comparison, together with the two headline examples of the
two-world non-garbling separation and the three-world strict separation.

It is imported from `LeanTest/HardProblems.lean`. It does not depend on any
other module of the book's companion.

## What is proved

* The core objects: experiments as row-stochastic matrices (`Experiment`,
  `IsExperiment`), success relations as `Finset (Finset (Fin n))`, randomized
  policies (`IsPolicy`), worldwise success (`worldSuccess`), the guarantee
  relation (`Guarantees`), the Bayes bound (`bayesBound`), and the dominance
  order (`Dominates`).
* `weak_duality`: for every policy and every prior, the guaranteed value is
  at most the Bayes bound at that prior. This is the soundness half of the
  minimax equality `val = min_pi B(pi, S)`; the matching existence of an
  optimal policy/prior pair (strong duality via linear programming, or the
  minimax theorem) is *not* formalized here, only used through explicit
  witnesses in the examples below.
* `garbling_dominates`: if `L = K * M` for a row-stochastic `M` then `K`
  dominates `L` (Blackwell sufficiency, easy direction), for arbitrary
  `n`, `m`, `m'`.
* Normalization lemmas for arbitrary `n`: a relation that fails to cover a
  world guarantees no positive success (`not_covers_guarantees_nonpos`), and
  a relation containing the full world set guarantees exactly probability
  one is achievable (`guarantees_one_of_univ_mem`), together with the
  elementary bound `worldSuccess_le_one` and downward closure of
  `Guarantees` in the target level `t` (`Guarantees.anti`).
* `guarantees_one_iff_possibilistic`: for arbitrary `n`, `Guarantees K S 1`
  holds iff every signal that occurs with positive probability somewhere has
  its full support contained in some action of `S`. Both directions are
  proved.
* The two-world example: `K2 = [[2/3,1/3],[1/3,2/3]]`,
  `L2 = [[1,0],[1/2,1/2]]`. `Dominates K2 L2` and `Dominates L2 K2` are
  proved **restricted to genuine success relations**, i.e. `S` whose members
  are all nonempty (matching the standing definition of a success relation
  as *"a nonempty family of nonempty subsets"* used throughout the research
  record; the fully unrestricted `Dominates` statement, which additionally
  allows the empty set as an inert member of `S`, is not formalized).
  `L2` is shown not to be `K2 * M` for any row-stochastic `M`.
* The three-world strict separation: `K3 = [[1,0],[1/4,3/4],[0,1]]`,
  `L3 = [[1/4,3/4],[1,0],[1,0]]`. `K3` guarantees `1` on
  `S = {{0,1},{1,2}}`; `L3` cannot guarantee more than `4/5` there, certified
  by the explicit prior `(4/5, 0, 1/5)`; `L3` is not `K3 * M` for any
  row-stochastic `M`.

## What is not proved

The full `Dominates K3 L3` via the eight-test reduction for three worlds
(`hard-problems-research-direction.md`, Milestone 3 suggestion 6, "if time
permits") is **not attempted** here: it needs a `decide`-based enumeration
over `Finset (Finset (Fin 3))` together with a general monotonicity lemma
for covering refinements, and the eight numeric values per experiment from
`book/research/wcs/paper_certificates.json`. The general monotonicity
normalization lemma (every action of `S` contained in some action of `S'`
implies `Guarantees K S t → Guarantees K S' t`, item 3 of the milestone
suggestion, general `n`) is likewise **not attempted**; the two-world
example only needs the two easier normalization lemmas above plus a direct
case analysis specific to `Fin 2`, so it was not required and was dropped to
keep the rest of the module solid. Strong duality (existence of an optimal
policy/prior pair, i.e. that `val_K(S) = min_pi B(pi,S)` is *attained* on
both sides) is not proved in general; only the explicit witnesses used in
the two examples are checked.

All numeric certificates below are stated over `ℝ` with literal rational
constants; Lean's `norm_num` verifies the resulting equalities and
inequalities exactly (no floating point is used anywhere in this file).
-/

open Finset

namespace HardProblems.WorstCaseSuccess

/-- A finite experiment with `n` worlds and `m` signals is a row-stochastic
matrix: `K w o` is the probability of observing signal `o` in world `w`. -/
abbrev Experiment (n m : ℕ) := Matrix (Fin n) (Fin m) ℝ

/-- `K` is a genuine experiment: nonnegative entries, each row a
probability distribution over signals. -/
def IsExperiment {n m : ℕ} (K : Experiment n m) : Prop :=
  (∀ w o, 0 ≤ K w o) ∧ ∀ w, ∑ o, K w o = 1

/-- `pi` is a prior distribution over worlds. -/
def IsPrior {n : ℕ} (pi : Fin n → ℝ) : Prop :=
  (∀ w, 0 ≤ pi w) ∧ ∑ w, pi w = 1

/-- A randomized policy `p : Fin m → Finset (Fin n) → ℝ` maps each signal to
a probability distribution over the actions of a success relation `S`.
`p o A` is the probability of choosing action `A` after observing `o`.
Only the values of `p` on `A ∈ S` are constrained or used. -/
def IsPolicy {n m : ℕ} (S : Finset (Finset (Fin n))) (p : Fin m → Finset (Fin n) → ℝ) : Prop :=
  (∀ o, ∀ A ∈ S, 0 ≤ p o A) ∧ ∀ o, ∑ A ∈ S, p o A = 1

/-- The probability, in world `w`, that the policy `p` succeeds against the
experiment `K` and the success relation `S`: the world-`w` marginal of
`∑_o K(o|w) ∑_{A ∈ S, w ∈ A} p(A|o)`. -/
noncomputable def worldSuccess {n m : ℕ} (K : Experiment n m) (S : Finset (Finset (Fin n)))
    (p : Fin m → Finset (Fin n) → ℝ) (w : Fin n) : ℝ :=
  ∑ o, K w o * ∑ A ∈ S.filter (fun A => w ∈ A), p o A

/-- `Guarantees K S t` holds when some valid policy succeeds with
probability at least `t` in *every* world; this is the book's quantifier
(one policy chosen first, worst case over worlds). -/
def Guarantees {n m : ℕ} (K : Experiment n m) (S : Finset (Finset (Fin n))) (t : ℝ) : Prop :=
  ∃ p : Fin m → Finset (Fin n) → ℝ, IsPolicy S p ∧ ∀ w, t ≤ worldSuccess K S p w

/-- `maxOver S f` is `max_{A ∈ S} f A`, taken to be `0` when `S` is empty
(a junk value that is never used: every lemma below either supplies
`S.Nonempty` or is about a nonempty `S` by hypothesis). -/
noncomputable def maxOver {n : ℕ} (S : Finset (Finset (Fin n))) (f : Finset (Fin n) → ℝ) : ℝ :=
  if h : S.Nonempty then S.sup' h f else 0

/-- The Bayes value of the prior `pi` against the success relation `S` and
experiment `K`: `∑_o max_{A ∈ S} ∑_{w ∈ A} pi(w) K(o|w)`. -/
noncomputable def bayesBound {n m : ℕ} (K : Experiment n m) (pi : Fin n → ℝ)
    (S : Finset (Finset (Fin n))) : ℝ :=
  ∑ o, maxOver S (fun A => ∑ w ∈ A, pi w * K w o)

/-- `K` worst-case dominates `L`: every guarantee `L` can give on every
success relation, `K` can also give. `S` ranges over *all* of
`Finset (Finset (Fin n))`, matching the milestone's definition literally;
see the module docstring for the restriction used in the worked examples. -/
def Dominates {n m m' : ℕ} (K : Experiment n m) (L : Experiment n m') : Prop :=
  ∀ (S : Finset (Finset (Fin n))) (t : ℝ), Guarantees L S t → Guarantees K S t

/-! ## Basic bounds and duality -/

variable {n m : ℕ}

theorem le_maxOver {S : Finset (Finset (Fin n))} {f : Finset (Fin n) → ℝ} {A : Finset (Fin n)}
    (hA : A ∈ S) : f A ≤ maxOver S f := by
  have hS : S.Nonempty := ⟨A, hA⟩
  simp only [maxOver, dif_pos hS]
  exact Finset.le_sup' f hA

/-- Every world-success value is at most one, for a genuine experiment and
policy. -/
theorem worldSuccess_le_one {K : Experiment n m} (hK : IsExperiment K)
    {S : Finset (Finset (Fin n))} {p : Fin m → Finset (Fin n) → ℝ} (hp : IsPolicy S p)
    (w : Fin n) : worldSuccess K S p w ≤ 1 := by
  have hstep : ∀ o, K w o * ∑ A ∈ S.filter (fun A => w ∈ A), p o A ≤ K w o * ∑ A ∈ S, p o A := by
    intro o
    have hfilt : ∑ A ∈ S.filter (fun A => w ∈ A), p o A ≤ ∑ A ∈ S, p o A :=
      Finset.sum_le_sum_of_subset_of_nonneg (Finset.filter_subset _ _)
        (fun i hi _ => hp.1 o i hi)
    exact mul_le_mul_of_nonneg_left hfilt (hK.1 w o)
  calc worldSuccess K S p w
      = ∑ o, K w o * ∑ A ∈ S.filter (fun A => w ∈ A), p o A := rfl
    _ ≤ ∑ o, K w o * ∑ A ∈ S, p o A := Finset.sum_le_sum (fun o _ => hstep o)
    _ = ∑ o, K w o * 1 := by simp [hp.2]
    _ = ∑ o, K w o := by simp
    _ = 1 := hK.2 w

/-- `Guarantees` is downward closed in the target level. -/
theorem Guarantees.anti {K : Experiment n m} {S : Finset (Finset (Fin n))} {t t' : ℝ}
    (h : Guarantees K S t) (hle : t' ≤ t) : Guarantees K S t' := by
  obtain ⟨p, hp, hval⟩ := h
  exact ⟨p, hp, fun w => hle.trans (hval w)⟩

/-- Every nonempty relation trivially guarantees probability zero, using a
policy that always plays a single fixed action. -/
theorem guarantees_zero {K : Experiment n m} (hK : IsExperiment K)
    {S : Finset (Finset (Fin n))} (hS : S.Nonempty) : Guarantees K S 0 := by
  obtain ⟨A0, hA0⟩ := hS
  refine ⟨fun _ A => if A = A0 then 1 else 0, ⟨?_, ?_⟩, ?_⟩
  · intro o A _
    dsimp only; by_cases h : A = A0 <;> simp [h]
  · intro o
    simp [Finset.sum_ite_eq', hA0]
  · intro w
    have : (0:ℝ) ≤ worldSuccess K S (fun _ A => if A = A0 then 1 else 0) w := by
      unfold worldSuccess
      apply Finset.sum_nonneg
      intro o _
      apply mul_nonneg (hK.1 w o)
      apply Finset.sum_nonneg
      intro A _
      dsimp only; by_cases h : A = A0 <;> simp [h]
    linarith

/-- **Weak duality.** Every policy's worst-world success is at most the
Bayes bound at every prior: the guaranteed level `t` of any policy is
bounded by `B(pi, S)` for every prior `pi`. -/
theorem weak_duality {K : Experiment n m} {S : Finset (Finset (Fin n))}
    {p : Fin m → Finset (Fin n) → ℝ} (hp : IsPolicy S p)
    {pi : Fin n → ℝ} (hpi : IsPrior pi)
    {t : ℝ} (ht : ∀ w, t ≤ worldSuccess K S p w) :
    t ≤ bayesBound K pi S := by
  have step1 : t ≤ ∑ w, pi w * worldSuccess K S p w := by
    have : t * ∑ w, pi w ≤ ∑ w, pi w * worldSuccess K S p w := by
      rw [Finset.mul_sum]
      apply Finset.sum_le_sum
      intro w _
      have := ht w
      have hnn := hpi.1 w
      nlinarith
    simpa [hpi.2] using this
  have hfilterA : ∀ A : Finset (Fin n), (Finset.univ : Finset (Fin n)).filter (· ∈ A) = A := by
    intro A
    ext w
    simp
  have hwsum : ∀ (A : Finset (Fin n)) (o : Fin m),
      ∑ w : Fin n, (if w ∈ A then pi w * K w o * p o A else 0)
        = p o A * ∑ w ∈ A, pi w * K w o := by
    intro A o
    rw [← Finset.sum_filter, hfilterA, Finset.mul_sum]
    apply Finset.sum_congr rfl
    intro w _
    ring
  have step2 : ∑ w, pi w * worldSuccess K S p w
      = ∑ o, ∑ A ∈ S, p o A * ∑ w ∈ A, pi w * K w o := by
    unfold worldSuccess
    have expand : ∀ w : Fin n, pi w * ∑ o, K w o * ∑ A ∈ S.filter (fun A => w ∈ A), p o A
        = ∑ o, ∑ A ∈ S, (if w ∈ A then pi w * K w o * p o A else 0) := by
      intro w
      rw [Finset.mul_sum]
      apply Finset.sum_congr rfl
      intro o _
      rw [Finset.sum_filter, Finset.mul_sum, Finset.mul_sum]
      apply Finset.sum_congr rfl
      intro A _
      split <;> ring
    calc ∑ w, pi w * ∑ o, K w o * ∑ A ∈ S.filter (fun A => w ∈ A), p o A
        = ∑ w, ∑ o, ∑ A ∈ S, (if w ∈ A then pi w * K w o * p o A else 0) := by
          exact Finset.sum_congr rfl (fun w _ => expand w)
      _ = ∑ o, ∑ A ∈ S, ∑ w, (if w ∈ A then pi w * K w o * p o A else 0) := by
          rw [Finset.sum_comm]
          apply Finset.sum_congr rfl
          intro o _
          rw [Finset.sum_comm]
      _ = ∑ o, ∑ A ∈ S, p o A * ∑ w ∈ A, pi w * K w o := by
          apply Finset.sum_congr rfl
          intro o _
          apply Finset.sum_congr rfl
          intro A _
          exact hwsum A o
  have step3 : ∑ o, ∑ A ∈ S, p o A * ∑ w ∈ A, pi w * K w o ≤ bayesBound K pi S := by
    unfold bayesBound
    apply Finset.sum_le_sum
    intro o _
    have hbound : ∀ A ∈ S, p o A * ∑ w ∈ A, pi w * K w o
        ≤ p o A * maxOver S (fun A => ∑ w ∈ A, pi w * K w o) :=
      fun A hA => mul_le_mul_of_nonneg_left
        (le_maxOver (f := fun A => ∑ w ∈ A, pi w * K w o) hA) (hp.1 o A hA)
    calc ∑ A ∈ S, p o A * ∑ w ∈ A, pi w * K w o
        ≤ ∑ A ∈ S, p o A * maxOver S (fun A => ∑ w ∈ A, pi w * K w o) :=
          Finset.sum_le_sum hbound
      _ = (∑ A ∈ S, p o A) * maxOver S (fun A => ∑ w ∈ A, pi w * K w o) := by
          rw [Finset.sum_mul]
      _ = maxOver S (fun A => ∑ w ∈ A, pi w * K w o) := by rw [hp.2 o]; ring
  linarith [step1, step2, step3]

/-! ## Blackwell sufficiency (garbling implies dominance) -/

/-- **Garbling implies dominance.** If `L = K * M` for a row-stochastic `M`
then `K` dominates `L`: composing any `L`-policy with `M` produces a
`K`-policy with identical success in every world. -/
theorem garbling_dominates {K : Experiment n m} {m' : ℕ} {M : Experiment m m'}
    {L : Experiment n m'} (hM : IsExperiment M) (hL : L = K * M) :
    Dominates K L := by
  intro S t hgt
  obtain ⟨q, hq, hval⟩ := hgt
  set p : Fin m → Finset (Fin n) → ℝ := fun o A => ∑ o', M o o' * q o' A with hp_def
  have hpolicy : IsPolicy S p := by
    constructor
    · intro o A hA
      apply Finset.sum_nonneg
      intro o' _
      exact mul_nonneg (hM.1 o o') (hq.1 o' A hA)
    · intro o
      simp only [hp_def]
      rw [Finset.sum_comm]
      have : ∀ o', ∑ A ∈ S, M o o' * q o' A = M o o' * ∑ A ∈ S, q o' A := by
        intro o'; rw [Finset.mul_sum]
      simp only [this, hq.2, mul_one]
      exact hM.2 o
  have hLmul : ∀ w o', L w o' = ∑ o, K w o * M o o' := by
    intro w o'
    rw [hL]
    exact Matrix.mul_apply
  have hsucc : ∀ w, worldSuccess K S p w = worldSuccess L S q w := by
    intro w
    have step1 : ∀ o, K w o * ∑ A ∈ S.filter (fun A => w ∈ A), p o A
        = ∑ A ∈ S.filter (fun A => w ∈ A), ∑ o', K w o * M o o' * q o' A := by
      intro o
      simp only [hp_def, Finset.mul_sum]
      apply Finset.sum_congr rfl
      intro A _
      apply Finset.sum_congr rfl
      intro o' _
      ring
    calc worldSuccess K S p w
        = ∑ o, K w o * ∑ A ∈ S.filter (fun A => w ∈ A), p o A := rfl
      _ = ∑ o, ∑ A ∈ S.filter (fun A => w ∈ A), ∑ o', K w o * M o o' * q o' A :=
          Finset.sum_congr rfl (fun o _ => step1 o)
      _ = ∑ A ∈ S.filter (fun A => w ∈ A), ∑ o', ∑ o, K w o * M o o' * q o' A := by
          rw [Finset.sum_comm]
          apply Finset.sum_congr rfl
          intro A _
          rw [Finset.sum_comm]
      _ = ∑ A ∈ S.filter (fun A => w ∈ A), ∑ o', L w o' * q o' A := by
          apply Finset.sum_congr rfl
          intro A _
          apply Finset.sum_congr rfl
          intro o' _
          rw [← Finset.sum_mul, ← hLmul w o']
      _ = ∑ o', ∑ A ∈ S.filter (fun A => w ∈ A), L w o' * q o' A := by
          rw [Finset.sum_comm]
      _ = ∑ o', L w o' * ∑ A ∈ S.filter (fun A => w ∈ A), q o' A := by
          apply Finset.sum_congr rfl
          intro o' _
          rw [← Finset.mul_sum]
      _ = worldSuccess L S q w := rfl
  exact ⟨p, hpolicy, fun w => (hsucc w) ▸ hval w⟩

/-! ## Normalization lemmas -/

/-- If some world is in no action of `S`, then `S` cannot guarantee any
positive success level. -/
theorem not_covers_guarantees_nonpos {K : Experiment n m} {S : Finset (Finset (Fin n))}
    {w0 : Fin n} (huncov : ∀ A ∈ S, w0 ∉ A) {t : ℝ} (ht : 0 < t) :
    ¬ Guarantees K S t := by
  rintro ⟨p, hp, hval⟩
  have hzero : worldSuccess K S p w0 = 0 := by
    unfold worldSuccess
    have : S.filter (fun A => w0 ∈ A) = ∅ := by
      apply Finset.filter_false_of_mem
      intro A hA
      exact huncov A hA
    simp [this]
  have := hval w0
  rw [hzero] at this
  linarith

/-- A relation containing the full world set can always guarantee
probability one (this is the best possible level, by
`worldSuccess_le_one`). -/
theorem guarantees_one_of_univ_mem {K : Experiment n m} (hK : IsExperiment K)
    {S : Finset (Finset (Fin n))} (hS : (Finset.univ : Finset (Fin n)) ∈ S) :
    Guarantees K S 1 := by
  refine ⟨fun _ A => if A = Finset.univ then 1 else 0, ⟨?_, ?_⟩, ?_⟩
  · intro o A _
    dsimp only; by_cases h : A = Finset.univ <;> simp [h]
  · intro o
    simp [Finset.sum_ite_eq', hS]
  · intro w
    have hfix : ∀ A : Finset (Fin n), (if w ∈ A then (if A = Finset.univ then (1:ℝ) else 0) else 0)
        = (if A = Finset.univ then (1:ℝ) else 0) := by
      intro A
      by_cases h : A = Finset.univ
      · simp [h]
      · simp [h]
    have hval : worldSuccess K S (fun _ A => if A = Finset.univ then 1 else 0) w
        = ∑ o, K w o * ∑ A ∈ S, (if A = Finset.univ then (1:ℝ) else 0) := by
      unfold worldSuccess
      apply Finset.sum_congr rfl
      intro o _
      congr 1
      rw [Finset.sum_filter]
      exact Finset.sum_congr rfl (fun A _ => hfix A)
    rw [hval]
    simp [Finset.sum_ite_eq', hS, hK.2 w]


/-! ## Value one is possibilistic -/

/-- The support of a signal `o` under experiment `K`: the worlds where `o`
occurs with positive probability. -/
noncomputable def signalSupport {K : Experiment n m} (o : Fin m) : Finset (Fin n) :=
  Finset.univ.filter (fun w => 0 < K w o)

/-- **Value one is possibilistic.** `Guarantees K S 1` holds iff every
signal that occurs with positive probability somewhere has its support
contained in some action of `S`. Requires `S` nonempty, matching the
standing definition of a success relation; without it the left side is
always false (no policy can satisfy `IsPolicy ∅ p`) while the right side
can be vacuously true. -/
theorem guarantees_one_iff_possibilistic {K : Experiment n m} (hK : IsExperiment K)
    {S : Finset (Finset (Fin n))} (hSne : S.Nonempty) :
    Guarantees K S 1 ↔
      ∀ o : Fin m, (signalSupport (K := K) o).Nonempty →
        ∃ A ∈ S, signalSupport (K := K) o ⊆ A := by
  constructor
  · rintro ⟨p, hp, hval⟩ o ⟨w1, hw1⟩
    -- Key fact: at any world w0 reachable through o (K w0 o > 0), every
    -- action of S missing w0 gets zero probability under signal o.
    have key : ∀ w0 : Fin n, 0 < K w0 o → ∀ A ∈ S, w0 ∉ A → p o A = 0 := by
      intro w0 hw0pos A hA hnotA
      have hle : worldSuccess K S p w0 ≤ 1 := worldSuccess_le_one hK hp w0
      have hge : (1:ℝ) ≤ worldSuccess K S p w0 := hval w0
      have heq1 : worldSuccess K S p w0 = 1 := le_antisymm hle hge
      have hterm_le : ∀ o' : Fin m,
          K w0 o' * ∑ A ∈ S.filter (fun A => w0 ∈ A), p o' A ≤ K w0 o' * 1 := by
        intro o'
        apply mul_le_mul_of_nonneg_left _ (hK.1 w0 o')
        calc ∑ A ∈ S.filter (fun A => w0 ∈ A), p o' A
            ≤ ∑ A ∈ S, p o' A :=
              Finset.sum_le_sum_of_subset_of_nonneg (Finset.filter_subset _ _)
                (fun i hi _ => hp.1 o' i hi)
          _ = 1 := hp.2 o'
      have hsum_eq : ∑ o' : Fin m, K w0 o' * ∑ A ∈ S.filter (fun A => w0 ∈ A), p o' A
          = ∑ o' : Fin m, K w0 o' * 1 := by
        show worldSuccess K S p w0 = _
        rw [heq1]; simp [hK.2 w0]
      have hall_eq := (Finset.sum_eq_sum_iff_of_le (fun o' _ => hterm_le o')).mp hsum_eq
      have ho' := hall_eq o (Finset.mem_univ o)
      have hfilt_eq_one : ∑ A ∈ S.filter (fun A => w0 ∈ A), p o A = 1 :=
        mul_left_cancel₀ (ne_of_gt hw0pos) ho'
      have hsplit := Finset.sum_filter_add_sum_filter_not S (fun A => w0 ∈ A) (p o)
      rw [hfilt_eq_one, hp.2 o] at hsplit
      have hcompl_zero : ∑ A ∈ S.filter (fun A => ¬ w0 ∈ A), p o A = 0 := by linarith
      have hAmem : A ∈ S.filter (fun A => ¬ w0 ∈ A) := Finset.mem_filter.mpr ⟨hA, hnotA⟩
      exact (Finset.sum_eq_zero_iff_of_nonneg
        (fun A hA => hp.1 o A (Finset.filter_subset _ _ hA))).mp hcompl_zero A hAmem
    obtain ⟨A, hA, hApos⟩ : ∃ A ∈ S, 0 < p o A := by
      by_contra hcon
      push Not at hcon
      have hz : ∑ A ∈ S, p o A = 0 :=
        Finset.sum_eq_zero (fun A hA => le_antisymm (hcon A hA) (hp.1 o A hA))
      rw [hp.2 o] at hz
      norm_num at hz
    refine ⟨A, hA, ?_⟩
    intro w hw
    simp only [signalSupport, Finset.mem_filter, Finset.mem_univ, true_and] at hw
    by_contra hwA
    exact absurd (key w hw A hA hwA) (ne_of_gt hApos)
  · intro hsupp
    classical
    choose f hf1 hf2 using fun o (h : (signalSupport (K := K) o).Nonempty) => hsupp o h
    obtain ⟨A0, hA0⟩ := hSne
    refine ⟨fun o A => if h : (signalSupport (K := K) o).Nonempty then
        (if A = f o h then (1:ℝ) else 0) else (if A = A0 then (1:ℝ) else 0), ⟨?_, ?_⟩, ?_⟩
    · intro o A _
      dsimp only
      split
      · split <;> norm_num
      · split <;> norm_num
    · intro o
      dsimp only
      split
      · rename_i h
        simp [Finset.sum_ite_eq', hf1 o h]
      · simp [Finset.sum_ite_eq', hA0]
    · intro w
      have hval : worldSuccess K S
          (fun o A => if h : (signalSupport (K := K) o).Nonempty then
              (if A = f o h then (1:ℝ) else 0) else (if A = A0 then (1:ℝ) else 0)) w
          = ∑ o, K w o := by
        unfold worldSuccess
        apply Finset.sum_congr rfl
        intro o _
        by_cases hor : 0 < K w o
        · have hsupne : (signalSupport (K := K) o).Nonempty := ⟨w, by
            simp [signalSupport, hor]⟩
          have hwmem : w ∈ f o hsupne := hf2 o hsupne (by simp [signalSupport, hor])
          have hcollapse : ∀ A ∈ S,
              (if w ∈ A then (if A = f o hsupne then (1:ℝ) else 0) else 0)
                = (if A = f o hsupne then (1:ℝ) else 0) := by
            intro A _
            by_cases hAeq : A = f o hsupne
            · simp [hAeq, hwmem]
            · simp [hAeq]
          have : ∑ A ∈ S.filter (fun A => w ∈ A), (if hh : (signalSupport (K := K) o).Nonempty
              then (if A = f o hh then (1:ℝ) else 0) else (if A = A0 then (1:ℝ) else 0)) = 1 := by
            rw [Finset.sum_filter]
            simp only [dif_pos hsupne]
            rw [Finset.sum_congr rfl hcollapse, Finset.sum_ite_eq' S (f o hsupne)]
            simp [hf1 o hsupne]
          rw [this, mul_one]
        · have : K w o = 0 := le_antisymm (not_lt.mp hor) (hK.1 w o)
          rw [this]; ring
      rw [hval, hK.2 w]

/-! ## The two-world example -/

namespace TwoWorldExample

noncomputable def K2 : Experiment 2 2 := !![2/3, 1/3; 1/3, 2/3]
noncomputable def L2 : Experiment 2 2 := !![1, 0; 1/2, 1/2]

theorem isExperiment_K2 : IsExperiment K2 :=
  ⟨by intro w o; fin_cases w <;> fin_cases o <;> norm_num [K2],
   by intro w; fin_cases w <;> simp [K2, Fin.sum_univ_two] <;> norm_num⟩

theorem isExperiment_L2 : IsExperiment L2 :=
  ⟨by intro w o; fin_cases w <;> fin_cases o <;> norm_num [L2],
   by intro w; fin_cases w <;> simp [L2, Fin.sum_univ_two] <;> norm_num⟩

/-- Every nonempty subset of `Fin 2` other than the universe is a singleton. -/
theorem finset_fin2_eq (A : Finset (Fin 2)) (hne : A.Nonempty) (hnu : A ≠ Finset.univ) :
    A = {0} ∨ A = {1} := by
  by_cases h0 : (0:Fin 2) ∈ A <;> by_cases h1 : (1:Fin 2) ∈ A
  · exfalso; apply hnu; ext x; fin_cases x <;> simp [h0, h1]
  · left; ext x; fin_cases x <;> simp [h0, h1]
  · right; ext x; fin_cases x <;> simp [h0, h1]
  · exfalso; exact hne.ne_empty (by ext x; fin_cases x <;> simp [h0, h1])

/-- The identification test on two worlds: `{{0}, {1}}`. -/
def S2 : Finset (Finset (Fin 2)) := {({0} : Finset (Fin 2)), {1}}

/-- Every genuine, covering success relation on two worlds that does not
contain the universal action is exactly the identification test. -/
theorem covering_not_univ_eq_S2 {S : Finset (Finset (Fin 2))} (hnE : ∀ A ∈ S, A.Nonempty)
    (hcov : ∀ w : Fin 2, ∃ A ∈ S, w ∈ A) (huniv : (Finset.univ : Finset (Fin 2)) ∉ S) :
    S = S2 := by
  apply Finset.Subset.antisymm
  · intro A hA
    have hne : A.Nonempty := hnE A hA
    have hnu : A ≠ Finset.univ := by rintro rfl; exact huniv hA
    rcases finset_fin2_eq A hne hnu with h | h <;> simp [S2, h]
  · intro A hA
    simp only [S2, Finset.mem_insert, Finset.mem_singleton] at hA
    rcases hA with h | h
    · subst h
      obtain ⟨A', hA', hmem⟩ := hcov 0
      have hne' := hnE A' hA'
      have hnu' : A' ≠ Finset.univ := by rintro rfl; exact huniv hA'
      rcases finset_fin2_eq A' hne' hnu' with h1 | h1
      · rwa [h1] at hA'
      · exfalso; rw [h1] at hmem; simp at hmem
    · subst h
      obtain ⟨A', hA', hmem⟩ := hcov 1
      have hne' := hnE A' hA'
      have hnu' : A' ≠ Finset.univ := by rintro rfl; exact huniv hA'
      rcases finset_fin2_eq A' hne' hnu' with h1 | h1
      · exfalso; rw [h1] at hmem; simp at hmem
      · rwa [h1] at hA'

/-- The prior `(1/3, 2/3)`, the exact minimizer of the Bayes bound on `S2`
for both `K2` and `L2`. -/
noncomputable def pi23 : Fin 2 → ℝ := ![1/3, 2/3]

theorem isPrior_pi23 : IsPrior pi23 := by
  refine ⟨?_, ?_⟩
  · intro w; fin_cases w <;> norm_num [pi23]
  · simp [pi23, Fin.sum_univ_two]; norm_num

theorem bayesBound_K2_S2 : bayesBound K2 pi23 S2 = 2/3 := by
  have hS2ne : (S2 : Finset (Finset (Fin 2))).Nonempty := ⟨{0}, by simp [S2]⟩
  unfold bayesBound maxOver
  simp only [dif_pos hS2ne]
  have hsup : ∀ o : Fin 2, S2.sup' hS2ne (fun A => ∑ w ∈ A, pi23 w * K2 w o) =
      max (∑ w ∈ ({0} : Finset (Fin 2)), pi23 w * K2 w o)
        (∑ w ∈ ({1} : Finset (Fin 2)), pi23 w * K2 w o) := by
    intro o
    simp [S2, Finset.sup'_insert, Finset.sup'_singleton]
  simp only [hsup]
  simp [Fin.sum_univ_two, K2, pi23]
  norm_num [max_def]

theorem bayesBound_L2_S2 : bayesBound L2 pi23 S2 = 2/3 := by
  have hS2ne : (S2 : Finset (Finset (Fin 2))).Nonempty := ⟨{0}, by simp [S2]⟩
  unfold bayesBound maxOver
  simp only [dif_pos hS2ne]
  have hsup : ∀ o : Fin 2, S2.sup' hS2ne (fun A => ∑ w ∈ A, pi23 w * L2 w o) =
      max (∑ w ∈ ({0} : Finset (Fin 2)), pi23 w * L2 w o)
        (∑ w ∈ ({1} : Finset (Fin 2)), pi23 w * L2 w o) := by
    intro o
    simp [S2, Finset.sup'_insert, Finset.sup'_singleton]
  simp only [hsup]
  simp [Fin.sum_univ_two, L2, pi23]
  norm_num [max_def]

theorem le_two_thirds_K2 {t : ℝ} (h : Guarantees K2 S2 t) : t ≤ 2/3 := by
  obtain ⟨p, hp, hval⟩ := h
  have hwd := weak_duality (K := K2) hp isPrior_pi23 hval
  rwa [bayesBound_K2_S2] at hwd

theorem le_two_thirds_L2 {t : ℝ} (h : Guarantees L2 S2 t) : t ≤ 2/3 := by
  obtain ⟨p, hp, hval⟩ := h
  have hwd := weak_duality (K := L2) hp isPrior_pi23 hval
  rwa [bayesBound_L2_S2] at hwd

/-- Deterministic policy for `K2`: guess the world matching the signal. -/
noncomputable def pK : Fin 2 → Finset (Fin 2) → ℝ :=
  fun o A => if A = ({(o : Fin 2)} : Finset (Fin 2)) then 1 else 0

theorem isPolicy_pK : IsPolicy S2 pK := by
  refine ⟨?_, ?_⟩
  · intro o A _; dsimp only [pK]; split_ifs <;> norm_num
  · intro o; fin_cases o <;> simp [S2, pK]

theorem guarantees_K2_S2 : Guarantees K2 S2 (2/3) := by
  refine ⟨pK, isPolicy_pK, fun w => le_of_eq ?_⟩
  fin_cases w <;>
    simp [worldSuccess, S2, pK, K2, Finset.filter_insert, Finset.filter_singleton]

/-- Randomized policy for `L2`: on signal `1` (certain that `w = 1`) always
guess `{1}`; on signal `0` mix `2/3` on `{0}` and `1/3` on `{1}`. -/
noncomputable def qL : Fin 2 → Finset (Fin 2) → ℝ :=
  fun o A => if o = 0 then (if A = {0} then 2/3 else if A = {1} then 1/3 else 0)
             else (if A = {1} then 1 else 0)

theorem isPolicy_qL : IsPolicy S2 qL := by
  refine ⟨?_, ?_⟩
  · intro o A _
    fin_cases o <;> simp only [qL] <;> split_ifs <;> norm_num
  · intro o; fin_cases o <;> simp [S2, qL] <;> norm_num

theorem guarantees_L2_S2 : Guarantees L2 S2 (2/3) := by
  refine ⟨qL, isPolicy_qL, fun w => le_of_eq ?_⟩
  fin_cases w <;>
    simp [worldSuccess, S2, qL, L2, Finset.filter_insert, Finset.filter_singleton] <;> norm_num

/-- **The two-world example, first direction.** `K2` dominates `L2` on
every genuine success relation. -/
theorem dominates_K2_L2 {S : Finset (Finset (Fin 2))} (hnE : ∀ A ∈ S, A.Nonempty) :
    ∀ t : ℝ, Guarantees L2 S t → Guarantees K2 S t := by
  intro t hL
  have hSne : S.Nonempty := by
    obtain ⟨q, hq, _⟩ := hL
    by_contra hS0
    rw [Finset.not_nonempty_iff_eq_empty] at hS0
    have h1 := hq.2 (0 : Fin 2)
    rw [hS0] at h1
    simp at h1
  by_cases hcov : ∀ w : Fin 2, ∃ A ∈ S, w ∈ A
  · by_cases huniv : (Finset.univ : Finset (Fin 2)) ∈ S
    · have h1 : Guarantees K2 S 1 := guarantees_one_of_univ_mem isExperiment_K2 huniv
      obtain ⟨q, hq, hval⟩ := hL
      have h2 : t ≤ 1 := le_trans (hval 0) (worldSuccess_le_one isExperiment_L2 hq 0)
      exact h1.anti h2
    · have hSeq : S = S2 := covering_not_univ_eq_S2 hnE hcov huniv
      subst hSeq
      exact guarantees_K2_S2.anti (le_two_thirds_L2 hL)
  · by_cases ht : 0 < t
    · exfalso
      push Not at hcov
      obtain ⟨w0, hw0⟩ := hcov
      exact not_covers_guarantees_nonpos (K := L2) (S := S) (w0 := w0) hw0 ht hL
    · exact (guarantees_zero isExperiment_K2 hSne).anti (not_lt.mp ht)

/-- **The two-world example, second direction.** `L2` dominates `K2` on
every genuine success relation. -/
theorem dominates_L2_K2 {S : Finset (Finset (Fin 2))} (hnE : ∀ A ∈ S, A.Nonempty) :
    ∀ t : ℝ, Guarantees K2 S t → Guarantees L2 S t := by
  intro t hK
  have hSne : S.Nonempty := by
    obtain ⟨q, hq, _⟩ := hK
    by_contra hS0
    rw [Finset.not_nonempty_iff_eq_empty] at hS0
    have h1 := hq.2 (0 : Fin 2)
    rw [hS0] at h1
    simp at h1
  by_cases hcov : ∀ w : Fin 2, ∃ A ∈ S, w ∈ A
  · by_cases huniv : (Finset.univ : Finset (Fin 2)) ∈ S
    · have h1 : Guarantees L2 S 1 := guarantees_one_of_univ_mem isExperiment_L2 huniv
      obtain ⟨q, hq, hval⟩ := hK
      have h2 : t ≤ 1 := le_trans (hval 0) (worldSuccess_le_one isExperiment_K2 hq 0)
      exact h1.anti h2
    · have hSeq : S = S2 := covering_not_univ_eq_S2 hnE hcov huniv
      subst hSeq
      exact guarantees_L2_S2.anti (le_two_thirds_K2 hK)
  · by_cases ht : 0 < t
    · exfalso
      push Not at hcov
      obtain ⟨w0, hw0⟩ := hcov
      exact not_covers_guarantees_nonpos (K := K2) (S := S) (w0 := w0) hw0 ht hK
    · exact (guarantees_zero isExperiment_L2 hSne).anti (not_lt.mp ht)

/-- **`L2` is not a garbling of `K2`.** No row-stochastic `M` satisfies
`L2 = K2 * M`: the resulting linear system forces `M 0 1 < 0`. -/
theorem not_garbling_L2_K2 : ¬ ∃ M : Experiment 2 2, IsExperiment M ∧ L2 = K2 * M := by
  rintro ⟨M, hM, hL⟩
  have e00 : L2 0 0 = ∑ o, K2 0 o * M o 0 := by rw [hL]; exact Matrix.mul_apply
  have e10 : L2 1 0 = ∑ o, K2 1 o * M o 0 := by rw [hL]; exact Matrix.mul_apply
  simp [Fin.sum_univ_two, K2, L2] at e00 e10
  have r00 : M 0 0 + M 0 1 = 1 := by
    have := hM.2 0; simpa [Fin.sum_univ_two] using this
  have hnn : 0 ≤ M 0 1 := hM.1 0 1
  linarith

end TwoWorldExample

/-! ## The three-world strict separation -/

namespace ThreeWorldExample

noncomputable def K3 : Experiment 3 2 := !![1, 0; 1/4, 3/4; 0, 1]
noncomputable def L3 : Experiment 3 2 := !![1/4, 3/4; 1, 0; 1, 0]

theorem isExperiment_K3 : IsExperiment K3 :=
  ⟨by intro w o; fin_cases w <;> fin_cases o <;> norm_num [K3],
   by intro w; fin_cases w <;> simp [K3, Fin.sum_univ_two] <;> norm_num⟩

theorem isExperiment_L3 : IsExperiment L3 :=
  ⟨by intro w o; fin_cases w <;> fin_cases o <;> norm_num [L3],
   by intro w; fin_cases w <;> simp [L3, Fin.sum_univ_two] <;> norm_num⟩

/-- The two-test relation `{{0,1},{1,2}}` witnessing the strict separation. -/
def S3 : Finset (Finset (Fin 3)) := {({0,1} : Finset (Fin 3)), {1,2}}

/-- Deterministic policy for `K3`: on signal `0` guess `{0,1}`, on signal
`1` guess `{1,2}`. -/
noncomputable def pK3 : Fin 2 → Finset (Fin 3) → ℝ :=
  fun o A => if o = 0 then (if A = {0,1} then 1 else 0) else (if A = {1,2} then 1 else 0)

theorem isPolicy_pK3 : IsPolicy S3 pK3 := by
  refine ⟨?_, ?_⟩
  · intro o A _; fin_cases o <;> simp only [pK3] <;> split_ifs <;> norm_num
  · intro o; fin_cases o <;> simp [S3, pK3]

/-- **`K3` guarantees probability one on `S3`.** -/
theorem guarantees_K3_S3 : Guarantees K3 S3 1 := by
  refine ⟨pK3, isPolicy_pK3, fun w => le_of_eq ?_⟩
  fin_cases w <;>
    simp [worldSuccess, S3, pK3, K3, Finset.filter_insert, Finset.filter_singleton] <;> norm_num

/-- The prior `(4/5, 0, 1/5)` witnessing `L3`'s upper bound on `S3`. -/
noncomputable def pi3 : Fin 3 → ℝ := ![4/5, 0, 1/5]

theorem isPrior_pi3 : IsPrior pi3 := by
  refine ⟨?_, ?_⟩
  · intro w; fin_cases w <;> norm_num [pi3]
  · simp [pi3, Fin.sum_univ_three]; norm_num

theorem bayesBound_L3_S3 : bayesBound L3 pi3 S3 = 4/5 := by
  have hS3ne : (S3 : Finset (Finset (Fin 3))).Nonempty := ⟨{0,1}, by simp [S3]⟩
  unfold bayesBound maxOver
  simp only [dif_pos hS3ne]
  have hsup : ∀ o : Fin 2, S3.sup' hS3ne (fun A => ∑ w ∈ A, pi3 w * L3 w o) =
      max (∑ w ∈ ({0,1} : Finset (Fin 3)), pi3 w * L3 w o)
        (∑ w ∈ ({1,2} : Finset (Fin 3)), pi3 w * L3 w o) := by
    intro o
    simp [S3, Finset.sup'_insert, Finset.sup'_singleton]
  simp only [hsup]
  simp [Fin.sum_univ_two, L3, pi3, Finset.sum_insert, Finset.sum_singleton]
  norm_num [max_def]

/-- **`L3` cannot guarantee more than `4/5` on `S3`**, certified by the
explicit prior `pi3`. -/
theorem le_four_fifths_L3 {t : ℝ} (h : Guarantees L3 S3 t) : t ≤ 4/5 := by
  obtain ⟨p, hp, hval⟩ := h
  have hwd := weak_duality (K := L3) hp isPrior_pi3 hval
  rwa [bayesBound_L3_S3] at hwd

/-- **`L3` is not a garbling of `K3`.** The forced values of a hypothetical
row-stochastic `M` at rows `0` and `2` are inconsistent with row `1`. -/
theorem not_garbling_L3_K3 : ¬ ∃ M : Experiment 2 2, IsExperiment M ∧ L3 = K3 * M := by
  rintro ⟨M, _hM, hL⟩
  have e0 : L3 0 0 = ∑ o, K3 0 o * M o 0 := by rw [hL]; exact Matrix.mul_apply
  have e1 : L3 1 0 = ∑ o, K3 1 o * M o 0 := by rw [hL]; exact Matrix.mul_apply
  have e2 : L3 2 0 = ∑ o, K3 2 o * M o 0 := by rw [hL]; exact Matrix.mul_apply
  rw [Fin.sum_univ_two] at e0 e1 e2
  simp [K3, L3] at e0 e1 e2
  linarith [e0, e1, e2]

end ThreeWorldExample

end HardProblems.WorstCaseSuccess
Additional formal layer: WorstCaseSuccessExtended.lean

LeanTest/HardProblems/WorstCaseSuccessExtended.lean

import Mathlib
import LeanTest.HardProblems.WorstCaseSuccess

/-!
# Worst-case success: extensions (monotonicity, Lemma J, the pair-signal
identity, the reduction's key inequality)

This module is part of the book companion. It extends
`LeanTest.HardProblems.WorstCaseSuccess` with results from the operational
hardness research record, specifically
`book/research/wcs/irredundance/REPORT.md` (Lemma J) and
`book/research/wcs/complexity/REPORT.md` (Theorems 1 to 3). It imports the
existing module and adds no new axioms.

It is imported from `LeanTest/HardProblems.lean`. It depends only on
`LeanTest.HardProblems.WorstCaseSuccess`.

## What is proved

1. `guarantees_mono`: the general-`n`, `m` normalization lemma left open in
   `lean-module-report.md`. If every action of `S` is contained in some
   action of `S'`, any level `K` guarantees on `S` it also guarantees on
   `S'` (for a genuine experiment `K`).
2. `join`, and `lemma_J`: for disjoint `X, Y` covering all worlds and
   success relations `T1` (actions inside `X`) and `T2` (actions inside
   `Y`), the join `T1 ⋁ T2` guarantees exactly the conjunction of what
   `T1 ⋁ {Y}` and `{X} ⋁ T2` guarantee. The forward direction is
   monotonicity; the backward direction is the explicit product policy.
3. `maxOver_pair_uncovered` and `maxOver_pair_covered`: the two halves of
   the pair-signal Bayes-bound identity used in the proof of Theorem 1 of
   the complexity report.
4. `key_inequality` and `key_inequality_witness`: the pure real-arithmetic
   core of the SUBSET-SUM reduction (Theorem 3 of the complexity report),
   together with the converse witness `sigma = T, lambda = d`.

## What is not attempted

The full formalization of Theorems 1 to 3 (the general pair normal form,
the star formula, and the coNP-completeness reduction end to end) is out of
scope; only the specific algebraic cores named above are formalized, each
faithful to the corresponding statement in the reports. The eight-test
reduction for three worlds (milestone item 6) is not attempted.
-/

open Finset
open HardProblems.WorstCaseSuccess

namespace HardProblems.WorstCaseSuccessExtended

/-! ## 1. Monotonicity -/

/-- **Monotonicity of `Guarantees`.** If every action of `S` is contained in
some action of `S'`, then any level `K` guarantees on `S` it also guarantees
on `S'`. This is the general-`n`, `m` normalization lemma from item 3 of the
milestone that `lean-module-report.md` records as not attempted. -/
theorem guarantees_mono {n m : ℕ} {K : Experiment n m} (hK : IsExperiment K)
    {S S' : Finset (Finset (Fin n))} {t : ℝ}
    (hsub : ∀ A ∈ S, ∃ A' ∈ S', A ⊆ A') (h : Guarantees K S t) :
    Guarantees K S' t := by
  classical
  obtain ⟨p, hp, hval⟩ := h
  set f : Finset (Fin n) → Finset (Fin n) :=
    fun A => if h : A ∈ S then (hsub A h).choose else A with hf_def
  have hf_mem : ∀ A, A ∈ S → f A ∈ S' := by
    intro A hA
    simp only [hf_def, dif_pos hA]
    exact (hsub A hA).choose_spec.1
  have hf_sub : ∀ A, A ∈ S → A ⊆ f A := by
    intro A hA
    simp only [hf_def, dif_pos hA]
    exact (hsub A hA).choose_spec.2
  set p' : Fin m → Finset (Fin n) → ℝ :=
    fun o B => ∑ A ∈ S.filter (fun A => f A = B), p o A with hp'_def
  have hpolicy : IsPolicy S' p' := by
    refine ⟨fun o B _ => ?_, fun o => ?_⟩
    · exact Finset.sum_nonneg fun A hA => hp.1 o A (Finset.mem_filter.mp hA).1
    · have hfib := Finset.sum_fiberwise_of_maps_to hf_mem (fun A => p o A)
      simpa only [hp'_def] using hfib.trans (hp.2 o)
  have key : ∀ o : Fin m, ∀ w : Fin n,
      ∑ A ∈ S.filter (fun A => w ∈ A), p o A
        ≤ ∑ B ∈ S'.filter (fun B => w ∈ B), p' o B := by
    intro o w
    have hstep1 : ∑ A ∈ S.filter (fun A => w ∈ A), p o A
        ≤ ∑ A ∈ S.filter (fun A => w ∈ f A), p o A := by
      apply Finset.sum_le_sum_of_subset_of_nonneg
      · intro A hA
        obtain ⟨hAS, hAw⟩ := Finset.mem_filter.mp hA
        exact Finset.mem_filter.mpr ⟨hAS, hf_sub A hAS hAw⟩
      · intro A hA _
        exact hp.1 o A (Finset.mem_filter.mp hA).1
    have hmaps : ∀ A ∈ S.filter (fun A => w ∈ f A), f A ∈ S'.filter (fun B => w ∈ B) := by
      intro A hA
      obtain ⟨hAS, hAw⟩ := Finset.mem_filter.mp hA
      exact Finset.mem_filter.mpr ⟨hf_mem A hAS, hAw⟩
    have hfib := Finset.sum_fiberwise_of_maps_to hmaps (fun A => p o A)
    have hfilter_eq : ∀ B ∈ S'.filter (fun B => w ∈ B),
        (S.filter (fun A => w ∈ f A)).filter (fun A => f A = B)
          = S.filter (fun A => f A = B) := by
      intro B hB
      have hwB : w ∈ B := (Finset.mem_filter.mp hB).2
      rw [Finset.filter_filter]
      apply Finset.filter_congr
      intro A _
      constructor
      · exact fun hh => hh.2
      · intro hh
        refine ⟨?_, hh⟩
        rw [hh]; exact hwB
    have hstep2 : ∑ A ∈ S.filter (fun A => w ∈ f A), p o A
        = ∑ B ∈ S'.filter (fun B => w ∈ B), p' o B := by
      rw [← hfib]
      apply Finset.sum_congr rfl
      intro B hB
      simp only [hp'_def]
      rw [hfilter_eq B hB]
    exact hstep1.trans_eq hstep2
  refine ⟨p', hpolicy, fun w => le_trans (hval w) ?_⟩
  unfold worldSuccess
  exact Finset.sum_le_sum fun o _ => mul_le_mul_of_nonneg_left (key o w) (hK.1 w o)

/-! ## 2. Lemma J: joins are redundant -/

/-- The join of two success relations: the family of unions `A ∪ B` for
`A ∈ T1`, `B ∈ T2`. Matches `T1 ⋁ T2` in `irredundance/REPORT.md`. -/
def join {n : ℕ} (T1 T2 : Finset (Finset (Fin n))) : Finset (Finset (Fin n)) :=
  (T1 ×ˢ T2).image (fun p => p.1 ∪ p.2)

theorem mem_join {n : ℕ} {T1 T2 : Finset (Finset (Fin n))} {C : Finset (Fin n)} :
    C ∈ join T1 T2 ↔ ∃ A ∈ T1, ∃ B ∈ T2, A ∪ B = C := by
  unfold join
  simp only [Finset.mem_image, Finset.mem_product, Prod.exists]
  constructor
  · rintro ⟨A, B, ⟨hA, hB⟩, hC⟩; exact ⟨A, hA, B, hB, hC⟩
  · rintro ⟨A, hA, B, hB, hC⟩; exact ⟨A, B, ⟨hA, hB⟩, hC⟩

/-- If `X, Y` are disjoint and `A, A' ⊆ X`, `B, B' ⊆ Y`, then `A ∪ B` and
`A' ∪ B'` agree iff `A = A'` and `B = B'`: unions of disjoint-supported sets
determine their two parts. -/
theorem union_eq_union_iff_of_disjoint {n : ℕ} {X Y A B A' B' : Finset (Fin n)}
    (hdisj : Disjoint X Y) (hA : A ⊆ X) (hB : B ⊆ Y) (hA' : A' ⊆ X) (hB' : B' ⊆ Y) :
    A ∪ B = A' ∪ B' ↔ A = A' ∧ B = B' := by
  have hxy : ∀ w, w ∈ X → w ∉ Y := Finset.disjoint_left.mp hdisj
  have hyx : ∀ w, w ∈ Y → w ∉ X := Finset.disjoint_right.mp hdisj
  constructor
  · intro heq
    have hAeq : A = A' := by
      ext w
      constructor
      · intro hw
        rcases Finset.mem_union.mp (heq ▸ Finset.mem_union_left B hw) with h | h
        · exact h
        · exact absurd (hB' h) (hxy w (hA hw))
      · intro hw
        rcases Finset.mem_union.mp (heq.symm ▸ Finset.mem_union_left B' hw) with h | h
        · exact h
        · exact absurd (hB h) (hxy w (hA' hw))
    have hBeq : B = B' := by
      ext w
      constructor
      · intro hw
        rcases Finset.mem_union.mp (heq ▸ Finset.mem_union_right A hw) with h | h
        · exact absurd (hA' h) (hyx w (hB hw))
        · exact h
      · intro hw
        rcases Finset.mem_union.mp (heq.symm ▸ Finset.mem_union_right A' hw) with h | h
        · exact absurd (hA h) (hyx w (hB' hw))
        · exact h
    exact ⟨hAeq, hBeq⟩
  · rintro ⟨rfl, rfl⟩; rfl

theorem join_injOn {n : ℕ} {X Y : Finset (Fin n)} (hdisj : Disjoint X Y)
    {T1 T2 : Finset (Finset (Fin n))} (hT1 : ∀ A ∈ T1, A ⊆ X) (hT2 : ∀ B ∈ T2, B ⊆ Y) :
    Set.InjOn (fun p : Finset (Fin n) × Finset (Fin n) => p.1 ∪ p.2) (T1 ×ˢ T2 : Finset _) := by
  rintro ⟨A, B⟩ hp ⟨A', B'⟩ hq heq
  simp only [Finset.coe_product, Set.mem_prod, Finset.mem_coe] at hp hq
  have := (union_eq_union_iff_of_disjoint hdisj (hT1 A hp.1) (hT2 B hp.2)
    (hT1 A' hq.1) (hT2 B' hq.2)).mp heq
  simp only [Prod.mk.injEq]
  exact this

theorem join_singleton_right {n : ℕ} (T : Finset (Finset (Fin n))) (Y : Finset (Fin n)) :
    join T {Y} = T.image (fun A => A ∪ Y) := by
  ext C
  simp only [mem_join, Finset.mem_image, Finset.mem_singleton]
  constructor
  · rintro ⟨A, hA, B, rfl, rfl⟩; exact ⟨A, hA, rfl⟩
  · rintro ⟨A, hA, rfl⟩; exact ⟨A, hA, Y, rfl, rfl⟩

theorem join_singleton_left {n : ℕ} (X : Finset (Fin n)) (T : Finset (Finset (Fin n))) :
    join {X} T = T.image (fun B => X ∪ B) := by
  ext C
  simp only [mem_join, Finset.mem_image, Finset.mem_singleton]
  constructor
  · rintro ⟨A, rfl, B, hB, rfl⟩; exact ⟨B, hB, rfl⟩
  · rintro ⟨B, hB, rfl⟩; exact ⟨X, rfl, B, hB, rfl⟩

theorem inter_left_of_disjoint_union {n : ℕ} {X Y A B : Finset (Fin n)} (hdisj : Disjoint X Y)
    (hA : A ⊆ X) (hB : B ⊆ Y) : (A ∪ B) ∩ X = A := by
  ext w
  simp only [Finset.mem_inter, Finset.mem_union]
  constructor
  · rintro ⟨hw | hw, hwX⟩
    · exact hw
    · exact absurd hwX (Finset.disjoint_right.mp hdisj (hB hw))
  · intro hw
    exact ⟨Or.inl hw, hA hw⟩

theorem inter_right_of_disjoint_union {n : ℕ} {X Y A B : Finset (Fin n)} (hdisj : Disjoint X Y)
    (hA : A ⊆ X) (hB : B ⊆ Y) : (A ∪ B) ∩ Y = B := by
  ext w
  simp only [Finset.mem_inter, Finset.mem_union]
  constructor
  · rintro ⟨hw | hw, hwY⟩
    · exact absurd hwY (Finset.disjoint_left.mp hdisj (hA hw))
    · exact hw
  · intro hw
    exact ⟨Or.inr hw, hB hw⟩

/-- **Lemma J (joins are redundant).** For disjoint `X, Y` with `X ∪ Y`
the whole world set, and success relations `T1` supported on `X` and `T2`
supported on `Y`, the join `T1 ⋁ T2` guarantees `t` iff both `T1 ⋁ {Y}` and
`{X} ⋁ T2` guarantee `t`. -/
theorem lemma_J {n m : ℕ} {X Y : Finset (Fin n)} (hdisj : Disjoint X Y)
    (hcov : X ∪ Y = Finset.univ) {T1 T2 : Finset (Finset (Fin n))}
    (hT1 : ∀ A ∈ T1, A ⊆ X) (hT2 : ∀ B ∈ T2, B ⊆ Y)
    {K : Experiment n m} (hK : IsExperiment K) {t : ℝ} :
    Guarantees K (join T1 T2) t ↔
      Guarantees K (join T1 {Y}) t ∧ Guarantees K (join {X} T2) t := by
  have hTjoin : ∀ A ∈ T1, ∀ B ∈ T2, A ∪ B ⊆ X ∪ Y := fun A hA B hB =>
    Finset.union_subset_union (hT1 A hA) (hT2 B hB)
  constructor
  · intro h
    refine ⟨guarantees_mono hK ?_ h, guarantees_mono hK ?_ h⟩
    · intro C hC
      obtain ⟨A, hA, B, hB, hAB⟩ := mem_join.mp hC
      refine ⟨A ∪ Y, ?_, ?_⟩
      · rw [join_singleton_right]; exact Finset.mem_image_of_mem _ hA
      · rw [← hAB]; exact Finset.union_subset_union (Finset.Subset.refl A) (hT2 B hB)
    · intro C hC
      obtain ⟨A, hA, B, hB, hAB⟩ := mem_join.mp hC
      refine ⟨X ∪ B, ?_, ?_⟩
      · rw [join_singleton_left]; exact Finset.mem_image_of_mem _ hB
      · rw [← hAB]; exact Finset.union_subset_union (hT1 A hA) (Finset.Subset.refl B)
  · rintro ⟨⟨p, hp, hpval⟩, ⟨q, hq, hqval⟩⟩
    rw [join_singleton_right] at hp hpval
    rw [join_singleton_left] at hq hqval
    have hInjY : Set.InjOn (fun A => A ∪ Y) (T1 : Set (Finset (Fin n))) := by
      intro A hA A' hA' heq
      exact ((union_eq_union_iff_of_disjoint hdisj (hT1 A hA) (Finset.Subset.refl Y)
        (hT1 A' hA') (Finset.Subset.refl Y)).mp heq).1
    have hInjX : Set.InjOn (fun B => X ∪ B) (T2 : Set (Finset (Fin n))) := by
      intro B hB B' hB' heq
      exact ((union_eq_union_iff_of_disjoint hdisj (Finset.Subset.refl X) (hT2 B hB)
        (Finset.Subset.refl X) (hT2 B' hB')).mp heq).2
    set p1 : Fin m → Finset (Fin n) → ℝ := fun o A => p o (A ∪ Y) with hp1_def
    set q1 : Fin m → Finset (Fin n) → ℝ := fun o B => q o (X ∪ B) with hq1_def
    have hp1policy : IsPolicy T1 p1 := by
      refine ⟨fun o A hA => hp.1 o (A ∪ Y) (Finset.mem_image_of_mem _ hA), fun o => ?_⟩
      simp only [hp1_def]
      rw [← Finset.sum_image hInjY]
      exact hp.2 o
    have hq1policy : IsPolicy T2 q1 := by
      refine ⟨fun o B hB => hq.1 o (X ∪ B) (Finset.mem_image_of_mem _ hB), fun o => ?_⟩
      simp only [hq1_def]
      rw [← Finset.sum_image hInjX]
      exact hq.2 o
    set r : Fin m → Finset (Fin n) → ℝ := fun o C => p1 o (C ∩ X) * q1 o (C ∩ Y) with hr_def
    have hInjJoin := join_injOn hdisj hT1 hT2
    have hrval : ∀ o : Fin m, ∀ A ∈ T1, ∀ B ∈ T2, r o (A ∪ B) = p1 o A * q1 o B := by
      intro o A hA B hB
      have hXeq := inter_left_of_disjoint_union hdisj (hT1 A hA) (hT2 B hB)
      have hYeq := inter_right_of_disjoint_union hdisj (hT1 A hA) (hT2 B hB)
      simp only [hr_def]
      rw [hXeq, hYeq]
    have hpolicy : IsPolicy (join T1 T2) r := by
      constructor
      · intro o C hC
        obtain ⟨A, hA, B, hB, hAB⟩ := mem_join.mp hC
        rw [← hAB, hrval o A hA B hB]
        exact mul_nonneg (hp1policy.1 o A hA) (hq1policy.1 o B hB)
      · intro o
        unfold join
        rw [Finset.sum_image hInjJoin]
        have hpt : ∀ p ∈ T1 ×ˢ T2, r o (p.1 ∪ p.2) = p1 o p.1 * q1 o p.2 := by
          rintro ⟨A, B⟩ hpmem
          simp only [Finset.mem_product] at hpmem
          exact hrval o A hpmem.1 B hpmem.2
        rw [Finset.sum_congr rfl hpt]
        rw [Finset.sum_product' (f := fun x y => p1 o x * q1 o y)]
        rw [← Finset.sum_mul_sum]
        rw [hp1policy.2 o, hq1policy.2 o]
        ring
    refine ⟨r, hpolicy, fun w => ?_⟩
    rcases Finset.mem_union.mp (hcov ▸ Finset.mem_univ w) with hwX | hwY
    · have heqWS : worldSuccess K (join T1 T2) r w
          = worldSuccess K (T1.image (fun A => A ∪ Y)) p w := by
        unfold worldSuccess
        apply Finset.sum_congr rfl
        intro o _
        congr 1
        have hT1filt : T1.filter (fun A => w ∈ A) = T1.filter (fun A => w ∈ A ∪ Y) := by
          apply Finset.filter_congr
          intro A _
          simp only [Finset.mem_union]
          constructor
          · exact fun hw => Or.inl hw
          · rintro (hw | hw)
            · exact hw
            · exact absurd hwX (Finset.disjoint_right.mp hdisj hw)
        have hjoinFilt : (join T1 T2).filter (fun C => w ∈ C)
            = (T1.filter (fun A => w ∈ A) ×ˢ T2).image (fun p => p.1 ∪ p.2) := by
          unfold join
          rw [Finset.filter_image]
          congr 1
          ext ⟨A, B⟩
          simp only [Finset.mem_filter, Finset.mem_product, Finset.mem_union]
          constructor
          · rintro ⟨⟨hA, hB⟩, hw⟩
            refine ⟨⟨hA, ?_⟩, hB⟩
            rcases hw with hw | hw
            · exact hw
            · exact absurd hwX (Finset.disjoint_right.mp hdisj (hT2 B hB hw))
          · rintro ⟨⟨hA, hw⟩, hB⟩
            exact ⟨⟨hA, hB⟩, Or.inl hw⟩
        have hInjJoin' := join_injOn (T1 := T1.filter (fun A => w ∈ A)) hdisj
          (fun A hA => hT1 A (Finset.mem_of_mem_filter _ hA)) hT2
        rw [hjoinFilt, Finset.sum_image hInjJoin']
        have hpfilt : ∀ p ∈ T1.filter (fun A => w ∈ A) ×ˢ T2, r o (p.1 ∪ p.2) = p1 o p.1 * q1 o p.2 := by
          rintro ⟨A, B⟩ hpmem
          simp only [Finset.mem_product, Finset.mem_filter] at hpmem
          exact hrval o A hpmem.1.1 B hpmem.2
        rw [Finset.sum_congr rfl hpfilt]
        rw [Finset.sum_product' (f := fun x y => p1 o x * q1 o y)]
        have hpimage : (T1.image (fun A => A ∪ Y)).filter (fun C => w ∈ C)
            = (T1.filter (fun A => w ∈ A ∪ Y)).image (fun A => A ∪ Y) := by
          rw [Finset.filter_image]
        have hInjY' : Set.InjOn (fun A => A ∪ Y)
            (T1.filter (fun A => w ∈ A ∪ Y) : Set (Finset (Fin n))) := by
          intro A hA A' hA' heq
          exact hInjY (Finset.mem_of_mem_filter _ (Finset.mem_coe.mp hA))
            (Finset.mem_of_mem_filter _ (Finset.mem_coe.mp hA')) heq
        rw [hpimage, Finset.sum_image hInjY', ← hT1filt]
        apply Finset.sum_congr rfl
        intro A _
        simp only [hp1_def]
        rw [← Finset.mul_sum]
        have : ∑ y ∈ T2, q1 o y = 1 := hq1policy.2 o
        rw [this]
        ring
      rw [heqWS]
      exact hpval w
    · have heqWS : worldSuccess K (join T1 T2) r w
          = worldSuccess K (T2.image (fun B => X ∪ B)) q w := by
        unfold worldSuccess
        apply Finset.sum_congr rfl
        intro o _
        congr 1
        have hT2filt : T2.filter (fun B => w ∈ B) = T2.filter (fun B => w ∈ X ∪ B) := by
          apply Finset.filter_congr
          intro B _
          simp only [Finset.mem_union]
          constructor
          · exact fun hw => Or.inr hw
          · rintro (hw | hw)
            · exact absurd hwY (Finset.disjoint_left.mp hdisj hw)
            · exact hw
        have hjoinFilt : (join T1 T2).filter (fun C => w ∈ C)
            = (T1 ×ˢ T2.filter (fun B => w ∈ B)).image (fun p => p.1 ∪ p.2) := by
          unfold join
          rw [Finset.filter_image]
          congr 1
          ext ⟨A, B⟩
          simp only [Finset.mem_filter, Finset.mem_product, Finset.mem_union]
          constructor
          · rintro ⟨⟨hA, hB⟩, hw⟩
            refine ⟨hA, ⟨hB, ?_⟩⟩
            rcases hw with hw | hw
            · exact absurd hwY (Finset.disjoint_left.mp hdisj (hT1 A hA hw))
            · exact hw
          · rintro ⟨hA, ⟨hB, hw⟩⟩
            exact ⟨⟨hA, hB⟩, Or.inr hw⟩
        have hInjJoin' := join_injOn (T2 := T2.filter (fun B => w ∈ B)) hdisj hT1
          (fun B hB => hT2 B (Finset.mem_of_mem_filter _ hB))
        rw [hjoinFilt, Finset.sum_image hInjJoin']
        have hpfilt : ∀ p ∈ T1 ×ˢ T2.filter (fun B => w ∈ B), r o (p.1 ∪ p.2) = p1 o p.1 * q1 o p.2 := by
          rintro ⟨A, B⟩ hpmem
          simp only [Finset.mem_product, Finset.mem_filter] at hpmem
          exact hrval o A hpmem.1 B hpmem.2.1
        rw [Finset.sum_congr rfl hpfilt]
        rw [Finset.sum_product' (f := fun x y => p1 o x * q1 o y)]
        have hqimage : (T2.image (fun B => X ∪ B)).filter (fun C => w ∈ C)
            = (T2.filter (fun B => w ∈ X ∪ B)).image (fun B => X ∪ B) := by
          rw [Finset.filter_image]
        have hInjX' : Set.InjOn (fun B => X ∪ B)
            (T2.filter (fun B => w ∈ X ∪ B) : Set (Finset (Fin n))) := by
          intro B hB B' hB' heq
          exact hInjX (Finset.mem_of_mem_filter _ (Finset.mem_coe.mp hB))
            (Finset.mem_of_mem_filter _ (Finset.mem_coe.mp hB')) heq
        rw [hqimage, Finset.sum_image hInjX', ← hT2filt]
        rw [Finset.sum_comm]
        apply Finset.sum_congr rfl
        intro B _
        simp only [hq1_def]
        rw [← Finset.sum_mul]
        have : ∑ x ∈ T1, p1 o x = 1 := hp1policy.2 o
        rw [this]
        ring
      rw [heqWS]
      exact hqval w

/-! ## 3. The pair-signal Bayes-bound identity -/

/-- If `K w o` vanishes outside `{i, j}`, the full-world sum against a prior
collapses to the two-term sum. -/
theorem sum_eq_pair_of_support {n m : ℕ} (K : Experiment n m) (pi : Fin n → ℝ) (o : Fin m)
    {i j : Fin n} (hij : i ≠ j) (hsupp : ∀ w : Fin n, K w o ≠ 0 → w = i ∨ w = j) :
    ∑ w, pi w * K w o = pi i * K i o + pi j * K j o := by
  have hsub : ∑ w ∈ ({i, j} : Finset (Fin n)), pi w * K w o = ∑ w, pi w * K w o := by
    apply Finset.sum_subset (Finset.subset_univ _)
    intro x _ hx
    have hxi : x ≠ i := fun h => hx (by simp [h])
    have hxj : x ≠ j := fun h => hx (by simp [h])
    have hzero : K x o = 0 := by
      by_contra hne
      rcases hsupp x hne with h | h
      · exact hxi h
      · exact hxj h
    rw [hzero]; ring
  rw [← hsub, Finset.sum_pair hij]

/-- **The pair-signal identity, uncovered case.** If `S` covers all worlds,
signal `o` has support `{i, j}`, and no action of `S` contains both `i` and
`j`, then the Bayes bound's per-signal maximum is the larger of the two
individual terms. -/
theorem maxOver_pair_uncovered {n m : ℕ} {K : Experiment n m} (hK : IsExperiment K)
    {pi : Fin n → ℝ} (hpi : IsPrior pi) {S : Finset (Finset (Fin n))} (o : Fin m)
    {i j : Fin n} (hij : i ≠ j) (hsupp : ∀ w : Fin n, K w o ≠ 0 → w = i ∨ w = j)
    (hcovS : ∀ w : Fin n, ∃ A ∈ S, w ∈ A)
    (hncov : ∀ A ∈ S, ¬ (i ∈ A ∧ j ∈ A)) :
    maxOver S (fun A => ∑ w ∈ A, pi w * K w o) = max (pi i * K i o) (pi j * K j o) := by
  obtain ⟨Ai, hAi, hiAi⟩ := hcovS i
  obtain ⟨Aj, hAj, hjAj⟩ := hcovS j
  have hjAi : j ∉ Ai := fun h => hncov Ai hAi ⟨hiAi, h⟩
  have hiAj : i ∉ Aj := fun h => hncov Aj hAj ⟨h, hjAj⟩
  have hSne : S.Nonempty := ⟨Ai, hAi⟩
  have hzero_of_ne : ∀ x : Fin n, x ≠ i → x ≠ j → K x o = 0 := by
    intro x hxi hxj
    by_contra hne
    rcases hsupp x hne with h | h
    · exact hxi h
    · exact hxj h
  have hsumAi : ∑ w ∈ Ai, pi w * K w o = pi i * K i o := by
    apply Finset.sum_eq_single_of_mem i hiAi
    intro x hx hxi
    have hxj : x ≠ j := fun h => hjAi (h ▸ hx)
    rw [hzero_of_ne x hxi hxj]; ring
  have hsumAj : ∑ w ∈ Aj, pi w * K w o = pi j * K j o := by
    apply Finset.sum_eq_single_of_mem j hjAj
    intro x hx hxj
    have hxi : x ≠ i := fun h => hiAj (h ▸ hx)
    rw [hzero_of_ne x hxi hxj]; ring
  have hge : max (pi i * K i o) (pi j * K j o) ≤ maxOver S (fun A => ∑ w ∈ A, pi w * K w o) := by
    apply max_le
    · rw [← hsumAi]; exact le_maxOver (f := fun A => ∑ w ∈ A, pi w * K w o) hAi
    · rw [← hsumAj]; exact le_maxOver (f := fun A => ∑ w ∈ A, pi w * K w o) hAj
  have hle : maxOver S (fun A => ∑ w ∈ A, pi w * K w o) ≤ max (pi i * K i o) (pi j * K j o) := by
    unfold maxOver
    rw [dif_pos hSne]
    apply Finset.sup'_le
    intro A hA
    by_cases hiA : i ∈ A
    · have hjA : j ∉ A := fun h => hncov A hA ⟨hiA, h⟩
      have heq : ∑ w ∈ A, pi w * K w o = pi i * K i o := by
        apply Finset.sum_eq_single_of_mem i hiA
        intro x hx hxi
        have hxj : x ≠ j := fun h => hjA (h ▸ hx)
        rw [hzero_of_ne x hxi hxj]; ring
      rw [heq]; exact le_max_left _ _
    · by_cases hjA : j ∈ A
      · have heq : ∑ w ∈ A, pi w * K w o = pi j * K j o := by
          apply Finset.sum_eq_single_of_mem j hjA
          intro x hx hxj
          have hxi : x ≠ i := fun h => hiA (h ▸ hx)
          rw [hzero_of_ne x hxi hxj]; ring
        rw [heq]; exact le_max_right _ _
      · have heq : ∑ w ∈ A, pi w * K w o = 0 := by
          apply Finset.sum_eq_zero
          intro x _
          by_cases hxi : x = i
          · exact absurd (hxi ▸ ‹x ∈ A›) hiA
          · by_cases hxj : x = j
            · exact absurd (hxj ▸ ‹x ∈ A›) hjA
            · rw [hzero_of_ne x hxi hxj]; ring
        rw [heq]
        have h0i : (0:ℝ) ≤ pi i * K i o := mul_nonneg (hpi.1 i) (hK.1 i o)
        exact le_trans h0i (le_max_left _ _)
  exact le_antisymm hle hge

/-- **The pair-signal Bayes-bound identity, uncovered case.** Under the
hypotheses of `maxOver_pair_uncovered`, the prior mass of signal `o` not
captured by the best single action is the smaller of the two terms. -/
theorem pair_uncovered_loss {n m : ℕ} {K : Experiment n m} (hK : IsExperiment K)
    {pi : Fin n → ℝ} (hpi : IsPrior pi) {S : Finset (Finset (Fin n))} (o : Fin m)
    {i j : Fin n} (hij : i ≠ j) (hsupp : ∀ w : Fin n, K w o ≠ 0 → w = i ∨ w = j)
    (hcovS : ∀ w : Fin n, ∃ A ∈ S, w ∈ A)
    (hncov : ∀ A ∈ S, ¬ (i ∈ A ∧ j ∈ A)) :
    (∑ w, pi w * K w o) - maxOver S (fun A => ∑ w ∈ A, pi w * K w o)
      = min (pi i * K i o) (pi j * K j o) := by
  rw [sum_eq_pair_of_support K pi o hij hsupp,
    maxOver_pair_uncovered hK hpi o hij hsupp hcovS hncov]
  have := min_add_max (pi i * K i o) (pi j * K j o)
  linarith

/-- **The pair-signal identity, covered case.** If some action of `S`
contains both `i` and `j`, and signal `o` has support `{i, j}`, the Bayes
bound's per-signal maximum is the full sum: the loss `l_o` is zero. -/
theorem maxOver_pair_covered {n m : ℕ} {K : Experiment n m} (hK : IsExperiment K)
    {pi : Fin n → ℝ} (hpi : IsPrior pi) {S : Finset (Finset (Fin n))} (o : Fin m)
    {i j : Fin n} (hij : i ≠ j) (hsupp : ∀ w : Fin n, K w o ≠ 0 → w = i ∨ w = j)
    {A0 : Finset (Fin n)} (hA0 : A0 ∈ S) (hiA0 : i ∈ A0) (hjA0 : j ∈ A0) :
    maxOver S (fun A => ∑ w ∈ A, pi w * K w o) = pi i * K i o + pi j * K j o := by
  have hSne : S.Nonempty := ⟨A0, hA0⟩
  have hij_sub : ({i, j} : Finset (Fin n)) ⊆ A0 := by
    intro x hx
    simp only [Finset.mem_insert, Finset.mem_singleton] at hx
    rcases hx with rfl | rfl
    · exact hiA0
    · exact hjA0
  have hsumA0 : ∑ w ∈ A0, pi w * K w o = pi i * K i o + pi j * K j o := by
    rw [← Finset.sum_pair (f := fun w => pi w * K w o) hij]
    symm
    apply Finset.sum_subset hij_sub
    intro x _ hxij
    have hxi : x ≠ i := fun h => hxij (by simp [h])
    have hxj : x ≠ j := fun h => hxij (by simp [h])
    have hzero : K x o = 0 := by
      by_contra hne
      rcases hsupp x hne with h | h
      · exact hxi h
      · exact hxj h
    rw [hzero]; ring
  have hle : ∀ A ∈ S, ∑ w ∈ A, pi w * K w o ≤ pi i * K i o + pi j * K j o := by
    intro A _
    rw [← sum_eq_pair_of_support K pi o hij hsupp]
    apply Finset.sum_le_sum_of_subset_of_nonneg (Finset.subset_univ A)
    intro x _ _
    exact mul_nonneg (hpi.1 x) (hK.1 x o)
  have hge : pi i * K i o + pi j * K j o ≤ maxOver S (fun A => ∑ w ∈ A, pi w * K w o) :=
    hsumA0 ▸ le_maxOver (f := fun A => ∑ w ∈ A, pi w * K w o) hA0
  have hle2 : maxOver S (fun A => ∑ w ∈ A, pi w * K w o) ≤ pi i * K i o + pi j * K j o := by
    unfold maxOver
    rw [dif_pos hSne]
    exact Finset.sup'_le hSne _ hle
  exact le_antisymm hle2 hge

/-! ## 4. The key inequality of the reduction -/

/-- The `lambda`-range facts common to both bounds: from the separation
condition `c + P(lambda) > lambda ≥ c + Q(lambda)`, `lambda` is squeezed
into `(d(1-eps), d(1+eps))`, hence below `1`, and the `(1-lambda)^+` term
simplifies. Pure real arithmetic, independent of `T`, `kappa`, `sigma`. -/
theorem facts_ABC {d eps lambda c : ℝ} (hd0 : 0 < d) (hd1 : d ≤ 1/4)
    (hepspos : 0 < eps) (hepsle : eps ≤ 1/8)
    (hcP : c + max 0 ((d*(1+eps) - lambda)/2) > lambda)
    (hQc : lambda ≥ c + max 0 (d - lambda)) :
    lambda < d * (1 + eps) ∧ lambda > d * (1 - eps) ∧ lambda < 1 ∧
      max 0 (1 - lambda) = 1 - lambda := by
  have hQnn : 0 ≤ max 0 (d - lambda) := le_max_left 0 _
  have hPQ : max 0 ((d*(1+eps)-lambda)/2) > max 0 (d - lambda) := by linarith
  have hPpos : 0 < max 0 ((d*(1+eps)-lambda)/2) := lt_of_le_of_lt hQnn hPQ
  have hxpos : 0 < (d*(1+eps) - lambda)/2 := by
    by_contra hcon
    push Not at hcon
    rw [max_eq_left hcon] at hPpos
    exact absurd hPpos (lt_irrefl 0)
  have hFactA : lambda < d * (1 + eps) := by linarith
  have hPeqx : max 0 ((d*(1+eps)-lambda)/2) = (d*(1+eps) - lambda)/2 := max_eq_right (le_of_lt hxpos)
  have hFactB : lambda > d * (1 - eps) := by
    rcases le_or_gt lambda d with hcase | hcase
    · have hQeq : max 0 (d - lambda) = d - lambda := max_eq_right (by linarith)
      rw [hPeqx, hQeq] at hPQ
      nlinarith
    · nlinarith
  have hd1eps_lt1 : d * (1+eps) < 1 := by nlinarith
  have hlambda_lt1 : lambda < 1 := lt_trans hFactA hd1eps_lt1
  have hFactC : max 0 (1 - lambda) = 1 - lambda := max_eq_right (by linarith)
  exact ⟨hFactA, hFactB, hlambda_lt1, hFactC⟩

/-- The reduction's upper bound on `sigma`, isolated as pure arithmetic once
`lambda`'s range and the cleared-denominator form of `c ≤ lambda` are known. -/
theorem sigma_upper_bound {d T eps sigma lambda : ℝ}
    (hd0 : 0 < d) (hd1 : d ≤ 1/4) (hT : 1 ≤ T)
    (hTeps : T * eps = 1/8) (hepspos : 0 < eps)
    (hsigma : 0 ≤ sigma) (hlambda1 : lambda < 1)
    (hFactA : lambda < d * (1 + eps))
    (hmain : d * sigma * (1 - lambda) ≤ lambda * (T * (1 - d))) :
    sigma < T + 1 := by
  have hTpos : (0:ℝ) < T := lt_of_lt_of_le one_pos hT
  have hdenom1_pos : 0 < T*(1-d) + d*sigma := by nlinarith
  have hup1 : d*sigma ≤ lambda*(T*(1-d) + d*sigma) := by nlinarith
  have hup2 : 8*T*lambda < d*(8*T+1) := by nlinarith [hTeps, hFactA, hTpos]
  have hDenomPos : 0 < 8*T - (8*T+1)*d := by nlinarith
  have hcross : d*sigma*(8*T) < d*(8*T+1)*(T*(1-d)+d*sigma) := by
    have hlt : d*sigma / (T*(1-d)+d*sigma) < d*(8*T+1)/(8*T) := by
      have hle1 : d*sigma / (T*(1-d)+d*sigma) ≤ lambda := by
        rw [div_le_iff₀ hdenom1_pos]; linarith [hup1]
      have hlt2 : lambda < d*(8*T+1)/(8*T) := by
        rw [lt_div_iff₀ (by positivity : (0:ℝ) < 8*T)]; linarith [hup2]
      linarith [hle1, hlt2]
    rw [div_lt_div_iff₀ hdenom1_pos (by positivity : (0:ℝ) < 8*T)] at hlt
    linarith [hlt]
  have hineq : sigma*(8*T - (8*T+1)*d) < (8*T+1)*T*(1-d) := by nlinarith [hcross, hd0]
  have hfinal : (8*T+1)*T*(1-d) ≤ (T+1)*(8*T - (8*T+1)*d) := by nlinarith [hd1, hT, hd0]
  nlinarith [hineq, hfinal, hDenomPos]

/-- The reduction's lower bound on `sigma`, isolated as pure arithmetic once
`lambda`'s range and the cleared-denominator form of `c > d(1-2eps)` are
known. -/
theorem sigma_lower_bound {d T eps sigma lambda : ℝ}
    (hd0 : 0 < d) (hd1 : d ≤ 1/4) (hT : 1 ≤ T)
    (hTeps : T * eps = 1/8) (hepspos : 0 < eps)
    (hlambda1 : lambda < 1)
    (hFactB : lambda > d * (1 - eps))
    (hmain : d * (1 - 2*eps) * (T*(1-d)) < d * sigma * (1 - lambda)) :
    T - 1 < sigma := by
  have hTpos : (0:ℝ) < T := lt_of_lt_of_le one_pos hT
  have hTeps2 : T * (1 - 2*eps) = T - 1/4 := by nlinarith [hTeps]
  have hmain' : d * ((1-2*eps)*(T*(1-d))) < d * (sigma*(1-lambda)) := by nlinarith [hmain]
  have hstep : (1-2*eps)*(T*(1-d)) < sigma*(1-lambda) := lt_of_mul_lt_mul_left hmain' (le_of_lt hd0)
  have heq : (1-2*eps)*(T*(1-d)) = (T-1/4)*(1-d) := by linear_combination (1-d) * hTeps2
  have hmain2 : sigma * (1 - lambda) > (T - 1/4) * (1-d) := by rw [heq] at hstep; linarith
  have hlam_lt : 1 - lambda < 1 - d*(1-eps) := by linarith
  have hDpos : 0 < 1 - d*(1-eps) := by nlinarith
  have h1mlam_pos : 0 < 1 - lambda := by linarith
  have hCpos : 0 < (T - 1/4) * (1-d) := by nlinarith
  have step1 : sigma > (T-1/4)*(1-d) / (1 - lambda) := by
    rw [gt_iff_lt, div_lt_iff₀ h1mlam_pos]; nlinarith [hmain2]
  have step2 : (T-1/4)*(1-d) / (1 - lambda) > (T-1/4)*(1-d) / (1 - d*(1-eps)) :=
    div_lt_div_of_pos_left hCpos h1mlam_pos hlam_lt
  have step3 : (T-1/4)*(1-d) / (1 - d*(1-eps)) ≥ T - 1 := by
    rw [ge_iff_le, le_div_iff₀ hDpos]
    nlinarith [hTeps, hd0, hd1, hT, hepspos]
  linarith [step1, step2, step3]

/-- **The key inequality of the reduction** (`complexity/REPORT.md`,
Section 5, "Separation forces an exact subset"). For `d ∈ (0, 1/4]`,
`T ≥ 1`, `eps = 1/(8T)`, `kappa = d/(T(1-d))`, `sigma ≥ 0`, `lambda ≥ 0`,
with `P(lambda) = max(0, (d(1+eps)-lambda)/2)`, `Q(lambda) = max(0, d-lambda)`
and `c(lambda) = kappa sigma max(0, 1-lambda)`: if `c + P > lambda ≥ c + Q`
then `T - 1 < sigma < T + 1`. Pure real arithmetic; no reference to
experiments, policies, or the WCS order. -/
theorem key_inequality {d T eps kappa sigma lambda : ℝ}
    (hd0 : 0 < d) (hd1 : d ≤ 1/4) (hT : 1 ≤ T)
    (heps : eps = 1 / (8*T)) (hkappa : kappa = d / (T * (1 - d)))
    (hsigma : 0 ≤ sigma) (hlambda : 0 ≤ lambda)
    (hcP : kappa * sigma * max 0 (1 - lambda) + max 0 ((d*(1+eps) - lambda)/2) > lambda)
    (hQc : lambda ≥ kappa * sigma * max 0 (1 - lambda) + max 0 (d - lambda)) :
    T - 1 < sigma ∧ sigma < T + 1 := by
  have hTpos : (0:ℝ) < T := lt_of_lt_of_le one_pos hT
  have hepspos : 0 < eps := by rw [heps]; positivity
  have hepsle : eps ≤ 1/8 := by
    rw [heps, div_le_div_iff₀ (by positivity) (by norm_num)]
    nlinarith
  have hTeps : T * eps = 1/8 := by rw [heps]; field_simp
  have hTd_pos : 0 < T * (1 - d) := by nlinarith
  obtain ⟨hFactA, hFactB, hlambda_lt1, hFactC⟩ :=
    facts_ABC hd0 hd1 hepspos hepsle hcP hQc
  rw [hFactC] at hcP hQc
  have hkappa_cancel : kappa * (T * (1-d)) = d := by
    rw [hkappa]; exact div_mul_cancel₀ d (ne_of_gt hTd_pos)
  refine ⟨?_, ?_⟩
  · have hcval_gt : kappa * sigma * (1 - lambda) > d * (1 - 2*eps) := by
      have hPeqx : max 0 ((d*(1+eps)-lambda)/2) = (d*(1+eps) - lambda)/2 :=
        max_eq_right (by linarith [hFactA])
      rw [hPeqx] at hcP
      nlinarith [hcP, hFactB]
    have hmain : d * (1 - 2*eps) * (T*(1-d)) < d * sigma * (1 - lambda) := by
      have hstep : kappa * sigma * (1-lambda) * (T*(1-d)) > d * (1-2*eps) * (T*(1-d)) :=
        mul_lt_mul_of_pos_right hcval_gt hTd_pos
      have hcancel : kappa * sigma * (1 - lambda) * (T * (1 - d)) = d * sigma * (1 - lambda) := by
        calc kappa * sigma * (1 - lambda) * (T * (1 - d))
            = kappa * (T * (1-d)) * (sigma * (1 - lambda)) := by ring
          _ = d * (sigma * (1 - lambda)) := by rw [hkappa_cancel]
          _ = d * sigma * (1 - lambda) := by ring
      linarith [hstep, hcancel]
    exact sigma_lower_bound hd0 hd1 hT hTeps hepspos hlambda_lt1 hFactB hmain
  · have hcval_le : kappa * sigma * (1 - lambda) ≤ lambda := by
      have hQnn : 0 ≤ max 0 (d - lambda) := le_max_left 0 _
      linarith [hQc]
    have hmain : d * sigma * (1 - lambda) ≤ lambda * (T * (1 - d)) := by
      have hstep : kappa * sigma * (1-lambda) * (T*(1-d)) ≤ lambda * (T*(1-d)) :=
        mul_le_mul_of_nonneg_right hcval_le (le_of_lt hTd_pos)
      have hcancel : kappa * sigma * (1 - lambda) * (T * (1 - d)) = d * sigma * (1 - lambda) := by
        calc kappa * sigma * (1 - lambda) * (T * (1 - d))
            = kappa * (T * (1-d)) * (sigma * (1 - lambda)) := by ring
          _ = d * (sigma * (1 - lambda)) := by rw [hkappa_cancel]
          _ = d * sigma * (1 - lambda) := by ring
      linarith [hstep, hcancel]
    exact sigma_upper_bound hd0 hd1 hT hTeps hepspos hsigma hlambda_lt1 hFactA hmain

/-- **Converse witness.** `sigma = T`, `lambda = d` satisfy the two
inequalities of `key_inequality`: the yes-instance separating witness of
`complexity/REPORT.md`, Section 5 ("If `sigma = T`, take `lambda = d`"). -/
theorem key_inequality_witness {d T eps kappa : ℝ}
    (hd0 : 0 < d) (hd1 : d ≤ 1/4) (hT : 1 ≤ T)
    (heps : eps = 1 / (8*T)) (hkappa : kappa = d / (T * (1 - d))) :
    kappa * T * max 0 (1 - d) + max 0 ((d*(1+eps) - d)/2) > d ∧
      d ≥ kappa * T * max 0 (1 - d) + max 0 (d - d) := by
  have hTpos : (0:ℝ) < T := lt_of_lt_of_le one_pos hT
  have hepspos : 0 < eps := by rw [heps]; positivity
  have hd_lt1 : d < 1 := by linarith
  have hmax1d : max 0 (1 - d) = 1 - d := max_eq_right (by linarith)
  have hcancel : kappa * T * (1-d) = d := by
    rw [hkappa]
    have hTd_pos : 0 < T * (1 - d) := by nlinarith
    calc d / (T*(1-d)) * T * (1-d) = d / (T*(1-d)) * (T*(1-d)) := by ring
      _ = d := div_mul_cancel₀ d (ne_of_gt hTd_pos)
  rw [hmax1d, hcancel]
  have hxpos : 0 < (d*(1+eps) - d)/2 := by nlinarith [mul_pos hd0 hepspos]
  have hmaxx : max 0 ((d*(1+eps) - d)/2) = (d*(1+eps) - d)/2 := max_eq_right (le_of_lt hxpos)
  rw [hmaxx]
  have hmaxdd : max 0 (d - d) = (0:ℝ) := by norm_num
  rw [hmaxdd]
  constructor
  · nlinarith [mul_pos hd0 hepspos]
  · linarith

/-! ## 5. A star certificate: an exact non-dominance instance

The instance `s = (3,5,7)`, `T = 8` from
`book/research/wcs/complexity/star_certificates.json`: five worlds, six
signals, exact rational entries. `S5 = {{0,3},{1,2,3,4}}` is the separating
task from that file's `relation` field. -/
namespace StarCertificateExample


noncomputable def L5 : Experiment 5 6 := !![
  3/52, 5/52, 7/52, 2/15, 451/780, 0;
  1, 0, 0, 0, 0, 0;
  0, 1, 0, 0, 0, 0;
  0, 0, 1, 0, 0, 0;
  0, 0, 0, 2/15, 0, 13/15]

def S5 : Finset (Finset (Fin 5)) := {({0,3} : Finset (Fin 5)), ({1,2,3,4} : Finset (Fin 5))}

noncomputable def pA0 : Fin 6 → ℝ := ![2/15, 2/15, 1, 1, 1, 0]
noncomputable def pA1 : Fin 6 → ℝ := ![13/15, 13/15, 0, 0, 0, 1]

noncomputable def Lpolicy5 : Fin 6 → Finset (Fin 5) → ℝ :=
  fun o A => if A = ({0,3} : Finset (Fin 5)) then pA0 o
             else if A = ({1,2,3,4} : Finset (Fin 5)) then pA1 o
             else 0

theorem hA0ne1 : ({0,3} : Finset (Fin 5)) ≠ ({1,2,3,4} : Finset (Fin 5)) := by decide

theorem Lpolicy5_A0 : ∀ o, Lpolicy5 o ({0,3} : Finset (Fin 5)) = pA0 o := by
  intro o; simp [Lpolicy5]

theorem Lpolicy5_A1 : ∀ o, Lpolicy5 o ({1,2,3,4} : Finset (Fin 5)) = pA1 o := by
  intro o; simp [Lpolicy5, hA0ne1.symm]

theorem isPolicy_Lpolicy5 : IsPolicy S5 Lpolicy5 := by
  constructor
  · intro o A hA
    simp only [S5, Finset.mem_insert, Finset.mem_singleton] at hA
    rcases hA with rfl | rfl
    · rw [Lpolicy5_A0]; fin_cases o <;> norm_num [pA0]
    · rw [Lpolicy5_A1]; fin_cases o <;> norm_num [pA1]
  · intro o
    simp only [S5]
    rw [Finset.sum_pair hA0ne1, Lpolicy5_A0, Lpolicy5_A1]
    fin_cases o <;> norm_num [pA0, pA1]

theorem worldSuccess_L5_0 : worldSuccess L5 S5 Lpolicy5 0 = 13/15 := by
  unfold worldSuccess
  have hfilt : S5.filter (fun A => (0:Fin 5) ∈ A) = {({0,3} : Finset (Fin 5))} := by
    apply Finset.ext
    intro A
    simp only [S5, Finset.mem_filter, Finset.mem_insert, Finset.mem_singleton]
    constructor
    · rintro ⟨rfl | rfl, hmem⟩
      · rfl
      · exfalso; revert hmem; decide
    · rintro rfl
      exact ⟨Or.inl rfl, by decide⟩
  simp only [hfilt, Finset.sum_singleton, Lpolicy5_A0]
  rw [Fin.sum_univ_six]
  simp [L5, pA0]; norm_num

theorem worldSuccess_L5_1 : worldSuccess L5 S5 Lpolicy5 1 = 13/15 := by
  unfold worldSuccess
  have hfilt : S5.filter (fun A => (1:Fin 5) ∈ A) = {({1,2,3,4} : Finset (Fin 5))} := by
    apply Finset.ext
    intro A
    simp only [S5, Finset.mem_filter, Finset.mem_insert, Finset.mem_singleton]
    constructor
    · rintro ⟨rfl | rfl, hmem⟩
      · exfalso; revert hmem; decide
      · rfl
    · rintro rfl
      exact ⟨Or.inr rfl, by decide⟩
  simp only [hfilt, Finset.sum_singleton, Lpolicy5_A1]
  rw [Fin.sum_univ_six]
  simp [L5, pA1]

theorem worldSuccess_L5_2 : worldSuccess L5 S5 Lpolicy5 2 = 13/15 := by
  unfold worldSuccess
  have hfilt : S5.filter (fun A => (2:Fin 5) ∈ A) = {({1,2,3,4} : Finset (Fin 5))} := by
    apply Finset.ext
    intro A
    simp only [S5, Finset.mem_filter, Finset.mem_insert, Finset.mem_singleton]
    constructor
    · rintro ⟨rfl | rfl, hmem⟩
      · exfalso; revert hmem; decide
      · rfl
    · rintro rfl
      exact ⟨Or.inr rfl, by decide⟩
  simp only [hfilt, Finset.sum_singleton, Lpolicy5_A1]
  rw [Fin.sum_univ_six]
  simp [L5, pA1]

theorem worldSuccess_L5_3 : worldSuccess L5 S5 Lpolicy5 3 = 1 := by
  unfold worldSuccess
  have hfilt : S5.filter (fun A => (3:Fin 5) ∈ A) = S5 := by
    apply Finset.filter_true_of_mem
    intro A hA
    simp only [S5, Finset.mem_insert, Finset.mem_singleton] at hA
    rcases hA with rfl | rfl <;> decide
  rw [hfilt]
  have hsum1 : ∀ o, ∑ A ∈ S5, Lpolicy5 o A = 1 := isPolicy_Lpolicy5.2
  simp only [hsum1]
  rw [Fin.sum_univ_six]
  simp [L5]

theorem worldSuccess_L5_4 : worldSuccess L5 S5 Lpolicy5 4 = 13/15 := by
  unfold worldSuccess
  have hfilt : S5.filter (fun A => (4:Fin 5) ∈ A) = {({1,2,3,4} : Finset (Fin 5))} := by
    apply Finset.ext
    intro A
    simp only [S5, Finset.mem_filter, Finset.mem_insert, Finset.mem_singleton]
    constructor
    · rintro ⟨rfl | rfl, hmem⟩
      · exfalso; revert hmem; decide
      · rfl
    · rintro rfl
      exact ⟨Or.inr rfl, by decide⟩
  simp only [hfilt, Finset.sum_singleton, Lpolicy5_A1]
  rw [Fin.sum_univ_six]
  simp [L5, pA1]

theorem guarantees_L5_S5 : Guarantees L5 S5 (13/15) := by
  refine ⟨Lpolicy5, isPolicy_Lpolicy5, ?_⟩
  intro w
  fin_cases w
  · exact le_of_eq worldSuccess_L5_0.symm
  · exact le_of_eq worldSuccess_L5_1.symm
  · exact le_of_eq worldSuccess_L5_2.symm
  · rw [show (⟨3, by decide⟩ : Fin 5) = (3 : Fin 5) from rfl, worldSuccess_L5_3]; norm_num
  · exact le_of_eq worldSuccess_L5_4.symm


noncomputable def K5 : Experiment 5 6 := !![
  3/52, 5/52, 7/52, 13/192, 1607/2496, 0;
  1, 0, 0, 0, 0, 0;
  0, 1, 0, 0, 0, 0;
  0, 0, 1, 0, 0, 0;
  0, 0, 0, 13/96, 0, 83/96]

theorem isExperiment_K5 : IsExperiment K5 :=
  ⟨by intro w o; fin_cases w <;> fin_cases o <;> norm_num [K5],
   by intro w; fin_cases w <;> simp [K5, Fin.sum_univ_six] <;> norm_num⟩

theorem isExperiment_L5 : IsExperiment L5 :=
  ⟨by intro w o; fin_cases w <;> fin_cases o <;> norm_num [L5],
   by intro w; fin_cases w <;> simp [L5, Fin.sum_univ_six] <;> norm_num⟩

noncomputable def Kprior5 : Fin 5 → ℝ := ![26/43, 3/86, 5/86, 0, 13/43]

theorem isPrior_Kprior5 : IsPrior Kprior5 := by
  refine ⟨?_, ?_⟩
  · intro w; fin_cases w <;> norm_num [Kprior5]
  · simp [Kprior5, Fin.sum_univ_five]; norm_num

theorem bayesBound_K5_S5 : bayesBound K5 Kprior5 S5 = 3575/4128 := by
  have hS5ne : (S5 : Finset (Finset (Fin 5))).Nonempty := ⟨{0,3}, by simp [S5]⟩
  unfold bayesBound maxOver
  simp only [dif_pos hS5ne]
  have hsup : ∀ o : Fin 6, S5.sup' hS5ne (fun A => ∑ w ∈ A, Kprior5 w * K5 w o) =
      max (∑ w ∈ ({0,3} : Finset (Fin 5)), Kprior5 w * K5 w o)
        (∑ w ∈ ({1,2,3,4} : Finset (Fin 5)), Kprior5 w * K5 w o) := by
    intro o
    simp [S5, Finset.sup'_insert, Finset.sup'_singleton]
  simp only [hsup]
  rw [Fin.sum_univ_six]
  simp [K5, Kprior5]
  norm_num [max_def]

/-- **Every level `K5` guarantees on `S5` is at most `3575/4128`.** -/
theorem le_bound_K5_S5 {t : ℝ} (h : Guarantees K5 S5 t) : t ≤ 3575/4128 := by
  obtain ⟨p, hp, hval⟩ := h
  have hwd := weak_duality (K := K5) hp isPrior_Kprior5 hval
  rwa [bayesBound_K5_S5] at hwd

/-- **The star certificate: `K5` does not dominate `L5`.** `L5` guarantees
`13/15` on `S5`, but every level `K5` guarantees on `S5` is at most
`3575/4128 < 13/15`. -/
theorem not_dominates_K5_L5 : ¬ Dominates K5 L5 := by
  intro hdom
  have h1315 : Guarantees K5 S5 (13/15) := hdom S5 (13/15) guarantees_L5_S5
  have hle := le_bound_K5_S5 h1315
  norm_num at hle

end StarCertificateExample

end HardProblems.WorstCaseSuccessExtended