Skip to content

[Server] Share the S3 bucket region lookup between AWS S3 and S3-compatible storage - #2267

Merged
yili-db merged 1 commit into
unitycatalog:mainfrom
yili-db:fix/shared_region_lookup
Dec 2, 2026
Merged

yili-db merged 1 commit into
unitycatalog:mainfrom
yili-db:fix/shared_region_lookup

Conversation

@yili-db

@yili-db yili-db commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

PR Checklist

  • A description of the changes is added to the description of this PR.
  • If there is a related issue, make sure it is linked to this PR.
  • If you've fixed a bug or added code that should be tested, add tests!
  • If you've added or modified a feature, documentation in docs is updated

Description of changes

The server looked up S3 bucket regions in two places with two sets of rules: FileOperationsImpl for AWS buckets (the Iceberg client.region) and S3BucketRegions for S3-compatible storage (the vended signing region). Both send an anonymous HeadBucket, but only S3BucketRegions bounds its cache, rechecks regions, backs off after failures and runs one lookup per bucket. This shares that lookup, keeping the two fallback rules explicit.

  • S3BucketRegions.getAwsRegion(bucket) serves AWS buckets with the same lookup as getS3CompatibleRegion:
    • a reported region is cached per bucket, at most 10,000 buckets, and asked again after an hour (the AWS map was unbounded and never rechecked)
    • a failed recheck keeps the reported region, and the bucket is asked again only after the 30-second backoff
    • one lookup runs per bucket at a time
    • an AWS bucket in backoff whose reported region was evicted is asked again, never given the S3-compatible default (the two caches evict apart)
    • a failure to build the lookup client is handled as a failed request: as before on S3-compatible storage; for an AWS bucket it is now a retriable INTERNAL error instead of an unhandled exception
    • each request is capped at 10 seconds
    • AWS lookups address the bucket virtual-hosted, the SDK default as before; S3-compatible lookups keep the location's addressing style (path_style_access)
    • a 404 drops the reported region on S3-compatible storage, where the bucket may be created again with another region; an AWS bucket keeps it, as for any failed recheck (noted in the class javadoc)
  • Fallbacks stay explicit and unchanged:
    • S3-compatible storage without a known region uses us-east-1 and asks again later
    • an AWS bucket without a known region fails with FAILED_PRECONDITION (no region, such as no such bucket) or INTERNAL (transient), with the same messages as before, and is asked again on the next request
  • FileOperationsImpl keeps only the regions configured with s3.bucketPath.N/s3.region.N and asks S3BucketRegions for the rest
  • Tests:
    • S3BucketRegionsTest.testAwsBucketKeepsItsReportedRegionOnAFailedRecheck, parameterized over a recheck that fails with 503, 404, 403 without a region, 200 without a region, or a malformed region: the region is kept, the 30-second backoff holds, and an eviction during it fails the lookup (through a test-only evictReportedRegion)
    • testAwsBucketWithoutAKnownRegionHasNoDefault: no default for an AWS bucket
    • testConcurrentRequestsShareOneLookup, for a success and for a failing AWS lookup that a second caller waits on
    • testReportedRegionIsUsedAndCachedPerStorageAndBucket: two AWS buckets on one instance each get their own region, apart from the same name on S3-compatible storage, and the lookup client has the 10-second timeout
    • FileOperationsTest discovers the region of my_bucket, which is not a host name; the other region cases pass unchanged (their mock builder now also stubs overrideConfiguration, for the timeout)

Follow-up from the review of #2172. #2264 fixes how both places read a bucket name that is not a valid host name (URI::getAuthority); this PR already reads it that way, so whichever merges second needs a small rebase.

A configured region for S3-compatible storage, to avoid the lookup entirely, is left for a separate proposal.

Tests: build/sbt "server/testOnly *S3BucketRegionsTest *FileOperationsTest", and the server suite on H2 (dev/run-tests.py server/test).

Compatibility: no API or configuration change. An AWS bucket's region is now asked again after an hour instead of cached for the server's lifetime, and a recheck that fails keeps the earlier region. A malformed x-amz-bucket-region header from AWS is now refused like a missing one (FAILED_PRECONDITION, unless a region was reported before), as it already was for S3-compatible storage.

This pull request and its description were written by Isaac.

@yili-db
yili-db requested a review from tdas as a code owner November 17, 2026 07:11
@yili-db

yili-db commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@yili-db

yili-db commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

/review

1 similar comment
@yili-db

yili-db commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@timothyw553 timothyw553 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

no production code bugs found. just left a few comments on test coverage, javadoc, and logging.

assertThat(aws.getAwsRegion("bucket")).isEqualTo("eu-central-1");
now.addAndGet(S3BucketRegions.REPORTED_REGION_TTL.toMillis());
assertThat(aws.getAwsRegion("bucket")).isEqualTo("eu-central-1");
verify(s3, times(2)).headBucket(any(HeadBucketRequest.class));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this stops right after the failed refresh, so nothing verifies that we actually wait FAILURE_RETRY_DELAY before calling AWS again (removing backOff() from awsFailed() still passes). could we check both sides of the retry boundary here?

+ now.addAndGet(S3BucketRegions.FAILURE_RETRY_DELAY.toMillis() - 1);
+ assertThat(aws.getAwsRegion("bucket")).isEqualTo("eu-central-1");
+ verify(s3, times(2)).headBucket(any(HeadBucketRequest.class));
+ now.incrementAndGet();
+ assertThat(aws.getAwsRegion("bucket")).isEqualTo("eu-central-1");
+ verify(s3, times(3)).headBucket(any(HeadBucketRequest.class));

if (reported != null) {
return Optional.of(reported.region());
}
if (!storageBucket.isAws()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

what if reportedRegions evicts an AWS bucket while retryAfterMs still has it? right now removing this !storageBucket.isAws() check still passes all tests, so could we add a deterministic test (e.g. invalidating reportedRegions after a failed refresh) to verify it re-queries and throws INTERNAL instead of falling back to us-east-1?

.get()
.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_EAST_1)
.overrideConfiguration(c -> c.apiCallTimeout(DISCOVERY_TIMEOUT));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

tests stub overrideConfiguration on the mocked builder without checking what it configures, so dropping this timeout still passes all tests. could we capture the consumer in a test and assert apiCallTimeout is set to 10s?

@yili-db
yili-db force-pushed the fix/shared_region_lookup branch 2 times, most recently from 466cbae to c5ff432 Compare November 20, 2026 00:46
@yili-db

yili-db commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@yili-db
yili-db requested a review from timothyw553 November 20, 2026 00:48

@timothyw553 timothyw553 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

no production code issues, the shared lookup and caching changes look solid. just left a few comments on test coverage and one nit on the javadoc.

// An AWS bucket shares the lookup: its region is cached, and a failed recheck keeps it.
when(s3.headBucket(any(HeadBucketRequest.class)))
.thenReturn(HeadBucketResponse.builder().bucketRegion("eu-central-1").build())
.thenThrow(s3Exception(503, null));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

here we only test a 503 on the aws refresh, what about 404, 403 without a region header, 200 with no region, or a malformed region? unlike s3-compatible storage, aws should keep eu-central-1 and back off for FAILURE_RETRY_DELAY in all four cases, so could we add those cases too?

// getAuthority(), not getHost(): a valid bucket name is not always a valid host name.
return configured != null
? configured
: s3BucketRegions.getAwsRegion(storageBase.toUri().getAuthority());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this uses getAuthority() so bucket names where getHost() returns null (like my_bucket) still work, right now reverting to getHost() passes all tests. could we update testGetFileIOConfigS3DiscoversRegionWhenNotConfigured in FileOperationsTest to cover that?

-        fileOps.getFileIOConfig(NormalizedURL.from("s3://my-bucket/table"));
+        fileOps.getFileIOConfig(NormalizedURL.from("s3://my_bucket/table"));
 ...
-    assertThat(request.getValue().bucket()).isEqualTo("my-bucket");
+    assertThat(request.getValue().bucket()).isEqualTo("my_bucket");

when(builder.build()).thenReturn(client);
when(client.headBucket(any(HeadBucketRequest.class))).thenThrow(failure);
S3BucketRegions fresh = new S3BucketRegions(() -> builder, now::get);
for (int i = 0; i < 2; i++) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

these calls run sequentially, so nothing tests a second caller waiting on another caller's failing aws lookup (dropping the CompletionException unwrap in getRegion still passes). could we add a concurrent failure case that blocks the first lookup, waits for a second caller to join, then fails with 503 and checks both get BaseException (INTERNAL) while headBucket runs once?

@yili-db

yili-db commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@shba24 shba24 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

On lines this pull request does not change

server/src/main/java/io/unitycatalog/server/service/credential/aws/S3BucketRegions.java:130

Nit (not a blocker): Helpers still public after their only outside caller was removed

headBucketRegion (:130) and isTransient (:153) are still public static. Their only caller outside the class, FileOperationsImpl.discoverRegion, was deleted by this change. Leaving them public lets other code run HeadBucket directly and skip the cache, the backoff and DISCOVERY_TIMEOUT, which is the second lookup path this PR removes.

Cost of keeping it: A new caller in another package runs S3BucketRegions.headBucketRegion(S3Client.create(), bucket). It compiles, and the request has no timeout and no cache. git grep shows headBucketRegion is used outside the class only at S3BucketRegionsTest.java:98, in the same package, and isTransient has no outside caller.

  static String headBucketRegion(S3Client client, String bucket) {
Evidence
S3BucketRegions.java:130 `public static Optional<String> headBucketRegion(S3Client s3Client, String bucket) {` and :153 `public static boolean isTransient(S3Exception e) {`. The removed caller in FileOperationsImpl (base): `return S3BucketRegions.headBucketRegion(s3Client, bucket)` and `if (S3BucketRegions.isTransient(e)) {`. Running `grep -rn "headBucketRegion\|S3BucketRegions.isTransient"` over server/src, connectors and integration-tests at head finds only S3BucketRegionsTest.java:98 `S3BucketRegions.headBucketRegion(s3, "bucket")` outside the class itself.
How it was checked

Checked by 1 independent check: CONFIRMED

How about making headBucketRegion package-private and isTransient private?

server/src/main/java/io/unitycatalog/server/service/credential/aws/S3BucketRegions.java:265

Nit (not a blocker): No test gives an AWS bucket a malformed region on first lookup

The REGION_PATTERN check is exercised only for S3-compatible storage. A change that skips the check for AWS alone would pass every test, even though the PR body says a malformed AWS header is now refused. The same habit leaves other AWS-only branches untested: a recheck answered with 404, 403 without a region or 200 without a region; a RuntimeException recheck with a reported region (S3BucketRegions.java:297); and a concurrent AWS lookup that fails (:209).

For example: Fresh instance; HeadBucket returns bucketRegion("us east 1"); getAwsRegion("other") should throw FAILED_PRECONDITION. Today an AWS-only bypass of the check still passes.

In testAwsBucketKeepsItsReportedRegionAndHasNoDefault, use a fresh instance and stub headBucket to return bucketRegion("us east 1"). Assert that getAwsRegion("other") throws FAILED_PRECONDITION and that a second call reaches headBucket again. The other AWS-only branches listed above could be added as rows to the same test.

Evidence
server/src/main/java/io/unitycatalog/server/service/credential/aws/S3BucketRegions.java:265-266 reads `if (!region.get().matches(REGION_PATTERN)) { return withoutRegion(storageBucket, "a malformed region header"); }`. `withoutRegion` sends an AWS bucket to `awsFailed(..., isTransient=false, reason)`, which throws FAILED_PRECONDITION. The removed `FileOperationsImpl.discoverRegion` had no such check: `S3BucketRegions.headBucketRegion(s3Client, bucket).orElseThrow(...)` accepted any non-blank header. The only malformed-header test is in `testStorageWithoutRegionUsesDefault` (S3BucketRegionsTest.java:105-106), `new Failure(s3Exception("us east 1"), NO_REGION_RECHECK_DELAY)`. It goes through `getS3CompatibleRegion` and takes the 403-header route, not a 200 response. `testAwsBucketKeepsItsReportedRegionAndHasNoDefault` (lines 243-297) uses only a 503, a connection error, a 200 with no bucketRegion, and a valid `eu-central-1`. `FileOperationsTest` has no case with a malformed region. I searched both test files for `malformed` and found only that one comment. If the `matches` check is removed or its branch inverted, an AWS bucket with region `us east 1` is cached and passed to `AwsClientProperties.CLIENT_REGION`, and every test still passes.
How it was checked

Checked by 1 independent check: CONFIRMED

Could we add the malformed-region case, and the other AWS-only branches, to that test?

retryAfterMs.invalidate(storageBucket);
return region.get();
} catch (S3Exception e) {
if (storageBucket.isAws()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): A null endpoint stands for AWS, and five branches must remember it

StorageBucket uses a null s3Endpoint as a type tag (isAws()). The lookup checks it at knownRegion, both catch blocks of lookUp, discoveryClient and withoutRegion, and failure handling is split into failed and awsFailed. A branch that forgets the tag gives an AWS bucket the S3-compatible default, and bdf4301 and fca72fe each fixed one such gap. The same applies to the StorageBucket(String, String) record at :81 and its use in evictReportedRegion.

Cost of keeping it: A new rule that differs by storage kind, for example a separate TTL for AWS, needs an edit in every isAws() branch and a check against the cache-eviction interplay. A third storage kind would need another null-like value. Nothing serialized depends on this, so it does not need to block the merge.

Optional. Add static factories StorageBucket.aws(bucket) and StorageBucket.s3Compatible(endpoint, bucket), and have evictReportedRegion take a StorageBucket. A private enum Kind { AWS, S3_COMPATIBLE } carrying the no-region and failure rules could follow. A full outcome-type redesign must keep stale-region retention, backoff and eviction exactly as they are, so it is better as its own refactor PR.

Evidence
S3BucketRegions.java:81-84 `private record StorageBucket(String s3Endpoint, String bucket) { boolean isAws() { return s3Endpoint == null; } }`. It is checked at :241 `if (!storageBucket.isAws()) { return Optional.of(DEFAULT_S3_COMPATIBLE_REGION); }`, :275 `if (storageBucket.isAws()) { return awsFailed(storageBucket, e, isTransient(e)); }`, :297 `if (storageBucket.isAws()) { return awsFailed(storageBucket, e, /* isTransient= */ true); }`, :314 `if (!storageBucket.isAws()) { builder.endpointOverride(...)`, and :380 `if (storageBucket.isAws()) { return awsFailed(storageBucket, /* cause= */ null, /* isTransient= */ false, reason); }`. At :292-294 `} catch (BaseException e) { // An AWS lookup that already failed with its own error, as for no region. throw e; }` is a catch that exists only so the AWS policy error thrown inside the try gets past `catch (RuntimeException e)`. At :235-236 `// The two caches evict apart: an AWS bucket has no default, so without the reported region it is asked again rather than given the default of S3-compatible storage.` records the policy interplay that commit bdf43016 had to fix.
How it was checked

Checked by 1 independent check: NITPICK

Would you like the factories in this PR, or should the larger cleanup wait for a follow-up?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed that the null endpoint as a type tag is fragile. I will do the factories and a storage-kind enum in a follow-up refactor, keeping the retained region, the backoff and the eviction rule as they are. This PR is approved, and #2289 changes S3BucketRegions too, so I kept this round small.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for agreeing to the factories and the storage-kind enum, and for keeping region retention, backoff and eviction as they are. Doing that after #2289 lands, to avoid a conflict in S3BucketRegions, sounds right to me. It's a nit, so I'm happy with this as is.

Settled from our side, thanks. Please resolve this thread when you're ready.

this.storageCredentialVendor = storageCredentialVendor;
this.s3ClientBuilderSupplier = s3ClientBuilderSupplier;
this.s3BucketRegionMap = new ConcurrentHashMap<>();
this.s3BucketRegions = new S3BucketRegions(s3ClientBuilderSupplier);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): Two S3BucketRegions instances each hold their own cache budget

FileOperationsImpl and StorageCredentialVendorImpl (:40) each build their own S3BucketRegions, so the code is shared but the caches are not, and there are two MAX_BUCKETS budgets. The keys never overlap, because AWS buckets are looked up here and endpoint buckets in the vendor. Nothing breaks.

For example: Repositories.java:122 builds the vendor with new S3BucketRegions() and :127 builds FileOperationsImpl, which builds another. A server with 10,000 AWS buckets and 10,000 S3-compatible buckets can hold up to 20,000 cached entries across the two.

  // Separate from the vendor's instance: this one only sees AWS buckets, the vendor's only endpoint buckets.
Evidence
FileOperationsImpl.java:64 `this.s3BucketRegions = new S3BucketRegions(s3ClientBuilderSupplier);` and StorageCredentialVendorImpl.java:40 `this(cloudCredentialVendor, externalLocationUtils, serverProperties, new S3BucketRegions());`. Repositories.java:127 `new FileOperationsImpl(storageCredentialVendor, serverProperties));` already passes the vendor in, so a single instance could be handed to both.
How it was checked

Checked by 1 independent check: CONFIRMED

Would a one-line comment noting that the key sets are disjoint be enough, rather than sharing one instance?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Right, the two key sets never overlap: FileOperationsImpl only looks up AWS buckets and the vendor only endpoint buckets, so the extra budget is the only cost. I will share one instance in the same follow-up as the StorageBucket cleanup, since that is where the kind of a bucket becomes explicit.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for checking the key sets and for planning to share one S3BucketRegions in the follow-up. I re-read both callers at this head: FileOperationsImpl only looks up AWS buckets, and the vendor only looks up buckets with an endpoint. So the keys never overlap and the only cost is the second cache budget. Happy to leave it for the follow-up.

Settled from our side, thanks. Please resolve this thread when you're ready.

* @throws BaseException {@code FAILED_PRECONDITION} if the region cannot be determined (such as
* for no such bucket), or {@code INTERNAL} if the lookup failed transiently (retriable)
*/
public String getAwsRegion(String bucket) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): First request per AWS bucket each hour waits on HeadBucket

AWS buckets now share REPORTED_REGION_TTL. Once an hour the first request for each bucket runs an anonymous HeadBucket inline, capped at 10 seconds, where the old code cached the region for the server's lifetime. Concurrent callers get the old region, and a failure keeps it. This matters only for a bucket recreated in another region, and the PR's Compatibility section already discloses it.

For example: getAwsRegion("b") at t=0 and again at t=1h+1ms: the second call blocks on HeadBucket for up to 10s before it returns.

No change needed. If the inline recheck latency turns out to matter, skip the TTL for AWS buckets only.

Evidence
S3BucketRegions.java:186-188 `public String getAwsRegion(String bucket) { return getRegion(new StorageBucket(/* s3Endpoint= */ null, bucket)); }` sends AWS through the shared path. At :230 `if (reported != null && now < reported.recheckAtMs())` the cached region is served only until `recheckAtMs`, which :268-271 sets to `currentTimeMillis.getAsLong() + REPORTED_REGION_TTL.toMillis()`, with `REPORTED_REGION_TTL = Duration.ofHours(1)` at :71. After that, :212 `knownRegion(storageBucket).orElseGet(() -> lookUp(storageBucket))` runs HeadBucket on the calling thread, with `.overrideConfiguration(c -> c.apiCallTimeout(DISCOVERY_TIMEOUT))` at :313. The code removed from FileOperationsImpl only did `s3BucketRegionMap.putIfAbsent(storageBase, s3Region)` into a `ConcurrentHashMap` with no expiry. And for AWS, :275-276 `if (storageBucket.isAws()) { return awsFailed(storageBucket, e, isTransient(e)); }` keeps the old region on any recheck error, including a 404.
How it was checked

Checked by 1 independent check: CONFIRMED

Are you comfortable keeping the hourly recheck for AWS, given it is documented?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes, keeping it. The hourly recheck is what picks up a bucket that was recreated in another region without a restart, and it costs one HeadBucket per bucket per hour, capped at 10 seconds. Concurrent callers keep the old region meanwhile, and a failed recheck keeps it too.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for spelling out why the hourly recheck stays: picking up a bucket recreated in another region, at one capped HeadBucket per bucket per hour, is a fair trade for the old server-lifetime cache, so I'm happy to leave it as is.

Settled from our side, thanks. Please resolve this thread when you're ready.

@@ -227,6 +240,63 @@ public void testFailedRecheckKeepsTheReportedRegion() {
verify(s3, times(7)).headBucket(any(HeadBucketRequest.class));
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): PR description lists tests that are not in the head

The Tests section of the PR body names tests from an earlier plan that did not land. The same mismatch shows up in three places: S3BucketRegionsTest.java:244, S3BucketRegionsTest.java:136 and FileOperationsTest.java:716. It also leaves the open threads PRRT_kwDOMI92_s656OQP, PRRT_kwDOMI92_s656OQg and PRRT_kwDOMI92_s656OQT without the tests they asked for.

For example: The body names testAwsBucketKeepsItsReportedRegionOnAFailedRecheck (503, 404, 403 without a region, 200 without a region, malformed region) and testAwsBucketWithoutAKnownRegionHasNoDefault; git grep finds neither. The only AWS recheck test, testAwsBucketKeepsItsReportedRegionAndHasNoDefault, fails the recheck with 503 only. testConcurrentRequestsShareOneLookup uses only getS3CompatibleRegion with a successful lookup, and FileOperationsTest uses my-bucket, not the my_bucket the body describes.

Make the Tests section match the head. Either add the promised tests: a parameterized AWS failed-recheck test, a concurrent failing AWS lookup in testConcurrentRequestsShareOneLookup, and my_bucket in testGetFileIOConfigS3DiscoversRegionWhenNotConfigured. Or reword the section to describe what exists today (503 recheck only, concurrency on S3-compatible storage only, my-bucket).

Evidence
L5 check: “Does every sentence of my description/title map to a hunk?” The PR description claims parameterized AWS refresh tests, a failing concurrent AWS lookup, and a `my_bucket` test. At S3BucketRegionsTest.java:241, the AWS refresh test uses `.thenThrow(s3Exception(503, null))`; at S3BucketRegionsTest.java:136, the concurrent test exercises S3-compatible storage and returns a successful response; at FileOperationsTest.java:716, the discovery test uses `NormalizedURL.from("s3://my-bucket/table")`. These do not match the described coverage.
How it was checked

Checked by 1 independent check: CONTESTED

Which would you prefer: adding those tests (they would also settle the three open threads) or trimming the description to match what is there?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The tests were in 234fdcc07, but GitHub never moved the PR head off c5ff4323d, which is the commit this review ran on. The new push did move it (now 079b1d6ec), and the description matches that head: testAwsBucketKeepsItsReportedRegionOnAFailedRecheck, testAwsBucketWithoutAKnownRegionHasNoDefault, the failing AWS case in testConcurrentRequestsShareOneLookup, and my_bucket in FileOperationsTest.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for tracing this to the head and pushing again: our review ran on the earlier head, which lacked those tests, and the current head (079b1d6) has the failed-recheck, no-known-region and failing concurrent AWS tests in S3BucketRegionsTest plus my_bucket in FileOperationsTest, so I'm happy to drop this one.

Settled from our side, thanks. Please resolve this thread when you're ready.

.thenReturn(HeadBucketResponse.builder().bucketRegion("eu-central-1").build())
.thenThrow(s3Exception(503, null));
AtomicLong now = new AtomicLong();
S3BucketRegions aws = new S3BucketRegions(() -> builder, now::get);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): No AWS test looks up two buckets on one instance

The shared instance in the AWS test looks up only "bucket", and each lookup of "other" uses a fresh instance that fails. Only the S3-compatible test checks that buckets are isolated. The key StorageBucket(null, bucket) is correct today, so this matters only if the key later changes for AWS alone.

For example: One instance, getAwsRegion("a") returns eu-central-1, then getAwsRegion("b") with HeadBucket returning ap-south-1. A key that ignored the bucket name for AWS would serve eu-central-1 for both, and the suite would stay green.

On one instance, stub two successful HeadBucket answers with different regions for two AWS bucket names. Assert that each bucket gets its own region and that headBucket was called twice.

Evidence
S3BucketRegions.java:73,81,186-187: `private final Cache<StorageBucket, Reported> reportedRegions;` and `private record StorageBucket(String s3Endpoint, String bucket) {` and `return getRegion(new StorageBucket(/* s3Endpoint= */ null, bucket));`. S3BucketRegionsTest.java:250-252: `S3BucketRegions aws = new S3BucketRegions(() -> builder, now::get);` followed by two `aws.getAwsRegion("bucket")` assertions. The new AWS test uses one successful bucket per instance; I found no test with two successful AWS buckets on the same instance.
How it was checked

Checked by 2 independent checks: CONFIRMED

Would you add that two-bucket case to the AWS test?

// Each lookup is capped, so storage that does not answer cannot hold up the request.
ArgumentCaptor<Consumer<ClientOverrideConfiguration.Builder>> override =
ArgumentCaptor.forClass(Consumer.class);
verify(builder, times(2)).overrideConfiguration(override.capture());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): Timeout test breaks if the builder is configured another way

The test requires exactly two calls to the overrideConfiguration(Consumer) overload of the mocked builder, which couples it to how the client is configured. The effective timeout value is checked, which is good, but a behavior-preserving change to the overload or the call count fails the test.

Cost of keeping it: Change S3BucketRegions.java:313 to .overrideConfiguration(ClientOverrideConfiguration.builder().apiCallTimeout(DISCOVERY_TIMEOUT).build()). The timeout is unchanged, but the test fails with 'Wanted but not invoked'.

Verify with atLeastOnce() instead of times(2) and keep the check that applying the captured consumer sets apiCallTimeout to 10s. A real builder would decouple the test further but is not required.

Evidence
S3BucketRegionsTest.java:83-88: `ArgumentCaptor<Consumer<ClientOverrideConfiguration.Builder>> override = ArgumentCaptor.forClass(Consumer.class);`, `verify(builder, times(2)).overrideConfiguration(override.capture());`, then `override.getValue().accept(configuration);` and `assertThat(configuration.build().apiCallTimeout()).contains(Duration.ofSeconds(10));`. The assertion requires a particular overload and call count rather than just the resulting timeout.
How it was checked

Checked by 1 independent check: CONFIRMED

Would atLeastOnce() be enough to keep this check without pinning the call count?

* bucket is asked again after {@link #FAILURE_RETRY_DELAY}. A bucket without a known region has
* no default, so its lookup fails, and it is asked again on the next request. One lookup runs per
* bucket at a time.
*

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): Comment about AWS having no default sits above the wrong check

One comment block above if (reported != null) covers eviction, the single read, and the AWS no-default rule. The AWS rule is carried by the later if (!storageBucket.isAws()) check, so a reader meets the explanation before the code it describes. Nothing in the comment is false.

For example: A reader who stops at if (reported != null) sees a note about AWS buckets having no default but no AWS check next to it.

// Only S3-compatible storage has a default; an AWS bucket without a reported region is asked again.
Evidence
server/src/main/java/io/unitycatalog/server/service/credential/aws/S3BucketRegions.java:~178-187:
```
      // The two caches evict apart: an AWS bucket has no default, so without the reported region
      // it is asked again rather than given the default of S3-compatible storage.
      // The region already read: a second read could miss an entry evicted in between.
      if (reported != null) {
        return Optional.of(reported.region());
      }
      if (!storageBucket.isAws()) {
        return Optional.of(DEFAULT_S3_COMPATIBLE_REGION);
      }
```
The first comment says what happens when there is no reported region (an AWS bucket is asked again), but it sits above the `reported != null` branch. The AWS rule is carried by the `!storageBucket.isAws()` check further down. The comment above `if (reported != null)` is about the region that was read, not about the AWS rule, so a reader of `reported != null` is pointed at the wrong branch.
How it was checked

Checked by 1 independent check: NITPICK

How about moving the AWS sentence down to the isAws() branch and keeping the "region already read" line where it is?

return awsFailed(storageBucket, cause, isTransient, /* reason= */ null);
}

private String awsFailed(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): awsFailed takes a flag and two nullable arguments

awsFailed(storageBucket, Throwable cause, boolean isTransient, String reason) allows combinations no caller uses. The message and error-code selection at :349-352 is a nested ternary that has to be re-read whenever a new failure reason is added.

Cost of keeping it: Today lookUp's two catch blocks pass an exception, and withoutRegion passes a null cause with a reason, so nothing reaches an unplanned state. A later caller could pass a combination that the ternary at :349-352 never planned for.

Split it into awsTransientFailure(bucket, cause) and awsNoRegion(bucket, cause, detail), both sharing the keep-the-reported-region-and-back-off path, so no caller passes a flag or a null.

Evidence
S3BucketRegions.java:324-331: `private String awsFailed(StorageBucket storageBucket, Throwable cause, boolean isTransient)` and `private String awsFailed(StorageBucket storageBucket, Throwable cause, boolean isTransient, String reason)`. Callers: line 276 `awsFailed(storageBucket, e, isTransient(e))`, line 298 `awsFailed(storageBucket, e, /* isTransient= */ true)`, line 381 `awsFailed(storageBucket, /* cause= */ null, /* isTransient= */ false, reason)`. Three inputs (nullable `cause`, a boolean and a nullable `reason`) choose between a kept region, INTERNAL and FAILED_PRECONDITION. Combinations the code can express but never uses: `isTransient=true` with `cause=null`, and `cause` set together with `reason`. The message selection at lines 349-352 (`cause != null ? cause.getMessage() : reason != null ? reason : "HeadBucket returned no region"`) is what handles them.
How it was checked

Checked by 1 independent check: NITPICK

Would two small methods read better here than one with a flag?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, two methods would read better. I will split it in the same follow-up as the storage-kind enum, since the no-region and failure rules belong on that enum.

@timothyw553 timothyw553 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM.

@yili-db
yili-db force-pushed the fix/shared_region_lookup branch from 234fdcc to 079b1d6 Compare December 2, 2026 07:11
@yili-db

yili-db commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@yili-db
yili-db requested a review from shba24 December 2, 2026 07:12
…atible storage

- `FileOperationsImpl` kept its own unbounded region map and HeadBucket discovery for AWS buckets, next to `S3BucketRegions` for S3-compatible storage
- `S3BucketRegions.getAwsRegion` serves AWS buckets with the same lookup:
  - a reported region is cached, at most 10,000 buckets, and asked again after an hour
  - a failed recheck keeps it
  - one lookup runs per bucket at a time
  - each request is capped at 10 seconds
- The fallback rules stay explicit: S3-compatible storage falls back to `us-east-1`; an AWS bucket without a known region fails with `FAILED_PRECONDITION` or `INTERNAL` as before, and is asked again on the next request
- `FileOperationsImpl` keeps only the configured `s3.region.N` and asks `S3BucketRegions` for the rest
- `S3BucketRegionsTest.testAwsBucketKeepsItsReportedRegionAndHasNoDefault` covers the AWS rules

Signed-off-by: Yi Li <[email protected]>
Co-authored-by: Isaac <[email protected]>
Signed-off-by: Yi Li <[email protected]>
@yili-db
yili-db force-pushed the fix/shared_region_lookup branch from 079b1d6 to a4b642b Compare December 2, 2026 17:32
@yili-db
yili-db merged commit 2afd054 into unitycatalog:main Dec 2, 2026
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.

3 participants