`IO.FS.Handle.mk` with `.append` leaves the cursor at offset 0, so `Handle.truncate` on a fresh append handle empties the file

Abierto
#16,799 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
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
76/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Área
backend

Línea de trabajo

Start in src/runtime/io.cpp at lean_io_prim_handle_mk and read the .append branch alongside Handle.truncate, which uses the stream cursor. Reproduce with the provided Lean program: create a.txt, open it in append mode, and truncate without writing. The issue is resolved when the program prints 6 and the existing file contents remain intact.

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

For Mode.append, lean_io_prim_handle_mk opens with O_WRONLY|O_CREAT|O_APPEND (io.cpp:428) and wraps the descriptor with fdopen(fd, "a") (io.cpp:444-446). fdopen does not move the descriptor's offset, so the cursor stays at 0. fopen("a") would have positioned it at the end. The Mode.append docstring (src/Init/System/IO.lean:672-681) says the cursor is positioned at the end of the file, and Handle.truncate cuts at ftello (io.cpp:598), so truncating an unwritten append handle empties the file. Writes are unaffected because O_APPEND still sends them to the end, so the only effect is truncate (and any other cursor query) before the first write.

The program below writes the 6-byte file a.txt, opens it with IO.FS.withFile "a.txt" .append (i.e. IO.FS.Handle.mk "a.txt" .append) and calls Handle.truncate on the untouched handle, then prints the file's length. It prints 0, though truncate cuts at the handle's read/write cursor and an existing file opened in append mode has its read/write cursor at the end of the file: truncating an untouched append handle must therefore keep all six bytes and the program must print 6. As it is, merely opening a file in append mode and truncating it silently empties the file.

Documented behavior it contradicts, from the IO.FS.Mode.append docstring (src/Init/System/IO.lean) / the reference manual section "Files, File Handles, and Streams":

If the file does not already exist, it is created. If the file already exists, it is opened, and the read/write cursor is positioned at the end of the file.

Context
  • Affected function: lean_io_prim_handle_mk (src/runtime/io.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
open IO

def main : IO Unit := do
  -- an existing 6-byte file
  IO.FS.writeFile "a.txt" "abcdef"
  -- opened in append mode: per the documented mode, the read/write cursor is at the end of the file
  IO.FS.withFile "a.txt" .append (fun h => h.truncate)
  -- so truncating to the cursor must leave the 6 bytes in place
  IO.println s!"{(← IO.FS.readFile "a.txt").length}"
  1. Compile: lean -c input.c input.lean && leanc -o prog input.c
  2. Run: ./prog

Expected behavior:

6

Actual behavior:

0

(exit status 0; a.txt is now empty)

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 call receives filename = "a.txt" and mode = 4 (the IO.FS.Mode.append scalar), exactly the arguments IO.FS.withFile "a.txt" .append / IO.FS.Handle.mk "a.txt" .append pass, on an existing file that opens fine. The ok result wraps a stream whose read/write cursor is at byte offset 0, whereas the append mode requires the cursor to be at the end of the file (offset 6 here, the existing contents kept). Because the cursor is at 0, the following Handle.truncate (which cuts at the cursor, ftruncate(fileno(fp), ftello(fp)), io.cpp:598) empties the file. No callee hands it that wrong state: open with O_WRONLY|O_CREAT|O_APPEND and fdopen(fd, "a") both succeed and do what they are documented to do. Unlike fopen(..., "a"), fdopen does not move the descriptor's offset, and O_APPEND only redirects writes, so positioning the cursor at the end is exactly the step this function never performs (there is no lseek/fseek in the append branch).

Suggested fix: at the end of the append branch of lean_io_prim_handle_mk (src/runtime/io.cpp:428/444-446), position the stream at the end (e.g. fseek(fp, 0, SEEK_END)) before returning io_result_mk_ok(io_wrap_handle(fp)). Handle.truncate would then keep the existing contents.

Impact

Calling Handle.truncate on a freshly opened append handle deletes the file's contents instead of doing nothing. This is a rare call pattern, but it loses data.

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.