From 60519d42cec4ea7b4ec81208608c2ebb97a289db Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Thu, 26 Nov 2026 03:16:25 +0800 Subject: [PATCH] feat(remote): add presigned direct Blob V2 reads (#5210) ## What Add a capability-gated client path for large Blob V2 reads over LanceDB Enterprise: - A successful `describe` advertises `x-lancedb-blob-locations: 1`; the SDK then resolves pinned row locations through `POST /v1/table/{id}/blob_locations/`. - Whole reads (`fetch_blobs`) and seekable handles (`fetch_blob_files` / `open_blob_file`) read presigned object-store URLs directly for eligible values and ranges at or above a provisional internal 10 MiB threshold. - Small ranges and `fetch_blob_ranges` stay on the existing proxy path, including aggregate batches whose total exceeds the proxy byte limit. - Shared `Packed` / `Managed` sidecars translate logical ranges to physical offsets and validate the full numeric `Content-Range` tuple, not just its start or total. - Presigned traffic uses a separate HTTP client with no Enterprise default headers, so service credentials never reach object storage. - The first resolver response must carry a valid query-snapshot identity. That identity is then required on every later partition and preserved through object-URL refresh, proxy fallback and oversized whole-value recovery. A resolver `503` falls back once to the proxy path using any version and identity already pinned; other resolver errors propagate. Object-store `503`s do not masquerade as resolver unavailability. - A read that starts without the capability reuses its supplied `ReadSnapshot` if a later describe enables direct opening mid-operation. - Version and query-snapshot pinning, NULL/order alignment and empty values are preserved. ## Client network requirement On Enterprise clusters that enable direct Blob reads, large values and individual ranges may be fetched from short-lived object-store URLs instead of the LanceDB proxy. Clients then need network access to the object-store endpoint, including private endpoint routing, DNS, TLS trust and egress rules, in addition to the LanceDB endpoint. Small reads stay on the LanceDB proxy. ## Why Large Blob V2 reads currently stream every payload byte through `Object Store -> Plan Executor -> Query Node -> client`. That consumes internal bandwidth, inflates PE/QN memory use and pollutes executor caches with low-locality `.blob` data. This is the SDK half of ENT-4358; the server implementation is in Sophon. ## Compatibility No public SDK signatures change. Old clusters omit the capability header and keep the existing proxy behaviour with zero extra round trips. The 10 MiB threshold is an internal prototype choice pending the paired acceptance measurement; it is not a public knob. ## Validation - `cargo check -p lancedb --quiet --features remote --tests` passes. - `cargo test -p lancedb --quiet --features remote --lib remote::table::blobs::tests` passes: 65 tests. - New coverage includes direct whole reads, shared-sidecar physical offsets and Content-Range rejection, small-range proxy routing, mixed large/small range batches, resolver `503` fallback with pinned state, no second resolver after fallback, object-store `503` not triggering proxy fallback, missing/mismatched resolver identity rejection, resolver identity preservation through refresh/proxy/oversized recovery, supplied-snapshot reuse on mid-operation capability refresh, and NULL/order/null-preserving paths. A real-QN acceptance run with the candidate SDK binary is separate and still pending deployment of the candidate server image. --- python/python/lancedb/table.py | 15 + rust/lancedb/src/remote/client.rs | 68 +- rust/lancedb/src/remote/db.rs | 2 + rust/lancedb/src/remote/table.rs | 34 +- rust/lancedb/src/remote/table/blobs.rs | 3024 +++++++++++++++++++++++- rust/lancedb/src/table.rs | 23 +- 6 files changed, 3103 insertions(+), 63 deletions(-) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index cbd423d76..a34a36465 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2887,6 +2887,11 @@ class Table(ABC): ``table.take_offsets(offsets, with_row_id=True)`` first and pass the resulting ``_rowid`` values. + On Enterprise clusters that enable direct Blob reads, large values and + ranges may be fetched from short-lived object-store URLs. The client then + needs network access to the object-store endpoint, including private + endpoint routing, DNS, TLS trust and egress rules, in addition to the + LanceDB endpoint. Small reads stay on the LanceDB proxy. Blobs inside lists cannot be fetched by row id yet. LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob @@ -2921,6 +2926,11 @@ class Table(ABC): One missing or deleted row ID rejects the entire batch; no partial results are returned. + On Enterprise clusters that enable direct Blob reads, large values and + ranges may be fetched from short-lived object-store URLs. The client then + needs network access to the object-store endpoint, including private + endpoint routing, DNS, TLS trust and egress rules, in addition to the + LanceDB endpoint. Small reads stay on the LanceDB proxy. Row IDs can be obtained from a query with ``with_row_id(True)``. LanceDB Enterprise uses the batched endpoint when the server advertises support, partitioning at 1024 ranges and 64 MiB, including individual @@ -2949,6 +2959,11 @@ class Table(ABC): ``buffer_size`` controls sequential read-ahead in bytes (default 512 KiB). Set it to 0 for sparse reads. Explicit range reads bypass this buffer. + On Enterprise clusters that enable direct Blob reads, large values and + ranges may be fetched from short-lived object-store URLs. The client then + needs network access to the object-store endpoint, including private + endpoint routing, DNS, TLS trust and egress rules, in addition to the + LanceDB endpoint. Small reads stay on the LanceDB proxy. ``_rowid`` values stay valid after compaction when the table has stable row ids. One missing or deleted row ID rejects the entire batch; no partial diff --git a/rust/lancedb/src/remote/client.rs b/rust/lancedb/src/remote/client.rs index e253535c7..59d5b81de 100644 --- a/rust/lancedb/src/remote/client.rs +++ b/rust/lancedb/src/remote/client.rs @@ -17,6 +17,9 @@ use crate::utils::validate_database_name; const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-request-id"); const DEFAULT_BLOB_REQUEST_CONCURRENCY: usize = 8; +/// M1 prototype routing threshold for direct Blob reads. It stays internal +/// until the acceptance benchmark establishes the right default. +pub(crate) const DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES: u64 = 10 * 1024 * 1024; pub fn redact_sensitive_headers(headers: &mut HeaderMap) { const SENSITIVE_HEADERS: [&str; 5] = [ @@ -312,9 +315,16 @@ pub struct RetryConfig { #[derive(Clone)] pub struct RestfulLanceDbClient { client: reqwest::Client, + /// A separate client for presigned object-store traffic. It deliberately + /// carries none of the Enterprise default headers, so service credentials + /// never reach object storage. + object_store_client: reqwest::Client, host: String, pub(crate) retry_config: ResolvedRetryConfig, pub(crate) blob_request_semaphore: Arc, + /// Logical blob/range size at which a handle prefers a presigned direct + /// read over the existing proxy byte-range route. + pub(crate) blob_presign_threshold_bytes: u64, pub(crate) sender: S, pub(crate) header_provider: Option>, /// Connection-level read consistency interval. Drives the @@ -599,7 +609,7 @@ impl RestfulLanceDbClient { let client = client_builder .default_headers(default_headers) - .user_agent(client_config.user_agent) + .user_agent(client_config.user_agent.clone()) .build() .map_err(|err| Error::Other { message: "Failed to build HTTP client".into(), @@ -620,11 +630,29 @@ impl RestfulLanceDbClient { Self::resolve_max_bytes_per_request(client_config.max_bytes_per_request)?; let max_request_duration = Self::resolve_max_request_duration(client_config.max_request_duration, read_timeout)?; + + let mut object_store_builder = reqwest::Client::builder() + .connect_timeout(connect_timeout) + .read_timeout(read_timeout) + .pool_idle_timeout(pool_idle_timeout); + if let Some(timeout) = timeout { + object_store_builder = object_store_builder.timeout(timeout); + } + let object_store_client = object_store_builder + .user_agent(client_config.user_agent) + .build() + .map_err(|err| Error::Other { + message: "Failed to build object-store HTTP client".into(), + source: Some(Box::new(err)), + })?; + Ok(Self { client, + object_store_client, host, retry_config, blob_request_semaphore: Arc::new(Semaphore::new(blob_request_concurrency)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: client_config.header_provider, read_consistency_interval, @@ -824,6 +852,34 @@ impl RestfulLanceDbClient { self.client.post(full_uri) } + /// Start a presigned object-store request. This client has no Enterprise + /// default headers and no dynamic header provider. + pub(crate) fn object_store_get(&self, url: &str) -> RequestBuilder { + self.object_store_client.get(url) + } + + /// Send presigned object-store traffic without request logging, request + /// ids, service headers, or signed URLs in returned errors. + pub(crate) async fn send_object_store( + &self, + req: RequestBuilder, + ) -> Result<(String, Response)> { + let request_id = "blob-direct".to_string(); + let (client, request) = req.build_split(); + let request = request.map_err(|err| Error::Http { + source: Box::new(err.without_url()), + request_id: request_id.clone(), + status_code: None, + })?; + let response = self + .sender + .send(&client, request) + .await + .map_err(|err| err.without_url()) + .err_to_http(request_id.clone())?; + Ok((request_id, response)) + } + pub fn put(&self, uri: &str) -> RequestBuilder { let full_uri = format!("{}{}", self.host, uri); self.client.put(full_uri) @@ -1190,9 +1246,11 @@ pub mod test_utils { RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "http://localhost".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: MockSender { f: Arc::new(wrapper), }, @@ -1217,6 +1275,7 @@ pub mod test_utils { RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "http://localhost".to_string(), retry_config: config.retry_config.try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new( @@ -1224,6 +1283,7 @@ pub mod test_utils { .blob_request_concurrency .unwrap_or(DEFAULT_BLOB_REQUEST_CONCURRENCY), )), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: MockSender { f: Arc::new(wrapper), }, @@ -1868,9 +1928,11 @@ mod tests { // Create client with header provider let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, @@ -1907,9 +1969,11 @@ mod tests { // Create client with header provider let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, @@ -1972,9 +2036,11 @@ mod tests { let client = RestfulLanceDbClient { client: reqwest::Client::new(), + object_store_client: reqwest::Client::new(), host: "https://example.com".to_string(), retry_config: RetryConfig::default().try_into().unwrap(), blob_request_semaphore: Arc::new(Semaphore::new(DEFAULT_BLOB_REQUEST_CONCURRENCY)), + blob_presign_threshold_bytes: DEFAULT_BLOB_PRESIGN_THRESHOLD_BYTES, sender: Sender, header_provider: Some(Arc::new(provider) as Arc), read_consistency_interval: None, diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 9b26c9f3b..39017be37 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1814,6 +1814,7 @@ impl Database for RemoteDatabase { self.sql_client.clone(), )); table.seed_blob_ranges_capability(rsp.headers()); + table.seed_blob_locations_capability(rsp.headers()); Ok(table) } else { // Describe the table to confirm it exists before moving on. @@ -1837,6 +1838,7 @@ impl Database for RemoteDatabase { self.sql_client.clone(), )); table.seed_blob_ranges_capability(&describe_headers); + table.seed_blob_locations_capability(&describe_headers); // This describe already carries the schema, so hand it to the table // instead of making the first schema read fetch it again. A version or // branch pin applied after this invalidates the cache. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index ade840cfd..ab5b65893 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -701,6 +701,8 @@ pub struct RemoteTable { schema_cache: BackgroundCache, // Only a successful describe can opt into the batched range protocol. blob_ranges_supported: Arc, + // Only a successful describe can opt into presigned direct Blob reads. + blob_locations_supported: Arc, // WAL-PK-FUSION: delete, with its initializers below. wal_pk_fusion: PkFusionMemory, freshness: Arc>, @@ -1006,6 +1008,7 @@ impl RemoteTable { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -1022,6 +1025,20 @@ impl RemoteTable { ); } + pub(super) fn seed_blob_locations_capability(&self, headers: &http::HeaderMap) { + self.blob_locations_supported.store( + headers + .get("x-lancedb-blob-locations") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + } + + fn seed_blob_capabilities(&self, headers: &http::HeaderMap) { + self.seed_blob_ranges_capability(headers); + self.seed_blob_locations_capability(headers); + } + /// Seed the schema cache from a `describe` body the caller already fetched. /// /// Best effort. `open_table` succeeds today without reading this body, so a @@ -1053,6 +1070,7 @@ impl RemoteTable { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: self.blob_ranges_supported.clone(), + blob_locations_supported: self.blob_locations_supported.clone(), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, @@ -1298,7 +1316,7 @@ impl RemoteTable { }; let response = self.check_table_response(&request_id, response).await?; - self.seed_blob_ranges_capability(response.headers()); + self.seed_blob_capabilities(response.headers()); let batch_function_declaration = response .headers() .get("x-lancedb-batch-function-declaration") @@ -2196,6 +2214,7 @@ fn unwrap_shared_error(arc: Arc) -> Error { } } +#[allow(clippy::too_many_arguments)] async fn fetch_schema( client: &RestfulLanceDbClient, identifier: &str, @@ -2204,6 +2223,7 @@ async fn fetch_schema( branch: Option, freshness: Arc>, blob_ranges_supported: Arc, + blob_locations_supported: Arc, ) -> Result { let mut body = serde_json::json!({ "version": read_snapshot.version }); if let Some(branch) = &branch { @@ -2228,6 +2248,13 @@ async fn fetch_schema( .is_some_and(|value| value == "1"), AtomicOrdering::Relaxed, ); + blob_locations_supported.store( + response + .headers() + .get("x-lancedb-blob-locations") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); let body = response.text().await.map_err(|e| { let status_code = e.status(); Error::Http { @@ -2286,6 +2313,7 @@ mod test_utils { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2315,6 +2343,7 @@ mod test_utils { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2353,6 +2382,7 @@ mod test_utils { location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), blob_ranges_supported: Arc::new(AtomicBool::new(false)), + blob_locations_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -3209,6 +3239,7 @@ impl BaseTable for RemoteTable { let branch = self.branch.clone(); let freshness = self.freshness.clone(); let blob_ranges_supported = self.blob_ranges_supported.clone(); + let blob_locations_supported = self.blob_locations_supported.clone(); match self .schema_cache @@ -3221,6 +3252,7 @@ impl BaseTable for RemoteTable { branch, freshness, blob_ranges_supported, + blob_locations_supported, ) .await }) diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 34c6743b1..2b8c3be9a 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::ops::Range; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Duration; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arrow_array::builder::LargeBinaryBuilder; use arrow_array::{Array, LargeBinaryArray, StructArray, UInt8Array, UInt64Array}; @@ -23,7 +23,8 @@ use futures::{StreamExt, TryStreamExt}; use lance::dataset::ROW_ID; use lance_core::datatypes::BlobKind; use reqwest::{Response, StatusCode, header}; -use tokio::sync::{Mutex, OwnedSemaphorePermit}; +use serde::Deserialize; +use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock}; use crate::Error; use crate::blob::{BlobDescriptor, BlobDescriptorSource, BlobFile, BlobRangeRequest}; @@ -42,6 +43,13 @@ use super::{ // is handled by splitting a rejected request below. const MAX_FETCH_BLOBS_ROW_IDS: usize = 1024; const MAX_FETCH_BLOB_RANGE_BYTES: u64 = 64 * 1024 * 1024; +// Refresh shortly before expiry so a request does not start with a URL that +// expires while it is being signed and sent. +const BLOB_PRESIGN_REFRESH_SKEW: Duration = Duration::from_secs(30); + +fn is_blob_locations_unavailable(error: &Error) -> bool { + error.status_code() == Some(StatusCode::SERVICE_UNAVAILABLE) +} fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { matches!(error, Error::Http { @@ -63,7 +71,7 @@ enum RangeRequestMode { trait BlobRangeRequester: Send + Sync + std::fmt::Debug { async fn request_range( &self, - range_header: &str, + range: Range, mode: RangeRequestMode, version: Option, ) -> Result; @@ -74,6 +82,10 @@ trait BlobRangeRequester: Send + Sync + std::fmt::Debug { struct BlobRangeResponse { request_id: String, response: Response, + /// Whether the requester already validated the response's status and + /// `Content-Range` against the logical blob. Direct object-store responses + /// use physical coordinates, so the outer handle cannot re-check them. + validated: bool, _permit: Option, } @@ -83,6 +95,7 @@ impl From<(String, Response)> for BlobRangeResponse { Self { request_id, response, + validated: false, _permit: None, } } @@ -108,10 +121,11 @@ struct TableBlobRangeRequester { impl BlobRangeRequester for TableBlobRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, mode: RangeRequestMode, version: Option, ) -> Result { + let range_header = format!("bytes={}-{}", range.start, range.end.saturating_sub(1)); let permit = self .client .blob_request_semaphore @@ -157,6 +171,7 @@ impl BlobRangeRequester for TableBlobRangeRequester { return Ok(BlobRangeResponse { request_id, response, + validated: false, _permit: Some(permit), }); } @@ -169,6 +184,7 @@ impl BlobRangeRequester for TableBlobRangeRequester { Ok(BlobRangeResponse { request_id, response, + validated: false, _permit: Some(permit), }) } @@ -271,18 +287,20 @@ impl RemoteBlobFile { if range.is_empty() { return Ok(Bytes::new()); } - let range_header = format!("bytes={}-{}", range.start, range.end - 1); let BlobRangeResponse { request_id, response, + validated, _permit: permit, } = self .requester - .request_range(&range_header, RangeRequestMode::DataRead, self.version) + .request_range(range.clone(), RangeRequestMode::DataRead, self.version) .await .map_err(remote_blob_error)?; self.ensure_open()?; - validate_partial_response(&response, range.clone(), self.size)?; + if !validated { + validate_partial_response(&response, range.clone(), self.size)?; + } let bytes = read_blob_body(response, range.end - range.start, request_id).await?; drop(permit); self.ensure_open()?; @@ -509,6 +527,37 @@ fn validate_partial_response( response: &Response, expected: Range, size: u64, +) -> lance_core::Result<()> { + validate_content_range(response, expected.start, expected.end - 1, size, true) +} + +/// Validate a direct object-store response whose `Content-Range` uses physical +/// offsets in a shared sidecar. The object may be larger than the logical blob; +/// only its total must cover the full logical value. +fn validate_physical_content_range( + response: &Response, + expected: Range, + base_offset: u64, + logical_size: u64, +) -> lance_core::Result<()> { + let start = base_offset + .checked_add(expected.start) + .ok_or_else(|| remote_blob_error("blob physical range start overflows u64"))?; + let end = base_offset + .checked_add(expected.end) + .ok_or_else(|| remote_blob_error("blob physical range end overflows u64"))?; + let minimum_total = base_offset + .checked_add(logical_size) + .ok_or_else(|| remote_blob_error("blob physical range total overflows u64"))?; + validate_content_range(response, start, end - 1, minimum_total, false) +} + +fn validate_content_range( + response: &Response, + expected_start: u64, + expected_end: u64, + expected_total: u64, + exact_total: bool, ) -> lance_core::Result<()> { if response.status() != StatusCode::PARTIAL_CONTENT { return Err(remote_blob_error(format!( @@ -522,12 +571,14 @@ fn validate_partial_response( .and_then(|value| value.to_str().ok()) .and_then(parse_content_range) .ok_or_else(|| remote_blob_error("response is missing a valid Content-Range header"))?; - if content_range != (expected.start, expected.end - 1, size) { + if content_range.0 != expected_start + || content_range.1 != expected_end + || (exact_total && content_range.2 != expected_total) + || (!exact_total && content_range.2 < expected_total) + { return Err(remote_blob_error(format!( - "expected Content-Range 'bytes {}-{}/{}', got 'bytes {}-{}/{}'", - expected.start, - expected.end - 1, - size, + "expected Content-Range 'bytes {expected_start}-{expected_end}/{expected_total}{}', got 'bytes {}-{}/{}'", + if exact_total { "" } else { " or larger" }, content_range.0, content_range.1, content_range.2 @@ -536,6 +587,576 @@ fn validate_partial_response( Ok(()) } +#[derive(Debug, Clone, Deserialize)] +struct BlobLocationSource { + url: String, + #[serde(default)] + expires_at_unix_secs: Option, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +enum BlobLocationItem { + Presigned { + source_index: usize, + offset: u64, + size: u64, + }, + Inline { + size: u64, + data_base64: String, + }, + Proxy { + size: u64, + }, +} + +#[derive(Debug)] +struct ResolvedBlobLocations { + sources: Vec, + items: Vec>, + version: u64, + identity: Option, +} + +#[derive(Deserialize)] +struct BlobLocationsBody { + sources: Vec, + items: Vec>, +} + +/// One pinned table/column position used to resolve or refresh Blob locations. +#[derive(Clone)] +struct BlobLocationsContext { + client: RestfulLanceDbClient, + identifier: String, + table_name: String, + column: String, + version: Option, + branch: Option, + source_uri: Option, + source_commit_micros: Option, + row_is_address: bool, + expected_query_snapshot: Option, + freshness: Option, +} + +impl BlobLocationsContext { + async fn resolve( + &self, + row_ids: &[u64], + include_inline_data: bool, + ) -> Result { + let started = Instant::now(); + let mut body = serde_json::json!({ + "column": &self.column, + "version": self.version, + "row_ids": row_ids, + "row_is_address": self.row_is_address, + "include_inline_data": include_inline_data, + }); + if let Some(branch) = &self.branch { + body["branch"] = serde_json::Value::String(branch.clone()); + } + if let Some(source_uri) = &self.source_uri { + body["source_uri"] = serde_json::Value::String(source_uri.clone()); + } + if let Some(timestamp) = self.source_commit_micros { + body["source_commit_micros"] = serde_json::Value::Number(timestamp.into()); + } + + let mut request = self + .client + .post(&format!("/v1/table/{}/blob_locations/", self.identifier)) + .json(&body); + if let Some(identity) = &self.expected_query_snapshot { + request = request.header(QUERY_SNAPSHOT_HEADER, identity); + } + if let Some(freshness) = self.freshness { + request = freshness.apply(request); + } + // A resolver 503 means a PE lost the plan after describe. Do not spend + // transport retries on it: the caller falls back to proxy immediately. + let (request_id, response) = self.client.send(request).await?; + let response = + RemoteTable::::handle_table_not_found(&self.table_name, response, &request_id) + .await?; + let response = self + .client + .check_response(&request_id, response) + .await + .map_err(|error| { + if let Error::Http { + source, + request_id, + status_code: Some(StatusCode::BAD_REQUEST), + } = error + { + Error::InvalidInput { + message: format!("blob_locations (request {request_id}): {source}"), + } + } else { + error + } + })?; + check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + + let version = response + .headers() + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version != 0) + .ok_or_else(|| Error::Http { + source: "blob_locations response has no valid x-lancedb-version".into(), + request_id: request_id.clone(), + status_code: None, + })?; + if let Some(expected) = self.version + && expected != version + { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {version}, expected pinned version {expected}" + ) + .into(), + request_id, + status_code: None, + }); + } + let identity = match &self.expected_query_snapshot { + Some(expected) => Some(expected.clone()), + None => Some( + response + .headers() + .get(QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .map(str::to_owned) + .ok_or_else(|| Error::NotSupported { + message: + "Blob locations require a snapshot identity; upgrade every serving node" + .into(), + })?, + ), + }; + + let body = response.text().await.err_to_http(request_id.clone())?; + let parsed: BlobLocationsBody = + serde_json::from_str(&body).map_err(|error| Error::Http { + source: format!("failed to parse blob_locations response: {error}").into(), + request_id: request_id.clone(), + status_code: None, + })?; + if parsed.items.len() != row_ids.len() { + return Err(Error::Http { + source: format!( + "blob_locations returned {} items for {} row ids", + parsed.items.len(), + row_ids.len() + ) + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + for item in parsed.items.iter().flatten() { + match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + if *source_index >= parsed.sources.len() { + return Err(Error::Http { + source: format!( + "blob_locations item references source {source_index} of {}", + parsed.sources.len() + ) + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + offset.checked_add(*size).ok_or_else(|| Error::Http { + source: "blob_locations physical range overflows u64".into(), + request_id: request_id.clone(), + status_code: None, + })?; + } + BlobLocationItem::Inline { size, data_base64 } => { + if data_base64.len() as u64 > size.saturating_mul(4) { + return Err(Error::Http { + source: "blob_locations inline payload is larger than its decoded size" + .into(), + request_id: request_id.clone(), + status_code: None, + }); + } + } + BlobLocationItem::Proxy { .. } => {} + } + } + log::debug!( + "blob_locations resolved rows={} version={} elapsed_ms={:.3}", + row_ids.len(), + version, + started.elapsed().as_secs_f64() * 1000.0 + ); + Ok(ResolvedBlobLocations { + sources: parsed.sources, + items: parsed.items, + version, + identity, + }) + } +} + +fn decode_inline_data(data_base64: &str, expected_size: u64) -> Result { + use base64::Engine as _; + let bytes = base64::engine::general_purpose::STANDARD + .decode(data_base64) + .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(data_base64)) + .map_err(|error| Error::InvalidInput { + message: format!("blob_locations returned invalid inline base64: {error}"), + })?; + if bytes.len() as u64 != expected_size { + return Err(Error::InvalidInput { + message: format!( + "blob_locations inline item decoded to {} bytes, expected {expected_size}", + bytes.len() + ), + }); + } + Ok(Bytes::from(bytes)) +} + +enum PresignedBlobState { + Presigned { + url: String, + expires_at_unix_secs: Option, + base_offset: u64, + }, + Inline { + bytes: Bytes, + }, + Proxy, +} + +enum PresignedReadError { + Expired, + Failed(Error), +} + +struct PresignedBlobRangeRequester { + context: BlobLocationsContext, + row_id: u64, + logical_size: u64, + threshold_bytes: u64, + proxy: Arc, + state: RwLock, + refresh_lock: Mutex<()>, +} + +impl std::fmt::Debug for PresignedBlobRangeRequester { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PresignedBlobRangeRequester") + .field("row_id", &self.row_id) + .field("logical_size", &self.logical_size) + .finish_non_exhaustive() + } +} + +impl PresignedBlobRangeRequester { + fn new( + context: BlobLocationsContext, + row_id: u64, + logical_size: u64, + threshold_bytes: u64, + proxy: Arc, + source: &BlobLocationSource, + base_offset: u64, + ) -> Self { + Self { + context, + row_id, + logical_size, + threshold_bytes, + proxy, + state: RwLock::new(PresignedBlobState::Presigned { + url: source.url.clone(), + expires_at_unix_secs: source.expires_at_unix_secs, + base_offset, + }), + refresh_lock: Mutex::new(()), + } + } + + async fn proxy_validated( + &self, + range: Range, + mode: RangeRequestMode, + version: Option, + ) -> Result { + let mut response = self + .proxy + .request_range(range.clone(), mode, version) + .await?; + validate_partial_response(&response.response, range, self.logical_size)?; + response.validated = true; + Ok(response) + } + + async fn refresh(&self) -> Result<()> { + let _guard = self.refresh_lock.lock().await; + let resolved = match self.context.resolve(&[self.row_id], false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => { + // The resolver lost its PE plan. Keep this handle usable by + // switching it to the proxy route instead of failing the read. + *self.state.write().await = PresignedBlobState::Proxy; + return Ok(()); + } + Err(error) => return Err(error), + }; + let item = + resolved + .items + .into_iter() + .next() + .flatten() + .ok_or_else(|| Error::InvalidInput { + message: "presigned blob is no longer stored as a non-null value".into(), + })?; + let next = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + if size != self.logical_size { + return Err(Error::InvalidInput { + message: format!( + "presigned blob size changed from {} to {size} at the pinned version", + self.logical_size + ), + }); + } + let source = + resolved + .sources + .get(source_index) + .ok_or_else(|| Error::InvalidInput { + message: format!( + "presigned blob refresh references source {source_index} of {}", + resolved.sources.len() + ), + })?; + PresignedBlobState::Presigned { + url: source.url.clone(), + expires_at_unix_secs: source.expires_at_unix_secs, + base_offset: offset, + } + } + BlobLocationItem::Inline { size, data_base64 } => PresignedBlobState::Inline { + bytes: decode_inline_data(&data_base64, size)?, + }, + BlobLocationItem::Proxy { size } => { + if size != self.logical_size { + return Err(Error::InvalidInput { + message: format!( + "proxied blob size changed from {} to {size} at the pinned version", + self.logical_size + ), + }); + } + PresignedBlobState::Proxy + } + }; + *self.state.write().await = next; + Ok(()) + } + + async fn direct_read( + &self, + url: &str, + base_offset: u64, + range: Range, + ) -> std::result::Result { + let permit = self + .context + .client + .blob_request_semaphore + .clone() + .acquire_owned() + .await + .expect("blob request semaphore is never closed"); + let start = base_offset.checked_add(range.start).ok_or_else(|| { + PresignedReadError::Failed(Error::InvalidInput { + message: "presigned physical range start overflows u64".into(), + }) + })?; + let end = base_offset.checked_add(range.end).ok_or_else(|| { + PresignedReadError::Failed(Error::InvalidInput { + message: "presigned physical range end overflows u64".into(), + }) + })?; + let request = self + .context + .client + .object_store_get(url) + .header(header::RANGE, format!("bytes={start}-{}", end - 1)); + let (request_id, response) = self + .context + .client + .send_object_store(request) + .await + .map_err(PresignedReadError::Failed)?; + if matches!( + response.status(), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN + ) { + return Err(PresignedReadError::Expired); + } + if response.status() != StatusCode::PARTIAL_CONTENT { + return Err(PresignedReadError::Failed(Error::Http { + source: format!( + "expected HTTP 206 Partial Content, got {}", + response.status() + ) + .into(), + request_id, + status_code: Some(response.status()), + })); + } + validate_physical_content_range(&response, range.clone(), base_offset, self.logical_size) + .map_err(|error| PresignedReadError::Failed(error.into()))?; + let content_range = response + .headers() + .get(header::CONTENT_RANGE) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + log::debug!( + "blob_direct row={} content_range={} logical_range={}..{}", + self.row_id, + content_range, + range.start, + range.end + ); + Ok(BlobRangeResponse { + request_id, + response, + validated: true, + _permit: Some(permit), + }) + } +} + +#[async_trait::async_trait] +impl BlobRangeRequester for PresignedBlobRangeRequester { + async fn request_range( + &self, + range: Range, + mode: RangeRequestMode, + version: Option, + ) -> Result { + if !matches!(mode, RangeRequestMode::DataRead) { + return Err(Error::InvalidInput { + message: "presigned blob handles only serve data reads".into(), + }); + } + let range_len = range.end.saturating_sub(range.start); + if range_len < self.threshold_bytes { + return self.proxy_validated(range, mode, version).await; + } + let mut refreshed = false; + loop { + let state = self.state.read().await; + match &*state { + PresignedBlobState::Proxy => { + drop(state); + return self.proxy_validated(range, mode, version).await; + } + PresignedBlobState::Inline { bytes } => { + let bytes = bytes.clone(); + drop(state); + return inline_range_response(bytes, range, self.logical_size); + } + PresignedBlobState::Presigned { + url, + expires_at_unix_secs, + base_offset, + } => { + let url = url.clone(); + let expires = *expires_at_unix_secs; + let base_offset = *base_offset; + drop(state); + let now = unix_now_secs(); + if expires.is_some_and(|expires| { + expires <= now.saturating_add(BLOB_PRESIGN_REFRESH_SKEW.as_secs()) + }) && !refreshed + { + self.refresh().await?; + refreshed = true; + continue; + } + match self.direct_read(&url, base_offset, range.clone()).await { + Ok(response) => return Ok(response), + Err(PresignedReadError::Expired) if !refreshed => { + self.refresh().await?; + refreshed = true; + } + Err(PresignedReadError::Expired) => { + return Err(Error::InvalidInput { + message: "presigned blob URL expired after refresh".into(), + }); + } + Err(PresignedReadError::Failed(error)) => return Err(error), + } + } + } + } + } +} + +fn unix_now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_secs()) +} + +fn inline_range_response(bytes: Bytes, range: Range, size: u64) -> Result { + let start = usize::try_from(range.start).map_err(|_| Error::InvalidInput { + message: "inline blob range start exceeds addressable memory".into(), + })?; + let end = usize::try_from(range.end).map_err(|_| Error::InvalidInput { + message: "inline blob range end exceeds addressable memory".into(), + })?; + let slice = bytes + .get(start..end) + .ok_or_else(|| Error::InvalidInput { + message: "inline blob range exceeds the resolved value".into(), + })? + .to_vec(); + let response = http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header( + header::CONTENT_RANGE, + format!("bytes {}-{}/{size}", range.start, range.end - 1), + ) + .body(slice) + .map_err(|error| Error::Other { + message: format!("failed to build inline blob response: {error}"), + source: None, + })?; + Ok(BlobRangeResponse { + request_id: "blob-inline".into(), + response: Response::from(response), + validated: true, + _permit: None, + }) +} + impl RemoteTable { async fn reject_list_blob_path_if_known(&self, column: &str) -> Result<()> { // A dotted path needs client-side validation because the server may @@ -595,6 +1216,23 @@ impl RemoteTable { }); } let mut read_snapshot = self.snapshot_read_state().await; + let mut identity = self.expected_query_snapshot.clone(); + let mut allow_direct_fallback = true; + if self.blob_locations_supported.load(Ordering::Relaxed) { + match self + .fetch_blobs_via_locations(column, row_ids, &mut read_snapshot, &mut identity) + .await + { + Ok(Some(blobs)) => return Ok(blobs), + Ok(None) => { + log::warn!( + "blob_locations is unavailable (503); falling back to the proxy whole-blob path for this batch" + ); + allow_direct_fallback = false; + } + Err(error) => return Err(error), + } + } // A selection spanning requests must use one exact dataset version. // Resolve latest before the first chunk; a checked-out version is exact already. if row_ids.len() > MAX_FETCH_BLOBS_ROW_IDS && read_snapshot.version.is_none() { @@ -604,7 +1242,7 @@ impl RemoteTable { let mut blobs = BlobAccumulator::new(row_ids.len())?; while let Some(ids) = pending.pop() { match self - .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) + .fetch_blobs_chunk(column, ids, read_snapshot, identity.as_deref(), &mut blobs) .await { Ok(()) => {} @@ -619,7 +1257,13 @@ impl RemoteTable { // The whole-byte route cannot serve this blob. The Range route // has no aggregate response limit and preserves null alignment. let mut files = self - .fetch_blob_files_with_snapshot(column, ids, read_snapshot) + .fetch_blob_files_with_snapshot( + column, + ids, + read_snapshot, + allow_direct_fallback, + identity.clone(), + ) .await?; let blob = match files.pop().unwrap() { Some(file) => Some(file.read().await?), @@ -647,11 +1291,278 @@ impl RemoteTable { Ok(blobs.finish()?) } + /// Resolve locations once per batch, read large presigned values directly, + /// consume inline bytes in place, and proxy only the remaining rows. + /// + /// `Ok(None)` means the resolver returned 503 after possibly pinning a + /// version and identity; the caller must reuse that pinned state on the + /// proxy path and must not resolve again. + async fn fetch_blobs_via_locations( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result> { + let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); + let mut blobs = BlobAccumulator::new(row_ids.len())?; + while let Some(ids) = pending.pop() { + let context = self.blob_locations_context( + column, + read_snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(read_snapshot.freshness), + ); + let resolved = match context.resolve(ids, true).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if read_snapshot.version.is_none() { + read_snapshot.version = Some(resolved.version); + } + if read_snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, read_snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + let array = self + .fetch_blobs_locations_batch( + column, + ids, + &resolved, + *read_snapshot, + identity.as_deref(), + ) + .await?; + blobs.append(&array)?; + } + Ok(Some(blobs.finish()?)) + } + + async fn fetch_blobs_locations_batch( + &self, + column: &str, + row_ids: &[u64], + resolved: &ResolvedBlobLocations, + read_snapshot: ReadSnapshot, + identity: Option<&str>, + ) -> Result { + let mut values: Vec> = vec![None; row_ids.len()]; + let mut nulls = vec![false; row_ids.len()]; + let mut proxy_indices = Vec::new(); + let mut direct = Vec::new(); + for (index, item) in resolved.items.iter().enumerate() { + match item { + None => nulls[index] = true, + Some(BlobLocationItem::Inline { size, data_base64 }) => { + values[index] = Some(decode_inline_data(data_base64, *size)?); + } + Some(BlobLocationItem::Presigned { + source_index, + offset, + size, + }) if *size >= self.client.blob_presign_threshold_bytes => { + direct.push((index, *source_index, *offset, *size)); + } + Some(_) => proxy_indices.push(index), + } + } + + let proxy_array = if proxy_indices.is_empty() { + None + } else { + let proxy_row_ids = proxy_indices + .iter() + .map(|index| row_ids[*index]) + .collect::>(); + Some( + self.fetch_blobs_proxy_array( + column, + &proxy_row_ids, + read_snapshot, + identity.map(str::to_owned), + ) + .await?, + ) + }; + + let direct_futures = direct + .into_iter() + .map(|(index, source_index, offset, size)| { + let source = resolved.sources[source_index].clone(); + let row_id = row_ids[index]; + let identity = identity.map(str::to_owned); + async move { + let proxy = self.blob_range_requester_with_identity( + column, + row_id, + &read_snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + Some(resolved.version), + self.branch.clone(), + None, + identity, + None, + ); + let requester = Arc::new(PresignedBlobRangeRequester::new( + context, + row_id, + size, + self.client.blob_presign_threshold_bytes, + proxy, + &source, + offset, + )); + let response = requester + .request_range(0..size, RangeRequestMode::DataRead, Some(resolved.version)) + .await?; + let BlobRangeResponse { + request_id, + response, + validated: _, + _permit, + } = response; + let bytes = read_blob_body(response, size, request_id).await?; + Ok::<_, Error>((index, bytes)) + } + }); + let direct_values = futures::stream::iter(direct_futures) + .buffered(BLOB_REQUEST_CONCURRENCY) + .try_collect::>() + .await?; + for (index, bytes) in direct_values { + values[index] = Some(bytes); + } + + if let Some(proxy_array) = proxy_array { + for (proxy_offset, index) in proxy_indices.into_iter().enumerate() { + if proxy_array.is_null(proxy_offset) { + nulls[index] = true; + } else { + values[index] = Some(Bytes::copy_from_slice(proxy_array.value(proxy_offset))); + } + } + } + + let total_bytes = values + .iter() + .flatten() + .map(Bytes::len) + .try_fold(0usize, |total, length| total.checked_add(length)); + let mut builder = LargeBinaryBuilder::with_capacity( + row_ids.len(), + total_bytes.ok_or_else(|| Error::InvalidInput { + message: "blob batch length exceeds addressable memory".into(), + })?, + ); + for index in 0..row_ids.len() { + if nulls[index] { + builder.append_null(); + } else { + let value = values[index].take().ok_or_else(|| Error::Http { + source: format!("blob_locations left row {index} without a value").into(), + request_id: "blob-locations".into(), + status_code: None, + })?; + builder.append_value(value); + } + } + Ok(builder.finish()) + } + + async fn fetch_blobs_proxy_array( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: ReadSnapshot, + identity: Option, + ) -> Result { + let mut pending: Vec<&[u64]> = vec![row_ids]; + let mut parts = Vec::new(); + while let Some(ids) = pending.pop() { + match self + .fetch_blobs_array(column, ids, read_snapshot, identity.clone()) + .await + { + Ok(array) => parts.push(array), + Err(error) if is_fetch_blobs_byte_limit_error(&error) && ids.len() > 1 => { + let mid = ids.len() / 2; + pending.push(&ids[mid..]); + pending.push(&ids[..mid]); + } + Err(error) if is_fetch_blobs_byte_limit_error(&error) => { + let mut files = self + .fetch_blob_files_with_snapshot( + column, + ids, + read_snapshot, + false, + identity.clone(), + ) + .await?; + let blob = match files.pop().unwrap() { + Some(file) => Some(file.read().await?), + None => None, + }; + parts.push(match blob { + Some(bytes) => LargeBinaryArray::new( + OffsetBuffer::new(vec![0, bytes.len() as i64].into()), + Buffer::from(bytes), + None, + ), + None => LargeBinaryArray::new_null(1), + }); + } + Err(error) => return Err(error), + } + } + let mut blobs = BlobAccumulator::new(row_ids.len())?; + for part in parts { + blobs.append(&part)?; + } + Ok(blobs.finish()?) + } + + async fn fetch_blobs_array( + &self, + column: &str, + row_ids: &[u64], + read_snapshot: ReadSnapshot, + identity: Option, + ) -> Result { + let mut blobs = BlobAccumulator::new(row_ids.len())?; + self.fetch_blobs_chunk( + column, + row_ids, + read_snapshot, + identity.as_deref(), + &mut blobs, + ) + .await?; + Ok(blobs.finish()?) + } + async fn fetch_blobs_chunk( &self, column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, + identity: Option<&str>, blobs: &mut BlobAccumulator, ) -> Result<()> { let mut body = serde_json::json!({ @@ -665,7 +1576,8 @@ impl RemoteTable { .client .post(&format!("/v1/table/{}/fetch_blobs/", self.identifier)) .json(&body); - let request = if let Some(identity) = &self.expected_query_snapshot { + let expected_identity = identity.or(self.expected_query_snapshot.as_deref()); + let request = if let Some(identity) = expected_identity { request.header(QUERY_SNAPSHOT_HEADER, identity) } else { request @@ -674,7 +1586,7 @@ impl RemoteTable { .send_with_freshness(request, true, read_snapshot.freshness) .await?; if response.status().is_success() { - check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?; + check_query_snapshot_response(expected_identity, &response)?; } let mut stream = match self.read_arrow_response(&request_id, response).await { Ok(stream) => stream, @@ -733,9 +1645,8 @@ impl RemoteTable { column: &str, requests: &[BlobRangeRequest], ) -> Result { - let mut blobs = BlobAccumulator::new(requests.len())?; if requests.is_empty() { - return Ok(blobs.finish()?); + return Ok(LargeBinaryArray::from(Vec::>::new())); } for request in requests { request @@ -749,10 +1660,289 @@ impl RemoteTable { if !self.blob_ranges_supported.load(Ordering::Relaxed) { return self.fetch_blob_ranges_legacy(column, requests).await; } - // Select the protocol before issuing data requests. An advertised endpoint - // failing in a mixed deployment must fail truthfully, without fallback. - let mut snapshot = self.snapshot_read_state().await; + let snapshot = self.snapshot_read_state().await; let mut identity = self.expected_query_snapshot.clone(); + if self.blob_locations_supported.load(Ordering::Relaxed) + && requests + .iter() + .any(|request| request.length >= self.client.blob_presign_threshold_bytes) + { + let mut pinned = snapshot; + match self + .resolve_blob_range_locations(column, requests, &mut pinned, &mut identity) + .await + { + Ok(Some(locations)) => { + return self + .fetch_blob_ranges_mixed(column, requests, pinned, identity, locations) + .await; + } + Ok(None) => { + // The QN advertised direct locations, but a PE lost the + // plan after describe. Reuse any version/identity pinned by + // earlier resolver partitions and retry this operation on + // the proxy path, exactly once. + log::warn!( + "blob_locations is unavailable (503); falling back to the proxy range path for this batch" + ); + return self + .fetch_blob_ranges_proxy(column, requests, pinned, identity) + .await; + } + Err(error) => return Err(error), + } + } + self.fetch_blob_ranges_proxy(column, requests, snapshot, identity) + .await + } + + /// Resolve the rows that carry at least one individually large range. + /// + /// Only these rows need locations; small-only batches never reach this + /// method, so they keep their existing proxy round trips. + async fn resolve_blob_range_locations( + &self, + column: &str, + requests: &[BlobRangeRequest], + snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result>> { + let mut row_ids = requests + .iter() + .filter(|request| request.length >= self.client.blob_presign_threshold_bytes) + .map(|request| request.row_id) + .collect::>(); + row_ids.sort_unstable(); + row_ids.dedup(); + let mut locations = HashMap::with_capacity(row_ids.len()); + for chunk in row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS) { + let context = self.blob_locations_context( + column, + snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(snapshot.freshness), + ); + let resolved = match context.resolve(chunk, false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if snapshot.version.is_none() { + snapshot.version = Some(resolved.version); + } + if snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + for (row_id, item) in chunk.iter().zip(resolved.items.iter()) { + let location = match item { + None => BlobRangeLocation::Null, + Some(BlobLocationItem::Presigned { + source_index, + offset, + size, + }) => { + let source = + resolved + .sources + .get(*source_index) + .cloned() + .ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + })?; + BlobRangeLocation::Presigned { + source, + offset: *offset, + size: *size, + } + } + Some(BlobLocationItem::Inline { .. }) + | Some(BlobLocationItem::Proxy { .. }) => BlobRangeLocation::Proxy, + }; + locations.insert(*row_id, location); + } + } + Ok(Some(locations)) + } + + async fn fetch_blob_ranges_mixed( + &self, + column: &str, + requests: &[BlobRangeRequest], + snapshot: ReadSnapshot, + identity: Option, + locations: HashMap, + ) -> Result { + let threshold = self.client.blob_presign_threshold_bytes; + let mut values: Vec> = vec![None; requests.len()]; + let mut nulls = vec![false; requests.len()]; + let mut proxy_indices = Vec::new(); + let mut proxy_requests = Vec::new(); + let mut direct = Vec::new(); + for (index, request) in requests.iter().enumerate() { + if request.length < threshold { + proxy_indices.push(index); + proxy_requests.push(*request); + continue; + } + match locations.get(&request.row_id) { + Some(BlobRangeLocation::Null) => nulls[index] = true, + Some(BlobRangeLocation::Proxy) => { + proxy_indices.push(index); + proxy_requests.push(*request); + } + Some(BlobRangeLocation::Presigned { + source, + offset, + size, + }) => { + let end = request.offset.checked_add(request.length).ok_or_else(|| { + Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + } + })?; + if end > *size { + return Err(Error::InvalidInput { + message: format!( + "blob range end {end} exceeds blob size {size} for row {}", + request.row_id + ), + }); + } + if request.length == 0 { + values[index] = Some(Bytes::new()); + } else { + direct.push((index, *request, source.clone(), *offset, *size)); + } + } + None => { + return Err(Error::InvalidInput { + message: format!( + "blob range row {} was not resolved for a large range", + request.row_id + ), + }); + } + } + } + + let direct_futures = direct + .into_iter() + .map(|(index, request, source, offset, size)| { + let proxy = self.blob_range_requester_with_identity( + column, + request.row_id, + &snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + snapshot.version, + self.branch.clone(), + None, + identity.clone(), + None, + ); + async move { + let requester = PresignedBlobRangeRequester::new( + context, + request.row_id, + size, + threshold, + proxy, + &source, + offset, + ); + let response = requester + .request_range( + request.offset..request.offset + request.length, + RangeRequestMode::DataRead, + snapshot.version, + ) + .await?; + let BlobRangeResponse { + request_id, + response, + validated: _, + _permit, + } = response; + let bytes = read_blob_body(response, request.length, request_id).await?; + Ok::<_, Error>((index, bytes)) + } + }); + let direct_values = futures::stream::iter(direct_futures) + .buffered(BLOB_REQUEST_CONCURRENCY) + .try_collect::>() + .await?; + for (index, bytes) in direct_values { + values[index] = Some(bytes); + } + + if !proxy_indices.is_empty() { + let proxy_array = self + .fetch_blob_ranges_proxy(column, &proxy_requests, snapshot, identity) + .await?; + for (position, index) in proxy_indices.into_iter().enumerate() { + if proxy_array.is_null(position) { + nulls[index] = true; + } else { + values[index] = Some(Bytes::copy_from_slice(proxy_array.value(position))); + } + } + } + + let total_bytes = values + .iter() + .flatten() + .map(Bytes::len) + .try_fold(0usize, |total, length| total.checked_add(length)); + let mut builder = LargeBinaryBuilder::with_capacity( + requests.len(), + total_bytes.ok_or_else(|| Error::InvalidInput { + message: "blob range batch length exceeds addressable memory".into(), + })?, + ); + for index in 0..requests.len() { + if nulls[index] { + builder.append_null(); + } else { + let value = values[index].take().ok_or_else(|| Error::Http { + source: format!("blob range {index} has no resolved value").into(), + request_id: "blob-locations".into(), + status_code: None, + })?; + builder.append_value(value); + } + } + Ok(builder.finish()) + } + + async fn fetch_blob_ranges_proxy( + &self, + column: &str, + requests: &[BlobRangeRequest], + mut snapshot: ReadSnapshot, + mut identity: Option, + ) -> Result { + let mut blobs = BlobAccumulator::new(requests.len())?; + if requests.is_empty() { + return Ok(blobs.finish()?); + } let mut index = 0; let mut consumed = 0; let mut ranges = Vec::new(); @@ -814,7 +2004,15 @@ impl RemoteTable { .iter() .map(|request| request.row_id) .collect::>(); - let files = self.fetch_blob_files_impl(column, &row_ids).await?; + let files = self + .fetch_blob_files_with_route( + column, + &row_ids, + false, + None, + self.expected_query_snapshot.clone(), + ) + .await?; let mut builder = LargeBinaryBuilder::with_capacity(requests.len(), 0); for (file, request) in files.into_iter().zip(requests) { match file { @@ -998,6 +2196,24 @@ impl RemoteTable { &self, column: &str, row_ids: &[u64], + ) -> Result>> { + self.fetch_blob_files_with_route( + column, + row_ids, + true, + None, + self.expected_query_snapshot.clone(), + ) + .await + } + + async fn fetch_blob_files_with_route( + &self, + column: &str, + row_ids: &[u64], + use_direct: bool, + read_snapshot: Option, + identity: Option, ) -> Result>> { self.reject_list_blob_path_if_known(column).await?; // Empty requests do not require blob-route support. @@ -1006,7 +2222,11 @@ impl RemoteTable { } self.ensure_blob_files_supported()?; - let mut read_snapshot = self.snapshot_read_state().await; + let mut read_snapshot = match read_snapshot { + Some(read_snapshot) => read_snapshot, + None => self.snapshot_read_state().await, + }; + let mut identity = identity.or_else(|| self.expected_query_snapshot.clone()); let sizes = match self .take_blob_descriptor_sizes(column, row_ids, &mut read_snapshot) .await @@ -1014,25 +2234,93 @@ impl RemoteTable { Ok(sizes) => sizes, Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), }; - let version = read_snapshot.version; + let direct_candidates = + if use_direct && self.blob_locations_supported.load(Ordering::Relaxed) { + let mut candidates = sizes + .iter() + .filter_map(|(row_id, size)| match size { + DescriptorSize::Known { kind, size } + if *size >= self.client.blob_presign_threshold_bytes + && is_direct_blob_kind(*kind) => + { + Some(*row_id) + } + _ => None, + }) + .collect::>(); + candidates.sort_unstable(); + candidates + } else { + Vec::new() + }; + let resolved_handles = if direct_candidates.is_empty() { + HashMap::new() + } else { + match self + .resolve_blob_file_candidates( + column, + &direct_candidates, + &mut read_snapshot, + &mut identity, + ) + .await + { + Ok(Some(handles)) => handles, + Ok(None) => { + log::warn!( + "blob_locations is unavailable (503); keeping this handle batch on the proxy path" + ); + HashMap::new() + } + Err(error) => return Err(self.explain_list_blob_bad_request(column, error).await), + } + }; + let version = read_snapshot.version; let mut files = Vec::with_capacity(row_ids.len()); let mut probe_indices = Vec::new(); let mut probe_requesters = Vec::new(); for (index, row_id) in row_ids.iter().enumerate() { + if let Some(handle) = resolved_handles.get(row_id) { + if let DescriptorSize::Known { size, .. } = sizes[row_id] + && size != handle.size + { + return Err(Error::Http { + source: format!( + "blob_locations resolved row {row_id} as {} bytes, descriptor says {size}", + handle.size + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + files.push( + handle.requester.clone().map(|requester| { + RemoteBlobFile::new(requester, handle.size, version).into() + }), + ); + continue; + } match sizes[row_id] { DescriptorSize::Null => files.push(None), - DescriptorSize::Known(size) => { - let requester = self.blob_range_requester(column, *row_id, &read_snapshot); + DescriptorSize::Known { size, .. } => { + let requester = self.blob_range_requester_with_identity( + column, + *row_id, + &read_snapshot, + identity.as_deref(), + ); files.push(Some(RemoteBlobFile::new(requester, size, version).into())); } DescriptorSize::Unresolved => { files.push(None); probe_indices.push(index); - probe_requesters.push(self.blob_range_requester( + probe_requesters.push(self.blob_range_requester_with_identity( column, *row_id, &read_snapshot, + identity.as_deref(), )); } } @@ -1047,6 +2335,111 @@ impl RemoteTable { Ok(files) } + /// Resolve direct handles for descriptor rows whose logical size warrants + /// presigning. Each item must agree with the descriptor size. + async fn resolve_blob_file_candidates( + &self, + column: &str, + candidate_row_ids: &[u64], + read_snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result>> { + let mut handles = HashMap::with_capacity(candidate_row_ids.len()); + for chunk in candidate_row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS) { + let context = self.blob_locations_context( + column, + read_snapshot.version, + self.branch.clone(), + None, + identity.clone(), + Some(read_snapshot.freshness), + ); + let resolved = match context.resolve(chunk, false).await { + Ok(resolved) => resolved, + Err(error) if is_blob_locations_unavailable(&error) => return Ok(None), + Err(error) => return Err(error), + }; + if read_snapshot.version.is_none() { + read_snapshot.version = Some(resolved.version); + } + if read_snapshot.version != Some(resolved.version) { + return Err(Error::Http { + source: format!( + "blob_locations resolved version {} but this read is pinned to {:?}", + resolved.version, read_snapshot.version + ) + .into(), + request_id: "blob-locations".into(), + status_code: None, + }); + } + if identity.is_none() { + *identity = resolved.identity.clone(); + } + for (row_id, item) in chunk.iter().zip(resolved.items.iter()) { + let item = item.as_ref().ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations returned null for non-null descriptor row {row_id}" + ), + })?; + let size = match item { + BlobLocationItem::Presigned { size, .. } + | BlobLocationItem::Inline { size, .. } + | BlobLocationItem::Proxy { size } => *size, + }; + let requester = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + let source = resolved.sources.get(*source_index).ok_or_else(|| { + Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + } + })?; + let proxy = self.blob_range_requester_with_identity( + column, + *row_id, + read_snapshot, + identity.as_deref(), + ); + let context = self.blob_locations_context( + column, + Some(resolved.version), + self.branch.clone(), + None, + identity.clone(), + None, + ); + Some(Arc::new(PresignedBlobRangeRequester::new( + context, + *row_id, + *size, + self.client.blob_presign_threshold_bytes, + proxy, + source, + *offset, + )) as Arc) + } + BlobLocationItem::Inline { .. } | BlobLocationItem::Proxy { .. } => { + Some(self.blob_range_requester_with_identity( + column, + *row_id, + read_snapshot, + identity.as_deref(), + )) + } + }; + handles.insert(*row_id, ResolvedBlobHandle { size, requester }); + } + } + Ok(Some(handles)) + } + pub(super) async fn open_blob_file_impl( &self, descriptor: &BlobDescriptor, @@ -1062,15 +2455,26 @@ impl RemoteTable { }, ..Default::default() }; - let requester = self.blob_range_requester_with_source( + let proxy_requester = self.blob_range_requester_with_source( &source.column, source.row_reference, &snapshot, Some(source), ); + let descriptor_kind = BlobKind::try_from(descriptor.kind).unwrap_or(BlobKind::External); + let direct_candidate = self.blob_locations_supported.load(Ordering::Relaxed) + && descriptor.size >= self.client.blob_presign_threshold_bytes + && is_direct_blob_kind(descriptor_kind); + if direct_candidate + && let Some(file) = self + .open_blob_file_from_locations(descriptor, source, snapshot) + .await? + { + return Ok(file); + } let size = if descriptor.kind == 3 && descriptor.size == 0 { - let metadata = requester - .request_range("", RangeRequestMode::MetadataRead, Some(source.version)) + let metadata = proxy_requester + .request_range(0..0, RangeRequestMode::MetadataRead, Some(source.version)) .await?; if metadata.response.status() != StatusCode::OK { return Err(Error::InvalidInput { @@ -1089,22 +2493,122 @@ impl RemoteTable { } else { descriptor.size }; - Ok(RemoteBlobFile::new(requester, size, Some(source.version)).into()) + Ok(RemoteBlobFile::new(proxy_requester, size, Some(source.version)).into()) + } + + async fn open_blob_file_from_locations( + &self, + descriptor: &BlobDescriptor, + source: &BlobDescriptorSource, + snapshot: ReadSnapshot, + ) -> Result> { + let context = self.blob_locations_context_for_source(source); + let resolved = match context.resolve(&[source.row_reference], false).await { + Ok(resolved) => resolved, + Err(Error::Http { + status_code: Some(StatusCode::SERVICE_UNAVAILABLE), + .. + }) => { + log::warn!( + "blob_locations is unavailable (503); opening this descriptor on the proxy path" + ); + return Ok(None); + } + Err(error) => return Err(error), + }; + let proxy_requester = self.blob_range_requester_with_source_and_identity( + &source.column, + source.row_reference, + &snapshot, + Some(source), + resolved + .identity + .clone() + .or_else(|| self.expected_query_snapshot.clone()), + ); + let item = + resolved + .items + .into_iter() + .next() + .flatten() + .ok_or_else(|| Error::InvalidInput { + message: "non-null blob descriptor did not resolve to a stored value".into(), + })?; + let size = match &item { + BlobLocationItem::Presigned { size, .. } + | BlobLocationItem::Inline { size, .. } + | BlobLocationItem::Proxy { size } => *size, + }; + if size != descriptor.size { + return Err(Error::InvalidInput { + message: format!( + "blob descriptor size {} differs from resolved size {size}", + descriptor.size + ), + }); + } + let requester: Arc = match item { + BlobLocationItem::Presigned { + source_index, + offset, + size, + } => { + let source_info = + resolved + .sources + .get(source_index) + .ok_or_else(|| Error::InvalidInput { + message: format!( + "blob_locations references source {source_index} of {}", + resolved.sources.len() + ), + })?; + Arc::new(PresignedBlobRangeRequester::new( + self.blob_locations_context_for_source(source), + source.row_reference, + size, + self.client.blob_presign_threshold_bytes, + proxy_requester, + source_info, + offset, + )) + } + BlobLocationItem::Inline { .. } | BlobLocationItem::Proxy { .. } => proxy_requester, + }; + Ok(Some( + RemoteBlobFile::new(requester, size, Some(source.version)).into(), + )) } /// Probe each row once for its size. /// - /// Serves callers that must not issue a query, such as a single blob that - /// the whole-byte route could not return. + /// Serves callers that must not issue a descriptor query, such as a single + /// blob that the whole-byte route could not return. Direct resolution is + /// only used when the caller wants it and the server advertises it. async fn fetch_blob_files_with_snapshot( &self, column: &str, row_ids: &[u64], read_snapshot: ReadSnapshot, + prefer_direct: bool, + identity: Option, ) -> Result>> { + if prefer_direct && self.blob_locations_supported.load(Ordering::Relaxed) { + return self + .fetch_blob_files_with_route(column, row_ids, true, Some(read_snapshot), identity) + .await; + } let requesters = row_ids .iter() - .map(|row_id| self.blob_range_requester(column, *row_id, &read_snapshot)) + .map(|row_id| { + self.blob_range_requester_with_identity( + column, + *row_id, + &read_snapshot, + identity.as_deref(), + ) + }) .collect(); match probe_blob_files(requesters).await { Ok(files) => Ok(files), @@ -1211,6 +2715,18 @@ impl RemoteTable { .get(&VERSION_HEADER) .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse().ok()); + if let (Some(expected), Some(actual)) = (read_snapshot.version, response_version) + && expected != actual + { + return Err(Error::Http { + source: format!( + "blob descriptor take read version {actual}, expected pinned version {expected}" + ) + .into(), + request_id, + status_code: None, + }); + } let mut stream = self.read_arrow_response(&request_id, response).await?; let mut sizes = HashMap::with_capacity(row_ids.len()); @@ -1263,13 +2779,58 @@ impl RemoteTable { } } - fn blob_range_requester( + fn blob_locations_context( + &self, + column: &str, + version: Option, + branch: Option, + source: Option<&BlobDescriptorSource>, + identity: Option, + freshness: Option, + ) -> BlobLocationsContext { + BlobLocationsContext { + client: self.client.clone(), + identifier: self.identifier.clone(), + table_name: self.name.clone(), + column: column.to_string(), + version, + branch: source.map_or(branch, |source| source.branch.clone()), + source_uri: source.map(|source| source.uri.clone()), + source_commit_micros: source.map(|source| source.committed_at_micros), + row_is_address: source.is_some_and(|source| source.row_is_address), + expected_query_snapshot: identity, + freshness, + } + } + + fn blob_locations_context_for_source( + &self, + source: &BlobDescriptorSource, + ) -> BlobLocationsContext { + self.blob_locations_context( + &source.column, + Some(source.version), + source.branch.clone(), + Some(source), + self.expected_query_snapshot.clone(), + None, + ) + } + + fn blob_range_requester_with_identity( &self, column: &str, row_id: u64, read_snapshot: &ReadSnapshot, + identity: Option<&str>, ) -> Arc { - self.blob_range_requester_with_source(column, row_id, read_snapshot, None) + self.blob_range_requester_with_source_and_identity( + column, + row_id, + read_snapshot, + None, + identity.map(str::to_owned), + ) } fn blob_range_requester_with_source( @@ -1278,6 +2839,23 @@ impl RemoteTable { row_id: u64, read_snapshot: &ReadSnapshot, source: Option<&BlobDescriptorSource>, + ) -> Arc { + self.blob_range_requester_with_source_and_identity( + column, + row_id, + read_snapshot, + source, + self.expected_query_snapshot.clone(), + ) + } + + fn blob_range_requester_with_source_and_identity( + &self, + column: &str, + row_id: u64, + read_snapshot: &ReadSnapshot, + source: Option<&BlobDescriptorSource>, + identity: Option, ) -> Arc { let path = format!( "/v1/table/{}/blob/{}/{row_id}/bytes", @@ -1290,7 +2868,7 @@ impl RemoteTable { version: read_snapshot.version, branch: source.map_or_else(|| self.branch.clone(), |source| source.branch.clone()), source_uri: source.map(|source| source.uri.clone()), - expected_query_snapshot: self.expected_query_snapshot.clone(), + expected_query_snapshot: identity, source_commit_micros: source.map(|source| source.committed_at_micros), row_is_address: source.is_some_and(|source| source.row_is_address), freshness: Arc::new(std::sync::Mutex::new(read_snapshot.freshness_state)), @@ -1305,12 +2883,42 @@ impl RemoteTable { #[derive(Debug, Clone, Copy)] enum DescriptorSize { Null, - Known(u64), + Known { + kind: BlobKind, + size: u64, + }, /// An external blob that recorded no size. Its length is the whole /// object's, which only the server can resolve. Unresolved, } +/// A resolved handle candidate. `requester` is `None` only when the server +/// resolved a non-null descriptor to null, which is a protocol error. +struct ResolvedBlobHandle { + size: u64, + requester: Option>, +} + +/// A row's resolved backing object for a large range request. +enum BlobRangeLocation { + Null, + Presigned { + source: BlobLocationSource, + offset: u64, + size: u64, + }, + Proxy, +} + +/// Blob kinds that M1 may read directly. Inline bytes stay on the proxy route, +/// and External URIs keep their existing authority and lifecycle. +fn is_direct_blob_kind(kind: BlobKind) -> bool { + matches!( + kind, + BlobKind::Dedicated | BlobKind::Packed | BlobKind::Managed | BlobKind::ManagedWithBase + ) +} + /// The `kind` and `size` children of a blob v2 descriptor array. struct BlobDescriptorSizes<'a> { descriptors: &'a StructArray, @@ -1337,7 +2945,7 @@ impl<'a> BlobDescriptorSizes<'a> { Ok(if kind == BlobKind::External && size == 0 { DescriptorSize::Unresolved } else { - DescriptorSize::Known(size) + DescriptorSize::Known { kind, size } }) } } @@ -1376,9 +2984,10 @@ async fn probe_blob_file(requester: Arc) -> Result { @@ -1468,6 +3077,10 @@ mod tests { use super::*; const PAYLOAD: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz"; + const TEST_SNAPSHOT_IDENTITY: &str = + "v1:0000000000000000000000000000000000000000000000000000000000000000"; + const SNAPSHOT_A: &str = "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const SNAPSHOT_B: &str = "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; fn null_blob_response() -> http::Response> { http::Response::builder() @@ -1685,7 +3298,7 @@ mod tests { row_ids: &[u64], ) -> Result>> { let read_snapshot = self.snapshot_read_state().await; - self.fetch_blob_files_with_snapshot(column, row_ids, read_snapshot) + self.fetch_blob_files_with_snapshot(column, row_ids, read_snapshot, false, None) .await } } @@ -1737,6 +3350,7 @@ mod tests { assert_eq!(body["with_row_id"], serde_json::json!(true)); assert_eq!(body["use_rte"], serde_json::json!(false)); let requested = filter_row_ids(body["filter"].as_str().unwrap()); + let requested_version = body["version"].as_u64(); captured.lock().unwrap().push(TakeMockRequest::Query { row_ids: requested.clone(), version: body["version"].as_u64(), @@ -1768,7 +3382,9 @@ mod tests { writer.finish().unwrap(); drop(writer); let mut response = http::Response::builder().status(200); - if let Some(version) = query_version { + if let Some(version) = requested_version { + response = response.header(VERSION_HEADER, version.to_string()); + } else if let Some(version) = query_version { response = response.header(VERSION_HEADER, version); } return response.body(body).unwrap(); @@ -2904,11 +4520,11 @@ mod tests { impl BlobRangeRequester for CountingProbeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { - assert_eq!(range_header, "bytes=0-0"); + assert_eq!(range, 0..1); let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1; self.max_in_flight.fetch_max(now, Ordering::SeqCst); // Earlier probes sleep longer, so later probes finish first and the @@ -3086,7 +4702,7 @@ mod tests { impl BlobRangeRequester for CountingRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { @@ -3094,13 +4710,8 @@ mod tests { self.max_in_flight.fetch_max(now, Ordering::SeqCst); tokio::time::sleep(Duration::from_millis(5)).await; self.in_flight.fetch_sub(1, Ordering::SeqCst); - let (start, end) = range_header - .strip_prefix("bytes=") - .unwrap() - .split_once('-') - .unwrap(); - let start = start.parse::().unwrap(); - let end = end.parse::().unwrap(); + let start = range.start as usize; + let end = (range.end - 1) as usize; let response = http::Response::builder() .status(StatusCode::PARTIAL_CONTENT) .header( @@ -3311,17 +4922,12 @@ mod tests { impl BlobRangeRequester for BlockingRangeRequester { async fn request_range( &self, - range_header: &str, + range: Range, _mode: RangeRequestMode, _version: Option, ) -> Result { - let (start, end) = range_header - .strip_prefix("bytes=") - .unwrap() - .split_once('-') - .unwrap(); - let start: usize = start.parse().unwrap(); - let end: usize = end.parse().unwrap(); + let start = range.start as usize; + let end = (range.end - 1) as usize; if start == self.block_start { self.started.notify_one(); self.release.wait().await; @@ -3384,4 +4990,1302 @@ mod tests { .contains("already closed") ); } + + fn blob_ipc_stream(values: &[Option<&[u8]>], column: &str) -> Vec { + let array = LargeBinaryArray::from(values.to_vec()); + let batch = + RecordBatch::try_from_iter([(column, Arc::new(array) as Arc)]).unwrap(); + let mut bytes = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + bytes + } + + fn blob_locations_json(body: serde_json::Value, version: u64) -> http::Response> { + http::Response::builder() + .status(200) + .header(VERSION_HEADER, version.to_string()) + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body(body.to_string().into_bytes()) + .unwrap() + } + + fn direct_blob_file_table( + kind: BlobKind, + size: u64, + object_handler: F, + ) -> RemoteTable + where + F: Fn(reqwest::Request) -> http::Response> + Send + Sync + 'static, + { + RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return object_handler(request); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some((kind, size))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([10])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10])); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(body["include_inline_data"], serde_json::json!(false)); + return blob_locations_json( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + "expires_at_unix_secs": 4102444800u64, + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": size, + }], + }), + 7, + ); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!( + request + .url() + .query_pairs() + .find(|(name, _)| name == "version") + .map(|(_, value)| value.into_owned()), + Some("7".to_string()) + ); + let response = range_response(&request, PAYLOAD); + let content_range = response.headers()[header::CONTENT_RANGE].clone(); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, content_range) + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .header(VERSION_HEADER, "7") + .body(response.into_body()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ) + } + + #[tokio::test] + async fn describe_seeds_blob_locations_capability() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + |_| { + http::Response::builder() + .status(200) + .header("x-lancedb-blob-locations", "1") + .body(r#"{"version":1,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + table.describe().await.unwrap(); + assert!( + table + .blob_locations_supported + .load(std::sync::atomic::Ordering::Relaxed) + ); + } + + #[tokio::test] + async fn direct_blob_file_translates_physical_offsets_and_preserves_nulls() { + let object_requests = Arc::new(StdMutex::new(Vec::new())); + let captured = object_requests.clone(); + let table = + direct_blob_file_table(BlobKind::Packed, PAYLOAD.len() as u64, move |request| { + assert_eq!(request.method(), reqwest::Method::GET); + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=106-110" + ); + assert!(request.headers().get("authorization").is_none()); + assert!(request.headers().get("x-api-key").is_none()); + captured.lock().unwrap().push(request.url().to_string()); + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 106-110/500") + .body(PAYLOAD[6..11].to_vec()) + .unwrap() + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!( + file.read_range(6..11).await.unwrap().as_ref(), + &PAYLOAD[6..11] + ); + assert_eq!(object_requests.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn direct_blob_file_small_ranges_stay_on_the_proxy() { + let table = direct_blob_file_table(BlobKind::Managed, PAYLOAD.len() as u64, |_| { + panic!("small range must not read from object storage") + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!( + file.read_range(6..11).await.unwrap().as_ref(), + &PAYLOAD[6..11] + ); + } + + #[tokio::test] + async fn direct_blob_file_rejects_mismatched_content_range() { + let table = direct_blob_file_table(BlobKind::Packed, PAYLOAD.len() as u64, |_| { + http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-104/500") + .body(PAYLOAD[..5].to_vec()) + .unwrap() + }); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + let error = file.read_range(6..11).await.unwrap_err(); + assert!(error.to_string().contains("Content-Range"), "{error}"); + } + + #[tokio::test] + async fn direct_blob_file_refreshes_expired_url_once() { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let locations = Arc::new(AtomicUsize::new(0)); + let captured_locations = locations.clone(); + let object = Arc::new(AtomicUsize::new(0)); + let captured_object = object.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + let call = captured_object.fetch_add(1, Ordering::SeqCst) + 1; + if request + .url() + .query() + .is_some_and(|query| query.contains("sig=old")) + { + return http::Response::builder() + .status(StatusCode::FORBIDDEN) + .body(Vec::new()) + .unwrap(); + } + assert_eq!(call, 2); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-104/500") + .body(PAYLOAD[..5].to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some(( + BlobKind::Packed, + PAYLOAD.len() as u64, + ))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([10])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let call = captured_locations.fetch_add(1, Ordering::SeqCst) + 1; + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + let sig = if call == 1 { "old" } else { "new" }; + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": format!("https://objects.example/sidecar.blob?sig={sig}"), + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let mut files = table.fetch_blob_files_impl("image", &[10]).await.unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!(file.read_range(0..5).await.unwrap().as_ref(), &PAYLOAD[..5]); + assert_eq!(locations.load(Ordering::SeqCst), 2); + assert_eq!(object.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn fetch_blobs_reads_large_presigned_inline_and_proxy_rows_in_order() { + const IDENTITY: &str = + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let proxied = Arc::new(StdMutex::new(Vec::new())); + let captured_proxied = proxied.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=100-135" + ); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-135/500") + .body(PAYLOAD.to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10, 20, 30, 40])); + assert_eq!(body["include_inline_data"], serde_json::json!(true)); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [ + { "kind": "presigned", "source_index": 0, "offset": 100, "size": PAYLOAD.len() }, + { "kind": "inline", "size": 4, "data_base64": "AQIDBA==" }, + { "kind": "proxy", "size": PAYLOAD.len() }, + null + ], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([30])); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + captured_proxied.lock().unwrap().push(30); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table + .fetch_blobs_impl("image", &[10, 20, 30, 40]) + .await + .unwrap(); + assert_eq!( + blobs, + LargeBinaryArray::from(vec![ + Some(PAYLOAD), + Some(b"\x01\x02\x03\x04".as_slice()), + Some(PAYLOAD), + None, + ]) + ); + assert_eq!(*proxied.lock().unwrap(), [30]); + } + + #[tokio::test] + async fn fetch_blobs_keeps_small_presigned_values_on_the_proxy() { + let proxied = Arc::new(StdMutex::new(Vec::new())); + let captured_proxied = proxied.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("small presigned value must not use object storage"); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + captured_proxied.lock().unwrap().push(10); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 100; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + assert_eq!(*proxied.lock().unwrap(), [10]); + } + + #[tokio::test] + async fn fetch_blob_ranges_routes_large_ranges_direct_and_small_ranges_proxy() { + const IDENTITY: &str = + "v1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + assert_eq!( + request.headers().get(header::RANGE).unwrap(), + "bytes=100-109" + ); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 100-109/500") + .body(PAYLOAD[..10].to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["row_ids"], serde_json::json!([10, 30, 40])); + assert_eq!(body["include_inline_data"], serde_json::json!(false)); + assert_eq!(body["version"], serde_json::Value::Null); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [ + { "kind": "presigned", "source_index": 0, "offset": 100, "size": PAYLOAD.len() }, + { "kind": "proxy", "size": PAYLOAD.len() }, + null + ], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blob_ranges/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + assert_eq!( + body["ranges"], + serde_json::json!([ + { "row_id": 20, "offset": 0, "length": 9 }, + { "row_id": 30, "offset": 0, "length": 12 }, + ]) + ); + let body = + blob_ipc_stream(&[Some(&PAYLOAD[..9]), Some(&PAYLOAD[..12])], "value"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 10), + BlobRangeRequest::new(20, 0, 9), + BlobRangeRequest::new(30, 0, 12), + BlobRangeRequest::new(40, 0, 10), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![ + Some(&PAYLOAD[..10]), + Some(&PAYLOAD[..9]), + Some(&PAYLOAD[..12]), + None, + ]) + ); + } + + #[tokio::test] + async fn fetch_blob_ranges_falls_back_to_proxy_when_locations_lose_their_plan() { + const IDENTITY: &str = + "v1:dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blob_ranges/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!( + body["ranges"], + serde_json::json!([ + { "row_id": 10, "offset": 0, "length": 10 }, + { "row_id": 20, "offset": 0, "length": 1 }, + ]) + ); + let body = + blob_ipc_stream(&[Some(&PAYLOAD[..10]), Some(&PAYLOAD[..1])], "value"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 10), + BlobRangeRequest::new(20, 0, 1), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(&PAYLOAD[..10]), Some(&PAYLOAD[..1])]) + ); + } + + #[tokio::test] + async fn fetch_blob_ranges_small_only_batches_never_resolve_locations() { + const IDENTITY: &str = + "v1:eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + assert_ne!(path, "/v1/table/my_table/blob_locations/"); + assert_eq!(path, "/v1/table/my_table/fetch_blob_ranges/"); + let body = blob_ipc_stream(&[Some(&PAYLOAD[..1]), Some(&PAYLOAD[1..2])], "value"); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(body) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 10; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + table.seed_blob_locations_capability(&headers); + + let ranges = table + .fetch_blob_ranges( + "image", + &[ + BlobRangeRequest::new(10, 0, 1), + BlobRangeRequest::new(20, 1, 1), + ], + ) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(&PAYLOAD[..1]), Some(&PAYLOAD[1..2])]) + ); + } + + #[tokio::test] + async fn fetch_blobs_falls_back_to_proxy_when_locations_lose_their_plan() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + assert_eq!(path, "/v1/table/my_table/fetch_blobs/"); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .body(body) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + } + + #[tokio::test] + async fn blob_file_resolver_503_after_pinning_keeps_version_and_identity_on_proxy() { + const IDENTITY: &str = + "v1:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let requested = filter_row_ids(body["filter"].as_str().unwrap()); + let rows = requested + .iter() + .map(|row_id| (*row_id, Some((BlobKind::Packed, PAYLOAD.len() as u64)))) + .collect::>(); + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors( + &rows.iter().map(|(_, row)| *row).collect::>(), + )) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values( + rows.iter().map(|(row_id, _)| *row_id), + )) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + if path == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let requested = body["row_ids"].as_array().unwrap().len(); + if requested != MAX_FETCH_BLOBS_ROW_IDS { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + let items = (0..requested) + .map(|_| { + serde_json::json!({ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }) + }) + .collect::>(); + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": items, + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/0/bytes" { + let parameters = request + .url() + .query_pairs() + .into_owned() + .collect::>(); + assert_eq!(parameters["version"], "7"); + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], IDENTITY); + let response = range_response(&request, PAYLOAD); + let content_range = response.headers()[header::CONTENT_RANGE].clone(); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, content_range) + .header(QUERY_SNAPSHOT_HEADER, IDENTITY) + .header(VERSION_HEADER, "7") + .body(response.into_body()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let row_ids = (0..MAX_FETCH_BLOBS_ROW_IDS as u64 + 1).collect::>(); + let files = table + .fetch_blob_files_impl("image", &row_ids) + .await + .unwrap(); + assert_eq!(files.len(), row_ids.len()); + let file = files[0].as_ref().unwrap(); + assert_eq!(file.read_range(0..1).await.unwrap().as_ref(), &PAYLOAD[..1]); + } + + #[tokio::test] + async fn oversized_whole_blob_fallback_after_resolver_503_does_not_resolve_again() { + let locations = Arc::new(AtomicUsize::new(0)); + let captured_locations = locations.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("proxy fallback must not use object storage"); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + captured_locations.fetch_add(1, Ordering::SeqCst); + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/describe/" { + return http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + return http::Response::builder() + .status(StatusCode::BAD_REQUEST) + .body( + "fetch_blobs accepts at most 64 MiB of total blob bytes per request" + .as_bytes() + .to_vec(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + return range_response(&request, PAYLOAD); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let blobs = table.fetch_blobs_impl("image", &[10]).await.unwrap(); + assert_eq!(blobs, LargeBinaryArray::from(vec![Some(PAYLOAD)])); + assert_eq!(locations.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn object_store_503_does_not_masquerade_as_resolver_unavailable() { + let proxy_calls = Arc::new(AtomicUsize::new(0)); + let captured_proxy = proxy_calls.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + return http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, TEST_SNAPSHOT_IDENTITY) + .body( + serde_json::json!({ + "sources": [{ + "url": "https://objects.example/sidecar.blob?sig=test", + }], + "items": [{ + "kind": "presigned", + "source_index": 0, + "offset": 100, + "size": PAYLOAD.len(), + }], + }) + .to_string() + .into_bytes(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + captured_proxy.fetch_add(1, Ordering::SeqCst); + let body = blob_ipc_stream(&[Some(PAYLOAD)], "image"); + return http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .body(body) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 13, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + + let error = table.fetch_blobs_impl("image", &[10]).await.unwrap_err(); + assert_eq!(error.status_code(), Some(StatusCode::SERVICE_UNAVAILABLE)); + assert_eq!(proxy_calls.load(Ordering::SeqCst), 0); + } + + fn location_response( + identity: Option<&str>, + item: serde_json::Value, + ) -> http::Response> { + location_response_count(identity, item, 1) + } + + fn location_response_count( + identity: Option<&str>, + item: serde_json::Value, + count: usize, + ) -> http::Response> { + let mut response = http::Response::builder() + .status(200) + .header(VERSION_HEADER, "7"); + if let Some(identity) = identity { + response = response.header(QUERY_SNAPSHOT_HEADER, identity); + } + response + .body( + serde_json::json!({ + "sources": [{"url": "https://objects.example/object"}], + "items": vec![item; count], + }) + .to_string() + .into_bytes(), + ) + .unwrap() + } + + fn descriptor_take_response(version: u8, row_id: u64) -> http::Response> { + let batch = RecordBatch::try_from_iter([ + ( + "image", + Arc::new(descriptors(&[Some((BlobKind::Packed, 1))])) as Arc, + ), + ( + ROW_ID, + Arc::new(UInt64Array::from_iter_values([row_id])) as Arc, + ), + ]) + .unwrap(); + let mut body = Vec::new(); + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + http::Response::builder() + .status(200) + .header(VERSION_HEADER, version.to_string()) + .body(body) + .unwrap() + } + + #[tokio::test] + async fn resolver_rejects_a_response_without_a_snapshot_identity() { + let object_calls = Arc::new(AtomicUsize::new(0)); + let captured_object = object_calls.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + captured_object.fetch_add(1, Ordering::SeqCst); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .body(b"A".to_vec()) + .unwrap(); + } + if request.url().path() == "/v1/table/my_table/blob_locations/" { + return location_response( + None, + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + + let error = table + .fetch_blob_ranges_impl("image", &[BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap_err(); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + assert_eq!(object_calls.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn resolver_rejects_a_different_identity_in_a_later_partition() { + let resolves = Arc::new(AtomicUsize::new(0)); + let captured_resolves = resolves.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + panic!("no object read should happen after an identity mismatch"); + } + if request.url().path() == "/v1/table/my_table/blob_locations/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + let count = body["row_ids"].as_array().unwrap().len(); + let call = captured_resolves.fetch_add(1, Ordering::SeqCst); + let identity = if call == 0 { SNAPSHOT_A } else { SNAPSHOT_B }; + return location_response_count( + Some(identity), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + count, + ); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + let requests = (0..=MAX_FETCH_BLOBS_ROW_IDS as u64) + .map(|row_id| BlobRangeRequest::new(row_id, 0, 1)) + .collect::>(); + let error = table + .fetch_blob_ranges_impl("image", &requests) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + fn refresh_503_table() -> RemoteTable { + let resolves = Arc::new(AtomicUsize::new(0)); + let mut table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::FORBIDDEN) + .body(Vec::new()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/blob_locations/" { + if resolves.fetch_add(1, Ordering::SeqCst) == 0 { + return location_response( + Some(SNAPSHOT_A), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + return http::Response::builder() + .status(StatusCode::SERVICE_UNAVAILABLE) + .body(Vec::new()) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, SNAPSHOT_B) + .body(b"B".to_vec()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + table.seed_blob_ranges_capability(&headers); + table + } + + #[tokio::test] + async fn whole_read_proxy_fallback_after_refresh_503_keeps_resolver_identity() { + let error = refresh_503_table() + .fetch_blobs_impl("image", &[10]) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn range_read_proxy_fallback_after_refresh_503_keeps_resolver_identity() { + let error = refresh_503_table() + .fetch_blob_ranges_impl("image", &[BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn oversized_proxy_fallback_keeps_resolver_identity() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path(); + if path == "/v1/table/my_table/describe/" { + return http::Response::builder() + .status(200) + .body(r#"{"version":7,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap(); + } + if path == "/v1/table/my_table/fetch_blobs/" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::BAD_REQUEST) + .body( + b"fetch_blobs accepts at most 64 MiB of total blob bytes per request" + .to_vec(), + ) + .unwrap(); + } + if path == "/v1/table/my_table/blob/image/10/bytes" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .header(VERSION_HEADER, "7") + .header(QUERY_SNAPSHOT_HEADER, SNAPSHOT_B) + .body(b"B".to_vec()) + .unwrap(); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let error = table + .fetch_blobs_proxy_array("image", &[10], snapshot, Some(SNAPSHOT_A.into())) + .await + .unwrap_err(); + assert!( + error + .to_string() + .contains("did not verify the query snapshot identity"), + "{error}" + ); + } + + #[tokio::test] + async fn direct_open_keeps_the_supplied_snapshot_when_capability_appears() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().path() == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + return descriptor_take_response(8, 20); + } + panic!("unexpected request: {}", request.url().path()); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let error = table + .fetch_blob_files_with_snapshot("image", &[20], snapshot, true, Some(SNAPSHOT_A.into())) + .await + .unwrap_err(); + assert!( + error.to_string().contains("expected pinned version 7"), + "{error}" + ); + } + + #[tokio::test] + async fn direct_open_succeeds_at_the_supplied_snapshot() { + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + if request.url().host_str() == Some("objects.example") { + return http::Response::builder() + .status(StatusCode::PARTIAL_CONTENT) + .header(header::CONTENT_RANGE, "bytes 0-0/1") + .body(b"A".to_vec()) + .unwrap(); + } + let path = request.url().path(); + if path == "/v1/table/my_table/query/" { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()) + .unwrap(); + assert_eq!(body["version"], serde_json::json!(7)); + return descriptor_take_response(7, 20); + } + if path == "/v1/table/my_table/blob_locations/" { + assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], SNAPSHOT_A); + return location_response( + Some(SNAPSHOT_A), + serde_json::json!({ + "kind": "presigned", "source_index": 0, "offset": 0, "size": 1 + }), + ); + } + panic!("unexpected request: {path}"); + }, + Some(Version::new(1, 15, 0)), + ); + let mut table = table; + table.client.blob_presign_threshold_bytes = 1; + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-locations", "1".parse().unwrap()); + table.seed_blob_locations_capability(&headers); + let snapshot = ReadSnapshot { + version: Some(7), + ..Default::default() + }; + let mut files = table + .fetch_blob_files_with_snapshot("image", &[20], snapshot, true, Some(SNAPSHOT_A.into())) + .await + .unwrap(); + let file = files.pop().unwrap().unwrap(); + assert_eq!(file.read_range(0..1).await.unwrap().as_ref(), b"A"); + } } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index c85049be5..aa6b68747 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1552,6 +1552,12 @@ impl Table { /// # } /// ``` /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// Blobs inside lists cannot be fetched by row id. Returns /// [`Error::InvalidInput`] for those paths, when the column does not exist, /// or when it is not a blob column. Returns [`Error::NotSupported`] on @@ -1603,6 +1609,12 @@ impl Table { /// # } /// ``` /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// Returns an error when a range is invalid, a requested row id does not /// exist, or the column is not a blob column. Returns /// [`Error::NotSupported`] on table types without blob support. @@ -1630,6 +1642,12 @@ impl Table { /// `ClientConfig::blob_request_concurrency` or the /// `LANCE_CLIENT_BLOB_REQUEST_CONCURRENCY` environment variable to tune it. /// + /// On LanceDB Enterprise clusters that enable direct Blob reads, large + /// values and individual ranges may be fetched from short-lived object-store + /// URLs instead of the LanceDB proxy. Clients then need network access to + /// the object-store endpoint, including private endpoint routing, DNS, TLS + /// trust and egress rules, in addition to the LanceDB endpoint. Small reads + /// stay on the LanceDB proxy. /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no /// partial handles are returned. @@ -1657,7 +1675,10 @@ impl Table { /// /// The descriptor carries its table version, branch, column and row identity. /// Opening does not materialize the payload or change this table's checkout. - /// Remote reads use the table's authenticated HTTP byte-range endpoint. + /// On Enterprise clusters that enable direct Blob reads, large range reads + /// may use a short-lived object-store URL; the client needs network access + /// to that endpoint in addition to the LanceDB endpoint. Small reads stay + /// on the authenticated LanceDB byte-range endpoint. /// /// ``` /// use lancedb::{Table, blob::BlobDescriptor};