Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ changes go in their respective binding's NEXT_CHANGELOG.
### Fixed

- `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession.
- A CloudFetch download that cloud storage rejects with 401, 403 or 404 (an expired or invalid presigned URL) now refreshes the chunk's link before retrying, instead of retrying the same URL. The retry still counts against the download attempt budget.

---
*Note: When making changes, please add your change under the appropriate
Expand Down
234 changes: 234 additions & 0 deletions src/reader/cloudfetch/streaming_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1124,6 +1124,18 @@ impl StreamingCloudFetchProvider {
if attempts >= ctx.max_retries {
return Err(e);
}
// Storage refused the presigned URL itself (an expired or invalid
// signature; GCS answers 404 for an expired one), so retrying it
// cannot succeed. Mark the cached link expired: the next attempt
// then refreshes it through the usual expiry path.
if matches!(e.http_status, Some(401 | 403 | 404)) {
if let Some(mut entry) = ctx.chunks.get_mut(&chunk_index) {
if let Some(cached) = entry.link.as_mut().filter(|l| l.url == link.url)
{
cached.expiration = chrono::Utc::now();
}
}
}
// Stale-snapshot detection. Two ways a download
// can fail against a URL that became stale while
// the request was in flight:
Expand Down Expand Up @@ -1955,6 +1967,228 @@ mod tests {
);
}

#[tokio::test]
async fn rejected_presigned_url_is_refreshed_before_retry() {
for status in [401, 403, 404] {
assert_download_recovers(status, true).await;
}
// Other 4xx statuses keep the same-URL retry.
assert_download_recovers(400, false).await;
}

async fn assert_download_recovers(status: u16, expect_refresh: bool) {
use crate::client::retry::{build_retry_configs, RetryConfig};
use crate::client::{DatabricksHttpClient, HttpClientConfig};
use crate::types::sea::CompressionCodec;
use arrow_array::Int32Array;
use arrow_ipc::writer::StreamWriter;
use arrow_schema::{DataType, Field, Schema};
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
let batch = RecordBatch::try_new(
schema.clone(),
vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
)
.unwrap();
let mut ipc_bytes = Vec::new();
{
let mut writer = StreamWriter::try_new(&mut ipc_bytes, &schema).unwrap();
writer.write(&batch).unwrap();
writer.finish().unwrap();
}

// The original URL fails once; a refreshed URL is served by a second path.
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/chunk-0-old.arrow"))
.respond_with(ResponseTemplate::new(status))
.up_to_n_times(1)
.mount(&server)
.await;
for chunk_path in ["/chunk-0-old.arrow", "/chunk-0-new.arrow"] {
Mock::given(method("GET"))
.and(path(chunk_path))
.respond_with(ResponseTemplate::new(200).set_body_bytes(ipc_bytes.clone()))
.mount(&server)
.await;
}

#[derive(Debug)]
struct RefreshingFetcher {
fresh_url: String,
refresh_calls: AtomicUsize,
}

#[async_trait::async_trait]
impl ChunkLinkFetcher for RefreshingFetcher {
async fn fetch_links(&self, _: i64, _: i64) -> Result<ChunkLinkFetchResult> {
unreachable!()
}

async fn refetch_link(&self, _: i64, _: i64) -> Result<CloudFetchLink> {
unreachable!()
}

async fn refetch_links_from(&self, _: i64, _: i64) -> Result<Vec<CloudFetchLink>> {
self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst);
Ok(vec![CloudFetchLink {
url: self.fresh_url.clone(),
..create_test_link(0)
}])
}
}

let retry = RetryConfig {
max_retries: 0,
..RetryConfig::default()
};
let http_client = Arc::new(
DatabricksHttpClient::new(
HttpClientConfig::default(),
build_retry_configs(&retry, &HashMap::new()),
)
.unwrap(),
);
let fetcher = Arc::new(RefreshingFetcher {
fresh_url: format!("{}/chunk-0-new.arrow", server.uri()),
refresh_calls: AtomicUsize::new(0),
});
let chunks = Arc::new(DashMap::new());
let original = CloudFetchLink {
url: format!("{}/chunk-0-old.arrow", server.uri()),
..create_test_link(0)
};
chunks.insert(0, entry_with_state(original, ChunkState::Downloading));
let ctx = DownloadCtx {
downloader: Arc::new(ChunkDownloader::new(
http_client,
CompressionCodec::None,
0.1,
)),
link_fetcher: fetcher.clone(),
chunks,
refresh_coordinator: Arc::new(RefreshCoordinator::default()),
cancel_token: CancellationToken::new(),
statement_id: None,
metrics: Arc::new(CloudFetchMetrics::new(Some(1))),
max_retries: 3,
retry_delay: std::time::Duration::ZERO,
download_timeout: std::time::Duration::ZERO,
};

let batches = StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx)
.await
.unwrap_or_else(|e| panic!("HTTP {status}: one failed download must recover: {e}"));
assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 3);

let paths: Vec<String> = server
.received_requests()
.await
.unwrap()
.iter()
.map(|r| r.url.path().to_string())
.collect();
let (expected_paths, expected_refreshes) = if expect_refresh {
(vec!["/chunk-0-old.arrow", "/chunk-0-new.arrow"], 1)
} else {
(vec!["/chunk-0-old.arrow", "/chunk-0-old.arrow"], 0)
};
assert_eq!(paths, expected_paths, "HTTP {status}: downloaded URLs");
assert_eq!(
fetcher.refresh_calls.load(AtomicOrdering::SeqCst),
expected_refreshes,
"HTTP {status}: link refreshes",
);
}

#[tokio::test]
async fn refused_url_with_failing_refresh_surfaces_the_refresh_error() {
use crate::client::retry::{build_retry_configs, RetryConfig};
use crate::client::{DatabricksHttpClient, HttpClientConfig};
use crate::types::sea::CompressionCodec;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, ResponseTemplate};

// The refresh RPC retries transient errors itself, so an error it
// returns is final for this chunk: no further download of the refused URL.
let server = MockServer::start().await;
Mock::given(method("GET"))
.respond_with(ResponseTemplate::new(403))
.mount(&server)
.await;

#[derive(Debug)]
struct FailingFetcher {
refresh_calls: AtomicUsize,
}

#[async_trait::async_trait]
impl ChunkLinkFetcher for FailingFetcher {
async fn fetch_links(&self, _: i64, _: i64) -> Result<ChunkLinkFetchResult> {
unreachable!()
}

async fn refetch_link(&self, _: i64, _: i64) -> Result<CloudFetchLink> {
unreachable!()
}

async fn refetch_links_from(&self, _: i64, _: i64) -> Result<Vec<CloudFetchLink>> {
self.refresh_calls.fetch_add(1, AtomicOrdering::SeqCst);
Err(Error::unavailable().message("refresh RPC down"))
}
}

let retry = RetryConfig {
max_retries: 0,
..RetryConfig::default()
};
let http_client = Arc::new(
DatabricksHttpClient::new(
HttpClientConfig::default(),
build_retry_configs(&retry, &HashMap::new()),
)
.unwrap(),
);
let fetcher = Arc::new(FailingFetcher {
refresh_calls: AtomicUsize::new(0),
});
let chunks = Arc::new(DashMap::new());
let original = CloudFetchLink {
url: format!("{}/chunk-0.arrow", server.uri()),
..create_test_link(0)
};
chunks.insert(0, entry_with_state(original, ChunkState::Downloading));
let ctx = DownloadCtx {
downloader: Arc::new(ChunkDownloader::new(
http_client,
CompressionCodec::None,
0.1,
)),
link_fetcher: fetcher.clone(),
chunks,
refresh_coordinator: Arc::new(RefreshCoordinator::default()),
cancel_token: CancellationToken::new(),
statement_id: None,
metrics: Arc::new(CloudFetchMetrics::new(Some(1))),
max_retries: 3,
retry_delay: std::time::Duration::ZERO,
download_timeout: std::time::Duration::ZERO,
};

let error = StreamingCloudFetchProvider::download_chunk_with_retry(0, &ctx)
.await
.expect_err("a refused URL whose refresh fails must fail");
assert_eq!(error.message, "Link refresh RPC failed for chunk 0");
let cause = error.cause.expect("the refresh error is the cause");
assert_eq!(cause.message, "refresh RPC down");
assert_eq!(fetcher.refresh_calls.load(AtomicOrdering::SeqCst), 1);
assert_eq!(server.received_requests().await.unwrap().len(), 1);
}

// ─── End-to-end download deadline (issue #321 / audit H05) ───────────
//
// These tests exercise `download_chunk_with_retry`'s absolute
Expand Down
Loading