Skip to content

fix(fields): make the KoalaBear Rabin certificates replay-safe - #396

Merged
alexanderlhicks merged 3 commits into
Verified-zkEVM:mainfrom
zksecurity:rabin-replay-safe-koalabear
Nov 19, 2026
Merged

alexanderlhicks merged 3 commits into
Verified-zkEVM:mainfrom
zksecurity:rabin-replay-safe-koalabear

Conversation

@kobizk

@kobizk kobizk commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Applies the KoalaBear Rabin criteria at ZMod fieldSize as one fully-applied term, so sexticPoly_irreducible and quinticPoly_irreducible replay from an empty kernel environment in about 5s each, which is what Comparator-style checkers do on every run. Statements and certificates are unchanged; the docs and AGENTS.md record the rule. Rebased onto current main (Lean 4.36).

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🤖 PR Summary

Protocols / Soundness

  • The core fix addresses a kernel-replay defect in the KoalaBear Rabin irreducibility certificates for the sextic and quintic extension polynomials. The proofs of sexticPoly_irreducible and quinticPoly_irreducible are refactored from block-style proofs using implicit typeclass arguments to single-term explicit @‑applications that pass (ZMod fieldSize), (ZMod.instField fieldSize), and (ZMod.fintype fieldSize) alongside the existing certificate data. This ensures the certificates verify fully from an empty kernel environment (about 5s each) without triggering kernel unfolding of X ^ (fieldSize ^ n) - X into Polynomial.pow → npowRec, which would cause unacceptable slowdown in a Comparator-style checker that re-plays every certificate from scratch. The statements themselves are unchanged; only the proof term structure is altered.

  • In CompPoly/Data/Polynomial/Rabin.lean, the existing comment block is expanded to explain why a module context can hide the kernel defect: definitions not marked @[expose] lack bodies during module compilation, so only a full‑closure replay reveals the slow path. It cross‑references CompPoly/Data/Polynomial/RabinCertificate.lean for concrete tests.

Refactoring

  • CompPoly/Fields/KoalaBear/Ext5/QuinticIrreducible.lean: The proof of quinticPoly_irreducible is rewritten from irreducible_of_rabin_prime_degree with implicit instances to an explicit @‑application. Docstring updated to note the explicit form and cross‑reference sexticPoly_irreducible. No other declarations changed.
  • CompPoly/Fields/KoalaBear/Ext6/SexticIrreducible.lean: The proof of sexticPoly_irreducible undergoes the same transformation from a refine block to an explicit @‑application. A new block comment documents the kernel unfolding rationale. The instance : Fact (Irreducible sexticPoly) is unchanged.

Documentation

  • docs/wiki/field-extensions.md is updated to explain how a kernel‑replay defect can survive lake build (because un-@[expose]d definitions are opaque during module compilation) and provides concrete guidance for writing irreducible proofs using term‑mode application (e.g., @irreducible_of_rabin_degree_six (ZMod fieldSize) ...), warning against refine or abbrev‑based spellings that build but fail on full‑closure replay.
  • AGENTS.md is mentioned in the PR body as recording the rule, but its per‑file summary was unavailable (AI generation failure). This file's content cannot be confirmed from the summaries.

No sorry or admit introduced in any changed file.


Statistics

Metric Count
📝 Files Changed 5
✅ Lines Added 62
❌ Lines Removed 31

Lean Declarations

✏️ Affected: 2 declaration(s) (line number changed)
  • theorem quinticPoly_irreducible : Irreducible quinticPoly in CompPoly/Fields/KoalaBear/Ext5/QuinticIrreducible.lean moved from L111 to L114
  • theorem sexticPoly_irreducible : Irreducible sexticPoly in CompPoly/Fields/KoalaBear/Ext6/SexticIrreducible.lean moved from L139 to L155

sorry Tracking

  • No sorrys were added, removed, or affected.

📋 **Additional Analysis**

Review of PR Diff

The diff introduces substantive changes across multiple files. Below is a section-by-section analysis, keyed to the instructions in CONTRIBUTING.md.


1. Title Format

  • Observation: The diff does not include a title. The final title must follow <type>(<scope>): <subject>. Based on the content, a likely title is fix(extensions): ensure kernel replay safety for Rabin criterion applications. The current absence is not a violation, but the author must supply a compliant title when opening the PR.

2. Description

  • Observation: The diff itself has no description. The author must provide one that explains: (1) the problem (a Eq.mpr transport around huge exponents can cause kernel deep recursion), (2) the fix (use an explicit @-application at ZMod fieldSize with ZMod.instField and ZMod.fintype so that carrier and instances match the certificate lemmas exactly), (3) why lake build alone is insufficient, (4) any impact on documentation (docs/wiki/field-extensions.md is updated, and AGENTS.md gains a new bullet), and (5) that validation commands (lake build, lake test, lake exe axiomsweep --check) were run. The description should also have a Closes #... if this addresses a known issue.

3. Alignment with the Performance Contribution Rules

  • Assessment: This is not a performance contribution. The diff does not touch bench/, does not add @[csimp] or _eq_ theorems, and makes no A/B claims. The performance section of CONTRIBUTING.md is not applicable here.

4. New Types Owe a Codec

  • Assessment: No new types are introduced. This section of CONTRIBUTING.md is not applicable.

5. Style and Naming Guidelines

  • File naming: QuinticIrreducible.lean and SexticIrreducible.lean already exist and are not being renamed. No violation.
  • Theorem naming: The renamed proofs (quinticPoly_irreducible and sexticPoly_irreducible) are unchanged in name. No violation.
  • Module layout: The Rabin certificate comments are updated in Rabin.lean; the actual theorems remain in their existing files. No violation.
  • Line length: The updated docstrings in SexticIrreducible.lean contain lines over 100 characters (e.g., the explanation about lake build). The linter only applies to .lean source lines. These are docstring comments, not code, but they still reside in a .lean file. While the contributing doc says the rule is only enforced by scripts/lint-style.py on .lean files, writing recommends 100 chars for readability. This is a minor style advisory, not a hard violation, because no automation is cited as blocked.
  • Normal forms: The new code uses explicit @-applications. This is not prohibited; the normal-forms section is silent on explicit binder style.

6. Documentation Standards

  • Docstring updates: The updated module docstrings in Rabin.lean, QuinticIrreducible.lean, and SexticIrreducible.lean now explain the kernel-replay issue and the rationale for the explicit-application pattern. This is better than before.
  • Wiki update: docs/wiki/field-extensions.md is modified to include the same reasoning and concrete application instructions. This matches the requirement that docs be updated in the same PR when contributor guidance changes.
  • AGENTS.md update: A new bullet is added about applying the Rabin criterion with explicit carrier and instances and why lake build is not reliable. This is appropriate.

7. Check for Overlap

  • Observation: Not applicable during a diff review; the author must have done this before starting. No finding.

8. Summary of Compliance

Requirement Status Notes
Title format N/A (diff does not contain the PR title) Must be <type>(<scope>): <subject>
Description proportional to change Pending Author must supply a description covering the points in §2
Validation commands Must be reported in description Author states that lake build, lake test, lake exe axiomsweep --check pass
Docs updated in same PR ✅ AGENTS.md, Rabin.lean, QuinticIrreducible.lean, SexticIrreducible.lean, docs/wiki/field-extensions.md all updated
Performance rules N/A Not a performance PR
New types codec N/A No new types
Style violations ⚠️ Minor advisory Some docstring lines exceed 100 characters, but the linter does not enforce this for comments
Overlap check N/A Author responsibility before opening PR

9. Specific Findings

Finding 1 – Docstring clarity and explanation (positive):
The added comments in SexticIrreducible.lean and QuinticIrreducible.lean are thorough. They clearly explain the kernel-replay hazard, the insufficiency of lake build, and why @-application at ZMod fieldSize (with explicit instances) is necessary. This is exactly the kind of documentation the project expects for subtle correctness-critical patterns.

Finding 2 – Potential naming inconsistency (minor):
The contributing guide says theorem names use snake_case. quinticPoly_irreducible and sexticPoly_irreducible are already snake_case and are not renamed. No change needed.

Finding 3 – Line length in Lean docstrings:
Lines such as With KoalaBear.Fieldin place ofZMod fieldSize, or with in SexticIrreducible.lean exceed 100 characters. The linter targets only source code, so this does not cause a CI failure, but the PR description should note that the author chose readability over strict 100-char enforcement for these explanatory comments.


10. Conclusion

The diff is a well-motivated fix to a subtle kernel-replay reliability problem. The documentation updates are thorough. The primary remaining requirements are (a) providing a compliant PR title and (b) writing a description that states the problem, the fix, the validation commands run, and any related issues. No style or structural violations prevent merging, assuming the description is provided.


📄 **Per-File Summaries**
  • AGENTS.md: Summary unavailable — AI generation failed.
  • CompPoly/Data/Polynomial/Rabin.lean: The long comment block explaining why Eq.mpr transports around large exponents are avoided (to prevent kernel recursion) was expanded. It now explains that compiling the defining module is not evidence against the kernel slowdown because, inside a module, imported definitions not marked @[expose] lack bodies for the kernel, whereas a full-closure replay sees every body and can trigger the slow path. This clarifies the rationale for the module's design and references CompPoly/Data/Polynomial/RabinCertificate.lean for concrete tests.
  • CompPoly/Fields/KoalaBear/Ext5/QuinticIrreducible.lean: The proof of quinticPoly_irreducible is refactored: the previous block-style proof that invoked irreducible_of_rabin_prime_degree with implicit field and fintype instances is replaced by a single-term proof that passes those arguments explicitly as (ZMod fieldSize), (ZMod.instField fieldSize), and (ZMod.fintype fieldSize). The docstring is expanded to note it is applied at ZMod fieldSize and to cross-reference sexticPoly_irreducible for the rationale behind the explicit @-form. No other declarations are changed and no sorry or admit are introduced.
  • CompPoly/Fields/KoalaBear/Ext6/SexticIrreducible.lean: The proof of sexticPoly_irreducible is rewritten from a refine block using irreducible_of_rabin_degree_six with implicit typeclass arguments to an explicit @ application that passes the carrier ZMod fieldSize, the field instance ZMod.instField fieldSize, and the fintype instance ZMod.fintype fieldSize alongside the certificate arguments already used. A block comment is added that documents why the explicit spelling is necessary: to avoid kernel unfolding of X ^ (fieldSize ^ 6) - X into Polynomial.pow → npowRec when the instances are given differently, and explains that the module context avoids the slow path but a full-closure replay would reject the alternative spellings. The instance : Fact (Irreducible sexticPoly) is unchanged.
  • docs/wiki/field-extensions.md: The documentation now explains how a kernel-replay defect can survive lake build because imported definitions not marked @[expose] lack bodies during module compilation, so only a full-closure replay triggers the slow path. It also adds concrete guidance for assembling irreducible proofs using term-mode application (e.g., @irreducible_of_rabin_degree_six (ZMod fieldSize) ...) and warns against using refine with the field's abbrev or respelling with named arguments, as both build but a full-closure replay does not.

Last updated: 2026-11-19 21:21 UTC.

@kobizk kobizk changed the title Make the KoalaBear Rabin certificates replay-safe fix(fields): make the KoalaBear Rabin certificates replay-safe Oct 2, 2026
@kobizk

kobizk commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Two corrections to the generated summary above, which ran before the title and body were fixed.

The title is now fix(fields): …. And the line "the refine form no longer requires set_option maxRecDepth at elaboration" is wrong — neither theorem ever carried one, so nothing was removed. Elaboration is unaffected by this change; the set_option maxRecDepth settings on the certificate lemmas are untouched and irrelevant to replay, since Lean.Replay calls addDeclCore 0 0 and 0 means unlimited. The only thing that changes is cold-replay cost.

@alexanderlhicks alexanderlhicks left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR. I reproduced the bug and the fix independently, so the code change itself is right. Before we merge, I'd like to correct the stated cause, because #369 already built docs on a similar explanation, and to make sure the docs say what actually makes the fix work. Evidence is below, then four concrete changes.

1. Reproduction

I replayed each declaration's full dependency closure (about 20.4k declarations) into mkEmptyEnvironment with Lean.Kernel.Environment.replay, which is what Comparator does. The script is at the end.

Declaration main this PR
KoalaBear.sexticPoly_irreducible ❌ (kernel) deep recursion detected ✅
KoalaBear.quinticPoly_irreducible ❌ (kernel) deep recursion detected ✅

The other criterion callers replay cleanly on main: {KoalaBear,BabyBear,Hachi}.ext4Params_poly_irreducible, AesField.modulus_irreducible, BF64.basePoly_irreducible, and the two fixtures in tests/CompPolyTests/Data/Polynomial/RabinCertificate.lean. The PR touches exactly the right two declarations.

2. Why lake build accepted the old proof

The description says the elaborator reconciles the two instance terms, while a replay from an empty environment "need not take the same path". The kernel is deterministic, though. What changes between the two runs is which definition bodies it can see:

  • Inside a module file, imported definitions that aren't @[expose]d are axioms to the kernel. Compiling SexticIrreducible.lean, about 20k imported definitions have no body, among them Mathlib's Polynomial.instAdd.
  • A full-closure replay sees every body, and so does any non-module file that imports this one.

Here is what shows it:

  1. main's stored proof term is structurally identical in both settings (same Expr.hash), and so is every constant the module declares. Yet sending it to addDeclCore passes in 17 ms inside the module, and fails with deep recursion in about 1 s after a plain import. No replay is involved. The original refine proof doesn't even elaborate in a non-module importer.
  2. Replaying main's term with only Polynomial.instAdd made opaque passes. I found it by bisecting the 17 bodiless Polynomial, MonoidAlgebra, Finsupp and ZMod definitions in the closure; with all ~20k bodiless definitions made opaque, the replay passes in about 7 s. When the body is visible, the kernel unfolds X ^ (fieldSize ^ 6) - X through Sub into Polynomial.instAdd, and then has to normalise X ^ (fieldSize ^ 6) itself through npowRec.

So the boundary isn't elaboration versus replay, or an empty versus a full environment. It's between the defining module's check, which runs against Mathlib's public interface, and any check that sees all the bodies. The "serialized and reconstructed expression graph" wording that #369 put in Rabin.lean and field-extensions.md should be corrected the same way.

3. What actually makes the fix work

The criterion has to be instantiated at exactly the carrier and instance the certificate lemmas use. Neither change alone is enough:

Spelling full replay
@… (ZMod fieldSize) (ZMod.instField fieldSize) … (this PR) ✅
@… KoalaBear.Field (ZMod.instField fieldSize) … ❌
@… (ZMod fieldSize) KoalaBear.instFieldField … ❌
irreducible_of_rabin_degree_six (F := ZMod fieldSize) (ZMod.card _) … (instance synthesized) ❌
original refine, plus attribute [-instance] instFieldField ❌
original refine, plus letI := ZMod.instField fieldSize ❌

Every one of these builds cleanly. So the positional @ form can't be simplified: anyone who later rewrites it with named arguments brings the bug back, and nothing in CI notices.

4. Requested changes

  1. Docstrings (inline suggestions below): state the real cause, say that the carrier and the instance are both required, and say not to simplify the @ form.
  2. Wiki and agent guide. These files still teach the pattern that broke:
    • The recipe in docs/wiki/field-extensions.md (step 3, around lines 353–358) tells authors to write hcard : Fintype.card Field = fieldSize := ZMod.card _, and points to these two files as the worked examples. Suggested replacement:

      Assemble with one term-mode application whose carrier and instances are exactly those of the certificate lemmas, e.g. @irreducible_of_rabin_degree_six (ZMod fieldSize) (ZMod.instField fieldSize) (ZMod.fintype fieldSize) f fieldSize (ZMod.card _) …. Do not refine against a goal stated over the field's abbrev (KoalaBear.Field): it builds, but a full-closure replay does not.

    • In the "Field Size Enters As A Numeral" section (around lines 263–270) and the matching section comment in CompPoly/Data/Polynomial/Rabin.lean, replace the "serialized and reconstructed expression graph" explanation with the cause from §2.
    • Add to the TCB policy in AGENTS.md:

      Apply a Rabin criterion at exactly the carrier and instances its certificate lemmas use (ZMod p, ZMod.instField p, ZMod.fintype p), as one term. lake build cannot detect a mismatch: inside a module, unexposed Mathlib bodies such as Polynomial.instAdd are opaque, so the slow path only appears in a full replay.

  3. Regression guard (fine as a follow-up PR). lake build, lake test and axiomsweep all passed while this bug was live. The script below takes about 1–2 minutes per declaration and could become a lake exe run over the certificate theorems. One caveat: it also fails BF128Ghash.ghashPoly_irreducible today, at gcd_start_reduction (Fields/Binary/BF128Ghash/XPowTwoPowGcdCertificate.lean:61, a rw under X^(2^64)). That bug predates this PR and needs its own issue before the check can gate CI.
Replay script (lake env lean --run Replay.lean <Module> <decl>…)
import Lean
open Lean

partial def closure (env : Environment) (roots : List Name) : Std.HashMap Name ConstantInfo := Id.run do
  let mut seen : Std.HashMap Name ConstantInfo := {}
  let mut todo := roots
  while !todo.isEmpty do
    match todo with
    | [] => break
    | n :: rest =>
      todo := rest
      if seen.contains n then continue
      let some ci := env.find? n | continue
      seen := seen.insert n ci
      todo := ci.getUsedConstantsAsSet.toList ++ todo
      match ci with
      | .inductInfo v => todo := v.ctors ++ (Name.mkStr n "rec") :: todo
      | .ctorInfo v => todo := v.induct :: todo
      | .recInfo v => todo := v.all ++ todo
      | _ => pure ()
  return seen

def main (args : List String) : IO UInt32 := do
  initSearchPath (← findSysroot)
  let env ← importModules #[{ module := args[0]!.toName }] {} (loadExts := false)
  let cs := closure env ((args.drop 1).map String.toName)
  IO.println s!"closure: {cs.size} constants"
  let t0 ← IO.monoMsNow
  try
    let _ ← (← mkEmptyEnvironment).toKernelEnv.replay cs
    IO.println s!"OK in {(← IO.monoMsNow) - t0} ms"; return 0
  catch e =>
    IO.println s!"FAILED after {(← IO.monoMsNow) - t0} ms: {(toString e).take 300}"; return 1

For the Polynomial.instAdd experiment, I replaced that constant's ConstantInfo in the map with an axiomInfo of the same type. I also turned the closure's other theorems into axioms, so only the target declaration was checked against the opaque body.

Comment on lines +138 to +148
factors, with kernel-checked certificates for all three conditions.

Applied at `ZMod fieldSize` as one fully-applied term, rather than by `refine` against the
`Field`-shaped goal. `Field` is reducibly `ZMod fieldSize`, but the two sides carry different
instance *terms* for the same instance -- `Field.toCommRing instFieldField` against
`ZMod.commRing fieldSize` -- and the types carrying them contain `X ^ (fieldSize ^ 6)`. The
elaborator reconciles them, but a kernel replay from an empty environment need not take the same
path, and reducing that power through `Polynomial.pow → npowRec → Nat.rec` does not finish. This is
the hazard the section comment in `CompPoly/Data/Polynomial/Rabin.lean` describes, reached through
the instance path rather than through a cast. Fixing every argument keeps each instance path on one
side, so they meet only at `Irreducible sexticPoly`, where no exponent appears. -/

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This explanation is the part to correct (see §2–3 of the review). The two instance terms aren't "reconciled by the elaborator". The defining module's kernel check passes only because Mathlib's Polynomial.instAdd has no visible body inside a module. Also, the carrier is as load-bearing as the instance: @… KoalaBear.Field (ZMod.instField fieldSize) … still fails a full replay. Suggested wording:

Suggested change
factors, with kernel-checked certificates for all three conditions.
Applied at `ZMod fieldSize` as one fully-applied term, rather than by `refine` against the
`Field`-shaped goal. `Field` is reducibly `ZMod fieldSize`, but the two sides carry different
instance *terms* for the same instance -- `Field.toCommRing instFieldField` against
`ZMod.commRing fieldSize` -- and the types carrying them contain `X ^ (fieldSize ^ 6)`. The
elaborator reconciles them, but a kernel replay from an empty environment need not take the same
path, and reducing that power through `Polynomial.pow → npowRec → Nat.rec` does not finish. This is
the hazard the section comment in `CompPoly/Data/Polynomial/Rabin.lean` describes, reached through
the instance path rather than through a cast. Fixing every argument keeps each instance path on one
side, so they meet only at `Irreducible sexticPoly`, where no exponent appears. -/
factors, with kernel-checked certificates for all three conditions.
Applied as one term at exactly the carrier and instances the certificate lemmas use:
`ZMod fieldSize`, `ZMod.instField fieldSize` and `ZMod.fintype fieldSize`. The carrier and the
instance are both required. With `KoalaBear.Field` in place of `ZMod fieldSize`, or with
`instFieldField` (or any synthesized instance, as `(F := ZMod fieldSize)` gives) in place of
`ZMod.instField fieldSize`, the kernel unfolds `X ^ (fieldSize ^ 6) - X` into
`Polynomial.pow → npowRec`, and a full-closure replay hits deep recursion. `lake build` cannot
catch this: inside a `module`, Mathlib's `Polynomial.instAdd` has no visible body, so the kernel
never takes that path. Keep the explicit `@` application. -/

Comment on lines +112 to +113
Applied at `ZMod fieldSize` as one fully-applied term, for the reason given on
`sexticPoly_irreducible`. -/

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same correction, kept short since the sextic docstring carries the explanation:

Suggested change
Applied at `ZMod fieldSize` as one fully-applied term, for the reason given on
`sexticPoly_irreducible`. -/
Applied as one term at `ZMod fieldSize` with `ZMod.instField fieldSize`; see
`sexticPoly_irreducible` for why both are required and why the explicit `@` form must stay. -/

@kobizk

kobizk commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks — this is a better explanation than the one I shipped, and I've taken it. Pushed as bacb7ed.

Your mechanism is right and mine was hand-waving. "A replay need not take the same path" describes the symptom; the kernel is deterministic and the asymmetry is exposure. I've replaced it everywhere with the module/@[expose] account, including in the two places that taught the broken pattern.

I verified the carrier claim independently rather than take it on faith, since it's what the docs now assert. It holds — KoalaBear.Field with the right instance, and ZMod fieldSize with instFieldField, both fail a full-closure replay, so neither change alone suffices. One correction, though: they don't always build. At the default maxRecDepth the mismatched spellings fail to elaborate; only with a raised limit do they compile and leave a replay as the sole check. So "lake build cannot catch this" is too strong — whether it catches it depends on the recursion budget in scope, which is worth saying precisely, because a future author may well see a build failure and never learn why. The docstring says that.

One thing I did not do as asked. You asked to replace the "serialized and reconstructed expression graph" explanation in the Rabin.lean section comment. I replaced that sentence, but kept the paragraph around it: it documents the rw [hcard] → Eq.mpr-transport hazard, which is a different mechanism from the carrier/instance mismatch and is still live. Deleting it would lose a real warning. Same in the wiki's "Field Size Enters As A Numeral" section.

On the regression guard — I'd rather land it than defer it. You're right that the docstring decays: nothing stops someone respelling the @ application with named arguments, and I'd add that the exposure mechanism makes the protection incidental rather than designed, since the day Mathlib exposes Polynomial.instAdd the build's behaviour changes under us. I have the harness already and am happy to write the lake exe over the certificate theorems in this PR or immediately after, whichever you prefer. Your BF128Ghash.ghashPoly_irreducible finding is the blocker for gating CI, and it looks independent of this change — say the word and I'll open an issue for it with the gcd_start_reduction detail.

Minor: my timings in the description were on a ~20.0k closure against your ~20.4k, because my traversal didn't add constructors and recursors explicitly. Yours is the better script; the conclusion is unchanged.

Disclosure: This comment was written by AI.

kobizk and others added 3 commits November 19, 2026 16:18
`sexticPoly_irreducible` and `quinticPoly_irreducible` applied the Rabin criteria
by `refine` against the `Field`-shaped goal. `Field` is reducibly `ZMod fieldSize`,
but the two sides carry different instance terms for the same instance, and the
types carrying them contain `X ^ (fieldSize ^ d)`. The elaborator reconciles them;
a kernel replay from an empty environment reduces that power through
`Polynomial.pow → npowRec → Nat.rec` and does not finish. Applying the criteria at
`ZMod fieldSize` as one fully-applied term keeps each instance path on one side, so
they meet only at `Irreducible f`, where no exponent appears. Same statements, same
certificates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ing too

Review feedback. The previous explanation said the elaborator reconciles the two
instance terms while a replay "need not take the same path"; the kernel is
deterministic, and the actual asymmetry is exposure. Inside a `module`, imported
definitions that are not `@[expose]`d have no body for the kernel -- Mathlib's
`Polynomial.instAdd` among them -- so the unfolding path does not exist while the
defining module compiles, and a full-closure replay, which sees every body, takes
it.

The carrier matters as much as the instance: `KoalaBear.Field` with the right
instance, or `ZMod fieldSize` with `instFieldField` or a synthesized one, all fail
a full replay. The docstrings now say both are required and that the explicit `@`
application must not be respelled.

One correction to the reviewer's note: the mismatched spellings do not always
build. At the default `maxRecDepth` they fail to elaborate; only with a raised
limit do they compile and leave a replay as the sole check. The docs say that
rather than "`lake build` cannot catch this".

Also updates the recipe in `docs/wiki/field-extensions.md`, which still taught the
`hcard : Fintype.card Field = fieldSize` pattern, and adds the rule to the TCB
policy in `AGENTS.md`. The cast hazard the `Rabin.lean` section comment documents
is a separate mechanism and is kept; only its build-versus-replay sentence changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kobizk
kobizk force-pushed the rabin-replay-safe-koalabear branch from 1f87c6b to b3e9e5b Compare November 19, 2026 21:20
@alexanderlhicks
alexanderlhicks merged commit cc71356 into Verified-zkEVM:main Nov 19, 2026
7 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants