Repository navigation
Remove and rewrite the core, executor, reader and init filesystem tests (GH-1328) - #1430
laughingman7743 wants to merge 4 commits into
Conversation
…1328 audit (GH-1328) - test_s3_core.py: drop the matches on undocumented messages of the identity, ACL, path and delete-batch checks; the exception type fails every mutation of those checks. - test_s3_executor.py: remove test_submit_to, whose outcomes fail other tests; add test_shutdown_without_threads for a pool that has no threads, which the stdlib pool's own check does not cover. - test_reader.py: the close tests release the gated reads once close() waits for them or has closed the file, and assert that the file is closed after the reads end, instead of join(0.2) plus is_alive(). - test_init.py: assert a WARNING record of pyathena.filesystem instead of the log text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…H-1328) - test_object_operations_reject_paths keeps its former IDs. - The close tests of ReadAheadStream take the gate from a fixture that releases the reads at teardown, and wait for one event that the close or its wait sets instead of polling. - The registration test expects exactly one warning, and no warning of any logger when PyAthena's own filesystem is registered again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The wait signal of the close tests is a method of the recording file, counts its interrupts, and leaves the release of the gate after a failure to the fixture. - The close order is checked by the number of ended reads. - One filter of warning records serves both registration checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| self.closes += 1 | ||
| self.close_progressed.set() | ||
|
|
||
| def assert_closed_after_reads(self, stream): |
There was a problem hiding this comment.
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:
- The close tests had lost the
try/finallythat released the gate, so a failure before the close left the gated reads blocked forEVENT_TIMEOUT. Now the gate comes from a fixture that sets it at teardown. - The close helper polled two conditions every 1 ms. It now waits for one event,
close_progressed, which the file'sclose()and the wait ofclose()both set.signal_close_waitbecame a method of the recording file. - 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_closebefore the wait failed them at57f28148.- 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.waitcouples the tests to howclose()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_closealready patched that name.
| ("replace_object_metadata", (S3Path("bucket", "key", "null"), S3Metadata({}), {})), | ||
| ], | ||
| ids=[ | ||
| "head_object-args0-has no key", |
There was a problem hiding this comment.
Round 1 (continued): the IDs of test_object_operations_reject_paths were changed by removing the match column; they are restored with explicit ids= (CLAUDE.md: preserve test IDs). The suffixes now name the rejected condition, not a message the test checks.
Deferred: TestS3DeleteBatch::test_invalid and other match= sites of this file still match undocumented messages; they are not rows of the #1328 audit, and dropping the match there would keep message text in preserved IDs too. Recorded in the PR body.
| pass | ||
|
|
||
|
|
||
| def _warnings(caplog): |
There was a problem hiding this comment.
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 frompyathena.filesystem.s3. - Rewording the message passes.
| assert events == ["pending finished"] | ||
|
|
||
| @pytest.mark.parametrize("released", [False, True], ids=["unused", "released"]) | ||
| def test_shutdown_without_threads(self, released): |
There was a problem hiding this comment.
Round 1 (continued): the released case checks only the shutdown check. It does not check that release() dropped the threads.
- If
release()kept the executor, the case would take the stdlib path. It would still fail only when the shutdown check is also missing, so only two regressions at once would hide. test_release_after_callscovers the release itself.- Deferred.
| ("replace_object_metadata", (S3Path("bucket", "key", "v1"), S3Metadata({}), {})), | ||
| ("replace_object_metadata", (S3Path("bucket", "key", "null"), S3Metadata({}), {})), | ||
| ], | ||
| ids=[ |
There was a problem hiding this comment.
Self-review round 2 (claims and evidence), at eb64d92d.
Claims checked against the full offline suite (1377 tests that run without S3; the 461 that need S3 deselected):
- Collected IDs of the five files at
703aaad8and here differ only by the removedtest_submit_toand the two addedtest_shutdown_without_threadscases; the body said these IDs lost their suffix, which was no longer true after the explicitids=. Corrected. - The keep rows: K1-K9 and E1-E7 re-run on the full suite. Two audit claims of "only detector" no longer hold:
from Nonealso failstest_call_failure_frees_request[True]andtest_s3.pytests that readS3ClientError.code_of(s3.py:3786,s3.py:4458), andparamswinning over the given parts also failstest_open_parameters_named_as_request_fields[False]. Both tests stay as the direct core-level tests; the body records the change.
|
|
||
| assert events == ["pending finished"] | ||
|
|
||
| @pytest.mark.parametrize("released", [False, True], ids=["unused", "released"]) |
There was a problem hiding this comment.
Round 2: the body quoted the submit_to removal counts (25 and 6) from test_s3_executor.py and test_s3_writer.py only. On the full offline suite a dropped result fails 276 tests and a dropped exception 58; corrected. The removed test's contract stays covered several times over.
| assert self.events[-1] == "close" | ||
| assert len(self.events) == len(self.reads) + 1 | ||
|
|
||
| def signal_close_wait(self, monkeypatch, interrupts=0): |
There was a problem hiding this comment.
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).
| with caplog.at_level(logging.WARNING, logger="pyathena.filesystem"): | ||
| register_s3_filesystem() | ||
| assert not caplog.text | ||
| assert not _warnings(caplog) |
There was a problem hiding this comment.
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.
…1328) The close tests re-raise an error of the closing thread instead of leaving it as a thread warning, the registration test pins the s3a registration so that only s3 is replaced, and the ValueError tests build their inputs before the raises block, which without a message match would also accept an error of the input construction. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| self._gate.set() | ||
| closer.join(EVENT_TIMEOUT) | ||
| assert not closer.is_alive() | ||
| assert not errors |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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): |
There was a problem hiding this comment.
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.
| """ | ||
| remaining = interrupts | ||
|
|
||
| def signalling_wait(futures, *args, **kwargs): |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| del response[missing] | ||
| with pytest.raises(ValueError, match=message): | ||
| getattr(core, method)(S3MultipartUpload(response), *args) | ||
| upload = S3MultipartUpload(response) |
There was a problem hiding this comment.
Independent review, finding 8 (low) — fixed. Without a message match, a ValueError from building the input (S3MultipartUpload(response), the paths of from_paths) satisfied the assertion. Both inputs are built before the raises block in 0f5f031a. The parametrized args of test_acl_validation and test_object_operations_reject_paths are built at collection, so they are unaffected.
| pool.release() | ||
| pool.shutdown() | ||
| with pytest.raises(RuntimeError): | ||
| pool.submit(sum, [1, 2]) |
There was a problem hiding this comment.
Independent review, finding 6 (medium) — rejected. The scenario moves the shutdown check after enqueuing, but _get_executor() (s3_executor.py:993) checks before an executor exists and every submission goes through it, so there is no queue to reach first. The thread created when the check is removed exists only in a failing run.
Finding 7 (low) — rejected. The removed test_submit_to was the only case with a built-in callable failing (int("x")). The cleanup is traceback.clear_frames(e.__traceback__) (s3_executor.py:112), which walks the traceback without assuming a Python callee frame; the scenario needs a hypothetical rewrite. Dropping the exception fails 58 tests of the full offline suite.
WHAT
Implements group 2 of the #1328 audit (comment, at
766d79d0):test_s3_core.py,test_s3_errors.py,test_s3_executor.py,test_reader.pyandtest_init.py. Only these test files change;pyathena/filesystem/does not.35 commits changed these files after the audit (#1332, #1337, #1338, #1342 and others), so every verdict was re-checked on
703aaad8with mutations ofpyathena/filesystem/. The collected test IDs of the five files are unchanged except for the removed and added tests below.Removed:
TestS3Executor::test_submit_totest_submit_context,TestS3ThreadPool::test_run_contextand theTestS3PoolScopetests; a dropped exception fails 58, includingtest_submit_to_failure_frees_arguments,test_map_counts_failuresandTestS3File::test_commit_stops_at_failed_partRewritten:
TestS3Core::test_multipart_upload_requires_identity,test_acl_validation,test_object_operations_reject_paths,TestS3DeleteBatch::test_from_paths: nomatch=on the undocumented messages; the docstrings document onlyValueError. Removing eachraise ValueErrorofs3_core.pyin turn fails exactly the same cases with and without the matches. The inputs are built before theraisesblock, so an error of their construction cannot satisfy it.test_multipart_upload_requires_identitynow runs under the stub, so a missing check fails without sending a request.# noqa: PT011as in Audit the asyncio filesystem tests (GH-1328) #1349. The message column oftest_object_operations_reject_pathsis gone, and explicitids=keep its IDs ([head_object-args0-has no key]and so on).TestS3ThreadPool::test_shutdown_without_threads[unused|released](added next totest_shutdown): a shut-down pool that has no threads, never used or released, rejects calls. Without the pool's own shutdown check, both cases fail, andtest_shutdownstill passes because the stdlib pool raises the same error.TestReadAheadStream::test_close_waits_for_running_reads,test_interrupted_close,test_close_with_queued_reads: the gated reads are released onceclose()either waits for them (signalled through a wrapper ofreader.wait) or, if it does not wait, has closed the file; the file must then be closed after every started read ended. Agatefixture releases the reads at teardown, and an error raised by the closing thread fails the test instead of leaving a thread warning. Before,join(0.2)plusis_alive()let a regression pass whenever the closer took more than 0.2 s to reachclose(): with a 0.3 s delay at the start ofclose()and no wait, the oldtest_close_waits_for_running_readspassed and the new one fails.test_register_s3_filesystem_overwrites_existing_registration: asserts exactly one record atWARNINGor above, aWARNINGofpyathena.filesystem, instead of the log text; the re-registration of the same class asserts no record atWARNINGor above.s3ais pinned toS3FileSystem, so onlys3is replaced whatever was registered before. No warning, and the warning from another logger (pyathena.filesystem.s3), each fail; a reworded message passes.Verdicts that changed since the audit:
TestS3Executor::test_submit_to_executor_shut_down,test_submit_to_cancelled_executor_shut_down("decide with Consolidate the filesystem executors before parallel batch operations #1332", dropmatch): Merge the filesystem thread pools into one S3ThreadPool type (GH-1332) #1357 replaced them withtest_submit_to_executor_failureandtest_submit_to_cancelled_executor_failure, which use_DeferringExecutorinstead of the privateexecutor._pool.shutdown(). Theirmatch="after shutdown"now matches the error that the test itself sets, so they are kept unchanged.TestS3Executor::test_submit_to_loop_shutdown(keep): Merge the filesystem thread pools into one S3ThreadPool type (GH-1332) #1357 replaced it withtest_submit_to_dropped, since the loop dispatch no longer exists.TestS3AioThreadPool::*(keep): renamedTestS3ThreadPoolby Merge the filesystem thread pools into one S3ThreadPool type (GH-1332) #1357; the rows stand.test_call_translates_errors(keep, "only detector of__cause__"):from Nonenow also failstest_call_failure_frees_request[True], which asserts the cause in passing, andtest_cat_file_range[*]andtest_clear_multipart_uploads_race[NoSuchUpload-None]oftest_s3.py, which read the code of the cause. It stays as the direct test of the documented translation ofcall()per status and code.test_complete_multipart_upload(keep, "only detector of the given parts"): lettingparamswin over the given parts also failstest_open_parameters_named_as_request_fields[False]oftest_s3.py, a filesystem-level test of a different contract. It stays as the core-level test of the precedence.Kept: the other keep rows of these files remain the only detectors of their mutations in the full offline suite:
test_request_kwargs_is_a_copy(the copy),test_get_object_range_parameter[range_0-bytes=0-2](call parameters win over the range field),test_list_objects(storage_class),test_upload_part_uses_creation_algorithm_and_identityandTestS3MultipartWriter::test_writer_requests(per-call fields),test_replace_object_metadata(retained encryption),test_generate_presigned_url[*](unsignedrequest_kwargs),test_abort_multipart_upload_in_stopped_scope(unstoppable_retries()), andTestS3ThreadPool::test_default_max_workers,test_run_cancelled_after_return,test_run_cancelled_before_start[False],test_release_after_calls(withTestS3PoolScope::test_release_waits_for_waiting_calls),test_kept_future_keeps_no_pool,test_release_after_interrupted_submit,test_fork.test_s3_errors.pystays unchanged: removing each entry of the error tables that has a case fails exactly that case. Ten entries have no case (AccountProblem,AllAccessDisabled,InvalidObjectState,InvalidPayer,InvalidSecurity,NoSuchBucketPolicy,NoSuchLifecycleConfiguration,NotSignedUp,RequestTimeTooSkewed,RestoreAlreadyInProgress). Two cases cannot detect the removal of their entry, since it maps to the fallbackEIO:InternalError(the case has no status code) and the500status. The audit did not list these, and this PR does not add cases for them.Left as is:
TestS3DeleteBatch::test_invalidand the othermatch=sites outside the audit rows keep their matches; dropping them would put the message text only in their IDs.return_when="FIRST_COMPLETED"failedtest_close_waits_for_running_readsin 2 of 5 runs. A deterministic check needs a gate per read and a bounded negative wait.pyathena.filesystem.reader.wait, so they need updating ifclose()stops using that name; without the patch they fail on the timeout ofclose_progressed, not silently.Overlap: #1431 (GH-1388) adds a test after the last line of
test_init.pythat this PR changes;git merge-treereports a conflict there only, resolved by keeping both.test_s3_executor.pymerges cleanly.WHY
Part of #1328: tests that repeat another test's contract, match undocumented messages, or depend on unsynchronized timing. Groups 1 (#1349) and 3 (
test_s3.py, with #1340) are separate.TEST
At
0f5f031a(the offline runs of the five files and the reader and registration mutations; the full-suite runs used the tests ofeb64d92d, which0f5f031achanges only as described above):just lint: passed.--noconftest), the five files: 338 passed; the 4 failures,TestS3Core::test_call_retries_stream_body[*], also fail on master with the endpoint override and pass without it.tests/pyathena/filesystem(with these test files on703aaad8, 15 s timeout): 1488 passed, 189 failed, 450 errors, all of them tests that need S3 (test_s3.py,test_fsspec_conformance.py,test_s3_async.py) and the 4 above. The mutation runs deselect these 461 and run the other 1377.pyathena/filesystem/, run without bytecode caches and reverted after each run, with the results above. Reader mutations, three runs each ontest_reader.py: without the wait, the three close tests fail; waiting also for the cancelled parts, and not cancelling the queued parts, each failtest_close_with_queued_reads; callingon_closebefore the wait fails the three andtest_close_before_end; raising after the close fails the three (it passed ateb64d92d).pyathena.filesystem.s3, and a warning for PyAthena's own class each fail.🤖 Generated with Claude Code