`Runtime.deepCopy` and `ShareCommon` copies drop the `markLinear` marker, so `LEAN_ABORT_ON_NONLINEAR` no longer fires

Aperta
#16,800 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
55/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Ambito
backend

Direzione di ricerca

Start by reading the five allocation sites named in src/runtime/io.cpp and src/runtime/sharecommon.cpp, along with the existing marker propagation examples cited in src/runtime/object.cpp. Reproduce the LEAN_ABORT_ON_NONLINEAR cases from the issue, then check that deep copy and both ShareCommon paths preserve the marker for arrays, scalar arrays, and strings. Done means each affected case panics on a later non-linear use as expected.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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

Five runtime functions that rebuild arrays, scalar arrays and strings allocate a fresh object and never copy the LEAN_LINEAR_MARK_MASK bit from the source object. Every other runtime copy of a marked object keeps it on purpose (src/runtime/object.cpp:2128, 2230, 2614 for strings, 2714 for scalar arrays, 2872 for arrays, e.g. if (lean_array_is_marked_linear(a)) lean_array_mark_linear_core(r);). As a result, after a value marked with Array.markLinear / ByteArray.markLinear / String.markLinear goes through one of these functions, the marker is silently gone, and with LEAN_ABORT_ON_NONLINEAR set a later non-linear use silently copies instead of panicking. The program's values stay correct; only the debugging check is lost.

Affected sites (all unchanged in the nightly source):

Function Site Kind
lean_runtime_deep_copy src/runtime/io.cpp:1744-1769 (lean_alloc_array / lean_alloc_sarray / lean_alloc_string) Array, ScalarArray, String
sharecommon_fn::visit_array src/runtime/sharecommon.cpp:186 (lean_alloc_array) Array
sharecommon_fn::visit_sarray src/runtime/sharecommon.cpp:197 (lean_alloc_sarray, sets m_other to the bare element size) ByteArray/FloatArray
sharecommon_fn::visit_string src/runtime/sharecommon.cpp:206 (lean_set_st_header(new_a, LeanString, 0)) String
sharecommon_quick_fn::visit_array src/runtime/sharecommon.cpp:406 (lean_alloc_array) Array

sharecommon_fn is the stateful pass (ShareCommon.State.shareCommon, extern lean_state_sharecommon); sharecommon_quick_fn is ShareCommon.shareCommon. The quick pass reaches strings and scalar arrays through visit_terminal, which returns the same object and so keeps the mark; only its visit_array is affected.

Runtime.deepCopy is logically the identity (src/Init/System/IO.lean:2035), and ShareCommon only changes sharing, so the markLinear promise that every later non-linear use panics under LEAN_ABORT_ON_NONLINEAR is broken by them.

Documented behavior it contradicts, from the docstring of Array.markLinear (src/Init/Data/Array/Basic.lean; ByteArray.markLinear and String.markLinear say the same for byte arrays / strings):

Marks an array as linear, which is a no-op logically.

At runtime the array is first made unique, copying it if the reference is not already unique, and
then marked. If the environment variable LEAN_ABORT_ON_NONLINEAR is set, every non-linear use
from that point on causes a panic instead of a silent copy.

Context
  • Affected functions: lean_runtime_deep_copy (src/runtime/io.cpp), lean::sharecommon_fn::visit_array, lean::sharecommon_fn::visit_sarray, lean::sharecommon_fn::visit_string, lean::sharecommon_quick_fn::visit_array (src/runtime/sharecommon.cpp)
  • Upstream: no existing issue found; the cited code is unchanged in nightly-2026-11-26. Runtime.deepCopy was added in PR #15586, after markLinear (PR #15052; cf. RFC #16234), so this looks like an oversight of the newer copy paths.
Steps to Reproduce

Each program below is compiled and run with:

  1. Save the program as input.lean (imports only Init/Std).
  2. Compile: lean -c input.c input.lean && leanc -o prog input.c
  3. Run: ./prog

All five programs set LEAN_ABORT_ON_NONLINEAR=1 at run time. In each case, the same program without the copying call (e.g. let b := xs instead of let b ← Runtime.deepCopy xs, or let r := (a, 0) instead of going through shareCommon) aborts on nightly with INTERNAL PANIC: ... marked by ... was used non-linearly and exit status 1, as the docstring requires.

1. lean_runtime_deep_copy

The program makes xs := (Array.replicate 5 0).markLinear (a unique, marked linear array), copies it with b ← Runtime.deepCopy xs, and then uses b.set! 0 1 while b is still shared (it is read again as b.size right after), which is exactly the non-linear mutation that Array.markLinear documents as panicking.

import Std

initialize do
  Std.Internal.UV.System.osSetenv "LEAN_ABORT_ON_NONLINEAR" "1"

def bad (n : Nat) : IO Nat := do
  let xs := (Array.replicate n 0).markLinear
  let b ← Runtime.deepCopy xs
  let ys := b.set! 0 1
  return ys.size + b.size

def main : IO Unit := do
  IO.println s!"env={← IO.getEnv "LEAN_ABORT_ON_NONLINEAR"}"
  IO.println (← bad 5)

Expected behavior: env=(some 1), then INTERNAL PANIC: array marked by Array.markLinear was used non-linearly, exit status 1 (what the same program with let b := xs does).

Actual behavior: no panic, exit status 0:

env=(some 1)
10

The LeanScalarArray and LeanString branches of the same function have the same omission.

2. sharecommon_fn::visit_array (ShareCommon.State.shareCommon on an Array)

The program marks the run-time array #[1,2,3], hands (that array, 0) to ShareCommon.State.shareCommon (with the documented StateFactory builder), then makes the returned array non-unique (let q := (r.1, r.1)) and pushes onto it.

import Std

open ShareCommon

/-- The same state factory Lean's own `Lean.Util.ShareCommon.objectFactory` builds. -/
def factory : StateFactory :=
  StateFactory.mk {
    Map := Std.HashMap, mkMap := (Std.HashMap.emptyWithCapacity ·), mapFind? := (·.get?), mapInsert := (·.insert)
    Set := Std.HashSet, mkSet := (Std.HashSet.emptyWithCapacity ·), setFind? := (·.get?), setInsert := (·.insert)
  }

@[noinline] def mkArr : Array Nat := #[1, 2, 3]

unsafe def main : IO Unit := do
  Std.Async.System.setEnvVar "LEAN_ABORT_ON_NONLINEAR" "1"
  let a : Array Nat := mkArr.markLinear
  let st : State.{0} factory := State.mk factory
  let p : (Array Nat × Nat) × State.{0} factory := State.shareCommon st (a, 0)
  let r : Array Nat × Nat := p.1
  let q := (r.1, r.1)
  let pushed := q.1.push 9
  IO.println s!"pushed={pushed}"
  IO.println s!"other={q.2}"

Expected behavior: INTERNAL PANIC: array marked by Array.markLinear was used non-linearly, exit status 1, empty stdout.

Actual behavior: exit status 0:

pushed=#[1, 2, 3, 9]
other=#[1, 2, 3]
3. sharecommon_fn::visit_sarray (ShareCommon.State.shareCommon on a ByteArray)
import Std

open ShareCommon

def factory : StateFactory :=
  StateFactory.mk {
    Map := Std.HashMap, mkMap := (Std.HashMap.emptyWithCapacity ·), mapFind? := (·.get?), mapInsert := (·.insert)
    Set := Std.HashSet, mkSet := (Std.HashSet.emptyWithCapacity ·), setFind? := (·.get?), setInsert := (·.insert)
  }

@[noinline] def mkBA : ByteArray := ByteArray.mk #[1, 2, 3]

unsafe def main : IO Unit := do
  Std.Async.System.setEnvVar "LEAN_ABORT_ON_NONLINEAR" "1"
  let a : ByteArray := mkBA.markLinear
  let st : State.{0} factory := State.mk factory
  let p : (ByteArray × Nat) × State.{0} factory := State.shareCommon st (a, 0)
  let r : ByteArray × Nat := p.1
  let q := (r.1, r.1)
  let pushed := q.1.push 9
  IO.println s!"pushed={pushed}"
  IO.println s!"other={q.2}"

Expected behavior: INTERNAL PANIC: scalar array marked by markLinear was used non-linearly, exit status 1, empty stdout.

Actual behavior: exit status 0:

pushed=[1, 2, 3, 9]
other=[1, 2, 3]
4. sharecommon_fn::visit_string (ShareCommon.State.shareCommon on a String)

The program builds "hello" at run time as "h" ++ "ello", marks it, passes (s, 1) through State.shareCommon, and then uses the returned string twice so that q.1.push '!' is a non-linear use.

import Std

open ShareCommon

/-- The same state factory Lean's own `Lean.Util.ShareCommon.objectFactory` builds. -/
def factory : StateFactory :=
  StateFactory.mk {
    Map := Std.HashMap, mkMap := (Std.HashMap.emptyWithCapacity ·), mapFind? := (·.get?), mapInsert := (·.insert)
    Set := Std.HashSet, mkSet := (Std.HashSet.emptyWithCapacity ·), setFind? := (·.get?), setInsert := (·.insert)
  }

@[noinline] def mkStr (x : String) : String := "h" ++ x

unsafe def main : IO Unit := do
  Std.Async.System.setEnvVar "LEAN_ABORT_ON_NONLINEAR" "1"
  let s : String := (mkStr "ello").markLinear
  let st : State.{0} factory := State.mk factory
  let p : (String × Nat) × State.{0} factory := State.shareCommon st (s, 1)
  let r : String × Nat := p.1
  let q := (r.1, r.1)
  let x := q.1.push '!'
  IO.println s!"x={x} y={q.2} n={r.2}"

Expected behavior: INTERNAL PANIC: string marked by String.markLinear was used non-linearly, exit status 1, empty stdout.

Actual behavior: exit status 0:

x=hello! y=hello n=1
5. sharecommon_quick_fn::visit_array (ShareCommon.shareCommon on an Array)
import Std.Async.System

@[noinline] def mkArr (n : Nat) : Array Nat := Id.run do
  let mut a : Array Nat := #[]
  for i in [0:n] do a := a.push (i+1)
  return a

unsafe def main : IO Unit := do
  Std.Async.System.setEnvVar "LEAN_ABORT_ON_NONLINEAR" "1"
  let c : Array Nat := (mkArr 3).markLinear
  let r := ShareCommon.shareCommon (c, 0)
  let p := (r.1, r.1)
  IO.println s!"pushed={p.1.push 9}"
  IO.println s!"orig={p.2}"

Expected behavior: INTERNAL PANIC: array marked by Array.markLinear was used non-linearly, exit status 1, empty stdout.

Actual behavior: exit status 0:

pushed=#[1, 2, 3, 9]
orig=#[1, 2, 3]
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.

  • lean_runtime_deep_copy: its argument is an Array Nat produced by Array.markLinear (header m_tag=246, m_other=128 = LEAN_LINEAR_MARK_MASK). The case LeanArray branch (io.cpp:1744-1756) allocates with lean_alloc_array(sz, sz) and copies only the elements, so the copy's m_other is 0 instead of 0x80. The LeanScalarArray (1757-1763) and LeanString (1764-1769) branches have the same omission. lean_alloc_array itself is not at fault; it returns a fresh object with m_other=0 by definition.
  • sharecommon_fn::visit_array (sharecommon.cpp:175-192): the argument is a marked array (tag 246, m_rc 1, m_other 128). The copy it allocates with lean_alloc_array(sz, sz) at line 186 and hands to save has m_other 0. That unmarked copy is what save records as the maximally shared representative, so it is what operator() returns; the later push reaches lean_copy_expand_array_nonlinear with m_other 0 and copies silently.
  • sharecommon_fn::visit_sarray (sharecommon.cpp:193-200): the argument has m_other 129 (element size 1 plus the 0x80 marker); the copy from lean_alloc_sarray(elem_sz, sz, sz) at line 197 has m_other 1. That copy reaches lean_copy_sarray_nonlinear without the marker.
  • sharecommon_fn::visit_string (sharecommon.cpp:202-212): the argument has m_other 128; the copy's header is written with lean_set_st_header((lean_object*)new_a, LeanString, 0) at line 206, so its m_other is 0.
  • sharecommon_quick_fn::visit_array (sharecommon.cpp:401-411): the array it receives has m_other 128; the array it builds with lean_alloc_array(sz, sz) at line 406 and hash-conses has m_other 0.

Suggested fix: after each allocation, propagate the marker as lean_copy_expand_array / lean_copy_sarray / lean_copy_string do, e.g.

if (lean_array_is_marked_linear(a)) lean_array_mark_linear_core((lean_object*)new_a);
if (lean_sarray_is_marked_linear(a)) lean_sarray_mark_linear_core(new_a);
if (lean_string_is_marked_linear(a)) lean_string_mark_linear_core((lean_object*)new_a);

The new object has rc 1 at that point, so mark_linear_core's uniqueness precondition holds. Hash-consing does not merge the mark away, because lean_sharecommon_eq (sharecommon.cpp:22) compares lean_ptr_other, so a marked and an unmarked equal object are distinct set entries. Alternatively, deepCopy could treat copying a marked object as the non-linear use and panic. One PR can fix all sites.

Impact

Someone who debugs linearity with markLinear and LEAN_ABORT_ON_NONLINEAR silently loses the check on anything passed through Runtime.deepCopy, ShareCommon.shareCommon (arrays) or ShareCommon.State.shareCommon (arrays, byte/float arrays, strings). Normal programs are not affected; values stay correct.

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

Lingua principale
Lean
Stelle
10.3k
Fork
1.1k
Merge medio
16h 45m
PR unite (30g)
361

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di leanprover/lean4

Tutte le issue di leanprover/lean4

Issue simili

Altre issue su Backend & API Design

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.