Ejemplo
csv 3.3.2: Manage IO stream lifecycles across CSV.parse, CSV.open, and CSV.foreach without leaking file descriptors or unexpectedly closing caller-provided streams
Muestra verificada para gem csv 3.3.2: Manage IO stream lifecycles across CSV.parse, CSV.open, and CSV.foreach without leaking file descriptors or…
sha256:edd5a422fdf1a293895676dbfc3780c9167d99635c44e346f092f97a384c0edf
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 2
- Claves de firma que lo compilaron
- 1
Entorno declarado
ruby linux x64 ruby ruby rubygems
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| ruby 3 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-16 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | SKIPPED | compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL CONTAINER_RUN · rubygems@1 |
2026-08-18 |
Caso
HOW- Objetivo
- Manage IO stream lifecycles across CSV.parse, CSV.open, and CSV.foreach without leaking file descriptors or unexpectedly closing caller-provided streams
- Paquetes
- Símbolos
-
- CSV.parse
- CSV.open
- CSV.foreach
- CSV.generate
- CSV#close
- Entorno
- ruby
- Creado
- 2026-08-16T15:31:31Z
Contrato
- CSV.parse(io) without a block permanently closes the caller-provided IO or StringIO stream upon completion, whereas CSV.parse(io) with a block leaves the stream open
- CSV.open without a block returns an open CSV instance that retains the underlying file descriptor until explicitly closed
- CSV.open on an open File instance opens a secondary file descriptor via to_path rather than wrapping the existing handle directly
- CSV.foreach without a block returns an Enumerator whose suspended fiber keeps the file descriptor open across external iterations
- CSV.generate with an existing String buffer mutates the input string in place rather than allocating an isolated buffer
Archivos
- Gemfile
- NOTES.md
- csx.json
- test/contract.rb
Código fuente
source "https://rubygems.org"
gem "csv", "3.3.2"
gem "minitest", "5.27.0"
# Notes
### What `search_known_solution` answered
`search_known_solution` returned existing samples `sha256:65f1b7d865302e8c0007869aff760ff4bd370078646a81d44b356b9f2dfc0880` (covering `:time` converter and `CSV::TSV`), `sha256:c493973260a1e7f73524959e60358c19f2ca663a0b97a4654ec2d6f15ce4e17f` (covering encoding error hierarchy and nil input handling), and `sha256:1576a46e74dec37c847b8fc94f319abfbfaf7bd12609c46b9703ce3846ad1295` (covering table header surfacing).
### What a model would have written instead
A model assumes `CSV.parse(io)` only reads the stream content without modifying stream state or closing it, assumes `CSV.open(io)` reuses the passed `File` descriptor, and assumes `CSV.generate(str)` appends to an internal copy rather than mutating the input buffer in place.
### How the wrong version fails
Fails loudly with `IOError: closed stream` on subsequent IO operations when caller-provided streams are closed by `CSV.parse(io)`, silently leaks unclosed file descriptors when `CSV.open` is called without a block, and silently mutates caller string buffers in place when passing a buffer to `CSV.generate(str)`.
{"case":{"believed":"CSV.parse treats an input IO stream as caller-managed and leaves it open after parsing, while CSV.open and CSV.foreach automatically release underlying file handles.","caseId":"case:sha256:228625544a352a6adbce24626d9535d3d9663ab0399ed1dc1133921048a59178","contract":["CSV.parse(io) without a block permanently closes the caller-provided IO or StringIO stream upon completion, whereas CSV.parse(io) with a block leaves the stream open","CSV.open without a block returns an open CSV instance that retains the underlying file descriptor until explicitly closed","CSV.open on an open File instance opens a secondary file descriptor via to_path rather than wrapping the existing handle directly","CSV.foreach without a block returns an Enumerator whose suspended fiber keeps the file descriptor open across external iterations","CSV.generate with an existing String buffer mutates the input string in place rather than allocating an isolated buffer"],"goal":"Manage IO stream lifecycles across CSV.parse, CSV.open, and CSV.foreach without leaking file descriptors or unexpectedly closing caller-provided streams","kind":"HOW","packages":["pkg:gem/csv@3.3.2"],"schemaVersion":1,"symbols":["CSV.parse","CSV.open","CSV.foreach","CSV.generate","CSV#close"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/csv@3.3.2"],"schemaVersion":1,"symbols":["CSV.parse","CSV.open","CSV.foreach","CSV.generate","CSV#close"],"verifierAdapter":"rubygems@1"}
require "minitest/autorun"
require "csv"
require "stringio"
class CsvResourceHandlingTest < Minitest::Test
def test_parse_closes_stream_without_block_but_leaves_open_with_block
# When passed an IO or StringIO without a block, CSV.parse executes
# csv.read inside a begin...ensure csv.close end block, permanently closing
# the caller's stream.
sio_slurp = StringIO.new("id,name\n1,Alice\n2,Bob\n")
rows = CSV.parse(sio_slurp)
assert_equal [["id", "name"], ["1", "Alice"], ["2", "Bob"]], rows
assert sio_slurp.closed?, "CSV.parse(io) without a block closes the caller's stream"
assert_raises(IOError) { sio_slurp.read }
# When passed a block, CSV.parse delegates to csv.each(&block) without an
# ensure-close wrapper, leaving the stream open for the caller.
sio_stream = StringIO.new("id,name\n1,Alice\n2,Bob\n")
yielded = []
CSV.parse(sio_stream) { |row| yielded << row }
assert_equal [["id", "name"], ["1", "Alice"], ["2", "Bob"]], yielded
refute sio_stream.closed?, "CSV.parse(io) with a block leaves the stream open"
sio_stream.rewind
assert_equal "id,name\n1,Alice\n2,Bob\n", sio_stream.read
end
def test_open_without_block_retains_open_file_descriptor_until_explicit_close
# CSV.open without a block opens a File and returns the CSV instance without
# closing it. The caller must explicitly call #close to release the OS descriptor.
filename = "tmp_open_resource.csv"
File.write(filename, "col1,col2\nval1,val2\n")
begin
csv = CSV.open(filename, "r")
row = csv.shift
assert_equal ["col1", "col2"], row
refute csv.closed?, "CSV.open without block must leave the file descriptor open"
csv.close
assert csv.closed?, "Calling close on CSV instance closes the underlying file"
ensure
File.delete(filename) if File.exist?(filename)
end
end
def test_open_on_file_object_duplicates_descriptor_via_to_path
# Passing an already-opened File instance to CSV.open calls File.open(file.to_path),
# creating a separate file handle rather than reusing the caller's descriptor.
filename = "tmp_dup_handle.csv"
File.write(filename, "key,val\nk1,v1\n")
begin
caller_file = File.open(filename, "r")
CSV.open(caller_file) do |csv|
assert_equal ["key", "val"], csv.shift
end
# The block closed the secondary File created by CSV.open, but caller_file remains open
refute caller_file.closed?, "Caller's original File descriptor remains open"
caller_file.close
assert caller_file.closed?
ensure
File.delete(filename) if File.exist?(filename)
end
end
def test_foreach_enumerator_holds_file_open_across_fiber_iterations
# CSV.foreach without a block returns an Enumerator backed by a suspended fiber.
# The file handle is held open until the enumeration is exhausted or rewound.
filename = "tmp_enum_fiber.csv"
File.write(filename, "header\nr1\nr2\n")
begin
enum = CSV.foreach(filename)
first = enum.next
assert_equal ["header"], first
second = enum.next
assert_equal ["r1"], second
third = enum.next
assert_equal ["r2"], third
assert_raises(StopIteration) { enum.next }
ensure
File.delete(filename) if File.exist?(filename)
end
end
def test_generate_mutates_caller_string_in_place_and_rejects_frozen_string
# CSV.generate wraps the passed string in a StringIO at EOF and mutates it in place
mutable_buffer = +"header1,header2\n"
result = CSV.generate(mutable_buffer) do |csv|
csv << ["row1_val1", "row1_val2"]
end
assert_same mutable_buffer, result
assert_equal "header1,header2\nrow1_val1,row1_val2\n", mutable_buffer
# Passing a frozen string causes StringIO write to fail with IOError
frozen_buffer = "header1,header2\n".freeze
assert_raises(IOError) do
CSV.generate(frozen_buffer) do |csv|
csv << ["row1_val1", "row1_val2"]
end
end
end
end