Skip to content

Evict the cached entries that a fresh result contradicts (GH-1525) - #1626

Open
laughingman7743 wants to merge 15 commits into
masterfrom
fix/1525-contradicting-cache-entries
Open

laughingman7743 wants to merge 15 commits into
masterfrom
fix/1525-contradicting-cache-entries

Conversation

@laughingman7743

@laughingman7743 laughingman7743 commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

WHAT

Fixes #1525: a fresh result now evicts the cached entries that it contradicts, and lookups are cached by the parameters that their requests actually carry. The design follows the issue's decisions, with three choices that the maintainer made on 2026-11-30, after consulting Codex and Claude Fable 5.2:

  • One comparison for every result (2B). Every fresh result is compared, by one set of rules, with the cached entries that describe the same keys:

    • a complete listing, empty or not;
    • an object found or found missing;
    • a key prefix found by the probe of info(), or found to have no keys;
    • a version found missing.

    An entry that describes a key or a directory otherwise is evicted. Files are compared by etag, size and version_id, each where both entries have it. Lookups of explicit versions are never compared. This covers the issue's five rules and the same kind of contradiction beyond them, for example:

    • a lookup deeper than a child of a listed directory;
    • the recursive listings above a directory found empty;
    • a lookup without parameters that finds a key that a cached listing lacks.

    Each result is an observation object that chooses the cached keys it may contradict (_FoundObject, _MissingObject, _MissingVersion, _FoundDirectory, _Listed). The comparisons run inside S3ListingCache.put_listing(), put_lookup(), evict_missing() and evict_listing_without_directory(), as Give S3ListingCache one method per observation and document the listing cache #1524's coordination note asked.

  • Directory buckets (2a). A directory bucket's "/" listings also show the key prefixes of uploads in progress. So an empty listing does not refute its own directory as a listing above shows it, and a directory that a "/" listing or the probe shows does not require a key in a recursive listing. Everything else is compared as in other buckets.

  • evict_missing() is narrowed. It evicts a listing only where the listing lists the name as a file; a listing that lists a directory of the same name is kept. This was handed over from The listing cache keeps entries that a failed write or a failed request has shown to be stale #1523 and Evict a missing bucket's cached entries, check mkdir() uncached, and keep max_paths entries (GH-1492) #1561.

  • The probe of info() (ListObjectsV2 with MaxKeys=1) is compared with what its page lists: a file as it is, also with its cached lookups, and a common prefix as a directory that the listings above must show. A complete page, neither truncated nor counting keys that it does not name, lists the whole directory, so it is compared as a "/" listing (an empty one evicts the listings that show the directory), without caching it. The probe compares only the directory's own listings, those above it and the lookups of the listed files, so that a missing key does not scan the cache.

  • Generation guard. A token per bucket, compared by identity, changes before the entries are invalidated through the cache: by a write, invalidate_cache(), creating or deleting a bucket, and clear() (generation()). A lookup or listing whose request started before it is not cached, and still evicts what it contradicts. That is the only order that the cache keeps without a lock. After three review rounds found new windows in wider guards (stamps of stores and of S3 observations), the maintainer chose this contract after consulting Codex and Claude Fable 5.2; the class docstring states that of the results of overlapping requests an older one can stay cached until it is invalidated, a later result contradicts it, or it expires.

  • Effective lookup parameters (case 6, decision 1A). S3FileSystem._lookup_params() merges a call's authorization parameters over the filesystem's request_kwargs, for the operation that the path needs.

    • When the result equals the filesystem's own parameters, the lookup uses the cache of a lookup without parameters, including the listings.
    • Other values are cached by everything that the request carries.
    • HeadBucket sends, and is keyed by, ExpectedBucketOwner only.
  • metadata(). A call with only lookup parameters is a lookup, whose result the cache compares and keeps, as for info(). Other parameters, including a VersionId that the path does not name, keep it out of the cache.

  • Index of cached listings (3B). A stored listing is a list subclass that indexes its entries by name the first time it is compared.

Case 7 (du) is #1519's; copy and get lookups of listed entries are #1456's.

WHY

The cache stored each fresh result next to older entries of the same keys, and the next call answered from whichever it found first. All of the following reproduce on master:

  • info() returned a size from before ls(refresh=True);
  • find() and du() still listed an object that HeadObject had found missing;
  • isdir() and ls(bucket) still showed a directory that walk() had found empty;
  • exists() returned False although a lookup with SSE-C parameters had just found the key;
  • a version-aware info() returned a pinned version that had been found missing;
  • the same request was answered from the cache or sent again, depending on whether the SSE-C parameters came from the filesystem or from the call.

Release notes (behavior visible to callers; not breaking). A 4.x backport needs #1536 (#1523) and #1561 (#1492) on 4.x first, and its _head_object() hunk differs from master's after #1618.

  • Some calls send more requests than before: those that previously answered from an entry that a fresher result contradicted.
  • A lookup that passes the filesystem's own s3_additional_kwargs or RequestPayer explicitly is now answered from cached listings, as one without them is. Such a listing entry lacks HeadObject fields such as content_type, and a listing checks neither a customer-provided key nor ExpectedBucketOwner; refresh=True sends the lookup. docs/filesystem.md is updated.
  • A bucket lookup with RequestPayer or SSE-C parameters reuses the cached bucket listing and HeadBucket result.
  • fs.metadata(path) and getxattr() now update the cache with their result, as info() does.
  • While this filesystem writes to or invalidates a bucket, the lookups and listings of that bucket that were in flight are not cached, and the next call sends them again.

Cost, measured offline at eb6c167c with Python 3.15:

Operation Cost
put_listing() scan, 10k entries stored 0.30 ms
put_listing() scan, 100k entries stored 4.4 ms
First comparison with a 100k-entry recursive listing (builds the index) 16 ms
Each later comparison with the same listing 4 µs

The scan of the stored keys per fresh listing is accepted (decision 3B). max_paths bounds it.

Known limits:

  • Of overlapping requests, an older answer can stay cached until it is invalidated, contradicted or expired, as the class docstring states. This includes a HeadObject answered before another call finds the key missing. A result that the guard rejects can be read in the moment between its store and its removal.
  • The probe of info() compares only the listings of the directory and those above it and the lookups of the files that it lists, not the other entries below the directory, so that each missing key does not scan the cache.
  • The prefix probe keeps reading the parent listing of the path as given; trailing-slash paths belong to Settle one contract for caller-supplied S3 path strings #1493.

TEST

Tested commit: 174a6e95. Merge base: 06d48025.

  • just lint and just docs lint: pass.
  • just test offline: 4815 passed.
  • Offline filesystem suite (tests/pyathena/filesystem, -m "not aws", run with a per-process memory cap): 2407 passed, plus TestAioS3StreamedFile (98 passed), which runs separately with --noconftest.
  • New regression tests in test_s3.py (70 cases): 59 fail on master. Of the other 11:
    • 6 are neighbor cases, including a probe page that counts keys without naming them;
    • 5 protect behavior that master gets from its broader 404 eviction or from not caching, and that this branch keeps through new rules (the empty listing's parent and isdir, the empty probe, the directory-bucket probe, the versioned metadata()).
    • Removing each rule of the change in turn (mutation checks, rerun after every repair) fails at least one of these tests. The exceptions are equivalent forms: the prefix match of bucket eviction (the ARN-aware bucket name gives the same answer for the cached keys) and the ":" form of an access point ARN (cutting the name at its first slash gives the same bucket).
  • Live, targeted: uv run --with 'botocore[crt]' --env-file .env pytest -m aws -n 1 tests/pyathena/filesystem/test_s3.py tests/pyathena/filesystem/test_s3_async.py -k "info or exists or ls or find or cache or isdir or walk or glob or du": 15 passed at 174a6e95. The other 72 AWS filesystem tests were not run locally.
  • Differential check (.agents/skills/development-workflow): 44 cases, run twice on the merge base and once on the branch.
    • 25 intended differences, all present, and 19 neighbors unchanged. Nothing unexpected.
    • The neighbors include the documented limits: a HEAD answered before a 404, or before a fresh listing, can still be cached, as on master.
    • The cases cover all six issue cases, the sync and aio variants, version-aware mode, filesystem-level SSE-C and requester_pays, the guard against a HEAD answered before a write, directory buckets with an upload in progress, the empty probe, and metadata(). Access point ARNs are covered by unit tests only.
    • The matrix is kept with the review records.

🤖 Generated with Claude Code

laughingman7743 and others added 4 commits December 1, 2026 00:02
The cache stored each fresh result next to older entries of the same keys,
so the next call could answer from an entry that the result had just shown
to be stale: a lookup older than a fresh listing, a recursive listing that
still lists an object found missing, a listing of a directory found empty,
or the current entry that names a version found missing.

Each result is now compared, by one set of rules, with the cached entries
that describe the same keys, and those that describe a key or a directory
otherwise are removed: the lookups of the same path with other parameters,
the lookups and listings below a listed directory, its listing with the
other delimiter, and the listings of the directories above. Files are
compared by ETag, size and version ID where both entries have them. In a
directory bucket, whose listings also show the key prefixes of uploads in
progress, the directories that listings show are not compared.

An object found missing now removes a listing only where it lists the
object as a file, not a directory of the same name. A result whose request
started before a removal in its bucket, such as a write, is not cached.

Cached listings index their entries by name when first compared, so that a
comparison with a large recursive listing does not scan it each time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A lookup chose its cached result by the authorization parameters of the
call alone, while every request also carries those of the filesystem. A
call that repeated the filesystem's SSE-C parameters or RequestPayer sent
HeadObject again although the request was the same as without them, and a
file kept a cache slot of its own apart from info(). HeadBucket results
were keyed by all five parameters although only ExpectedBucketOwner is
sent.

A lookup whose parameters, merged over the filesystem's, are the
filesystem's own now uses the cache of a lookup without them, including
the cached listings; other values are cached by all the parameters that
the request carries, and HeadBucket results by ExpectedBucketOwner alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…okups by HeadBucket (GH-1525)

First self-review of #1626:

- A result now counts as stale when an entry of its bucket was removed
  after its request started, and then leaves the cache unchanged, instead
  of still evicting what it contradicts.
- The generation also counts stores. A result that contradicts a cached
  entry while another result of its bucket was stored after its request
  started is not cached, since either may be the older one; this covers a
  HeadObject answered before a fresh listing that no longer lists the key.
  A listing is compared with the cached listing under its own key too.
- A bucket path normalizes its lookup parameters by what HeadBucket sends,
  so RequestPayer or SSE-C parameters keep using the cached bucket listing.
- In a directory bucket, a key prefix that the probe of info() finds can be
  that of an upload in progress, so it evicts no listing.
- Sizes are compared only where both entries have one; a listing above the
  listed directory checks only the directory that leads to it; unreachable
  branches are removed, and the bucket test of cache keys is shared.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…g index (GH-1525)

/simplify of #1626:

- Each observation chooses the cached keys that it may contradict and
  compares files itself, so a missing version goes through the same
  comparison as other results (_MissingVersion) and the comparator has no
  type check for listings.
- One function names the directory directly below a listed one, and the
  completeness check of a cached listing is a single decision per name.
- The listing index sorts its names only when a prefix is first looked up,
  walks them by index instead of copying the tail, and answers
  has_file_below() with one bisection; a listing observation reuses the
  index cached on the listing.
- One helper stores an entry and removes it again after a removal of its
  bucket; the bucket listing now counts as a store too.
- evict_missing() is flattened and bumps the generation from the result
  of the comparison.
- _lookup_params() chooses HeadObject or HeadBucket from the path.
- Tests reuse _looked_up_file() for listed entries, and _cache() stores the
  bucket listing through put_buckets().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pyathena/filesystem/s3_cache.py Outdated
self._stores: dict[str, int] = {}
self._cleared = 0

def generation(self, bucket: str) -> tuple[int, int, int]:

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): /code-review high of the PR at 4bda3ca5 (base 06d480255a2532f8fdf5461a8fd40cb18d5e9945), then /simplify, reviewed head c4eb4296286ce08ebb57a43b17fe8a427a1b1bd9. Covered: every S3ListingCache method that stores or evicts, the observation classes, _lookup_params() and its four callers, the sync paths that the aio filesystem delegates to, and the new and changed tests. Result: FINDINGS (9), all verified against the code.

Repaired in 3b4e96d3:

  1. The guard counted removals only: a HeadObject answered before a fresh listing that no longer lists the key still evicted that listing and cached a stale "exists". The generation now also counts stores; a result that contradicts a cached entry while another result of its bucket has been stored since its request started is not cached (the contradicted entry is still removed). A listing is also compared with the cached listing under its own key. Test: test_lookup_answered_before_an_eviction_is_not_cached[listed_missing-False]; matrix row c7_delayed_head_after_listing.
  2. A result that the guard judged stale still evicted what it contradicted and bumped the generation. It now leaves the cache unchanged. Test: test_result_answered_before_an_eviction_changes_nothing.
  3. A bucket path normalized its parameters by HeadObject, so RequestPayer or SSE-C parameters skipped the cached bucket listing. It now normalizes by HeadBucket. Test: test_bucket_lookup_with_object_parameters_uses_bucket_listing.
  4. size was compared even when one entry lacked it; now only where both have it, as documented.
  5. A "/" listing above the listed directory was checked against every fresh file below it; one check of the leading directory answers it.
  6. Unreachable branches of _Listed.directory() and _FoundDirectory.directory() removed.
  7. In a directory bucket, the probe of info() can find only an upload's prefix; it now evicts no listing (decision 2a). Test: test_prefix_found_keeps_listings_of_directory_bucket; matrix row c2a_directory_bucket_probe.
  8. _in_bucket() replaced by _bucket_of(key) == bucket.

Not changed: 6. _lookup_params() repeats an idempotent normalization; measured 1.8 µs per call, against a HeadObject round trip.

/simplify (four angles: reuse, simplification, efficiency, altitude), applied in c4eb4296: observations choose the keys they may contradict and compare files themselves, so a missing version uses the same comparator (_MissingVersion); one _child() rule; the index sorts lazily, walks by index instead of copying the tail, and answers has_file_below() with one bisection; one _store() helper (the bucket listing now counts as a store); evict_missing() flattened; _lookup_params() takes the path; tests reuse _looked_up_file(). Skipped, with reasons: dropping the probe's parent-listing check (changes trailing-slash paths, #1493's), one directory-bucket gate (would also drop file-derived checks), the stored-key scan and own-key comparison (decided cost / needed for repair 1), reusing serve_s3_keys (needs per-key size and ETag and upload prefixes), removing evict_listing/since=None and indexing get_entries (#1524's API work).

Validation at c4eb4296286ce08ebb57a43b17fe8a427a1b1bd9: just lint; offline filesystem suite (memory-capped) 2367 passed; differential check 41 cases, 27 intended, none unexpected; 13 mutations of the change each fail a new test.

Comment thread pyathena/filesystem/s3.py
**{k: v for k, v in client_kwargs.items() if k in self._CLIENT_PASSING_ARGS},
)

def _lookup_params(self, params: Mapping[str, Any], path: S3Path) -> dict[str, Any]:

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, finding 3 (repaired): _lookup_params() now takes the looked-up path and normalizes a bucket path by what HeadBucket sends (ExpectedBucketOwner), so info("s3://bucket", RequestPayer=...) and exists("s3://bucket", **sse_c) keep using the cached bucket listing. Finding 6 (repeated, idempotent normalization in exists() → _path_info() → _head_*()) was measured at 1.8 µs per call and kept, so that the direct _head_object() callers (_object_exists, _key_exists, the copy pairing) are normalized too.

Comment thread pyathena/filesystem/s3_cache.py Outdated
path: The path that was found to be a key prefix.
name: The name of the directory that the path was found to be.
"""
if path.is_directory_bucket:

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, finding 8 (repaired): a directory bucket lists the key prefixes of multipart uploads in progress, so a prefix that the probe finds may have no key; the probe evicts no listing there, as decision 2a treats the directories that listings show. The parent-listing check above the comparator is kept as it was (its trailing-slash spelling belongs to #1493).

…-1525)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pyathena/filesystem/s3.py Outdated
missing removes the cached listings that list it as a file, an
object found removes those that do not list it as it is, and a key
prefix found removes the cached listings above it that do not show
it, except in a directory bucket, where it can be the prefix of a

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 2 (claims, callers, operations): base 06d480255a2532f8fdf5461a8fd40cb18d5e9945, head 0c1b73a9827b3693d5f1d3c17cffe8fbcaa5bfe9. Result: FINDINGS (4, all in the PR text and docstrings; corrected).

Claims checked, with evidence:

  • "Not breaking": the cache methods gained only an optional since; get_listing() returns a list subclass; _in_bucket() was private; AioS3FileSystem reaches the cache only through the sync filesystem (no direct _listing_cache use in s3_async.py). just test offline 4775 passed at 0c1b73a9827b3693d5f1d3c17cffe8fbcaa5bfe9.
  • Corrected: "backportable to 4.x" was too broad. origin/4.x has no _evicting_stale() or _stored(), so a backport needs Evict cached entries that failed writes and requests show to be stale (GH-1523) #1536 and Evict a missing bucket's cached entries, check mkdir() uncached, and keep max_paths entries (GH-1492) #1561 there first, and the _head_object() hunk differs after Name explicit versions in info() and record HeadObject's VersionId (GH-1529) #1618. The PR body now says so.
  • Corrected: the PR body described the guard as counting evictions only; after round 1 it counts stores too. The body now describes both conditions.
  • Added to the release notes: under concurrent writes to a bucket, the lookups and listings of that bucket that were in flight are not cached, so the next call repeats them. This is the operator-visible cost of the guard.
  • Corrected: cost figures re-measured at 0c1b73a9827b3693d5f1d3c17cffe8fbcaa5bfe9 (index sorting is now lazy): put_listing() scan 0.42 ms with 10k stored entries and 5.5 ms with 100k; first comparison with a 100k-entry recursive listing 20 ms, later ones 5 µs.
  • Corrected: "the new tests fail on master". Run against master's package: 24 of 30 fail. Five of the other six are neighbor cases, and test_result_answered_before_an_eviction_changes_nothing protects a round-1 repair (it passes on master, which compares nothing, and fails with its rule removed).
  • Release note on explicit filesystem-level SSE-C (listing metadata without content_type, no key check, refresh=True sends HEAD): checked against docs/filesystem.md (updated paragraph) and the info()/exists() docstrings.
  • Corrected: the info() docstring now states the directory-bucket exception of the prefix probe (this line).
  • Live: the earlier targeted run was at 72ef66e9, before the round-1 repairs; rerun at 0c1b73a9827b3693d5f1d3c17cffe8fbcaa5bfe9: 15 passed (-m aws, -k "info or exists or ls or find or cache or isdir or walk or glob or du"). The other 72 AWS filesystem tests were not run locally; CI runs them after Ready.

Comment thread docs/filesystem.md
`touch(truncate=False)`, send these parameters of the file or the write. A lookup with them uses only the cached results of lookups with the same
values, not cached listings. The existence checks do not use the listing cache.
`touch(truncate=False)`, send these parameters of the file or the write. A lookup
whose parameters, over those of `s3_additional_kwargs` and `requester_pays`, are the

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, documentation reader: this paragraph was checked against _lookup_params() (merged over core.request_kwargs, compared per operation) and the tests test_lookup_with_filesystem_parameters_uses_cache and test_bucket_lookup_with_object_parameters_uses_bucket_listing. The other cache statements in this guide (around lines 200, 493 and 840) are unchanged by the PR and still hold.

@laughingman7743 laughingman7743 added this to the 5.0.0 milestone Nov 30, 2026
laughingman7743 and others added 2 commits December 1, 2026 01:00
Independent review of #1626:

- A result is not stored when another result of its bucket was stored
  while it was being compared, since either can be the older one.
- The removal and store records are stamps from one counter, which never
  repeat, so concurrent updates cannot restore a generation that a
  request recorded; clear() drops them.
- An empty listing, a key prefix found by info(), and a bucket found
  missing change the generation even when nothing was cached: they show
  that results in progress are older (the last also for the bucket
  listing). A bucket listing is not cached when another one was stored
  after its request started.
- The prefix probe of info() that finds no key reports the directory as
  an empty listing, which the narrower HeadObject 404 no longer evicts.
- metadata() with only lookup parameters and VersionId is a lookup, whose
  result the cache compares and keeps.
- The docs say that listings do not check ExpectedBucketOwner either.
- Tests check each evicted entry before another request can repair it,
  tell the compared fields apart (ETag only, version only), and seed the
  copy test's files without comparing them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…in directory buckets (GH-1525)

Self-review of the repairs of #1626:

- A result whose request started before a removal in its bucket is still
  not cached, but it again removes the cached entries that it
  contradicts, which is safe whichever is older; a refreshed listing
  answered while another request found a key missing left the older
  listing in place.
- In a directory bucket, a listing with the delimiter "/" shows the key
  prefixes of uploads in progress too, so a prefix that the probe of
  info() finds again evicts a cached listing that lacks it, as on master;
  otherwise info() answered otherwise than info(refresh=True) had.
- metadata() with a VersionId parameter is not cached as a lookup, whose
  entry info() names with the version.
- Removing the entries of a bucket records one removal, not one per entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pyathena/filesystem/s3.py Outdated
return directory
if directory.key:
# The probe lists the prefix of the directory, which has no keys.
self._listing_cache.put_listing(directory.name, "/", [], since)

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 result): reviewer codex exec -s read-only (Codex CLI default model). It was a static review of a detached snapshot at 0c1b73a9827b3693d5f1d3c17cffe8fbcaa5bfe9 (base 06d480255a2532f8fdf5461a8fd40cb18d5e9945). The prompt carried the agreed behavior, the diff and the matrix, but no PR text or earlier findings. No edits, builds or tests; the snapshot and the PR worktree were unchanged afterwards. Result: FINDINGS (14).

Verified and repaired in ff46ad2d:

  1. An empty prefix probe left a deleted directory cached in its parent listing. It is now reported as an empty listing. Test: test_prefix_found_empty_evicts_listings_of_the_directory.
  2. A store could land between a result's comparison and its own store. Stores now check the stamp taken before the comparison. Test: test_lookup_stored_while_another_is_compared_is_kept.
  3. An empty listing, or a probe that found a directory, left no generation change when nothing was cached. Both now record a removal. Test: [listed_empty-False].
  4. An older bucket listing could overwrite a newer one, and a bucket found missing did not count against the bucket listing. Both are fixed. Test: test_bucket_listing_answered_before_a_change_is_not_cached (listed, head_bucket).
  5. Concurrent increments could restore an earlier generation. Generations are now unique stamps from one counter.
  6. fs.metadata() returned successful HEADs without the cache comparing them. A call with only lookup parameters is now a lookup. Test: test_metadata_lookup_evicts_contradicted_listing.
  7. The docs now say that listings do not check ExpectedBucketOwner.
  8. clear() drops the stamps.
  9. Tests now check each evicted entry before another request can repair it.
  10. Tests now tell the compared fields apart: an ETag-only change, and a version-only change.
  11. The copy test seeds its files without comparing them.

Not changed, with reasons:
6. A delayed 404 can evict an entry cached after an invalidation. Eviction costs only a request; it never leaves a wrong answer.
9. The quadratic scan of stored keys: decision 3B accepted the scan cost, and it is measured in the PR.
11. The trailing-slash parent of the probe is the behavior that #1561 preserved, and it belongs to #1493.

Comment thread pyathena/filesystem/s3_cache.py Outdated
else:
self.evict_listing(name, delimiter)
bucket = self._bucket_of(name)
kept = self._kept(since, bucket)

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 of the independent-review repairs (both perspectives), head a4addef11cc9cb5990025daca6ade2c155bc5db3: /code-review high of the PR at ff46ad2d. Result: FINDINGS (10).

Verified and repaired in a4addef1:

  1. metadata(path, VersionId=...) cached an entry named without the version under the version's key. Such a call is no longer cached. Test: test_metadata_with_version_parameter_is_not_cached.
  2. A result that the guard rejected skipped its evictions, so a refreshed listing left the older listing in place. It now evicts what it contradicts and skips only its store. This partly reverses round 1's repair 2. Tests: test_refresh_answered_before_an_eviction_still_evicts_stale_entries, and test_result_answered_before_an_eviction_leaves_fresh_answers (rewritten).
  3. Round 1's directory-bucket exception for the probe made info() answer differently from info(refresh=True). It is reverted. In a directory bucket, a "/" listing shows upload prefixes too, so a listing that lacks the prefix is stale (as on master). Recursive listings are still not compared there. Test: test_prefix_found_evicts_listing_of_directory_bucket.
  4. Removing a bucket's entries now records one removal, not one per entry.

Not changed, with reasons:
4. The guard records a removal on every 404, empty listing and found prefix. This costs the in-flight results of the bucket; the user chose the guard for correctness, and per-key records would grow without bound. The cost is now stated in the release notes.
5. The scan cost was decided under 3B.
6. The trailing-slash parent is #1493's.
7. _lookup_params repeats: 1.8 µs.
9. The _Listing copy costs about 0.4 ms per 100k entries; avoiding it would import a private class in s3.py.
10. The probe's parameters: a merged dict sends each key once, with the same values that S3Core would add.

Round 2, the claims: the PR body is rewritten to the final behavior.

  • The guard now evicts on rejected results, and records removals for empty listings, found directories and missing buckets.
  • The 2a wording is updated, and the metadata() behavior and the in-flight cost are in the release notes.
  • The costs are re-measured at a4addef1.
  • The test counts are re-run on master: 40 of 50 new tests fail there, and the other 10 are explained.
  • The info() docstring's directory-bucket exception, added in round 2, is removed again.

Validation at a4addef1: just lint; just test offline 4795 passed; filesystem suite 2387 passed; differential check 44 cases, 27 intended, none unexpected; 24 mutations each fail a test.

laughingman7743 and others added 3 commits December 1, 2026 01:32
… complete pages (GH-1525)

Independent review follow-up of #1626:

- In a directory bucket, a listing with the delimiter "/" shows the
  prefixes of uploads in progress, as the listings above it do, so a
  directory that such a listing shows again requires the listing above
  to show it; only recursive listings are not required to hold a key.
- An empty probe of info() is taken as an empty listing only when its
  page is not truncated, and also for the key "/", whose directory a
  listing names "bucket/".
- The docs name the bucket listing (ListBuckets) as the one that does not
  check ExpectedBucketOwner.
- Tests: a size-only change, the listing after metadata(), and the
  current version after metadata() with a VersionId parameter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t its order (GH-1525)

Independent review follow-up of #1626 showed that stamps of stores and of
observations cannot make a check and a store atomic without a lock: every
repair left another window. As decided after consulting Codex and Claude
Fable 5.2, the guard now keeps one order only, which it can keep without
a lock:

- A token per bucket, compared by identity, changes before the entries
  are invalidated through the cache: by a write, invalidate_cache(),
  creating or deleting a bucket, and clear(), which replaces an epoch
  token. A lookup or listing whose request started before it is not
  cached, and still evicts what it contradicts.
- Results of S3 (a key found missing, an empty listing, a key prefix
  found) no longer change the generation, and the store stamps, the check
  of stores during a comparison and the special cases are removed.
- A bucket listing that is not cached removes the cached one, which it
  would have replaced.
- The class docstring states the limit: of the results of overlapping
  requests, an older one can stay cached until it is invalidated, a later
  result contradicts it, or it expires.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…and probe without a scan (GH-1525)

Self-review of the guard change of #1626:

- In a directory bucket, only two directory facts are uncertain: that an
  empty listing shows its own directory gone, and that a recursive
  listing without keys below a directory shows it gone. A listing with
  the delimiter "/" that no longer shows a subdirectory again evicts the
  cached listings of it.
- An empty probe of info() compares only the listings of the directory
  and those above it, so that a missing key no longer scans the cache.
- A fresh lookup removes only the results with other parameters that it
  contradicts.
- The keys of the listings above a name come from one helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
self._invalidations: dict[str, object] = {}
self._epoch = object()

def generation(self, bucket: str) -> tuple[object, object]:

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 follow-up 1 (relayed Codex result): reviewer codex exec -s read-only. It was a static review of the repairs 0c1b73a9..a4addef1 on a detached snapshot of a4addef11cc9cb5990025daca6ade2c155bc5db3, with the earlier findings and their handling as context. Result: FINDINGS (14).

Concurrency findings, resolved by a contract decision. Findings 1–6, 8 and 11 were further windows in the generation guard: overlapping ListBuckets, a store during comparison, the publication of parameterized lookups, scan-before-stamp ordering, discarded refreshes, clear() racing a write, expiry, and growing bookkeeping. Three rounds had each found new ones. Codex and Claude Fable 5.2 were consulted in parallel, and both recommended narrowing the guard: stamps cannot make a check and a store atomic without a lock. The maintainer chose this contract.

  • A token per bucket changes before every invalidation through the cache: a write, invalidate_cache(), creating or deleting a bucket, and clear().
  • A result whose request started before that change is not cached, and still evicts what it contradicts.
  • S3 observations no longer change the generation, and the store stamps are removed.
  • The class docstring states the remaining limit for overlapping requests.

This is implemented in d664e258. Finding 11 (bookkeeping growth) is now bounded by the buckets invalidated. Finding 6 (clear()) is resolved by an epoch token, compared by identity.

Repaired in 248e1645:

    1. A directory-bucket "/" listing that shows a subdirectory now evicts a listing above that lacks it.
    1. The probe of key / is reconciled too.
    1. Only a complete (untruncated) probe page is taken as an empty listing.
    1. The docs now name ListBuckets as the listing that does not check ExpectedBucketOwner.
  • 13 and 14. New tests check the listing after metadata(), the current version after a VersionId call, and a size-only change.

Comment thread pyathena/filesystem/s3.py
return directory
if not page.is_truncated:
# The probe lists the prefix of the directory, which has no keys.
self._listing_cache.put_listing(directory.name, "/", [], since, below=False)

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 of the guard change (both perspectives): /code-review high of the PR at d664e258, head eb6c167c3ec094b2eff36c839e71a4f7ea5415dc. Result: FINDINGS (7).

Repaired in eb6c167c:

  1. weak_directories turned off every directory comparison in directory buckets. Only two facts are uncertain there: an empty listing's own directory, and a recursive listing's directories without keys. Test: test_listing_without_upload_prefix_evicts_listing_below_of_directory_bucket.
  2. The empty probe scanned the whole cache on every missing key. It now compares only the directory's own listings and those above it (put_listing(..., below=False)).
  3. The PR body was rewritten to the decided contract. Tested commit, costs, limits and test counts (43 of 53 new tests fail on master) are re-run at eb6c167c.
  4. A fresh lookup now removes only the contradicted results with other parameters. No test separates this from evicting the whole dictionary: such a dictionary needs overlapping requests, so this is stated as a limit of the evidence.
  5. The keys of the listings above a name come from one helper (_listings_above()).

Not changed, with reasons:
5. The trailing-slash parent of the probe belongs to #1493.
6. _lookup_params repeats: 1.8 µs per call.

Validation at eb6c167c: just lint; just test offline 4799 passed; filesystem suite 2391 passed; differential check 44 cases, 25 intended (the HEAD-after-404 and HEAD-after-listing rows are neighbors now, as documented limits), none unexpected; the guard's mutations (6) and the directory-bucket rule each fail a test.

…d probe in directory buckets (GH-1525)

Independent review follow-up 2 of #1626:

- The bucket of a cache key that names an access point ARN includes the
  access point's name after "accesspoint/", so that an invalidation of
  its path changes the generation that its lookups took; removing the
  entries of a bucket matches its name as a prefix again, as before.
- In a directory bucket, a probe of info() that lists a key below the
  directory is compared with recursive listings too.
- An empty probe page with a continuation token is not taken as empty.
- A dictionary of lookups with parameters that the comparison empties is
  removed.
- The class docstring states that a result that does not stay cached can
  be read in the moment between its store and its removal, and that an
  empty probe compares no entries below the directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pyathena/filesystem/s3_cache.py Outdated
while isinstance(key, tuple):
key = key[0]
name = cast(str, key)
if name.startswith("arn:"):

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 follow-up 2 (relayed Codex result): codex exec -s read-only. It was a static review of a4addef1..eb6c167c on a detached snapshot of eb6c167c, judged against the decided guard contract. Result: FINDINGS (8).

Repaired in 09f87eef, with self-review of both perspectives:

  • 4 (a regression introduced by /simplify). _bucket_of cut the bucket at the first slash, so for an access point ARN, an invalidation of its path changed another token than its lookups took. The bucket of an ARN now includes the access point's name, also in the Outposts form, and bucket eviction matches the name as a prefix again, as The listing cache keeps or drops entries around missing buckets, mkdir() and max_paths #1492 had it. Test: test_access_point_arn_lookup_answered_before_an_invalidation_is_not_cached.
    1. A directory-bucket probe that lists a key (Contents) is now compared with recursive listings. Test: test_prefix_found_with_a_key_evicts_recursive_listing_of_directory_bucket.
    1. An empty probe page with only a continuation token is not taken as empty. Test: [continuation_token].
    1. A dictionary of lookups with parameters that the comparison empties is removed.
    1. A missing version now removes, of one key's results with parameters, only those that name it. Test: test_missing_version_keeps_other_lookups_with_parameters.
  • 1 and 2. The class docstring and the PR's limits now state that a rejected result can be read between its store and its removal (no lock), and that an empty probe compares no entries below the directory (the scan cost from the self-review).

Not changed: 7. PreconditionFailed calls invalidate(path), which is an invalidation through the cache, as the contract states.

Validation at 09f87eef: just lint; just test offline 4802 passed; filesystem suite 2394 passed; differential check 44 cases, 25 intended, none unexpected; 47 of 57 new tests fail on master; the mutations of these repairs fail their tests. The exception is the prefix match of bucket eviction, which the ARN-aware bucket name makes equivalent.

…probe lists (GH-1525)

Independent review follow-up 3 of #1626:

- The bucket of a cache key that names an access point ARN follows the
  ARN grammar, with ":" or "/" before the access point's name and the
  Outposts form, so that a key below it that contains "accesspoint" is
  not taken for part of the bucket.
- A probe of info() that lists a key below the directory compares that
  file with the listings above, so that a recursive listing that lists
  only other keys there is evicted.
- A dictionary of lookups with parameters that the final check empties is
  removed.
- The docstring of the probe's observation states the directory-bucket
  rule as it now is; tests tell the truncated and continuation-token pages
  apart, and check a cache hit before the eviction of an ARN bucket.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# The bucket of an access point ARN, which includes the name of the access
# point: arn:partition:service:region:account:accesspoint/name, with ":" or
# "/" before the name, and the Outposts form ...:outpost/id/accesspoint/name.
_ACCESS_POINT_ARN = re.compile(

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 follow-up 3 (relayed Codex result): codex exec -s read-only. It was a static review of eb6c167c..09f87eef on a detached snapshot of 09f87eef, judged against the decided contract. Result: FINDINGS (7).

Repaired in f8ddddad, with both self-review perspectives applied:

  1. The ARN with : before the access point's name, and a key that contains accesspoint, gave the wrong bucket. ARNs are now matched by their grammar (this line), including the Outposts form. Tests: test_access_point_arn_lookup_answered_before_an_invalidation_is_not_cached for the slash, colon and Outposts forms.
  2. A keyed probe passed only a flag, so a recursive listing that showed another key below the directory was kept. The probe now passes the listed file, which the listings above must list as it is. Test: test_prefix_found_with_another_key_evicts_recursive_listing.
  3. A dictionary emptied by the final generation check is now removed.
  4. The truncated-page case no longer also carries a token, so each case now tests one signal.
  5. The probe's docstring now states the current directory-bucket rule.
  6. The ARN test now checks a cache hit before the bucket eviction.

Not changed: 3. Removing an emptied dictionary can drop a replacement that another thread stored meanwhile. That costs one request, within the documented concurrency limit.

Validation at f8ddddad: just lint; just test offline 4805 passed; filesystem suite 2397 passed; differential check 44/25, none unexpected; 50 of 60 new tests fail on master. The mutations fail their tests, except two equivalent forms that the PR body names.

… complete (GH-1525)

Independent review follow-up 4 of #1626:

- The probe's page lists entries directly below the directory as
  _ls_prefix() names them. A file there is compared as it is, also with
  its cached lookups, and a common prefix as a directory that the
  listings above must show.
- A complete page (neither truncated nor with a continuation token) lists
  the whole directory, so it is compared as a listing with the delimiter
  "/" is, without the scan below and without caching it.
- Tests: the probe's page, complete and truncated; a complete page that
  shows a key gone; the Outposts ARN with ":" and an Object Lambda ARN;
  the continuation-token test checks only the cache. The stubbed probe of
  stub_move_with_source_params lists a/x with the size that its lookup
  found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pyathena/filesystem/s3.py Outdated
*(S3Object.directory(path.bucket, c.prefix[:-1]) for c in page.common_prefixes),
*(S3Object.from_summary(o) for o in page.objects),
]
complete = not (page.is_truncated or page.next_continuation_token)

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 follow-up 4 (relayed Codex result): codex exec -s read-only. It was a static review of 09f87eef..f8ddddad on a detached snapshot of f8ddddad, judged against the decided contract. Result: FINDINGS (6).

Repaired in b2d8c4b2, with both self-review perspectives applied:
1, 2, 3. The probe discarded most of what its page lists, so the cached lookups and listings of a listed file, a listed common prefix, and (on a complete page) a key gone from the directory stayed stale. Now:

  • files on the page are compared as they are, also with their lookups;
  • common prefixes must show in the listings above;
  • a complete page is compared as a "/" listing (this line), without caching it, because caching would change what later calls send.

Tests: test_prefix_found_compares_the_entries_of_its_page (complete, truncated) and test_prefix_found_on_a_complete_page_shows_deleted_keys. The stubbed probe in stub_move_with_source_params now lists a/x with the size that its lookup found.
5. The continuation-token test now checks only the cache. A probe reads one page, as before.
6. The ARN test adds the Outposts form with : and an Object Lambda ARN.

Not changed: 4. An emptied dictionary restored by racing refreshes costs one entry, within the documented concurrency limit.

Validation at b2d8c4b2: just lint; just test offline 4810 passed; filesystem suite 2402 passed; differential check 44/25, none unexpected; 55 of 65 new tests fail on master; the mutations of these repairs (probe entries, complete page, file lookups, Outposts colon) fail their tests.

…named page as whole (GH-1525)

Independent review follow-up 5 of #1626:

- A probe of info() whose page is truncated also compares its entries
  with the cached listings of the directory itself.
- A page that counts keys without naming any is not taken as a listing
  of the whole directory.
- Tests: a file and a common prefix of the probe's page are checked apart,
  a counted page without entries keeps the listing of the directory, and
  the continuation-token fixture answers the next page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pyathena/filesystem/s3.py
*(S3Object.directory(path.bucket, c.prefix[:-1]) for c in page.common_prefixes),
*(S3Object.from_summary(o) for o in page.objects),
]
# A page that counts keys without naming them lists nothing whole.

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 follow-up 5 (relayed Codex result): codex exec -s read-only. It was a static review of f8ddddad..b2d8c4b2 on a detached snapshot of b2d8c4b2. Result: FINDINGS (4). All 4 were repaired in 5e605896, with both self-review perspectives applied:

  1. A truncated probe did not compare the directory's own cached listings. It does now. Test: test_prefix_found_compares_a_file_of_its_page[truncated].
  2. A page that counts keys without naming them was taken as an empty listing of the whole directory. It no longer is (this line). Test: test_prefix_found_counted_without_entries_is_no_listing.
  3. The test of the probe's page now checks a file and a common prefix apart: test_prefix_found_compares_a_file_of_its_page and test_prefix_found_compares_a_directory_of_its_page.
  4. The continuation-token fixture now answers the next page.

Validation at 5e605896: just lint; just test offline 4813 passed; filesystem suite 2405 passed; differential check 44/25, none unexpected; 57 of 68 new tests fail on master; the mutations of these repairs fail their tests.

…ove, and name the path's parent in the docstring (GH-1525)

Independent review follow-up 6 of #1626, whose review of the runtime
changes was clean: a truncated probe page against the directory's own
recursive listing, a page that only counts keys against a recursive
listing above, and the listing that holds the path as given among the
listings that the probe compares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
results of overlapping requests an older one can stay cached until it is
invalidated, a later result contradicts it, or it expires. The probe of
``info()`` compares only the listings of the directory and those above
it, also the listing that holds the path as it was given, and the

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 follow-up 6 (relayed Codex result): codex exec -s read-only. It was a static review of b2d8c4b2..5e605896 on a detached snapshot of 5e605896. The reviewer confirmed that the runtime changes address both previously reported cache failures. Result: FINDINGS (3 Low; tests and docs only). All were addressed in 174a6e95:

  1. The class docstring now names the listing that holds the path as given among those that the probe compares (this line).
  2. New test: a truncated probe page against the directory's own recursive listing (test_prefix_found_on_a_truncated_page_evicts_recursive_listing_of_it). Removing (name, "") from the probe's keys fails it.
  3. New test: a page that only counts keys against a recursive listing above (test_prefix_found_counted_without_entries_evicts_recursive_listing_above).

No runtime code changed after this review, so no further independent follow-up was run.

Final validation at 174a6e95: just lint and just docs lint; just test offline 4815 passed; filesystem suite 2407 passed, and TestAioS3StreamedFile 98 passed; differential check 44 cases, 25 intended, none unexpected; 59 of 70 new tests fail on master; targeted live S3 tests 15 passed.

@laughingman7743
laughingman7743 marked this pull request as ready for review November 30, 2026 18:29

This branch has not been deployed

No deployments
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.

Fresh lookups and listings leave contradicting cached entries of the same paths

1 participant