Exemplo
json 2.9.1: Manage IO stream lifecycles, EOF positions, and monolithic buffer allocations in JSON.dump and JSON.load
Amostra verificada para gem json 2.9.1: Manage IO stream lifecycles, EOF positions, and monolithic buffer allocations in JSON.dump and JSON.load. O contrato…
sha256:ab7ff319b674d45bcbd2a67d43b257f7a387c8b14d38d85018607794429d5106
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 2
- Chaves de assinatura que o compilaram
- 2
Ambiente declarado
ruby linux x64 ruby ruby rubygems
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-17 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-18 |
Caso
HOW- Objetivo
- Manage IO stream lifecycles, EOF positions, and monolithic buffer allocations in JSON.dump and JSON.load
- Pacotes
- Símbolos
-
- JSON.dump
- JSON.load
- JSON.parse
- JSON::Parser
- JSON::State
- Ambiente
- ruby
- Criado
- 2026-08-17T02:43:58Z
Contrato
- assert JSON.dump and JSON.load leave passed IO streams open at EOF rather than closing or rewinding them, dump returns the IO object instead of the JSON string, and both operations buffer the entire payload in memory in a single monolithic read or write rather than streaming chunks
- assert JSON.dump and JSON.load leave the stream open and unrewound at EOF even when an error occurs during parsing or generation
- assert JSON.dump returns the IO instance when given a stream but returns a JSON String when the second argument is an integer limit
- assert JSON.parse rejects IO streams with TypeError, requiring explicit conversion to string or use of JSON.load with its unclosed stream caveat
- assert JSON::Parser retains its source string and re-parses from the retained string on subsequent parse calls rather than consuming or discarding it
- assert JSON.dump buffers the complete document before calling IO#write once, so a slow or aborted dump writes zero bytes rather than partial fragments
Arquivos
- Gemfile
- Gemfile.lock
- NOTES.md
- csx.json
- src/resource_ops.rb
- test/contract.rb
Código-fonte
source "https://rubygems.org"
gem "json", "2.9.1"
gem "minitest", "5.27.0"
GEM
remote: https://rubygems.org/
specs:
json (2.9.1)
minitest (5.27.0)
PLATFORMS
ruby
x64-mingw-ucrt
DEPENDENCIES
json (= 2.9.1)
minitest (= 5.27.0)
CHECKSUMS
bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
json (2.9.1) sha256=d2bdef4644052fad91c1785d48263756fe32fcac08b96a20bb15840e96550d11
minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
BUNDLED WITH
4.0.18
# Ruby `json` IO Stream Resource Handling and Lifecycle
## 1. What `search_known_solution` answered
`search_known_solution` returned a match for sample `sha256:bec86395ce786b02c01ea89597d38d802ad97a4c997dc95aaa3f09e24aeeffe9` ("Read and write JSON in Ruby on an image with no C compiler, where oj cannot be installed, without the built-in json defaults changing the data"). That sample focused on `to_json` receiving `JSON::State`, `allow_nan` defaults, `decimal_class: String` precision, and default gem resolution on environments lacking a C compiler.
## 2. What a model would confidently expect
A model or developer expects that passing an `IO` or `File` stream to `JSON.dump` or `JSON.load` streams parsing and generation incrementally without buffering the full document in memory, closes or cleans up the stream upon completion, and returns the serialized JSON `String` from `JSON.dump`.
## 3. How the wrong version fails
- **Loud failure**: `JSON.parse(io)` fails loudly with `TypeError: no implicit conversion of StringIO into String`. `JSON.dump(data, io)` returns the `IO` instance rather than a `String`, so subsequent string operations (such as `result.start_with?("{")` or regexp matching) fail with `NoMethodError`.
- **Silent failure with green build**: `JSON.dump(data, io)` and `JSON.load(io)` leave file descriptors open even when parsing/dumping raises an exception, silently exhausting available file descriptors. `JSON.dump` leaves the stream position at EOF, so subsequent reads from the stream return `""` rather than the written payload unless explicitly rewound. `JSON.load(io)` and `JSON.dump(obj, io)` buffer the entire document into RAM in a single monolithic read/write call rather than streaming chunks, causing silent O(N) memory spikes on large streams.
{"case":{"believed":"Passing an IO object to JSON.dump or JSON.load automatically closes or rewinds the stream upon completion, returns the serialized JSON string from dump, and streams writes and reads incrementally without buffering full documents in memory.","caseId":"case:sha256:703e974228b4287799263ec81a6c713a05f3da164a7054105974ea92906be86f","contract":["assert JSON.dump and JSON.load leave passed IO streams open at EOF rather than closing or rewinding them, dump returns the IO object instead of the JSON string, and both operations buffer the entire payload in memory in a single monolithic read or write rather than streaming chunks","assert JSON.dump and JSON.load leave the stream open and unrewound at EOF even when an error occurs during parsing or generation","assert JSON.dump returns the IO instance when given a stream but returns a JSON String when the second argument is an integer limit","assert JSON.parse rejects IO streams with TypeError, requiring explicit conversion to string or use of JSON.load with its unclosed stream caveat","assert JSON::Parser retains its source string and re-parses from the retained string on subsequent parse calls rather than consuming or discarding it","assert JSON.dump buffers the complete document before calling IO#write once, so a slow or aborted dump writes zero bytes rather than partial fragments"],"goal":"Manage IO stream lifecycles, EOF positions, and monolithic buffer allocations in JSON.dump and JSON.load","kind":"HOW","packages":["pkg:gem/json@2.9.1"],"schemaVersion":1,"symbols":["JSON.dump","JSON.load","JSON.parse","JSON::Parser","JSON::State"]},"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/json@2.9.1"],"schemaVersion":1,"symbols":["JSON.dump","JSON.load","JSON.parse","JSON::Parser","JSON::State"],"verifierAdapter":"rubygems@1"}
# frozen_string_literal: true
require "json"
require "stringio"
module JsonResourceOps
# Custom IO wrapper to observe read/write calls, buffering, and closure state
class MonitoredIO < StringIO
attr_reader :write_calls, :read_calls, :flush_calls
def initialize(*args)
super(*args)
@write_calls = []
@read_calls = 0
@flush_calls = 0
end
def write(str)
@write_calls << str.to_s
super(str)
end
def read(*args)
@read_calls += 1
super
end
def flush
@flush_calls += 1
super
end
end
# Safe dump wrapper that ensures the IO stream is flushed/closed or rewound
# according to caller requirements, and exposes the generated content.
def self.safe_dump_to_io(obj, io, rewind: false)
ret = JSON.dump(obj, io)
io.rewind if rewind
ret
end
# Safe load wrapper that reads from an IO and guarantees the IO is closed
# if managed by this method.
def self.safe_load_from_io(io, close_after: true)
result = JSON.load(io)
result
ensure
io.close if close_after && io.respond_to?(:close) && !io.closed?
end
end
# frozen_string_literal: true
require "minitest/autorun"
require_relative "../src/resource_ops"
class JsonResourceContract < Minitest::Test
def test_dump_and_load_leave_io_streams_open_at_eof_and_buffer_monolithically
# Contract Line 1:
# JSON.dump and JSON.load leave passed IO streams open at EOF rather than closing or rewinding them,
# dump returns the IO object instead of the JSON string, and both operations buffer the entire
# payload in memory in a single monolithic read or write rather than streaming chunks.
data = { "user_id" => 42, "roles" => %w[admin auditor], "active" => true }
expected_json = '{"user_id":42,"roles":["admin","auditor"],"active":true}'
out_io = JsonResourceOps::MonitoredIO.new
dump_return = JSON.dump(data, out_io)
# 1. dump returns the IO instance, NOT the JSON string
assert_same out_io, dump_return
refute_equal expected_json, dump_return
# 2. dump leaves the stream open and at EOF
refute out_io.closed?
assert_equal expected_json.bytesize, out_io.pos
assert out_io.eof?
assert_equal "", out_io.read # Immediate read returns empty string without rewind
# 3. dump performs a single monolithic write rather than streaming chunks
assert_equal 1, out_io.write_calls.length
assert_equal expected_json, out_io.write_calls.first
# 4. JSON.load leaves the input stream open and at EOF
in_io = JsonResourceOps::MonitoredIO.new(expected_json)
loaded_data = JSON.load(in_io)
# JSON.load reads the entire stream via a single unchunked read call
assert_equal 1, in_io.read_calls
assert_equal data, loaded_data
refute in_io.closed?
assert_equal expected_json.bytesize, in_io.pos
assert in_io.eof?
assert_equal "", in_io.read # Immediate read returns empty string without rewind
assert_equal 2, in_io.read_calls
end
def test_dump_and_load_leave_io_open_and_unrewound_even_on_errors
# When serialization or parsing fails with an exception, the IO stream is still left open.
# On JSON.load with invalid JSON, the stream has been fully consumed to EOF and remains unclosed.
bad_json = '{"key": incomplete...'
in_io = JsonResourceOps::MonitoredIO.new(bad_json)
err = assert_raises(JSON::ParserError) do
JSON.load(in_io)
end
assert_includes err.message, "unexpected token"
refute in_io.closed?
assert in_io.eof?
assert_equal bad_json.bytesize, in_io.pos
# On JSON.dump when depth limit is exceeded, dump raises before writing,
# but the output IO remains unclosed.
out_io = JsonResourceOps::MonitoredIO.new
assert_raises(ArgumentError) do
JSON.dump({ "a" => { "b" => { "c" => 1 } } }, out_io, 1)
end
refute out_io.closed?
assert_equal 0, out_io.pos
assert_equal 0, out_io.write_calls.length
end
def test_dump_return_type_polymorphism_between_io_and_nesting_limit
# JSON.dump(obj, anIO = nil, limit = nil)
# When second argument is an IO, it writes to IO and returns the IO.
# When second argument is an Integer (limit), it treats it as max_nesting and returns a String.
payload = { "status" => "ok" }
sio = StringIO.new
io_ret = JSON.dump(payload, sio)
assert_kind_of StringIO, io_ret
assert_same sio, io_ret
int_ret = JSON.dump(payload, 5)
assert_kind_of String, int_ret
assert_equal '{"status":"ok"}', int_ret
end
def test_parse_strictly_rejects_io_streams
# JSON.parse expects a String; passing an IO or StringIO raises TypeError.
# To parse from an IO without JSON.load, caller must explicitly read it.
sio = StringIO.new('{"id":100}')
err = assert_raises(TypeError) do
JSON.parse(sio)
end
assert_includes err.message, "no implicit conversion of StringIO into String"
# Reading the stream first into a String succeeds with JSON.parse
parsed = JSON.parse(sio.string)
assert_equal({ "id" => 100 }, parsed)
end
def test_parser_retains_source_string_across_multiple_parse_calls
# JSON::Parser retains its source string in @source.
# Multiple calls to parser.parse re-parse the retained source, producing fresh object allocations.
doc = '{"metrics":{"cpu":75,"mem":50}}'
parser = JSON::Parser.new(doc)
assert_equal doc, parser.source
result1 = parser.parse
result2 = parser.parse
assert_equal result1, result2
refute_same result1, result2 # Fresh allocation per parse call
refute_same result1["metrics"], result2["metrics"]
end
def test_dump_buffers_completely_before_writing_leaving_target_empty_on_early_abort
# Because JSON.dump generates the full string before writing to the IO,
# if generation fails (e.g. non-finite float without allow_nan or nested depth limit),
# zero bytes are written to the IO, preventing corrupt partial writes.
out_io = JsonResourceOps::MonitoredIO.new
assert_raises(ArgumentError) do
JSON.dump({ "outer" => { "inner" => 1 } }, out_io, 1)
end
assert_equal 0, out_io.write_calls.size
assert_equal "", out_io.string
end
end