`Nat.shiftRight` panics ("Nat.shiftr exponent is too big") for shift amounts above `UINT_MAX` whose result is nonzero

Abierto
#16,804 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
52/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo

Línea de trabajo

Start in src/runtime/object.cpp at lean_nat_big_shiftr and follow its call to div2k in src/runtime/mpz.h. Check how the shift-count limit interacts with the big-number division routine, then run the reproduction from the issue and relevant runtime tests. Done means the example shifts to 1 and exits successfully without regressing other large shifts.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug
Prerequisites
  • Check that your issue is not already filed:
    https://github.com/leanprover/lean4/issues
  • Reduce the issue to a minimal, self-contained, reproducible test case.
    Avoid dependencies to Mathlib or Batteries.
  • Test your test case against the latest nightly release, for example on
    https://live.lean-lang.org/#project=lean-nightly
    (You can also use the settings there to switch to “Lean nightly”)
  • When reporting a perceived soundness bug: Does it affect lake check --paranoid?
    If in doubt, please reach out on [email protected] for responsible disclosure.
    (Not a soundness bug.)
Description

lean_nat_big_shiftr (src/runtime/object.cpp:1633-1654) calls lean_internal_panic when s > UINT_MAX and a.log2() >= s, because div2k takes an unsigned bit count (mpz.h:282). For n = 2^(2^32) and s = 2^32, the right result is the small value 1, and Nat.shiftRight is a total function by its definition, so the panic is a real gap. The code comment shows the limit is deliberate, and reaching it needs a natural number of more than 2^32 bits (512 MB).

The program builds n = 2 <<< 4294967295 = 2^4294967296 (a nat with 4294967297 bits, built by the runtime's own shiftl), prints "log2n=4294967296", and then evaluates n >>> 4294967296. Instead of printing the shifted value 1 and exiting 0, the process writes "INTERNAL PANIC: Nat.shiftr exponent is too big" to stderr and exits with status 1; "log2n=4294967296" is all that reaches stdout. n >>> 4294967296 is 1: the Lean definition of shiftRight is total (shiftRight n (succ m) = shiftRight n m / 2), the runtime itself computes n >>> 4294967295 = 2 in this same input, and the identical program with the shift split as (n >>> 4294967295) >>> 1 prints "log2n=4294967296\nshift=1\n" and exits 0. The refusal is not a resource guard: the result is the tiny number 1, GMP's div2k takes a 64-bit bit count, and only this runtime's unsigned k parameter makes shift amounts above UINT_MAX unacceptable, so no documented limit covers it.

(The initialize block sets LEAN_MAIN_USE_THREAD=0, LEAN_NUM_THREADS=1 and LEAN_STACK_SIZE_KB=1024 only to reduce the address space used next to the 512 MiB nat; it does not affect the shift.)

Documented behavior it contradicts (docstring of Nat.shiftRight):

Shifts the binary representation of a value right by the specified number of bits. Usually accessed
via the >>> operator.

def shiftRight : @& Nat → @& Nat → Nat
  | n, 0 => n
  | n, succ m => shiftRight n m / 2
Context
  • Affected function: lean_nat_big_shiftr (src/runtime/object.cpp)
  • Upstream: no existing issue found. The cited code is unchanged in nightly-2026-11-26.
Steps to Reproduce
  1. Save the following as input.lean (imports only Init/Std):
import Std

/-
Free address space so that the 2^4294967296 of `n` below fits an address-space
limit: run `main` on the process's own thread instead of a fresh 1 GiB-stack thread, and give
the remaining runtime threads a small stack. Both variables are read by the runtime itself.
-/
initialize do
  Std.Async.System.setEnvVar "LEAN_MAIN_USE_THREAD" "0"
  Std.Async.System.setEnvVar "LEAN_NUM_THREADS" "1"
  Std.Async.System.setEnvVar "LEAN_STACK_SIZE_KB" "1024"

def main : IO Unit := do
  -- n = 2^4294967296, a natural number with 4294967297 bits
  let n : Nat := 2 <<< 4294967295
  IO.println s!"log2n={Nat.log2 n}"
  let r : Nat := n >>> 4294967296
  IO.println s!"shift={r}"
  1. Compile: lean -c input.c input.lean && leanc -o prog input.c
  2. Run: ./prog

Expected behavior:

log2n=4294967296
shift=1

exit status 0.

Actual behavior:

stdout:

log2n=4294967296

stderr:

INTERNAL PANIC: Nat.shiftr exponent is too big

exit status 1.

Versions

Lean (version 4.38.0-nightly-2026-11-26, arm64-apple-darwin24.6.0, commit e1228b8b45918ece1a00d68e5fc5e6a685ca59ee, Release)
macOS 26.6.2 (arm64)

Additional Information

Root cause analysis. The arguments are ones callers may pass: a2 is a small (unboxed) nat k = 4294967296 and a1 is the heap GMP nat n = 2^4294967296 (Nat.log2 of the very same object is 4294967296 = k). lean_nat_shiftr (src/include/lean/lean.h) forwards exactly this pair to lean_nat_big_shiftr because a1 is not a small nat. Instead of returning n / 2^k = 1, the function's own guard

if (s > UINT_MAX) {
    if (a.log2() >= s) {
        lean_internal_panic("Nat.shiftr exponent is too big");
    } else {
        return lean_box(0);
    }
}

(src/runtime/object.cpp:1643-1649) rejects every shift amount above UINT_MAX whose bits are still present in n, even though the quotient is a tiny nat here. No callee hands it a wrong value: a1 is a valid canonical big nat produced by lean_nat_big_shiftl, and mpz::log2 returns the correct 4294967296. The factor behind it is div2k(mpz&, mpz const&, unsigned k) (src/runtime/mpz.h:282), unlike GMP's mp_bitcnt_t-width shift.

Suggested fix: widen the bit count of div2k (GMP's mpz_fdiv_q_2exp/mpz_tdiv_q_2exp take mp_bitcnt_t), or shift in <= UINT_MAX chunks and fold, e.g. n >>> s = (n >>> UINT_MAX) >>> (s - UINT_MAX).

Impact

Only programs that right-shift natural numbers of more than 4 billion bits by more than UINT_MAX hit this; the process exits with an internal panic.

Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.

Lenguaje dominante
Lean
Estrellas
10.3k
Forks
1.1k
Merge medio
16 h 45 min
PR fusionados (30 d)
361

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de leanprover/lean4

Todos los issues de leanprover/lean4

Issues similares

Más issues de Backend & API Design

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.