Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions tests/pyathena/filesystem/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ class _DummyFileSystem:
pass


def _warnings(caplog):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 1 (continued): the registration test now uses one filter for both checks. The first registration produces exactly one record, a WARNING of pyathena.filesystem. Re-registering produces no WARNING or higher from any logger.
Mutations at eb64d92d:

  • These fail the test: no warning (info), a warning also for PyAthena's own class, and the warning from pyathena.filesystem.s3.
  • Rewording the message passes.

"""Return the captured records of level ``WARNING`` or higher.

Args:
caplog: The pytest caplog fixture.

Returns:
The records, of any logger.
"""
return [record for record in caplog.records if record.levelno >= logging.WARNING]


@pytest.fixture
def registry_state():
registry = dict(_registry)
Expand All @@ -41,15 +53,19 @@ def test_register_s3_filesystem(registry_state):

def test_register_s3_filesystem_overwrites_existing_registration(registry_state, caplog):
fsspec.register_implementation("s3", _DummyFileSystem, clobber=True)
# Only the s3 registration is replaced.
fsspec.register_implementation("s3a", S3FileSystem, clobber=True)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, finding 5 (medium) — fixed in part. With s3a already registered to another class, the exact one-record assertion would see two warnings; the test now pins s3a to S3FileSystem. Kept as designed: a warning of another logger fails the test (intended, so that a warning moved to pyathena.filesystem.s3 is caught), and the message text is not matched (undocumented). Mutations at 0f5f031a: no warning, the warning on pyathena.filesystem.s3, and a warning for PyAthena's own class each fail.


with caplog.at_level(logging.WARNING, logger="pyathena.filesystem"):
register_s3_filesystem()
# An explicitly registered filesystem class is overwritten with a warning.
assert fsspec.registry["s3"] is S3FileSystem
assert "will be overwritten" in caplog.text
assert [(r.name, r.levelno) for r in _warnings(caplog)] == [
("pyathena.filesystem", logging.WARNING)
]

# Re-registering PyAthena's own filesystem does not warn.
caplog.clear()
with caplog.at_level(logging.WARNING, logger="pyathena.filesystem"):
register_s3_filesystem()
assert not caplog.text
assert not _warnings(caplog)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2: the body now states what both assertions check (one WARNING of pyathena.filesystem; no record at WARNING or above on re-registration). Also: #1431 adds a test right after this line, and git merge-tree reports a conflict here only; whichever PR merges second keeps both. The errors-table paragraph was corrected too: ten entries have no case (RestoreAlreadyInProgress was missing), and InternalError and 500 cannot detect their removal because they map to the fallback EIO.

167 changes: 94 additions & 73 deletions tests/pyathena/filesystem/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,18 @@ def __init__(self, data, short=False, error_at=None, gate=None):
self.gated_read_started = threading.Event()
self.reads = []
self.closes = 0
# The offsets of the reads in the order they ended, and "close" when closed.
self.events = []
# Set when the file is closed, and by signal_close_wait() when close()
# starts to wait for the reads.
self.close_progressed = threading.Event()

def read_range(self, offset, size):
self.reads.append((offset, size))
if self._gate is not None and offset > 0:
self.gated_read_started.set()
assert self._gate.wait(EVENT_TIMEOUT)
self.events.append(offset)
if offset == self._error_at:
raise OSError("read failed")
return self._data[offset : offset + size - (1 if self._short else 0)]
Expand All @@ -43,7 +49,59 @@ def closed(self):
return self.closes > 0

def close(self):
self.events.append("close")
self.closes += 1
self.close_progressed.set()

def assert_closed_after_reads(self, stream):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review round 1 (implementation behavior, public contracts, simplicity, regression coverage), plus /code-review high and /simplify.
Base 703aaad82bfc0c11b35e35e80b03eba2507835fd, head b4e2bbde8ead3aa6918a9e30e41d2460229838d5; covered: all four changed test files, and the source they exercise (reader.py, s3_executor.py, s3_core.py, __init__.py).

FINDINGS, repaired in 57f28148 and eb64d92d:

  1. The close tests had lost the try/finally that released the gate, so a failure before the close left the gated reads blocked for EVENT_TIMEOUT. Now the gate comes from a fixture that sets it at teardown.
  2. The close helper polled two conditions every 1 ms. It now waits for one event, close_progressed, which the file's close() and the wait of close() both set. signal_close_wait became a method of the recording file.
  3. Every started read must end before the close, checked by count.

Re-checked at eb64d92d, each failing exactly the three close tests and nothing else:

  • close() without the wait failed them in each of three runs.
  • on_close before the wait failed them at 57f28148.
  • Waiting also for the cancelled parts, and not cancelling the queued parts, each fail test_close_with_queued_reads.

Deferred, with reasons:

  • A close() that waits only for some of the running reads is detected only by chance, because one gate releases them all. The old test had the same limit, and the target of this rewrite is a close that does not wait.
  • Patching pyathena.filesystem.reader.wait couples the tests to how close() waits. That coupling is what makes the check deterministic. A rewrite that waits differently fails with an explicit message ("close() neither waited for the reads nor closed the file"), so it cannot pass silently. test_interrupted_close already patched that name.

"""Check that closing the stream while the gated reads block closes the file last.

The stream is closed in a thread, and the reads are released once the
close waits for them (see :meth:`signal_close_wait`) or, if it does not
wait, has closed the file, which then precedes their end.

Args:
stream: The stream over the file.
"""
errors = []

def close():
try:
stream.close()
except BaseException as e:
errors.append(e)

closer = threading.Thread(target=close, daemon=True)
closer.start()
assert self.close_progressed.wait(EVENT_TIMEOUT), (
"close() neither waited for the reads nor closed the file"
)
self._gate.set()
closer.join(EVENT_TIMEOUT)
assert not closer.is_alive()
assert not errors

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review (relayed): Codex CLI 0.169.0, model gpt-6.2-astra, codex exec --sandbox read-only, session 01a1fee2-2855-7fb3-82f8-65b925ba271a. Static review of the detached snapshot 703aaad8..eb64d92d (diff, sources, docs/testing.md; no PR text or prior findings); the snapshot stayed unchanged. Result: FINDINGS (9; 6 medium, 3 low). Repairs in 0f5f031a.

Finding 4 (medium) — fixed. An exception of the closing thread left the test green (only a thread warning). Confirmed: with raise RuntimeError after super().close(), the three close tests passed at eb64d92d with 3 warnings; at 0f5f031a the closer records its error and assert not errors fails all three.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent follow-up (relayed): Codex CLI 0.169.0, model gpt-6.2-astra, read-only, session 01a1fef1-a46a-7770-ab6c-869f56ba1a18. Static review of the repair eb64d92d..0f5f031a (fixes for findings 4, 5 and 8) on a detached snapshot of 0f5f031a, which stayed unchanged; asked about intent, races, leaked state, false failures, IDs and the registry_state restore. Result: CLEAN.

# Every read that started ended before the file was closed.
assert self.events[-1] == "close"
assert len(self.events) == len(self.reads) + 1

def signal_close_wait(self, monkeypatch, interrupts=0):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2: the reader claims were measured at b4e2bbde/57f28148; re-run at eb64d92d, three runs each: no wait fails the three close tests; waiting also for the cancelled parts and not cancelling each fail test_close_with_queued_reads; on_close first fails the three and test_close_before_end. Deferred in the body: a partial wait is not detected, and the patch of reader.wait couples the tests to that name (a rename fails them through AttributeError or the close_progressed timeout, not silently).

"""Set ``close_progressed`` when ``ReadAheadStream.close()`` starts to wait for the reads.

Args:
monkeypatch: The pytest monkeypatch fixture.
interrupts: The number of first waits that raise ``KeyboardInterrupt``.
"""
remaining = interrupts

def signalling_wait(futures, *args, **kwargs):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, finding 1 (medium) — rejected. When close() waits for a cancelled future, the closer thread stays blocked after the test fails. This happens only in a run that already fails (12 s, on the close_progressed/join assertions), and the thread is a daemon; bounding the delegated wait would let that mutant finish and make its detection timing-dependent.

Finding 3 (medium) — deferred, as the PR body states. A correct close() that stops using reader.wait fails these tests through the close_progressed timeout (or AttributeError if the name goes); it fails loudly, never passes silently.

nonlocal remaining
if remaining:
remaining -= 1
raise KeyboardInterrupt
self.close_progressed.set()
return wait(futures, *args, **kwargs)

monkeypatch.setattr("pyathena.filesystem.reader.wait", signalling_wait)

def open_stream(self, **kwargs):
"""Open a stream over the file that closes it."""
Expand Down Expand Up @@ -79,6 +137,18 @@ def _new_future(self):
return _InterruptedFuture()


@pytest.fixture
def gate():
"""An event that blocks the gated reads of a ``_RecordingRangeFile`` until set.

It is set at teardown, so that a test that fails before releasing the reads
does not leave them blocked.
"""
gate = threading.Event()
yield gate
gate.set()


class TestReadAheadStream:
"""Tests for reading a file sequentially with parallel range reads."""

Expand Down Expand Up @@ -178,96 +248,47 @@ def test_interrupted_wait(self, monkeypatch):
assert sorted(file.reads) == [(0, 10), (10, 10), (20, 10)]
stream.close()

def test_interrupted_close(self, monkeypatch):
def test_interrupted_close(self, monkeypatch, gate):
"""An interrupted close leaves the file open, and closing again waits for the
running reads before closing the file."""
gate = threading.Event()
file = _RecordingRangeFile(bytes(100), gate=gate)
stream = file.open_stream(part_size=10, max_parts=2)
interrupts = [KeyboardInterrupt()]

def interrupted_wait(futures, *args, **kwargs):
if interrupts:
raise interrupts.pop()
return wait(futures, *args, **kwargs)

monkeypatch.setattr("pyathena.filesystem.reader.wait", interrupted_wait)
closer = threading.Thread(target=stream.close, daemon=True)
try:
assert stream.read(10) == bytes(10)
assert file.gated_read_started.wait(EVENT_TIMEOUT)
with pytest.raises(KeyboardInterrupt):
stream.close()
assert not file.closed
assert not stream.closed
# The stream reads nothing more once closing started.
with pytest.raises(ValueError, match="I/O operation on closed file"):
stream.read(10)
closer.start()
closer.join(0.2)
# A read of a later part is still blocked, so the retried close has not
# closed the file.
assert closer.is_alive()
assert not file.closed
finally:
gate.set()
if closer.is_alive():
closer.join(EVENT_TIMEOUT)
assert file.closed
file.signal_close_wait(monkeypatch, interrupts=1)
assert stream.read(10) == bytes(10)
assert file.gated_read_started.wait(EVENT_TIMEOUT)
with pytest.raises(KeyboardInterrupt):
stream.close()
assert not file.closed
assert not stream.closed
# The stream reads nothing more once closing started.
with pytest.raises(ValueError, match="I/O operation on closed file"):
stream.read(10)
file.assert_closed_after_reads(stream)
assert stream.closed

def test_close_with_queued_reads(self, monkeypatch):
def test_close_with_queued_reads(self, monkeypatch, gate):
"""Closing cancels a part that no worker has started and does not wait for it."""
shut_down = threading.Event()

class Executor(ThreadPoolExecutor):
def shutdown(self, wait=True, *, cancel_futures=False):
super().shutdown(wait=wait, cancel_futures=cancel_futures)
shut_down.set()

monkeypatch.setattr(
"pyathena.filesystem.reader.ThreadPoolExecutor",
lambda max_workers: Executor(max_workers=1),
lambda max_workers: ThreadPoolExecutor(max_workers=1),
)
gate = threading.Event()
file = _RecordingRangeFile(bytes(100), gate=gate)
stream = file.open_stream(part_size=10, max_parts=2)
closer = threading.Thread(target=stream.close, daemon=True)
try:
# The one worker blocks in the read of the second part, and the third waits.
assert stream.read(10) == bytes(10)
assert file.gated_read_started.wait(EVENT_TIMEOUT)
closer.start()
# The queued third part is cancelled, and close() waits for the second.
assert shut_down.wait(EVENT_TIMEOUT)
closer.join(0.2)
assert closer.is_alive()
finally:
gate.set()
closer.join(EVENT_TIMEOUT)
assert not closer.is_alive()
assert file.closed
file.signal_close_wait(monkeypatch)
# The one worker blocks in the read of the second part, and the third waits.
assert stream.read(10) == bytes(10)
assert file.gated_read_started.wait(EVENT_TIMEOUT)
file.assert_closed_after_reads(stream)
assert (20, 10) not in file.reads

def test_close_waits_for_running_reads(self):
def test_close_waits_for_running_reads(self, monkeypatch, gate):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent review, finding 2 (medium) — deferred, as the PR body already states. A close that waits for only some reads can pass. Measured: return_when="FIRST_COMPLETED" failed test_close_waits_for_running_reads in 2 of 5 runs. Detecting it deterministically needs per-read gates plus a bounded negative wait; the regressions that drop, misorder or over-extend the wait fail every run (three runs each at eb64d92d, rerun once at 0f5f031a).

Finding 9 (low) — kept. match="I/O operation on closed file" (lines 233, 264) is unchanged from master and outside the audit rows; it is the message of io's closed-file ValueError that the stream reproduces.

"""Closing waits for the reads in flight before closing the file."""
gate = threading.Event()
file = _RecordingRangeFile(bytes(100), gate=gate)
stream = file.open_stream(part_size=10, max_parts=2)
closer = threading.Thread(target=stream.close)
try:
assert stream.read(10) == bytes(10)
assert file.gated_read_started.wait(EVENT_TIMEOUT)
closer.start()
closer.join(0.2)
# A read of a later part is still blocked, so close() has not returned.
assert closer.is_alive()
assert not file.closed
finally:
gate.set()
if closer.is_alive():
closer.join(EVENT_TIMEOUT)
assert file.closed
file.signal_close_wait(monkeypatch)
assert stream.read(10) == bytes(10)
assert file.gated_read_started.wait(EVENT_TIMEOUT)
file.assert_closed_after_reads(stream)

def test_csv(self):
"""pyarrow reads a CSV through the stream with its own block size."""
Expand Down
Loading