Skip to content

Bound the response wait of the GCP OAuth token request instead of inheriting the caller's request timeout - #115531

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-gcp-oauth-credential-timeout
Aug 21, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-gcp-oauth-credential-timeout

Conversation

@groeneai

@groeneai groeneai commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fixed a hang of up to one hour in BACKUP/RESTORE ... TO S3, GCS disks and the s3 table function when the named collection sets http_client = 'gcp_oauth' and the Google OAuth2 token endpoint accepts the connection but never answers. The bearer token request no longer inherits the caller's data transfer request timeout; its response wait is bounded at 10 seconds, matching the STS AssumeRole request cap.

Description

Found in CI: BACKUP TABLE ... TO S3(<collection with http_client = 'gcp_oauth'>) sat for 695 s with read_rows: 0 until the test budget expired and the job reported Some queries hung. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107108&sha=7b0f0efd7803a3f3a603fe10adf92811bf16f468&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DBReplicated%2C%20WasmEdge%2C%20parallel%2C%203%2F3%29

BackupIO_S3.cpp sets requestTimeoutMs = 60 * 60 * 1000 because backup data transfers can legitimately take that long. That single value becomes both the send and the receive socket timeout, and PocoHTTPClientGCPOAuth reuses the same timeouts member for its bearer token round trip, so a credential request that should take milliseconds parked in the TLS header read for an hour (SecureSocketImpl::mustRetry under HTTPHeaderStreamBuf::readFromDevice). The S3 endpoint in the failing case is plain HTTP on localhost, so the TLS peer can only be the hardcoded Google token URL.

This bounds the response wait of that round trip at 10 seconds, independently of the data transfer timeouts, at both mint sites (explicit ADC triple, and the metadata service branch). The connect timeout is left as the caller set it: metadata_service is a user-configurable host, so its connect budget belongs to the deployment that configured it, and connect was never the unbounded phase (BackupIO_S3 already bounds it at 10 s). Data plane requests keep the full hour, and an already tighter timeout is kept. The 10 s matches the STS AssumeRole request cap, so it is named once in S3Defines.h.

Validated against a mock that accepts and never answers: the value passed before was still blocked after 40 s, the value passed now fails in 10.0 s. Exactly one request arrived in each arm, so backup_restore_s3_retry_attempts (default 1000) does not multiply the mint.

Not bounded here: session creation is retried up to 5 times, each attempt carrying the caller's connect budget, and the mint is not cancellation aware within the 10 s.


Workflow [PR]
Sync PR [sync-upstream/pr/115531]

Version info

  • Merged into: 26.8.1.1803 (included in 26.8 and later)

…request timeout

BackupIO_S3 sets requestTimeoutMs to one hour because backup data transfers can
legitimately take that long. getTimeoutsFromConfiguration turns that single value
into both the send and the receive socket timeout, and PocoHTTPClientGCPOAuth
reused that same `timeouts` member for its bearer token round trip. A credential
request that should take milliseconds therefore got a one hour socket receive
timeout and parked in the TLS response header read, observed in CI as a 695 s
BACKUP with read_rows 0 and a `Some queries hung` job failure.

The one hour value predates gcp_oauth by years (1365105, 2022-10-12), so
nobody chose it for a token mint; the mint inherited it.

Bound the credential round trip independently of the data transfer timeouts, at
both mint sites: the explicit ADC triple and the metadata service branch. This
restores an invariant the sibling credential paths in the same provider chain
already hold explicitly, STS AssumeRole at 1 s connect / 10 s request and EC2
IMDS at 50 ms / 1 s; GCP OAuth was the only member without a bound. The cap
value and the non-positive handling are taken from the STS precedent, so the
10 s is named once in S3Defines.h and the two STS literals now use it, leaving
fewer unnamed constants than before. A timeout already tighter than the cap is
kept rather than raised, and data plane requests keep the full hour.

Non-positive must map to the cap rather than being left alone: zero means "no
limit" to both ConnectionTimeouts::saturate and Poco's socket layer, so a
saturate-based clamp would leave a user who set s3_request_timeout_ms = 0 worse
off than the bug. Verified: a raw zero receive timeout still blocks past 25 s,
while the clamped value fails at 10.0 s.

BackupReaderS3 and BackupWriterS3 share one makeS3Client, so RESTORE is covered
with BACKUP, as are GCS disks and the s3 table function.

Validated against a mock that accepts the request and never responds: the value
the call site passed before was still blocked after 40 s, the value it passes now
fails at 10.0 s with a timeout. The mock received exactly one request in both
arms, so backup_restore_s3_retry_attempts (default 1000) does not multiply the
mint, matching S3HeadObject 1 in the reported 695 s dump.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (1 finding, adjudicated)

An independent model reviewed this diff cold against the PR description. One finding, plus three
raised by my own review. All four are recorded below with verdicts.

⚠️ test-liveness (major, DISAGREE on where the fix lands, defect conceded) -
src/IO/S3/tests/gtest_aws_s3_client.cpp

The claim is correct and I concede it: both shipped gtest arms call
getCredentialAcquisitionTimeouts directly, so restoring the raw timeouts argument at the two
call sites leaves every assertion green. I reached the same conclusion in my own review before the
second model ran. I am not adding the suggested mock-driven test, for reasons I measured rather
than argued:

  • The ADC branch cannot be redirected to a mock. fetchGCPOAuthToken is called with 5 arguments,
    so it uses its hardcoded default token_endpoint, and the client configuration carries no
    token-URL field. Adding production config purely to enable a test is not a trade I want to make.
  • The metadata branch cannot be mocked in-process. It hardcodes scheme http and supplies only a
    host, so Poco resolves the port to the well-known 80; binding port 80 as a non-root test process
    fails with EACCES. Putting host:port in the host field is stored verbatim and then fails DNS
    resolution.
  • An integration test against test_storage_gcp_auth (which does run a mock on port 80) is
    constructible, but its only available oracle is elapsed time - there is no ProfileEvent and no
    failpoint anywhere on this path to assert on instead. Timing oracles on this path are routinely
    removed as flaky, so that test would not survive.

What exists instead is a both-directions measurement at the real seam: with the value the call site
passed before, the request was still blocked after 40 s; with the value it passes now it throws
Timeout at 10.01 s. The mock received exactly one request in each arm. The two invariants that
could silently regress in a later refactor are both covered by the shipped arms: that a
non-positive timeout takes the cap (a saturate-based rewrite would return 0, i.e. unbounded), and
that the data plane keeps its full hour.

So the residual is real and it is future-regression protection, not missing evidence.

💡 Three nits from my own review, all DISAGREE, no change:

  • The 1 s connect cap overrides the backup path's deliberate 10 s. The already-merged STS clamp
    applies the same 1 s cap to the same value from the same caller, so this makes GCP OAuth
    consistent with shipped behaviour rather than inventing a bound. A slow connect is retried 5
    times, so the worst case is a few seconds, not a failure.
  • "Bounded at 10 seconds" describes the header read that hung. Including the 5 session-creation
    retries the ADC worst case is nearer 15 s - immaterial against 3600 s.
  • Renaming the two STS literals to the shared constant is slightly beyond the hang. It is
    bit-identical in behaviour and nets out fewer unnamed constants; happy to drop it to a file-local
    constant if you would rather this PR did not touch Credentials.cpp.

Session id: cron:clickhouse-review-slot-11:20260819-223600

@clickhouse-gh clickhouse-gh Bot closed this Aug 20, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3afa3ef]

Summary: ✅


AI Review

Summary

This PR decouples the GCP OAuth token-mint timeout from the S3 data-plane request timeout by capping send/receive waits at 10 seconds while preserving the caller's connect timeout, and it adds focused coverage for the timeout helper plus the unchanged data-plane budget. I did not find any remaining correctness, contract, or metadata issues in the current code.

Final Verdict

✅ No findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.90% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 78/78 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A local mock that accepts the request and never responds, driven through fetchGCPOAuthToken with the exact timeouts BackupIO_S3.cpp produces (connect 10 s, send/receive 3600 s). Blocks on every run, no randomness. The CI instance itself needs a blackholed route to Google and is deliberately not recreated.
b Root cause explained? Yes. BackupIO_S3.cpp sets requestTimeoutMs = 60 * 60 * 1000 for long data transfers; getTimeoutsFromConfiguration turns that one value into both the send and the receive socket timeout; PocoHTTPClientGCPOAuth reuses that same timeouts member for its bearer token round trip, so the token request inherits a one hour socket receive timeout and parks in the TLS header read.
c Fix matches root cause? Yes. The conflation of the two concerns is fixed where it happens: the credential round trip now derives its own bounded timeouts. The hour is left correct for data transfers, so this is not a threshold tweak or a guard at the symptom.
d Test intent preserved / new tests added? Yes. No existing test weakened; 04325_s3_user_credentials_hardening.sh is unchanged and its backup_gcp_adc assertion still reports pass. Two tests added to the existing gtest_aws_s3_client.cpp (no new gtest module): a table-driven clamp assertion and a data plane non-regression assertion. No wall-clock oracle in either.
e Both directions demonstrated? Yes, against the mock: the value the call site passed before this change was still blocked after 40 s; the value it passes now fails at 10.0 s with a timeout. Both runs on Build-ID-verified binaries (base 5c87c18b..., fixed 29692915...).
f Fix is general across code paths? Yes. Both mint sites are fixed, the ADC triple branch and the metadata service branch, so the bug is not left reachable through a server-configured metadata_service. All seven carriers were enumerated: STS and IMDS were already bounded (touched only to name the shared constant), BigLake and BigQuery derive from getHTTPTimeouts and never see the hour (verified by reading both call sites), and Client::getGCSOAuthToken is fixed transitively. BackupReaderS3 and BackupWriterS3 share one client factory, so RESTORE is covered with BACKUP.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. No columns or type wrappers are involved; the input axis here is the timeout value, covered as a matrix: one hour is lowered to the cap, zero (unbounded downstream) takes the cap, a value tighter than the cap is kept rather than raised, and a value exactly at the cap is kept. The zero case was additionally verified end to end: a raw zero receive timeout blocks, and the clamped one fails at 10.0 s.
h Backward compatible? Yes. No setting default changes, so no SettingsChangesHistory.cpp row; no new setting, no format or serialization change. The behaviour being replaced on this path is a hang. Data plane timeouts are unchanged, so large backups are unaffected.
i Invariants and contracts preserved? Yes. The helper is a pure function of its argument, allocates nothing and cannot throw, so no error or early-return path changes. It is called outside the bearer-token mutex critical section boundary already established by the callers, so no lock ordering changes. The failure surfaces the same way it would have after an hour, a Poco::TimeoutException converted by PocoHTTPClient::MakeRequest, and was verified not to be swallowed into a retry loop: the mock received exactly one request.

Session id: cron:clickhouse-impl-slot-40:20260819-201100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Michicosun @alesapin, could you review this? PocoHTTPClientGCPOAuth reused the data-transfer timeouts member for its bearer token round trip, so a token mint under BACKUP ... TO S3 inherited the one hour request timeout that BackupIO_S3 sets for large transfers and parked in the TLS header read for 695 s in CI. This bounds the credential round trip at both mint sites, the way STS AssumeRole and EC2 IMDS already are.

clang-tidy's google-runtime-int rejects the bare `long` in the two
`static_cast`s (Build (arm_tidy), src/IO/S3/Credentials.cpp:1274-1275). The
casts exist because Aws::Client::ClientConfiguration declares
connectTimeoutMs and requestTimeoutMs as bare `long`, so the caps have to
match that field type rather than a fixed-width spelling of our own choosing.

Deriving the type with decltype from the field being assigned keeps the type
identical, is immune to the check, and matches the max_retries cast two lines
above that already uses this form.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/IO/S3/PocoHTTPClient.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3afa3eff2 with master 90a20ccf8 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 703.89 MiB 700.85 MiB -3.04 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

71 translation units recompiled, 747 s compile time in total, 71 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.18 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +112.2 s (+18%) in total before that adjustment.

Job report

The first version of this change also lowered the credential connect timeout to
DEFAULT_CONNECT_TIMEOUT_MS. That was unrequested scope and it narrowed a supported contract.

`metadata_service` is a user-configurable host (S3AuthSettings.cpp:43), so the connect budget for
reaching it belongs to the deployment that configured it, and the metadata branch of
requestBearerToken has no retry loop, which makes a single premature connect failure terminal
there. The STS clamp is not a precedent for it either: every production caller passes an empty
sts_endpoint_override, so that path only ever dials AWS's own regional endpoint, and it pairs its
1 s connect cap with a bounded retry strategy.

Connect was never the unbounded phase. BackupIO_S3 already bounds it at 10 s, and the reported
695 s stall was entirely in the response wait, which Poco leaves at max(receive, send) through
SecureSocketImpl::getMaxTimeoutOrLimit. Capping the response wait alone fixes the hang.

The connect_cases arm of the gtest now pins the pass-through instead of the cap; reintroducing the
clamp locally fails it, along with the data-plane arm.
@groeneai groeneai changed the title Bound the GCP OAuth token request instead of inheriting the caller's request timeout Bound the response wait of the GCP OAuth token request instead of inheriting the caller's request timeout Aug 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3afa3ef

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR

CI finished clean on this head, so no row needs an owner: 147 checks succeeded, 24 were
skipped, and none failed. Config Workflow, Style check and Finish Workflow all
succeeded. I corroborated the green against the CI database at this commit: 298354 rows
over 149 checks, 263789 OK and 0 FAIL/ERROR, so the zero is measured rather than
missing ingestion.

Session id: cron:our-pr-ci-monitor:20260820-113000

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is good.

@alexey-milovidov alexey-milovidov self-assigned this Aug 21, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit d39369a Aug 21, 2026
177 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants