Repository navigation
perf(auth): share M2M discovery and tokens across live sessions - #455
vuanhphung wants to merge 18 commits into
Conversation
Each Session builds its own ClientCredentialsProvider, so N sessions opening at once run N OIDC discoveries and N token exchanges; at a few hundred concurrent opens the IdP answers 429 and the retry backoff stalls the opens for seconds. Providers with the same host, client id, secret and scopes now share one discovery result and one TokenStore through a process-wide registry. The registry keys on a SHA-256 of the secret and drops an entry with its last provider, so neither the token nor the key outlives the sessions using them. Callers that waited on a failed refresh now get that refresh's error. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Low
The sharing looks sound, with one low-severity concern. The weak-registry lifecycle avoids races with drop and nothing is dropped while the registry lock is held. The secret is hashed in the key, and each refresh runs on the calling provider's own HTTP client and runtime. The one gap: the new 'waiters get the refresh's error' behavior only applies when the store is empty, not when the token has expired. Nit: scopes go into the key in the order given, so [a, b] and [b, a] won't share. Sorting them would fix that, but it's harmless.
A failed blocking refresh of an expired token handed waiters the expired token while the caller that ran the refresh got the error. Return the error to waiters too, and key shared credentials on sorted scopes. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Medium · 1 Low
The registry, weak-entry cleanup and secret hashing look correct and are well tested. One medium concern: when the shared OIDC discovery fails, concurrent opens retry it one after another instead of failing together. There is also a low edge case where a waiter whose blocking refresh lost the race to a failed background refresh can get an expired token or a stale error.
There was a problem hiding this comment.
Verdict: 1 High
Solid design overall, with one high-severity lifecycle concern: because the TokenStore is now shared, a background refresh whose closure is dropped when its session's runtime shuts down leaves refreshing stuck at true. Every other session on that entry then hangs. The registry, the weak-entry cleanup, the transport fingerprint and the shared discovery with a retry after cancellation all look correct.
A shared store outlives the session whose runtime runs its background refresh. Tokio drops a blocking closure unrun when that runtime is shutting down, and the guard was created inside the closure, so 'refreshing' stayed set and every later blocking caller spun forever. The guard now exists before the spawn, and an unfinished refresh is recorded as a failed background one, so waiters refresh themselves. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 2 Low
The sharing design looks sound: the registry key is complete, the weak entries clean up correctly, and the transport fingerprint is deterministic (custom_headers is a Vec). I found 2 low-severity issues: the retry after a failed background refresh triggers on any error, not only on cancellation, and one test doesn't reach the failed-discovery replacement branch it claims to cover.
| // Another thread is already refreshing: wait for it to complete | ||
| self.wait_for_refresh() | ||
| let (result, background_failure) = self.wait_for_refresh(); | ||
| if result.is_err() && background_failure && retry { |
There was a problem hiding this comment.
🔵 Low — A blocking waiter retries after any failed background refresh, not only one that was cut short. Right now background_failure is true for every error recorded by BackgroundRefresh::finish(Some(e)), a real HTTP 429 included. Discovery works differently: SharedCredentials::endpoints retries only on ErrorCode::Cancelled.
Here is how it plays out under load:
- A stale-token background refresh hits a 429 after it has already used up the auth retry ladder.
- The token then expires.
- A blocking caller that was waiting on that refresh starts a second full ladder right away instead of getting the 429.
- If many sessions share the store, one of them wins that second refresh and the rest wait on it. So the expired-token path costs one extra rate-limited request and roughly twice the latency.
The PR description also says waiters on a failed background refresh get that refresh's error, which the code doesn't do. Two possible fixes: only retry when the recorded error came from the Drop path (it is Error::cancelled(), so it can be told apart), or have the refresh closure tag "runtime gone" failures explicitly. If retrying on everything is intended, please update the description and add a comment explaining the trade-off.
There was a problem hiding this comment.
Fixed in a1676bd. A waiter now retries only when the background refresh failed without an answer from the server: Cancelled (dropped unrun or panicked), NetworkError or Timeout, with no HTTP status (cut_short in token_store.rs). Those are the failures a closing runtime produces. A 429, a 401 or a 5xx after the retry ladder carries its status and reaches waiters as is, so there's no second ladder. New test test_store_waiters_get_the_servers_answer_to_a_background_refresh fails if the retry fires on any background failure. The description now says this.
There was a problem hiding this comment.
Thanks, that approach (retry only on Cancelled, NetworkError or Timeout with no HTTP status) would fix the problem. But I can't find it in the checked-out head. Line 274 still retries on background_failure, and there's no cut_short helper or test_store_waiters_get_the_servers_answer_to_a_background_refresh anywhere in the repo, so a1676bd may not have been pushed to this branch yet. Once it's pushed, the follow-up will run again on the new code.
| assert_eq!(discovery.received_requests().await.len(), 1); | ||
|
|
||
| assert!( | ||
| ClientCredentialsProvider::new(&uri, "client", "secret", client()) |
There was a problem hiding this comment.
🔵 Low — This assertion ("a failed discovery is retried by the next open") doesn't test the code path it describes. By the time the 9th open runs, all 8 failed providers have already dropped their Arc<SharedCredentials>. Drop has therefore removed the registry entry, and the 9th open just builds a fresh entry with an empty discovery slot.
The matches!(discovery.peek(), Some(Err(_))) branch in SharedCredentials::discovery, which replaces a failed in-entry attempt, never runs in any test. To cover it, keep an Arc to the entry alive across the failure, the way discovery_outlives_the_runtime_that_started_it holds shared. Then a second endpoints() call has to go through the peek-Err branch, and you can assert that it issues a new request.
There was a problem hiding this comment.
Fixed in a1676bd. The test now holds a SharedCredentials entry across a failed attempt and calls endpoints() twice on it. The second call has to go through the peek() is Err branch and send a new request (count 2 -> 3). With that branch replaced by if true, the test fails at 2.
There was a problem hiding this comment.
I looked at the head, and it doesn't seem to include the change from a1676bd. concurrent_opens_share_a_failed_discovery (lines 1154–1206) still ends with the same 9th ClientCredentialsProvider::new open, asserting a request count of 2 with the "a failed discovery is retried by the next open" message. The next test is discovery_outlives_the_runtime_that_started_it at line 1208, which is unchanged. The only shared.endpoints() calls on a held entry are in that test, at lines 1258 and 1264. I couldn't find a test that holds a SharedCredentials across a failed attempt and checks the count going from 2 to 3. Could you check that a1676bd was pushed to this branch? Once it's in the head, the peek-Err branch at line 82 will have test coverage.
…er answered A waiter retried after any failed background refresh, so a 429 that had already used up the auth retry ladder ran a second ladder. It now retries only for failures a closing runtime causes (cancelled, transport error or timeout, no HTTP status) and otherwise gets the server's answer. The failed-discovery test now holds the entry, so it reaches the branch that replaces a failed attempt. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Low
Looks good, with one low-severity note on test robustness. I checked the registry lifecycle (Weak entries, the Drop race when an entry is replaced under the same key), the transport fingerprint (it covers every TLS, proxy, timeout, header and auth-retry field), lock ordering in TokenStore, and the BackgroundRefresh drop ordering; all are sound.
The runtime-shutdown test slept 200 ms and assumed the first open had stored its attempt by then; on a slow runner it could pass without reaching the cancelled-retry path. It now waits until the slot holds an unresolved attempt and fails if that never happens. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Low
Looks good — one low-severity maintainability note on the transport fingerprint. I checked the registry lifecycle (no deadlock or race in Drop), the shared discovery across runtimes, and the order in which last_error and the token are written in TokenStore, and found no correctness issues. The tests cover sharing, isolation, failed discovery shared between concurrent opens, and runtime shutdown during discovery and background refresh.
…ingerprint The fingerprint read each config field by name, so a new TLS, proxy or retry field would compile and be left out, letting sessions with different transports share auth results. Destructuring every struct makes a new field a build error until it is either hashed or named as ignored. A test checks that proxy, header and auth-retry changes alter the fingerprint and the idle pool size doesn't. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 2 Low
Looks good overall. The registry lifecycle (weak entries, removal on drop, the replace race), the discovery sharing that only shares results, and the BackgroundRefresh drop guard ordering all check out. I found two low-severity edge cases: blocking refreshes don't get the cut-short retry that background ones do, and the cert-path fingerprint hashes the path rather than the file contents.
With the store shared, a blocking refresh can also fail only because the session running it closed. A waiter now refreshes once itself whenever the refresh it waited on got no answer from the server, blocking or background, so the background flag on the stored error is gone. The fingerprint docs note that a CA path is hashed by path. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 2 Low
Looks good overall, with two low-severity concerns, both about how waiters handle a refresh that failed or finished just before they reached it. The registry lifecycle, the drop race, cross-runtime discovery and the transport fingerprint look correct, and the tests cover them well.
…imeouts A caller that saw the token expired and won the CAS after another refresh had finished sent a second token request for every session sharing the store. It now returns the token already there if it isn't expired. Waiters no longer retry a refresh that timed out: a closing runtime doesn't produce Timeout, and a hung endpoint would rerun the longest ladder. Network errors are still retried once, documented as bounded. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Low
Looks good overall, with one low-severity inconsistency in how a failed refresh is handled. The registry lifetime (weak entries, replace-safe Drop), sharing discovery as a spawned task, and the cut-short retry ladder all look sound, and the tests cover them well. Nit: the transport fingerprint hashes custom_headers in order, so the same headers given in a different order won't share. That only reduces sharing and never mixes transports.
…ilure Waiters on a failed refresh already kept a cached token the server still accepts (inside the 40 s expiry buffer); the caller that ran the refresh returned the error. With the store shared, that put the failure on whichever session won the race. It now gets the same fallback, and the error is still recorded for waiters. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Low
Looks good. The sharing design is careful and well tested: weak registry entries with drop-time cleanup that is safe against races, discovery spawned per runtime with a single retry if it is cancelled, and refresh errors passed through to waiters. There is one low-severity concern about timing-dependent sleeps in the new token-store waiter tests, which could fail intermittently on CI.
The waiter tests slept 20 ms and assumed the spawned caller had reached wait_for_refresh; on a loaded runner it could take the refresh path itself and break the assertions. A test-only count of callers in wait_for_refresh lets the tests wait for the waiter instead. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Low · 1 Nit
Looks solid. The registry lifecycle (weak entries, the race in Drop), the transport fingerprint and the waiter error handling all hold up, and the tests cover them well. Two low-severity edge cases: a discovery task on a runtime that stays alive but is never driven again can hang later opens, and the refresher drops its refresh error without logging it.
Other findings
- ⚪ Nit — The shared discovery runs as a
tokio::spawntask on the runtime of whichever opener created it, and every other opener awaits that task'sJoinHandlethrough theShared. The PR handles the case where that runtime shuts down (you getCancelled, then one retry). It doesn't handle a runtime that stays alive but stops being driven. Example: a direct Rust caller on acurrent_threadruntime starts an open, then drops it (atimeout/select!loses) and stops callingblock_on. The task is parked, itsJoinHandlenever resolves,peek()staysNone, and every later open with the same key joins it and hangs. The HTTP timeouts can't help, because the task itself never gets polled. Multi-thread runtimes (pyo3, c_abi, adbc) aren't affected, so this is an edge case. Two possible fixes: put a timeout on the joiner side (e.g. the auth retryoverall_timeout) that treats a slow join asCancelled, or note in the doc comment that runtimes must be multi-thread.
The refreshing caller keeps a still-valid token after a failed refresh, and the error went only into the store. With one store serving many sessions, a token-endpoint 429 storm in the expiry window was then invisible; it is now logged as a warning. The discovery docs note that the starter's runtime must keep running tasks. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Medium · 2 Low
The registry and sharing design looks sound: the key is hashed, entries are weak and remove themselves, and discovery runs as a task on the starting session's runtime. The main gap is on the blocking-refresh path: if the refresh panics, which is likely when the refreshing session's runtime shuts down, last_error is not updated, so other sessions waiting on it can be handed an expired token as Ok.
A blocking refresh recorded its error only after refresh_fn returned, so a refresh_fn that panicked (its session's runtime shutting down mid-request) left last_error unchanged and waiters could get the expired token as Ok. Each claim of the refresh flag now records its own outcome: a cancelled "did not finish" before refresh_fn runs, replaced by the real result, and None when the claim reuses a token another caller just stored. Discovery outside a tokio runtime is now an error instead of a panic. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Medium · 1 Nit
The sharing design looks solid, with one medium concern: waiters on a shared refresh sleep-spin on tokio worker threads, which can stall the refresh. Separately, a low-severity race can hand waiters a placeholder error instead of the real one. The registry lifecycle, key and fingerprint construction, and discovery sharing look correct and are well tested.
Other findings
- ⚪ Nit —
last_erroris shared across claims, andwait_for_refreshreads it afterrefreshingdrops to false. Here is the race:
- Refresh A fails while the token is expired.
- Before a waiter reads
last_error, another caller wins the CAS and writes the placeholderCancelled("token refresh did not finish")at this line. - The waiter reads the placeholder, not A's real error (e.g. the 429).
cut_shorttreats it as a refresh that got no answer.
On the first wait this only costs an extra wait. On the retry pass (retry == false), the same race returns the placeholder Cancelled error to the user instead of the server's answer. That undercuts the PR's goal of surfacing the real refresh error to waiters.
The chance is small but grows with the number of sessions sharing a store during a 429 storm. One fix is a generation counter, so a waiter reads the outcome of the claim it actually waited on.
With one store per set of credentials, every session waiting on a refresh slept in place on a tokio worker thread. On a runtime shared by sessions the waiters could take every worker, and the refresh's own request, which needs a worker to drive its I/O and timers, never finished. Waiters on a multi-thread runtime now wait inside block_in_place; a test with eight callers on two workers hangs without it. A claimed blocking refresh now writes its outcome once, when it finishes (or Cancelled if refresh_fn panics), through the same guard as a background refresh, so a late waiter can't read another claim's placeholder. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
There was a problem hiding this comment.
Verdict: 1 Nit
Looks good. I found no correctness, lifecycle or error-handling problems in the shared-credentials registry, the discovery shared via Shared futures, or the ClaimedRefresh changes to TokenStore, and the tests cover the tricky paths (a runtime shutting down mid-discovery, a refresher that panics, a background task dropped unrun, CAS reuse of a stored token). One nit: the PR description is inconsistent about whether block_in_place was added.
Other findings
- ⚪ Nit — The PR description contradicts itself. One paragraph says "this adds no
block_in_place(waiters still wait the way they did)". Another says "waiters on a multi-thread runtime now wait insideblock_in_place", andtoken_store.rswait_for_refreshdoes add that call, guarded byruntime_flavor(). The flavor guard follows the same pattern asutil/runtime.rs, so the code looks fine. The description should be fixed so reviewers comparing this to #398 aren't misled.
Each
Sessionbuilds its ownClientCredentialsProvider, so N OAuth M2M sessions opening at once run N OIDC discoveries and N client-credentials token exchanges for the same service principal. A benchmark of 800 concurrent connections with M2M (RE-17633) hit HTTP 429 from the token endpoint, and the auth retry ladder (≥2 s, then ~4.5 s, then ~9 s) stretched connection setup to many seconds. Some opens failed outright once the retries ran out.Providers with the same host, client id, client secret, scopes, token-endpoint override and HTTP transport now share one discovery result and one
TokenStorethrough a process-wide registry. Transport means a fingerprint of the HTTP client's TLS options (custom CA, mTLS cert/key), proxy, timeouts, headers and auth retry policy, so a result fetched through one transport never stands in for another. A refresh still runs through the calling provider's own HTTP client and runtime, and the token lifecycle (fresh / stale background refresh / expired blocking refresh) is unchanged. The registry key holds a SHA-256 of the secret, never the secret. Entries are weak and remove themselves when their last provider drops, so neither the token nor the key outlives the sessions that use it, and a new session after that fetches a new token, as today. Azure service-principal data tokens share the same way, through the token-endpoint override; the Azure management token is still fetched per session, and the JWT and U2M providers are unchanged. Discovery runs as a task on the runtime of the session that starts it, and only its result is shared, because in the Python binding every session owns its own runtime. If that runtime shuts down mid-discovery, joiners retry once instead of driving a request bound to a dead runtime. Failures are shared the same way as successes. Opens that join one discovery all get its result, error included, and the next new open retries a failed attempt. Callers that waited on a failed refresh, blocking or background, keep the cached token while the server still accepts it. Once it is past expiry (or there is none), they get that refresh's error (e.g. the 429) instead of "no token available after refresh" or a dead token. This matters more once one refresh serves many sessions. For the same reason, waiters on a multi-thread runtime now wait insideblock_in_place, so sessions sharing one runtime can't take every worker while the refresh's own request needs one. A refresh, blocking or background, runs on the runtime of the session that started it, and that session may close first. If the refresh fails without an answer from the server (tokio dropped it unrun, its function panicked, or a transport error), a caller that waited on it refreshes once itself; a server's answer, such as a 429 after the retry ladder, and a timeout reach waiters as is. A real network outage therefore surfaces after one extra retry ladder, never more. A caller that wins the refresh after another caller has just stored a token uses that token instead of requesting another.#398 tried the same sharing earlier and was closed. Its review flagged a
block_in_placepanic path on current-thread runtimes and a lost OAutherror_description. Neither applies here. The oneblock_in_placethis adds, for waiters on a shared refresh, runs only whenruntime_flavor()reports a multi-thread runtime, as inutil/runtime.rs, so it can't reach #398's current-thread panic. It also doesn't touch how token errors are built. Waiters receive a clone of the refreshing caller's full error.Verified against a local mock OIDC + SEA server (pecotesting, the live warehouse used for the other numbers, uses a PAT). The mock adds 25 ms to every request and answers every second token request with 429. 200 threads connect at once through the Python connector (
use_kernel=True,main+ databricks/databricks-sql-python#1024), with kernelmainbuilt from source with and without this change, 3 interleaved runs each:mainIn the 2.94 s run, the one shared token request drew the mock's 429, so every session waited out a single backoff.
With a PAT nothing changes: PAT sessions have no token store, and an isolated 4 × 200 live run with a PAT showed no difference. The gain is for OAuth M2M (and Azure SP) sessions opened concurrently in one process, where each one otherwise runs its own discovery and token exchange and a rate-limiting IdP answers part of them with 429s.
New tests: providers with the same credentials share one discovery and one token, and the registry entry and token are gone once the last provider drops. Different secret, client id, scopes, host or transport never share (scope order doesn't matter). Concurrent opens share one failed discovery, and a discovery started on a runtime that shuts down still lets the sessions that joined it open. Providers on the token-endpoint override path (Azure SP) share one token. Waiters on a failed refresh keep a token that is still valid but inside the expiry buffer; with an empty store, an expired token or a background refresh in flight, they get that refresh's error. A background refresh that tokio drops unrun still clears the refresh flag and its waiters refresh themselves; a waiter on a blocking or background refresh that got no answer refreshes once itself, and a 429 reaches waiters without a second refresh; a failed discovery held by a live entry is replaced on the next call. The existing M2M and token-store tests (refresh, expiry, stale background refresh, 429/5xx retries) pass unchanged.
cargo test,cargo clippy --all-targets -- -D warningsandcargo fmt --checkpass.Live benchmark (staging Large Reyden warehouse)
Not exercised by the live C800 benchmark on the staging Large Real-Time warehouse: that harness authenticates with a user OAuth token, so no OAuth M2M token exchange happens. The numbers above (mock OIDC server with throttling) are the evidence for this change.
This pull request and its description were written by Isaac.