Skip to content

fix: finalize the ArrowWriter on a clean context-manager exit - #9113

Open
horizonbymuneeb wants to merge 1 commit into
huggingface:mainfrom
horizonbymuneeb:fix/arrow-writer-exit-finalizes
Open

horizonbymuneeb wants to merge 1 commit into
huggingface:mainfrom
horizonbymuneeb:fix/arrow-writer-exit-finalizes

Conversation

@horizonbymuneeb

Copy link
Copy Markdown

ArrowWriter is a context manager, but leaving the block silently discards everything still staged in the buffer:

with ArrowWriter(path=path) as writer:
    for i in range(3):
        writer.write({"a": i})

os.path.getsize(path)          # 0
pa.ipc.open_stream(path)       # ArrowInvalid: Tried reading schema message, was null or length 0

Root cause

__exit__ called close():

def __exit__(self, exc_type, exc_val, exc_tb):
    self.close()

close() closes pa_writer and the stream, but it does not flush anything. write() buffers examples in current_examples until it has writer_batch_size of them (1000 by default) and only finalize() writes that remainder out, so any block that wrote fewer than a full batch lost all of its data and left a 0-byte file. The context manager was usable in the only way that looked natural and broken in exactly that way.

Fix

has_staged_data = bool(self.current_examples or self.current_rows) or self.pa_writer is not None
if exc_type is None and not getattr(self.stream, "closed", False) and has_staged_data:
    self.finalize()
else:
    self.close()

finalize() writes the staged examples, closes the writer and closes the stream, so the file is complete and the existing "the stream is closed after the block" guarantee still holds.

finalize() is deliberately not called in three cases, to keep the previous behaviour rather than introduce new failures:

case behaviour
the block raised close() only — the data is incomplete by definition
nothing was written close() only — there is no schema to infer and finalize() would raise SchemaInferenceError
the caller already called finalize() / closed the stream close() only — the file is already complete

Tests

test_arrow_writer_context_manager_writes_staged_examples writes three examples through the context manager and asserts the stream is closed, the file is non-empty, and it reads back as three rows.

Mutation check — the new test fails without the fix:

state result
src/datasets/arrow_writer.py reverted assert os.path.getsize(path) > 0 → AssertionError: assert 0 > 0
fix applied 1 passed
run result
pytest tests/test_arrow_writer.py 91 passed in 0.66 s
ruff check / ruff format --check clean, files already formatted

The existing test_arrow_writer_closes_stream, which covers both the raising and the non-raising path, still passes, so no caller that relied on the old behaviour changes.

Compatibility

Behaviour change only for code that relied on the data loss: a with ArrowWriter(...) block now leaves a readable file instead of a 0-byte one. Explicit close() without finalize() keeps its current semantics, so anything that manages the writer by hand is unaffected.

`ArrowWriter` is a context manager, so `with ArrowWriter(path=...) as writer: writer.write(...)`
is the natural usage, but `__exit__` only called `close()`. `close()` closes `pa_writer` and the
stream without flushing anything: the examples staged in `current_examples` only reach the file
through `finalize()`. Everything written below `writer_batch_size` (1000 by default) was therefore
dropped, leaving a 0-byte file that pyarrow cannot read.

`__exit__` now calls `finalize()` when the block exits cleanly and there is staged data. It keeps
the previous quiet `close()` when the body raised, when nothing was written (there is no schema to
infer, so `finalize()` would raise `SchemaInferenceError`), or when the caller already finalized.

Found by reading the issue; reproduced with three staged examples, which produced a 0-byte file
before the fix and a readable 432-byte stream with three rows after it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ArrowWriter used as a context manager (or close() without finalize()) silently discards all staged data and leaves a 0-byte unreadable file

1 participant