diff --git a/Cargo.lock b/Cargo.lock index d4d6fdeb1..19678c930 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -193,9 +193,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.1" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" dependencies = [ "async-task", "concurrent-queue", diff --git a/api_changes/update_261104_stream_chunks_incrementally.md b/api_changes/update_261104_stream_chunks_incrementally.md new file mode 100644 index 000000000..c468d9479 --- /dev/null +++ b/api_changes/update_261104_stream_chunks_incrementally.md @@ -0,0 +1,29 @@ +This update makes download streams return each decompressed chunk as soon as it arrives, instead of after the whole xorb block (one HTTP range, often a ~64 MB xorb) has downloaded. Clients now write a block's decompressed chunks into a shared buffer that a term's readers consume while the download is still running. + +What changed +- New public type `xet_client::cas_client::XorbBlockData`: one block's decompressed data in a single fixed-size allocation. One writer appends chunks in order, moving a "ready" mark forward; readers take zero-copy `Bytes` of any range below the mark. Also new: `BlockByteRange` (a byte range anchored at a chunk index) and `ReadAmount` (`Available` / `All`). + - Constructors: `XorbBlockData::with_exact_size(size)` (checked by `finish`) and `XorbBlockData::with_size_bound(max_size)`. + - Writer side: `append_chunks(data, chunk_offsets)`, `append_compressed_chunk(header, compressed)`, `append_serialized_chunks(serialized, &mut skip_chunks)`, `finish()`, `fail(Arc)`. + - Reader side: `try_read`, `read` (async), `read_blocking` (not on wasm), `contents()` once complete, plus `num_chunks`, `ready_bytes`, `capacity`. +- `Client::get_file_term_data` signature changed: + - Before: `get_file_term_data(url_info, download_permit, progress_callback, uncompressed_size_if_known: Option) -> Result<(Bytes, Vec)>` + - After: `get_file_term_data(url_info, download_permit, progress_callback, output: Arc) -> Result<()>` + - Implementations append each chunk to `output` as it is decoded and do not call `finish`/`fail`; the caller does. A retried request must skip the chunks already appended (`output.num_chunks()` minus the count at the start of the call): signed URLs only allow the exact signed `Range`, so the retry downloads the whole range again. + - The size check moved out of the client: `XorbBlockData::finish` fails if a block created `with_exact_size` has a different size. A mismatch is no longer retried. +- `RemoteClient` decodes non-multipart bodies chunk by chunk into `output`; a retry after a partial body skips the chunks already appended. Multipart bodies are still read in full, then decoded part by part. +- `xet_core_structures::xorb_object`: new `decompress_chunk_into(header, compressed, out)`; `deserialize_async::try_read_chunk_header_async` is now public. +- `xet_data::file_reconstruction`: + - `XorbBlockData` is no longer defined or exported here (it moved to `xet_client::cas_client`). `XorbBlock::data` is now `Arc` (was `OnceCell>`), built by the new `XorbBlock::new(xorb_hash, chunk_ranges, xorb_block_index, references) -> Result`. New `XorbBlock::determine_size_bound` sizes a block whose terms overlap; a block that no set of terms covers is rejected as `CorruptedReconstruction`. + - `DataFuture` is removed. `DataWriter::set_next_term_data_source` takes `reader: TermReader` (new public type, exported from `xet_data::file_reconstruction`) instead of `data_future: DataFuture`. Writers check the reader's length against the byte range when the term is queued. + - `FileTerm::get_data_task` and `FileTerm::extract_bytes` are removed; terms are read through `TermReader`. + - `DownloadStream::next` / `blocking_next` and `UnorderedDownloadStream::next` / `blocking_next` may now return a term in several pieces. The unordered stream's offsets are each piece's own offset. + +Why this matters +- Streams such as `huggingface_hub` Parquet / WebDataset readers waited for a whole xorb block before receiving any bytes (16 to 25 s to first byte on laptops). They now get the first chunk after about one round trip plus one ~64 KB chunk. +- Non-stream paths (`reconstruct_to_file`, `reconstruct_to_writer`) still write each term once it is fully ready, as one zero-copy `Bytes`. Chunks are now decompressed straight into the block buffer instead of into a per-chunk `Vec` that was then copied. + +Migration +- Custom `Client` implementations: change `get_file_term_data` to the new signature. Decode each requested range and call `output.append_serialized_chunks(&serialized_range, &mut 0)?` (or `append_compressed_chunk` per chunk for streamed bodies), and return `Ok(())`. Wrappers forward `output` unchanged. +- Callers of `get_file_term_data`: create `Arc::new(XorbBlockData::with_exact_size(n))` (or `with_size_bound`), pass a clone, then call `output.finish()?` and read with `output.contents()` or the read methods. +- Code that implemented or called `DataWriter`: pass a `TermReader` (from `FileTerm::start_read`, crate-internal) instead of a `DataFuture`. +- Stream consumers must not assume one returned `Bytes` per term. diff --git a/xet_client/src/cas_client/interface.rs b/xet_client/src/cas_client/interface.rs index c98ec716a..248f854fe 100644 --- a/xet_client/src/cas_client/interface.rs +++ b/xet_client/src/cas_client/interface.rs @@ -9,6 +9,7 @@ use super::adaptive_concurrency::ConnectionPermit; use super::progress_tracked_streams::ProgressCallback; #[cfg(not(target_family = "wasm"))] use super::telemetry::TransferTelemetry; +use super::xorb_block_data::XorbBlockData; use crate::cas_types::{ BatchQueryReconstructionResponse, FileChunkHashesResponse, FileRange, HttpRange, QueryReconstructionResponseV2, ShardUploadEvent, @@ -65,15 +66,20 @@ pub trait Client: Send + Sync { async fn acquire_download_permit(&self) -> Result; + /// Downloads one xorb block and appends its decompressed chunks to `output`, in order, as each is decoded. + /// + /// Readers of `output` can consume the chunks while the download is still running. A chunk is appended at most + /// once: if a request is retried after some chunks were appended, those chunks are skipped in the retried + /// response. The caller marks `output` finished or failed once this returns. + /// /// Optional progress callback receives (delta, completed, total) in transfer bytes. - /// When [uncompressed_size_if_known] is [Some], the returned Bytes must have len() equal to that value. async fn get_file_term_data( &self, url_info: Box, download_permit: ConnectionPermit, progress_callback: Option, - uncompressed_size_if_known: Option, - ) -> Result<(Bytes, Vec)>; + output: Arc, + ) -> Result<()>; async fn query_for_global_dedup_shard(&self, prefix: &str, chunk_hash: &MerkleHash) -> Result>; diff --git a/xet_client/src/cas_client/mod.rs b/xet_client/src/cas_client/mod.rs index a7598a202..5cc4ad907 100644 --- a/xet_client/src/cas_client/mod.rs +++ b/xet_client/src/cas_client/mod.rs @@ -27,11 +27,13 @@ pub mod simulation; // No `XetRuntime::spawn` on wasm, so there is no way to report without blocking a transfer. #[cfg(not(target_family = "wasm"))] pub mod telemetry; +mod xorb_block_data; pub use interface::{ShardUploadProgressCallback, ShardUploadProgressType}; pub use progress_tracked_streams::{DownloadProgressStream, ProgressCallback, UploadProgressStream}; #[cfg(not(target_family = "wasm"))] pub use telemetry::{Direction, TelemetryEnvelope, TransferTelemetry, XorbUploadPathTotals}; +pub use xorb_block_data::{BlockByteRange, ReadAmount, XorbBlockData}; #[cfg(not(feature = "elevated_information_level"))] pub const INFORMATION_LOG_LEVEL: Level = Level::DEBUG; diff --git a/xet_client/src/cas_client/remote_client.rs b/xet_client/src/cas_client/remote_client.rs index 3fd372465..caa746426 100644 --- a/xet_client/src/cas_client/remote_client.rs +++ b/xet_client/src/cas_client/remote_client.rs @@ -5,6 +5,7 @@ use anyhow::anyhow; use bytes::Bytes; use crc_fast::CrcAlgorithm; use futures::TryStreamExt; +use futures::io::{AsyncRead, AsyncReadExt}; use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderMap, HeaderName, RANGE}; use http::{HeaderValue, Method}; use reqwest::{Body, Response, StatusCode, Url}; @@ -17,6 +18,7 @@ use web_time::Instant; use xet_core_structures::merklehash::MerkleHash; use xet_core_structures::metadata_shard::file_structs::{FileDataSequenceEntry, FileDataSequenceHeader, MDBFileInfo}; use xet_core_structures::xorb_object::SerializedXorbObject; +use xet_core_structures::xorb_object::deserialize_async::try_read_chunk_header_async; use xet_runtime::core::XetContext; use super::adaptive_concurrency::{ @@ -32,7 +34,7 @@ use super::retry_wrapper::{RetryWrapper, RetryableReqwestError}; use super::shard_upload_v2::read_shard_upload_ndjson; #[cfg(not(target_family = "wasm"))] use super::telemetry::TransferTelemetry; -use super::{Client, INFORMATION_LOG_LEVEL}; +use super::{Client, INFORMATION_LOG_LEVEL, XorbBlockData}; use crate::cas_client::ShardUploadProgressType; use crate::cas_types::{ BatchQueryReconstructionResponse, Checksum, FileChunkHashesResponse, FileRange, HttpRange, Key, @@ -1043,8 +1045,8 @@ impl Client for RemoteClient { url_info: Box, download_permit: ConnectionPermit, progress_callback: Option, - uncompressed_size_if_known: Option, - ) -> Result<(Bytes, Vec)> { + output: Arc, + ) -> Result<()> { let api_tag = "s3::get_range"; let http_client = self.http_client.clone(); let url_info = Arc::new(url_info); @@ -1058,7 +1060,11 @@ impl Client for RemoteClient { transfer_reporter = transfer_reporter.with_progress_callback(cb); } - let result = RetryWrapper::new(self.ctx.clone(), api_tag) + // The signed URL only allows the exact signed range, so a retry downloads the whole range again; chunks + // appended by an earlier attempt are skipped rather than appended twice. + let chunks_at_start = output.num_chunks(); + + RetryWrapper::new(self.ctx.clone(), api_tag) .with_retry_on_403() .with_connection_permit(download_permit, None) .run_and_process( @@ -1105,6 +1111,7 @@ impl Client for RemoteClient { }, move |resp: Response| { let transfer_reporter = transfer_reporter.clone(); + let output = output.clone(); async move { let content_type = resp .headers() @@ -1113,86 +1120,42 @@ impl Client for RemoteClient { .unwrap_or("") .to_string(); - let is_multipart = content_type.contains("multipart/byteranges"); + let mut skip_chunks = output.num_chunks() - chunks_at_start; - if is_multipart { + if content_type.contains("multipart/byteranges") { let body = resp .bytes() .await .map_err(|e| RetryableReqwestError::RetryableError(ClientError::from(e)))?; - let multipart_parts = crate::cas_client::multipart::parse_multipart_byteranges(&content_type, body) - .map_err(RetryableReqwestError::FatalError)?; + let multipart_parts = + crate::cas_client::multipart::parse_multipart_byteranges(&content_type, body) + .map_err(RetryableReqwestError::FatalError)?; - let mut all_decompressed = Vec::with_capacity(uncompressed_size_if_known.unwrap_or(0)); - let mut all_chunk_indices = Vec::::new(); - let mut total_compressed_bytes = 0u64; + // The whole body has been received: report it before appending, since readers may + // finish the reconstruction as soon as the last chunk is appended. + let total_compressed_bytes = multipart_parts.iter().map(|part| part.data.len()).sum(); + transfer_reporter.report_progress(total_compressed_bytes); for part in multipart_parts { - total_compressed_bytes += part.data.len() as u64; - - let (data, chunk_indices) = - xet_core_structures::xorb_object::deserialize_chunks(&mut std::io::Cursor::new(part.data.as_ref())) - .map_err(|e| { - RetryableReqwestError::RetryableError(ClientError::FormatError(e)) - })?; - - xet_core_structures::xorb_object::append_chunk_segment( - &mut all_decompressed, - &mut all_chunk_indices, - &data, - &chunk_indices, - ); - - transfer_reporter.report_progress(total_compressed_bytes as usize); + output + .append_serialized_chunks(&part.data, &mut skip_chunks) + .map_err(RetryableReqwestError::RetryableError)?; } - - if let Some(expected) = uncompressed_size_if_known - && expected != all_decompressed.len() - { - return Err(RetryableReqwestError::RetryableError(ClientError::Other(format!( - "get_file_term_data: expected {expected} uncompressed bytes, got {}", - all_decompressed.len() - )))); - } - Ok((Bytes::from(all_decompressed), all_chunk_indices)) + Ok(()) } else { let incoming_stream = DownloadProgressStream::wrap_stream( resp.bytes_stream().map_err(std::io::Error::other), transfer_reporter, ); - - let capacity = uncompressed_size_if_known.unwrap_or(0); - let mut buffer = Vec::with_capacity(capacity); - let mut writer = std::io::Cursor::new(&mut buffer); - - let result = xet_core_structures::xorb_object::deserialize_async::deserialize_chunks_to_writer_from_stream( - incoming_stream, - &mut writer, - ) - .await; - - match result { - Ok((_compressed_len, chunk_byte_indices)) => { - if let Some(expected) = uncompressed_size_if_known - && expected != buffer.len() - { - return Err(RetryableReqwestError::RetryableError(ClientError::Other(format!( - "get_file_term_data: expected {expected} uncompressed bytes, got {}", - buffer.len() - )))); - } - Ok((Bytes::from(buffer), chunk_byte_indices)) - }, - Err(e) => Err(RetryableReqwestError::RetryableError(ClientError::FormatError(e))), - } + append_chunks_from_stream(incoming_stream.into_async_read(), &output, skip_chunks) + .await + .map_err(RetryableReqwestError::RetryableError) } } }, ) - .await?; - - Ok(result) + .await } #[instrument(skip_all, name = "RemoteClient::get_file_reconstruction", fields(file.hash = file_hash.hex() @@ -1435,6 +1398,26 @@ impl Client for RemoteClient { } } +/// Decompresses the serialized chunks read from `reader` into `output` as each one arrives, skipping the first +/// `skip_chunks` (already appended by an earlier attempt). +async fn append_chunks_from_stream( + mut reader: impl AsyncRead + Unpin, + output: &XorbBlockData, + mut skip_chunks: usize, +) -> Result<()> { + let mut compressed = Vec::new(); + while let Some(header) = try_read_chunk_header_async(&mut reader).await? { + compressed.resize(header.get_compressed_length() as usize, 0); + reader.read_exact(&mut compressed).await?; + if skip_chunks > 0 { + skip_chunks -= 1; + continue; + } + output.append_compressed_chunk(&header, &compressed)?; + } + Ok(()) +} + #[cfg(test)] #[cfg(not(target_family = "wasm"))] mod tests { @@ -2244,4 +2227,275 @@ mod tests { assert_eq!(grant_fallbacks(&client), 0); } } + + /// `get_file_term_data` against a scripted HTTP server: chunks are appended as they arrive, a retry after a + /// dropped connection re-requests the exact signed range and skips the chunks already appended, and + /// multipart responses decode part by part. + mod file_term_data { + use std::sync::Mutex; + use std::time::Duration; + + use tokio::io::{AsyncReadExt as _, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + use tokio::sync::Notify; + use xet_core_structures::xorb_object::serialize_chunk; + use xet_runtime::config::XetConfig; + + use super::*; + use crate::cas_types::HttpRange; + + /// How the server answers one request. + enum Reply { + /// The whole body. + Full, + /// The first `n` body bytes, then the connection is dropped. + CutAfter(usize), + /// The first `n` body bytes, then waits for `resume` before sending the rest. + PauseAfter(usize, Arc), + /// A `multipart/byteranges` body with one part per requested range. + Multipart, + } + + struct TestServer { + url: String, + /// The `Range` header of every request received. + ranges: Arc>>, + } + + /// Serves `body` (the serialized xorb) for each request in turn with the next scripted reply. + async fn start_server(body: Vec, replies: Vec) -> TestServer { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/xorb", listener.local_addr().unwrap()); + let ranges = Arc::new(Mutex::new(Vec::new())); + let seen = ranges.clone(); + tokio::spawn(async move { + for reply in replies { + let (mut socket, _) = listener.accept().await.unwrap(); + let range = read_request_range(&mut socket).await; + seen.lock().unwrap().push(range.clone()); + respond(&mut socket, &body, &range, reply).await; + } + }); + TestServer { url, ranges } + } + + async fn read_request_range(socket: &mut TcpStream) -> String { + let mut request = Vec::new(); + let mut buf = [0u8; 1024]; + while !request.ends_with(b"\r\n\r\n") { + let n = socket.read(&mut buf).await.unwrap(); + assert!(n > 0, "connection closed before the request was read"); + request.extend_from_slice(&buf[..n]); + } + String::from_utf8(request) + .unwrap() + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("range").then(|| value.trim().to_string()) + }) + .expect("request has a Range header") + } + + /// Parses `bytes=a-b,c-d` into inclusive ranges. + fn parse_ranges(range: &str) -> Vec<(usize, usize)> { + range + .strip_prefix("bytes=") + .unwrap() + .split(',') + .map(|r| { + let (a, b) = r.split_once('-').unwrap(); + (a.parse().unwrap(), b.parse().unwrap()) + }) + .collect() + } + + async fn respond(socket: &mut TcpStream, body: &[u8], range: &str, reply: Reply) { + let ranges = parse_ranges(range); + if let Reply::Multipart = reply { + let mut payload = Vec::new(); + for &(start, end) in &ranges { + payload.extend_from_slice( + format!( + "--B\r\nContent-Type: application/octet-stream\r\nContent-Range: bytes {start}-{end}/{}\r\n\r\n", + body.len() + ) + .as_bytes(), + ); + payload.extend_from_slice(&body[start..=end]); + payload.extend_from_slice(b"\r\n"); + } + payload.extend_from_slice(b"--B--\r\n"); + write_response(socket, "multipart/byteranges; boundary=B", &payload).await; + return; + } + + assert_eq!(ranges.len(), 1); + let (start, end) = ranges[0]; + let payload = &body[start..=end]; + let head = format!( + "HTTP/1.1 206 Partial Content\r\nContent-Type: application/octet-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + ); + socket.write_all(head.as_bytes()).await.unwrap(); + match reply { + Reply::Full => socket.write_all(payload).await.unwrap(), + Reply::CutAfter(n) => socket.write_all(&payload[..n]).await.unwrap(), + Reply::PauseAfter(n, resume) => { + socket.write_all(&payload[..n]).await.unwrap(); + socket.flush().await.unwrap(); + resume.notified().await; + socket.write_all(&payload[n..]).await.unwrap(); + }, + Reply::Multipart => unreachable!(), + } + socket.flush().await.unwrap(); + } + + async fn write_response(socket: &mut TcpStream, content_type: &str, payload: &[u8]) { + let head = format!( + "HTTP/1.1 206 Partial Content\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + ); + socket.write_all(head.as_bytes()).await.unwrap(); + socket.write_all(payload).await.unwrap(); + socket.flush().await.unwrap(); + } + + struct FixedUrl { + url: String, + ranges: Vec, + } + + #[async_trait::async_trait] + impl URLProvider for FixedUrl { + async fn retrieve_url(&self) -> Result<(String, Vec)> { + Ok((self.url.clone(), self.ranges.clone())) + } + + async fn refresh_url(&self) -> Result<()> { + Ok(()) + } + } + + /// `n` distinct 64 KiB chunks, their serialized xorb bytes, and the serialized end offset of each chunk. + fn test_chunks(n: usize) -> (Vec>, Vec, Vec) { + let chunks: Vec> = (0..n) + .map(|i| (0..64 * 1024).map(|j| ((j * 31 + i * 7) % 251) as u8).collect()) + .collect(); + let mut serialized = Vec::new(); + let mut ends = Vec::new(); + for chunk in &chunks { + serialize_chunk(chunk, &mut serialized, CompressionScheme::LZ4).unwrap(); + ends.push(serialized.len()); + } + (chunks, serialized, ends) + } + + fn test_client() -> Arc { + let mut config = XetConfig::new(); + config.client.retry_base_delay = Duration::from_millis(5); + config.client.retry_max_attempts = 3; + let ctx = XetContext::from_external(tokio::runtime::Handle::current(), config); + RemoteClient::new(ctx, "http://127.0.0.1:1", &None, "", false, None) + } + + async fn fetch( + client: &RemoteClient, + url: &str, + ranges: Vec, + output: Arc, + ) -> Result<()> { + let permit = client.acquire_download_permit().await?; + let url_info = Box::new(FixedUrl { + url: url.to_string(), + ranges, + }); + client.get_file_term_data(url_info, permit, None, output).await + } + + fn expected_offsets(chunks: &[Vec]) -> Vec { + let mut offsets = vec![0u32]; + for chunk in chunks { + offsets.push(offsets.last().unwrap() + chunk.len() as u32); + } + offsets + } + + #[tokio::test] + async fn test_chunks_are_ready_before_the_body_ends() { + let (chunks, serialized, ends) = test_chunks(4); + let resume = Arc::new(Notify::new()); + let server = start_server(serialized.clone(), vec![Reply::PauseAfter(ends[0], resume.clone())]).await; + + let client = test_client(); + let output = Arc::new(XorbBlockData::with_exact_size(chunks.concat().len())); + let fetch_task = { + let output = output.clone(); + let ranges = vec![HttpRange::new(0, serialized.len() as u64 - 1)]; + tokio::spawn(async move { fetch(&client, &server.url, ranges, output).await }) + }; + + // The server holds back everything after the first chunk until the first chunk is readable. + tokio::time::timeout(Duration::from_secs(10), async { + while output.ready_bytes() < chunks[0].len() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("first chunk must be appended before the rest of the body is sent"); + assert_eq!(output.ready_bytes(), chunks[0].len()); + assert!(!fetch_task.is_finished()); + + resume.notify_one(); + fetch_task.await.unwrap().unwrap(); + output.finish().unwrap(); + assert_eq!(output.contents().unwrap().0, chunks.concat()); + } + + #[tokio::test] + async fn test_retry_after_partial_body_skips_appended_chunks() { + let (chunks, serialized, ends) = test_chunks(5); + // Drop the first connection in the middle of the third chunk, after two whole chunks. + let cut = ends[1] + (ends[2] - ends[1]) / 2; + let server = start_server(serialized.clone(), vec![Reply::CutAfter(cut), Reply::Full]).await; + + let client = test_client(); + let output = Arc::new(XorbBlockData::with_exact_size(chunks.concat().len())); + let range = HttpRange::new(0, serialized.len() as u64 - 1); + fetch(&client, &server.url, vec![range], output.clone()).await.unwrap(); + output.finish().unwrap(); + + // Both requests ask for the exact signed range; the retry is not narrowed to the remainder. + let requested = server.ranges.lock().unwrap().clone(); + assert_eq!(requested, vec![range.range_header(), range.range_header()]); + + // Every chunk is appended exactly once, in order. + let (data, offsets) = output.contents().unwrap(); + assert_eq!(data, chunks.concat()); + assert_eq!(offsets, expected_offsets(&chunks)); + } + + #[tokio::test] + async fn test_multipart_response() { + let (chunks, serialized, ends) = test_chunks(4); + let server = start_server(serialized.clone(), vec![Reply::Multipart]).await; + + // Two ranges: chunks 0..2 and chunks 3..4 (chunk 2 is not requested). + let ranges = vec![ + HttpRange::new(0, ends[1] as u64 - 1), + HttpRange::new(ends[2] as u64, ends[3] as u64 - 1), + ]; + let expected: Vec> = vec![chunks[0].clone(), chunks[1].clone(), chunks[3].clone()]; + + let client = test_client(); + let output = Arc::new(XorbBlockData::with_exact_size(expected.concat().len())); + fetch(&client, &server.url, ranges, output.clone()).await.unwrap(); + output.finish().unwrap(); + + let (data, offsets) = output.contents().unwrap(); + assert_eq!(data, expected.concat()); + assert_eq!(offsets, expected_offsets(&expected)); + } + } } diff --git a/xet_client/src/cas_client/simulation/local_client.rs b/xet_client/src/cas_client/simulation/local_client.rs index 53ac88a7f..664b67730 100644 --- a/xet_client/src/cas_client/simulation/local_client.rs +++ b/xet_client/src/cas_client/simulation/local_client.rs @@ -38,11 +38,11 @@ use xet_runtime::file_utils::SafeFileCreator; use super::deletion_controls::{ObjectETag, ObjectTagSet, last_upload_tag_set_now}; use super::direct_access_client::DirectAccessClient; use super::xorb_utils::{self, REFERENCE_INSTANT, duration_to_expiration_secs_ceil}; -use crate::cas_client::Client; use crate::cas_client::adaptive_concurrency::AdaptiveConcurrencyController; use crate::cas_client::chunk_window_builder::build_file_chunk_hashes_response; use crate::cas_client::interface::{ShardUploadProgressCallback, ShardUploadProgressType}; use crate::cas_client::progress_tracked_streams::ProgressCallback; +use crate::cas_client::{Client, XorbBlockData}; use crate::cas_types::{ BatchQueryReconstructionResponse, FileChunkHashesResponse, FileRange, HexMerkleHash, HttpRange, QueryReconstructionResponse, QueryReconstructionResponseV2, ShardUploadEvent, XorbMultiRangeFetch, @@ -1893,8 +1893,8 @@ impl Client for LocalClient { url_info: Box, _download_permit: super::super::adaptive_concurrency::ConnectionPermit, progress_callback: Option, - uncompressed_size_if_known: Option, - ) -> Result<(Bytes, Vec)> { + output: Arc, + ) -> Result<()> { // Retry loop: try to fetch, and if URL expired, refresh and retry once. for attempt in 0..2 { self.apply_api_delay().await; @@ -1922,43 +1922,24 @@ impl Client for LocalClient { // Read each byte range from the serialized file and deserialize the chunks. let mut file = File::open(&file_path).map_err(|_| ClientError::XORBNotFound(MerkleHash::default()))?; - let mut all_decompressed = Vec::new(); - let mut all_chunk_indices = Vec::::new(); - let mut total_transfer = 0u64; - + // Report each range as transferred before appending it: readers of `output` may finish the + // reconstruction as soon as the last chunk is appended. + let total_transfer: u64 = http_ranges.iter().map(|r| r.length()).sum(); + let mut completed_transfer = 0u64; for http_range in &http_ranges { let len = http_range.length() as usize; - total_transfer += http_range.length(); file.seek(SeekFrom::Start(http_range.start))?; let mut data = vec![0u8; len]; std::io::Read::read_exact(&mut file, &mut data)?; - let (decompressed, chunk_indices) = - xet_core_structures::xorb_object::deserialize_chunks(&mut Cursor::new(&data))?; - - xet_core_structures::xorb_object::append_chunk_segment( - &mut all_decompressed, - &mut all_chunk_indices, - &decompressed, - &chunk_indices, - ); - } - - if let Some(expected) = uncompressed_size_if_known { - debug_assert_eq!( - all_decompressed.len(), - expected, - "get_file_term_data: expected {} bytes, got {}", - expected, - all_decompressed.len() - ); - } - - if let Some(ref cb) = progress_callback { - cb(total_transfer, total_transfer, total_transfer); + completed_transfer += http_range.length(); + if let Some(ref cb) = progress_callback { + cb(http_range.length(), completed_transfer, total_transfer); + } + output.append_serialized_chunks(&data, &mut 0)?; } - return Ok((Bytes::from(all_decompressed), all_chunk_indices)); + return Ok(()); } // Should not reach here, but return error if we do. diff --git a/xet_client/src/cas_client/simulation/local_server/server.rs b/xet_client/src/cas_client/simulation/local_server/server.rs index cd3f62cbc..8015b163c 100644 --- a/xet_client/src/cas_client/simulation/local_server/server.rs +++ b/xet_client/src/cas_client/simulation/local_server/server.rs @@ -511,10 +511,10 @@ impl Client for LocalTestServer { url_info: Box, download_permit: crate::cas_client::adaptive_concurrency::ConnectionPermit, progress_callback: Option, - uncompressed_size_if_known: Option, - ) -> Result<(bytes::Bytes, Vec)> { + output: std::sync::Arc, + ) -> Result<()> { self.remote_client - .get_file_term_data(url_info, download_permit, progress_callback, uncompressed_size_if_known) + .get_file_term_data(url_info, download_permit, progress_callback, output) .await } diff --git a/xet_client/src/cas_client/simulation/local_server/simulation_control_client.rs b/xet_client/src/cas_client/simulation/local_server/simulation_control_client.rs index 75f226b50..2cd588c4d 100644 --- a/xet_client/src/cas_client/simulation/local_server/simulation_control_client.rs +++ b/xet_client/src/cas_client/simulation/local_server/simulation_control_client.rs @@ -207,10 +207,10 @@ impl Client for SimulationControlClient { url_info: Box, download_permit: crate::cas_client::adaptive_concurrency::ConnectionPermit, progress_callback: Option, - uncompressed_size_if_known: Option, - ) -> Result<(Bytes, Vec)> { + output: std::sync::Arc, + ) -> Result<()> { self.remote_client - .get_file_term_data(url_info, download_permit, progress_callback, uncompressed_size_if_known) + .get_file_term_data(url_info, download_permit, progress_callback, output) .await } diff --git a/xet_client/src/cas_client/simulation/memory_client.rs b/xet_client/src/cas_client/simulation/memory_client.rs index a0657ec5a..c7ede0561 100644 --- a/xet_client/src/cas_client/simulation/memory_client.rs +++ b/xet_client/src/cas_client/simulation/memory_client.rs @@ -26,6 +26,7 @@ use super::super::Client; use super::super::adaptive_concurrency::AdaptiveConcurrencyController; use super::super::interface::{ShardUploadProgressCallback, ShardUploadProgressType}; use super::super::progress_tracked_streams::ProgressCallback; +use super::super::xorb_block_data::XorbBlockData; use super::client_testing_utils::{FileTermReference, RandomFileContents}; #[cfg(not(target_family = "wasm"))] use super::deletion_controls::{ObjectETag, ObjectTagSet, last_upload_tag_set_now}; @@ -1082,8 +1083,8 @@ impl Client for MemoryClient { url_info: Box, _download_permit: super::super::adaptive_concurrency::ConnectionPermit, progress_callback: Option, - uncompressed_size_if_known: Option, - ) -> Result<(Bytes, Vec)> { + output: Arc, + ) -> Result<()> { self.apply_api_delay().await; let (url, http_ranges) = url_info.retrieve_url().await?; let (xorb_hash, url_timestamp) = parse_any_fetch_url(&url)?; @@ -1105,49 +1106,29 @@ impl Client for MemoryClient { let xorbs = &state.xorbs; let storage = xorbs.get(&xorb_hash).ok_or(ClientError::XORBNotFound(xorb_hash))?; - // Extract each byte range from the serialized data and deserialize - let mut all_decompressed = Vec::new(); - let mut all_chunk_indices = Vec::::new(); - let mut total_transfer = 0u64; - + // Report each range as transferred before appending it: readers of `output` may finish the + // reconstruction as soon as the last chunk is appended. + let total_transfer: u64 = http_ranges.iter().map(|r| r.length()).sum(); + let mut completed_transfer = 0u64; for http_range in &http_ranges { let start = http_range.start as usize; let end = http_range.end as usize + 1; - total_transfer += http_range.length(); + completed_transfer += http_range.length(); + if let Some(ref cb) = progress_callback { + cb(http_range.length(), completed_transfer, total_transfer); + } - let (data, chunk_indices) = match storage { + match storage { XorbStorage::Materialized { entry, .. } => { - let range_data = &entry.serialized_data[start..end]; - xet_core_structures::xorb_object::deserialize_chunks(&mut Cursor::new(range_data))? + output.append_serialized_chunks(&entry.serialized_data[start..end], &mut 0)?; }, XorbStorage::Random { xorb, .. } => { let range_data = xorb.get_serialized_range(start as u64, end as u64); - xet_core_structures::xorb_object::deserialize_chunks(&mut Cursor::new(range_data.as_ref()))? + output.append_serialized_chunks(&range_data, &mut 0)?; }, - }; - - xet_core_structures::xorb_object::append_chunk_segment( - &mut all_decompressed, - &mut all_chunk_indices, - &data, - &chunk_indices, - ); - } - - if let Some(expected) = uncompressed_size_if_known { - debug_assert_eq!( - all_decompressed.len(), - expected, - "get_file_term_data: expected {} bytes, got {}", - expected, - all_decompressed.len() - ); - } - - if let Some(ref cb) = progress_callback { - cb(total_transfer, total_transfer, total_transfer); + } } - Ok((Bytes::from(all_decompressed), all_chunk_indices)) + Ok(()) } async fn get_file_chunk_hashes( diff --git a/xet_client/src/cas_client/simulation/simulation_client.rs b/xet_client/src/cas_client/simulation/simulation_client.rs index e02aa643a..441fd27df 100644 --- a/xet_client/src/cas_client/simulation/simulation_client.rs +++ b/xet_client/src/cas_client/simulation/simulation_client.rs @@ -201,10 +201,10 @@ impl Client for RemoteSimulationClient { url_info: Box, download_permit: ConnectionPermit, progress_callback: Option, - uncompressed_size_if_known: Option, - ) -> Result<(Bytes, Vec)> { + output: std::sync::Arc, + ) -> Result<()> { self.inner - .get_file_term_data(url_info, download_permit, progress_callback, uncompressed_size_if_known) + .get_file_term_data(url_info, download_permit, progress_callback, output) .await } diff --git a/xet_client/src/cas_client/simulation/simulation_server.rs b/xet_client/src/cas_client/simulation/simulation_server.rs index 5975bf5b5..ca5747d18 100644 --- a/xet_client/src/cas_client/simulation/simulation_server.rs +++ b/xet_client/src/cas_client/simulation/simulation_server.rs @@ -560,10 +560,10 @@ impl Client for LocalTestServer { url_info: Box, download_permit: super::super::adaptive_concurrency::ConnectionPermit, progress_callback: Option, - uncompressed_size_if_known: Option, - ) -> Result<(bytes::Bytes, Vec)> { + output: std::sync::Arc, + ) -> Result<()> { self.remote_simulation_client - .get_file_term_data(url_info, download_permit, progress_callback, uncompressed_size_if_known) + .get_file_term_data(url_info, download_permit, progress_callback, output) .await } diff --git a/xet_client/src/cas_client/xorb_block_data.rs b/xet_client/src/cas_client/xorb_block_data.rs new file mode 100644 index 000000000..b6b1e606c --- /dev/null +++ b/xet_client/src/cas_client/xorb_block_data.rs @@ -0,0 +1,545 @@ +//! Decompressed data of one xorb block, shared between the task that downloads it and the readers of its terms. +//! +//! A block is one fetch: a chunk range of a xorb (or several, for a multi-range fetch) retrieved by one HTTP request. +//! [`XorbBlockData`] holds its decompressed bytes in a single allocation sized when the block is planned. The +//! downloading client appends each chunk as soon as it is decompressed and moves a "ready" mark forward; readers can +//! take any range below that mark as a zero-copy [`Bytes`] while the rest of the block is still being downloaded. +//! +//! Chunks are appended strictly in order, so everything below the ready mark is final and never written again. + +use std::ptr::NonNull; +#[cfg(not(target_family = "wasm"))] +use std::sync::Condvar; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; + +use bytes::Bytes; +use tokio::sync::watch; +use xet_core_structures::xorb_object::{XORB_CHUNK_HEADER_LENGTH, XorbChunkHeader, decompress_chunk_into}; + +use crate::error::{ClientError, Result}; + +/// A byte range of a block, anchored at a chunk: `len` bytes starting `offset_into_first_chunk` bytes after the start +/// of chunk `first_chunk` (an index into the block's chunks, in fetch order). +/// +/// Anchoring at a chunk lets a reader be created before the block's chunk sizes are known; its absolute position +/// becomes known once all chunks before `first_chunk` have been appended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BlockByteRange { + pub first_chunk: usize, + pub offset_into_first_chunk: usize, + pub len: usize, +} + +/// How much of a requested range must be ready before a read returns. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ReadAmount { + /// Return as soon as at least one byte is ready, with everything ready so far. + Available, + /// Return only once the whole requested range is ready. + All, +} + +/// Decompressed data of one xorb block; see the [module docs](self). +/// +/// Lifecycle: created empty with a capacity, then filled by one writer through the `append_*` methods, then either +/// [`finish`](Self::finish)ed or [`fail`](Self::fail)ed. Readers wait on the ready mark and see the failure, if any. +pub struct XorbBlockData { + /// Size of the allocation, in bytes. Appends beyond it are rejected. + capacity: usize, + /// Whether `capacity` is the block's exact decompressed size (checked by `finish`), or only an upper bound. + capacity_is_exact: bool, + /// The allocation; created on first append so that planned-but-unfetched blocks take no memory. + storage: OnceLock>, + /// Serializes writers, so that only one ever writes past the ready mark. + write_lock: Mutex<()>, + state: Mutex, + /// Wakes blocking readers when `state` changes. + #[cfg(not(target_family = "wasm"))] + state_changed: Condvar, + /// Wakes async readers when `state` changes. + updates: watch::Sender<()>, +} + +struct State { + /// Bytes below this offset are written and final. + ready_bytes: usize, + /// Start offset of every appended chunk, followed by the end of the last one: `[0, end_0, end_1, ...]`. + chunk_offsets: Vec, + status: Status, +} + +enum Status { + Filling, + Complete, + Failed(Arc), +} + +impl XorbBlockData { + /// Creates an empty block whose decompressed size is exactly `size` bytes. + pub fn with_exact_size(size: usize) -> Self { + Self::new(size, true) + } + + /// Creates an empty block whose decompressed size is at most `max_size` bytes. + pub fn with_size_bound(max_size: usize) -> Self { + Self::new(max_size, false) + } + + fn new(capacity: usize, capacity_is_exact: bool) -> Self { + Self { + capacity, + capacity_is_exact, + storage: OnceLock::new(), + write_lock: Mutex::new(()), + state: Mutex::new(State { + ready_bytes: 0, + chunk_offsets: vec![0], + status: Status::Filling, + }), + #[cfg(not(target_family = "wasm"))] + state_changed: Condvar::new(), + updates: watch::Sender::new(()), + } + } + + /// The size of the allocation: the block's exact decompressed size, or an upper bound on it. + pub fn capacity(&self) -> usize { + self.capacity + } + + /// The number of chunks appended so far. + pub fn num_chunks(&self) -> usize { + self.lock_state().chunk_offsets.len() - 1 + } + + /// The number of decompressed bytes appended so far. + pub fn ready_bytes(&self) -> usize { + self.lock_state().ready_bytes + } + + /// Appends already decompressed chunks. `chunk_offsets` are the chunk boundaries within `data`, in the format + /// returned by the chunk deserializers: `[0, end_0, ..., data.len()]`. + pub fn append_chunks(&self, data: &[u8], chunk_offsets: &[u32]) -> Result<()> { + let valid_offsets = chunk_offsets.first() == Some(&0) + && chunk_offsets.last().map(|&end| end as usize) == Some(data.len()) + && chunk_offsets.windows(2).all(|w| w[0] <= w[1]); + if !valid_offsets { + return Err(ClientError::Other(format!( + "invalid chunk offsets for {} bytes of block data: {chunk_offsets:?}", + data.len() + ))); + } + + self.append(data.len(), &chunk_offsets[1..], |out| { + out.copy_from_slice(data); + Ok(()) + }) + } + + /// Decompresses one serialized chunk (its header and the `compressed` payload after it) and appends it. + pub fn append_compressed_chunk(&self, header: &XorbChunkHeader, compressed: &[u8]) -> Result<()> { + let len = header.get_uncompressed_length() as usize; + self.append(len, &[len as u32], |out| Ok(decompress_chunk_into(header, compressed, out)?)) + } + + /// Decompresses and appends the serialized chunks in `serialized`, skipping the first `skip_chunks` of them. + /// + /// Used to resume a block after a retry: a retried request covers the same chunks again, and the ones already + /// appended are skipped without being decompressed. + pub fn append_serialized_chunks(&self, mut serialized: &[u8], skip_chunks: &mut usize) -> Result<()> { + while !serialized.is_empty() { + if serialized.len() < XORB_CHUNK_HEADER_LENGTH { + return Err(ClientError::Other("truncated chunk header in xorb block data".to_string())); + } + let header = xet_core_structures::xorb_object::deserialize_chunk_header(&mut serialized)?; + let compressed_len = header.get_compressed_length() as usize; + if serialized.len() < compressed_len { + return Err(ClientError::Other("truncated chunk data in xorb block data".to_string())); + } + let (compressed, rest) = serialized.split_at(compressed_len); + serialized = rest; + + if *skip_chunks > 0 { + *skip_chunks -= 1; + continue; + } + self.append_compressed_chunk(&header, compressed)?; + } + Ok(()) + } + + /// Writes `len` bytes past the ready mark with `fill`, then publishes them as chunks ending at `relative_ends` + /// (offsets relative to the start of the appended bytes; the last one must equal `len`). + fn append(&self, len: usize, relative_ends: &[u32], fill: impl FnOnce(&mut [u8]) -> Result<()>) -> Result<()> { + debug_assert_eq!(relative_ends.last().map(|&e| e as usize), Some(len)); + + let _writer = self.write_lock.lock().unwrap_or_else(|e| e.into_inner()); + + let start = { + let state = self.lock_state(); + match &state.status { + Status::Filling => {}, + Status::Complete => return Err(ClientError::Other("append to a finished xorb block".to_string())), + Status::Failed(err) => return Err(ClientError::Other(format!("append to a failed xorb block: {err}"))), + } + state.ready_bytes + }; + + let end = start.checked_add(len).filter(|&end| end <= self.capacity).ok_or_else(|| { + ClientError::Other(format!( + "xorb block data exceeds its expected size of {} bytes ({start} + {len})", + self.capacity + )) + })?; + u32::try_from(end).map_err(|_| ClientError::Other(format!("xorb block of {end} bytes is too large")))?; + + let storage = self.storage.get_or_init(|| Arc::new(Storage::zeroed(self.capacity))); + // SAFETY: `start..end` is within the allocation (checked against `capacity` above). It lies at or past the + // ready mark, so no reader has a reference into it, and `write_lock` ensures no other writer does either. + let out = unsafe { std::slice::from_raw_parts_mut(storage.ptr.as_ptr().add(start), len) }; + fill(out)?; + + let mut state = self.lock_state(); + state.chunk_offsets.extend(relative_ends.iter().map(|&e| start as u32 + e)); + state.ready_bytes = end; + drop(state); + self.notify(); + Ok(()) + } + + /// Marks the block complete. Fails (and marks the block failed) if its size is not the exact size it was created + /// with. + pub fn finish(&self) -> Result<()> { + let _writer = self.write_lock.lock().unwrap_or_else(|e| e.into_inner()); + let mut state = self.lock_state(); + match &state.status { + Status::Filling => {}, + Status::Complete => return Ok(()), + Status::Failed(err) => return Err(ClientError::Other(format!("xorb block failed: {err}"))), + } + + let result = if self.capacity_is_exact && state.ready_bytes != self.capacity { + let err = ClientError::Other(format!( + "xorb block: expected {} decompressed bytes, got {}", + self.capacity, state.ready_bytes + )); + state.status = Status::Failed(Arc::new(ClientError::Other(err.to_string()))); + Err(err) + } else { + state.status = Status::Complete; + Ok(()) + }; + drop(state); + self.notify(); + result + } + + /// Marks the block failed with `err`, waking every reader. Does nothing if the block is already complete or + /// failed. + pub fn fail(&self, err: Arc) { + let mut state = self.lock_state(); + if matches!(state.status, Status::Filling) { + state.status = Status::Failed(err); + drop(state); + self.notify(); + } + } + + /// The whole block and its chunk offsets (`[0, end_0, ...]`), once it is complete. + pub fn contents(&self) -> Option<(Bytes, Vec)> { + let state = self.lock_state(); + matches!(state.status, Status::Complete) + .then(|| (self.ready_slice(0, state.ready_bytes), state.chunk_offsets.clone())) + } + + /// Reads `range` starting `position` bytes into it, without waiting. Returns `None` if not enough of it is ready + /// yet. + pub fn try_read( + &self, + range: &BlockByteRange, + position: usize, + amount: ReadAmount, + ) -> std::result::Result, Arc> { + self.read_locked(&self.lock_state(), range, position, amount) + } + + /// Reads `range` starting `position` bytes into it, waiting until enough of it is ready. + pub async fn read( + &self, + range: &BlockByteRange, + position: usize, + amount: ReadAmount, + ) -> std::result::Result> { + // Subscribe before checking, so that an append between the check and the wait still wakes us. + let mut updates = self.updates.subscribe(); + loop { + if let Some(data) = self.try_read(range, position, amount)? { + return Ok(data); + } + // The sender lives in `self`, so this only errors if `self` is gone, which `&self` rules out. + let _ = updates.changed().await; + } + } + + /// Reads `range` starting `position` bytes into it, blocking the thread until enough of it is ready. + #[cfg(not(target_family = "wasm"))] + pub fn read_blocking( + &self, + range: &BlockByteRange, + position: usize, + amount: ReadAmount, + ) -> std::result::Result> { + let mut state = self.lock_state(); + loop { + if let Some(data) = self.read_locked(&state, range, position, amount)? { + return Ok(data); + } + state = self.state_changed.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + fn read_locked( + &self, + state: &State, + range: &BlockByteRange, + position: usize, + amount: ReadAmount, + ) -> std::result::Result, Arc> { + if let Status::Failed(err) = &state.status { + return Err(err.clone()); + } + if position >= range.len { + return Ok(Some(Bytes::new())); + } + let complete = matches!(state.status, Status::Complete); + let out_of_range = || { + Arc::new(ClientError::Other(format!( + "range {range:?} is beyond the {} bytes and {} chunks of its xorb block", + state.ready_bytes, + state.chunk_offsets.len() - 1 + ))) + }; + + // The range's start is known once its first chunk's start offset is recorded. + let Some(&chunk_start) = state.chunk_offsets.get(range.first_chunk) else { + return if complete { Err(out_of_range()) } else { Ok(None) }; + }; + let range_start = chunk_start as usize + range.offset_into_first_chunk; + let start = range_start + position; + let end = range_start + range.len; + + if complete && end > state.ready_bytes { + return Err(out_of_range()); + } + let ready_end = end.min(state.ready_bytes); + let enough = match amount { + ReadAmount::Available => ready_end > start, + ReadAmount::All => ready_end == end, + }; + Ok(enough.then(|| self.ready_slice(start, ready_end))) + } + + /// A zero-copy view of `start..end`, which must be below the ready mark. + fn ready_slice(&self, start: usize, end: usize) -> Bytes { + if start == end { + return Bytes::new(); + } + let storage = self.storage.get().expect("ready bytes imply an allocation").clone(); + Bytes::from_owner(ReadySlice { storage, start, end }) + } + + fn lock_state(&self) -> MutexGuard<'_, State> { + // State updates are single assignments, so a panic elsewhere cannot leave it inconsistent. + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn notify(&self) { + #[cfg(not(target_family = "wasm"))] + self.state_changed.notify_all(); + self.updates.send_replace(()); + } +} + +/// A fixed-size heap allocation written through raw pointers: the writer fills the part past the ready mark while +/// readers hold slices of the part below it, which `&mut [u8]` / `&[u8]` over the whole buffer could not express. +struct Storage { + ptr: NonNull, + len: usize, +} + +// SAFETY: `Storage` owns its allocation. Concurrent access follows the protocol in `XorbBlockData`: bytes are written +// once, by the single writer, before they are published below the ready mark (under the state mutex, which orders +// the write before any read); readers only read published bytes. +unsafe impl Send for Storage {} +unsafe impl Sync for Storage {} + +impl Storage { + fn zeroed(len: usize) -> Self { + let raw = Box::into_raw(vec![0u8; len].into_boxed_slice()); + Self { + // SAFETY: `Box::into_raw` never returns null. + ptr: unsafe { NonNull::new_unchecked(raw as *mut u8) }, + len, + } + } +} + +impl Drop for Storage { + fn drop(&mut self) { + // SAFETY: `ptr` and `len` came from `Box::into_raw` of a boxed slice in `zeroed`, and are freed only here. + drop(unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), self.len)) }); + } +} + +/// Owner of a [`Bytes`] view of published block bytes; keeps the allocation alive. +struct ReadySlice { + storage: Arc, + start: usize, + end: usize, +} + +impl AsRef<[u8]> for ReadySlice { + fn as_ref(&self) -> &[u8] { + // SAFETY: `start..end` is within the allocation and below the ready mark, so it is never written again. + unsafe { std::slice::from_raw_parts(self.storage.ptr.as_ptr().add(self.start), self.end - self.start) } + } +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use xet_core_structures::xorb_object::{CompressionScheme, serialize_chunk}; + + use super::*; + + fn range(first_chunk: usize, offset_into_first_chunk: usize, len: usize) -> BlockByteRange { + BlockByteRange { + first_chunk, + offset_into_first_chunk, + len, + } + } + + fn serialized(chunks: &[&[u8]]) -> Vec { + let mut out = Vec::new(); + for chunk in chunks { + serialize_chunk(chunk, &mut out, CompressionScheme::LZ4).unwrap(); + } + out + } + + #[test] + fn test_read_follows_ready_mark() { + let data = XorbBlockData::with_exact_size(10); + let term = range(0, 2, 6); + + assert_eq!(data.try_read(&term, 0, ReadAmount::Available).unwrap(), None); + + data.append_chunks(b"abcd", &[0, 4]).unwrap(); + assert_eq!(data.try_read(&term, 0, ReadAmount::Available).unwrap().unwrap(), Bytes::from_static(b"cd")); + assert_eq!(data.try_read(&term, 0, ReadAmount::All).unwrap(), None); + + data.append_chunks(b"efghij", &[0, 3, 6]).unwrap(); + assert_eq!(data.try_read(&term, 2, ReadAmount::Available).unwrap().unwrap(), Bytes::from_static(b"efgh")); + assert_eq!(data.try_read(&term, 0, ReadAmount::All).unwrap().unwrap(), Bytes::from_static(b"cdefgh")); + assert_eq!(data.num_chunks(), 3); + + data.finish().unwrap(); + let (all, offsets) = data.contents().unwrap(); + assert_eq!(all, Bytes::from_static(b"abcdefghij")); + assert_eq!(offsets, vec![0, 4, 7, 10]); + } + + #[test] + fn test_range_anchored_at_unknown_chunk_waits() { + let data = XorbBlockData::with_exact_size(6); + // Starts at chunk 2, whose offset is unknown until chunks 0 and 1 are in. + let term = range(2, 0, 2); + data.append_chunks(b"ab", &[0, 2]).unwrap(); + assert_eq!(data.try_read(&term, 0, ReadAmount::Available).unwrap(), None); + data.append_chunks(b"cd", &[0, 2]).unwrap(); + assert_eq!(data.try_read(&term, 0, ReadAmount::Available).unwrap(), None); + data.append_chunks(b"ef", &[0, 2]).unwrap(); + assert_eq!(data.try_read(&term, 0, ReadAmount::All).unwrap().unwrap(), Bytes::from_static(b"ef")); + } + + #[test] + fn test_serialized_chunks_with_skip() { + let chunks: [&[u8]; 3] = [b"first chunk ", b"second chunk ", b"third"]; + let bytes = serialized(&chunks); + + let data = XorbBlockData::with_exact_size(chunks.iter().map(|c| c.len()).sum()); + let mut skip = 0; + data.append_serialized_chunks(&bytes, &mut skip).unwrap(); + data.finish().unwrap(); + assert_eq!(data.contents().unwrap().0, Bytes::from_static(b"first chunk second chunk third")); + + // Resume after the first chunk: the retried data covers all three again. + let data = XorbBlockData::with_exact_size(30); + data.append_chunks(b"first chunk ", &[0, 12]).unwrap(); + let mut skip = 1; + data.append_serialized_chunks(&bytes, &mut skip).unwrap(); + assert_eq!(skip, 0); + data.finish().unwrap(); + assert_eq!(data.contents().unwrap().0, Bytes::from_static(b"first chunk second chunk third")); + assert_eq!(data.contents().unwrap().1, vec![0, 12, 25, 30]); + } + + #[test] + fn test_size_checks() { + let data = XorbBlockData::with_size_bound(4); + assert!(data.append_chunks(b"abcde", &[0, 5]).is_err()); + data.append_chunks(b"abc", &[0, 3]).unwrap(); + data.finish().unwrap(); + assert_eq!(data.ready_bytes(), 3); + + let data = XorbBlockData::with_exact_size(4); + data.append_chunks(b"abc", &[0, 3]).unwrap(); + assert!(data.finish().is_err()); + assert!(data.try_read(&range(0, 0, 1), 0, ReadAmount::Available).is_err()); + } + + #[test] + fn test_range_past_end_of_complete_block_errors() { + let data = XorbBlockData::with_size_bound(8); + data.append_chunks(b"abcd", &[0, 4]).unwrap(); + data.finish().unwrap(); + assert!(data.try_read(&range(0, 2, 4), 0, ReadAmount::All).is_err()); + assert!(data.try_read(&range(5, 0, 1), 0, ReadAmount::Available).is_err()); + } + + #[test] + fn test_failure_wakes_blocking_reader() { + let data = Arc::new(XorbBlockData::with_exact_size(4)); + let reader = { + let data = data.clone(); + std::thread::spawn(move || data.read_blocking(&range(0, 0, 4), 0, ReadAmount::All)) + }; + std::thread::sleep(Duration::from_millis(20)); + data.fail(Arc::new(ClientError::Other("boom".to_string()))); + assert!(reader.join().unwrap().is_err()); + } + + #[tokio::test] + async fn test_async_reader_wakes_per_append() { + let data = Arc::new(XorbBlockData::with_exact_size(4)); + let writer = { + let data = data.clone(); + tokio::spawn(async move { + for piece in [b"ab", b"cd"] { + tokio::time::sleep(Duration::from_millis(10)).await; + data.append_chunks(piece, &[0, 2]).unwrap(); + } + data.finish().unwrap(); + }) + }; + + let term = range(0, 0, 4); + let first = data.read(&term, 0, ReadAmount::Available).await.unwrap(); + assert_eq!(first, Bytes::from_static(b"ab")); + let rest = data.read(&term, first.len(), ReadAmount::All).await.unwrap(); + assert_eq!(rest, Bytes::from_static(b"cd")); + writer.await.unwrap(); + } +} diff --git a/xet_core_structures/src/xorb_object/xorb_chunk_format.rs b/xet_core_structures/src/xorb_object/xorb_chunk_format.rs index d9286a24e..95ea58845 100644 --- a/xet_core_structures/src/xorb_object/xorb_chunk_format.rs +++ b/xet_core_structures/src/xorb_object/xorb_chunk_format.rs @@ -188,6 +188,37 @@ fn deserialize_chunk_with_header_to_writer( Ok((header.get_compressed_length() as usize + XORB_CHUNK_HEADER_LENGTH, uncompressed_len as u32)) } +/// Decompresses one chunk's payload into `out`, whose length must equal the header's uncompressed length. +/// +/// `compressed` is the chunk's data following its header. This lets callers decode straight into a +/// preallocated buffer instead of allocating per chunk. +pub fn decompress_chunk_into(header: &XorbChunkHeader, compressed: &[u8], out: &mut [u8]) -> Result<(), CoreError> { + if out.len() != header.get_uncompressed_length() as usize + || compressed.len() != header.get_compressed_length() as usize + { + return Err(CoreError::MalformedData(format!( + "chunk buffer sizes ({} compressed, {} uncompressed) don't agree with chunk header ({}, {})", + compressed.len(), + out.len(), + header.get_compressed_length(), + header.get_uncompressed_length() + ))); + } + + let mut reader = compressed; + let mut writer = &mut out[..]; + let written = header + .get_compression_scheme()? + .decompress_from_reader(&mut reader, &mut writer)?; + + if written != header.get_uncompressed_length() as u64 { + return Err(CoreError::MalformedData( + "chunk is corrupted, uncompressed bytes len doesn't agree with chunk header".to_string(), + )); + } + Ok(()) +} + pub fn deserialize_chunks(reader: &mut R) -> Result<(Vec, Vec), CoreError> { let mut buf = Vec::new(); let (_, chunk_byte_indices) = deserialize_chunks_to_writer(reader, &mut buf)?; diff --git a/xet_core_structures/src/xorb_object/xorb_chunk_format/deserialize_async.rs b/xet_core_structures/src/xorb_object/xorb_chunk_format/deserialize_async.rs index bbc2ea96c..b06bfcaa5 100644 --- a/xet_core_structures/src/xorb_object/xorb_chunk_format/deserialize_async.rs +++ b/xet_core_structures/src/xorb_object/xorb_chunk_format/deserialize_async.rs @@ -56,7 +56,7 @@ pub async fn deserialize_chunk(reader: &mut R) -> Result<( /// Uses a single `read()` call to detect EOF (returns 0), then completes /// any partial header with `read_exact`. An `UnexpectedEof` from `read_exact` /// means the stream was truncated mid-header. -async fn try_read_chunk_header_async( +pub async fn try_read_chunk_header_async( reader: &mut R, ) -> Result, CoreError> { let mut header_buf = [0u8; XORB_CHUNK_HEADER_LENGTH]; diff --git a/xet_data/src/file_reconstruction/data_writer/data_writer.rs b/xet_data/src/file_reconstruction/data_writer/data_writer.rs index 3f9897995..900693994 100644 --- a/xet_data/src/file_reconstruction/data_writer/data_writer.rs +++ b/xet_data/src/file_reconstruction/data_writer/data_writer.rs @@ -1,17 +1,8 @@ -use std::future::Future; -use std::pin::Pin; - -use bytes::Bytes; use xet_client::cas_types::FileRange; use xet_runtime::utils::adjustable_semaphore::AdjustableSemaphorePermit; use super::super::Result; - -/// A future that produces the data bytes to be written. -#[cfg(not(target_family = "wasm"))] -pub type DataFuture = Pin> + Send + 'static>>; -#[cfg(target_family = "wasm")] -pub type DataFuture = Pin> + 'static>>; +use super::super::reconstruction_terms::TermReader; #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)] #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))] @@ -19,18 +10,19 @@ pub trait DataWriter: Send + 'static { /// Sets the data source for the next sequential term. /// /// The byte range must be sequential - its start must match the end of the - /// previous range (or 0 for the first call). The data future will be spawned - /// as a task and its result will be written when ready. + /// previous range (or 0 for the first call), and its length must match the + /// reader's. The reader's bytes become available as the term's xorb block is + /// downloaded; the writer consumes them when ready. /// /// SequentialWriter will ensure that the actual writes happen in order. /// /// An optional semaphore permit can be passed for rate limiting. The permit - /// will be released by the background writer after the data has been written. + /// will be released by the writer after the data has been written. async fn set_next_term_data_source( &mut self, byte_range: FileRange, permit: Option, - data_future: DataFuture, + reader: TermReader, ) -> Result<()>; /// Consumes the writer, waits until all data has been written, and returns the diff --git a/xet_data/src/file_reconstruction/data_writer/download_stream.rs b/xet_data/src/file_reconstruction/data_writer/download_stream.rs index a1219c141..6eab3f39e 100644 --- a/xet_data/src/file_reconstruction/data_writer/download_stream.rs +++ b/xet_data/src/file_reconstruction/data_writer/download_stream.rs @@ -6,9 +6,11 @@ use tokio::sync::mpsc::UnboundedReceiver; #[cfg(target_family = "wasm")] use tokio_with_wasm::alias as tokio; use tracing::info; +use xet_runtime::utils::adjustable_semaphore::AdjustableSemaphorePermit; -use super::super::error::{FileReconstructionError, Result}; +use super::super::error::Result; use super::super::file_reconstructor::FileReconstructor; +use super::super::reconstruction_terms::TermReader; use super::super::run_state::RunState; use super::sequential_writer::{SequentialRetrievalItem, SequentialWriter}; @@ -21,15 +23,19 @@ use super::sequential_writer::{SequentialRetrievalItem, SequentialWriter}; /// `start()`, `next()`, and `blocking_next()` do **not** require a tokio runtime /// context. /// -/// Data is delivered by pulling items directly from the sequential writer's +/// Data is delivered by pulling terms directly from the sequential writer's /// internal queue, bypassing the synchronous writer thread entirely. Each call /// to [`blocking_next`](Self::blocking_next) / [`next`](Self::next) returns the -/// next sequential chunk, or `None` when the download is complete. Any +/// next sequential bytes that are ready, as soon as they are decompressed: a +/// term's bytes arrive in several pieces while its xorb block downloads, rather +/// than all at once after it. Returns `None` when the download is complete. Any /// reconstruction error is surfaced on the call that would have returned the /// next chunk (or on the final `None` boundary) via the shared run state. pub struct DownloadStream { /// Channel receiver for sequential retrieval items from the writer queue. receiver: UnboundedReceiver, + /// The term being read and its buffer permit, released once the term has been returned in full. + current: Option<(TermReader, Option)>, /// Whether the stream has finished (no more data). finished: bool, /// Shared run state with the `FileReconstructor`. When cancelled, @@ -63,6 +69,7 @@ impl DownloadStream { Self { receiver, + current: None, finished: false, run_state, start_signal: Some(start_signal), @@ -123,26 +130,22 @@ impl DownloadStream { } self.ensure_started(); - match self.receiver.blocking_recv() { - Some(SequentialRetrievalItem::Data { receiver, permit }) => { - let data = match receiver.blocking_recv() { - Ok(data) => data, - Err(_) => { - self.run_state.check_error()?; - return Err(FileReconstructionError::InternalWriterError( - "Data sender was dropped before sending data.".to_string(), - )); - }, - }; - self.run_state.report_bytes_written(data.len() as u64); - drop(permit); - Ok(Some(data)) - }, - Some(SequentialRetrievalItem::Finish) | None => { - self.finished = true; - self.run_state.check_error()?; - Ok(None) - }, + loop { + if self.current.is_none() { + match self.receiver.blocking_recv() { + Some(SequentialRetrievalItem::Data { reader, permit }) => self.current = Some((reader, permit)), + Some(SequentialRetrievalItem::Finish) | None => return self.finish(), + } + } + + let Some((reader, _)) = self.current.as_mut() else { + continue; + }; + let piece = reader.read_next_blocking(); + let data = self.take_piece(piece)?; + if data.is_some() || self.finished { + return Ok(data); + } } } @@ -155,37 +158,70 @@ impl DownloadStream { } self.ensure_started(); - let item = if let Ok(item) = self.receiver.try_recv() { - Some(item) - } else { - tokio::select! { + loop { + if self.current.is_none() { + let item = if let Ok(item) = self.receiver.try_recv() { + Some(item) + } else { + tokio::select! { + biased; + recv = self.receiver.recv() => recv, + _ = self.run_state.cancelled() => None, + } + }; + match item { + Some(SequentialRetrievalItem::Data { reader, permit }) => self.current = Some((reader, permit)), + Some(SequentialRetrievalItem::Finish) | None => return self.finish(), + } + } + + let Some((reader, _)) = self.current.as_mut() else { + continue; + }; + let piece = tokio::select! { biased; - recv = self.receiver.recv() => recv, - _ = self.run_state.cancelled() => None, + piece = reader.read_next() => piece, + _ = self.run_state.cancelled() => return self.finish(), + }; + let data = self.take_piece(piece)?; + if data.is_some() || self.finished { + return Ok(data); } - }; + } + } - match item { - Some(SequentialRetrievalItem::Data { receiver, permit }) => { - let data = match receiver.await { - Ok(data) => data, - Err(_) => { - self.run_state.check_error()?; - return Err(FileReconstructionError::InternalWriterError( - "Data sender was dropped before sending data.".to_string(), - )); - }, - }; - self.run_state.report_bytes_written(data.len() as u64); - drop(permit); - Ok(Some(data)) - }, - Some(SequentialRetrievalItem::Finish) | None => { + /// Handles one read of the current term: reports returned bytes, and moves past the term (releasing its + /// buffer permit) once it has been returned in full. `None` means the term is done and the next one should + /// be read, unless the stream has finished. + fn take_piece(&mut self, piece: Result>) -> Result> { + let piece = match piece { + Ok(piece) => piece, + Err(e) => { self.finished = true; + self.current = None; self.run_state.check_error()?; - Ok(None) + // A cancelled reconstruction fails its block downloads; that is the end of the stream, not an error. + if self.run_state.is_cancelled() { + return Ok(None); + } + return Err(e); }, + }; + + if let Some(data) = &piece { + self.run_state.report_bytes_written(data.len() as u64); + } + if self.current.as_ref().is_some_and(|(reader, _)| reader.is_finished()) { + self.current = None; } + Ok(piece) + } + + fn finish(&mut self) -> Result> { + self.finished = true; + self.current = None; + self.run_state.check_error()?; + Ok(None) } /// Cancels the in-progress (or not-yet-started) download. @@ -198,6 +234,7 @@ impl DownloadStream { self.cancel_reconstruction(); let _ = self.start_signal.take(); self.receiver.close(); + self.current = None; self.finished = true; } } diff --git a/xet_data/src/file_reconstruction/data_writer/mod.rs b/xet_data/src/file_reconstruction/data_writer/mod.rs index 8724bd112..5d289370a 100644 --- a/xet_data/src/file_reconstruction/data_writer/mod.rs +++ b/xet_data/src/file_reconstruction/data_writer/mod.rs @@ -5,7 +5,7 @@ mod sequential_writer; pub mod unordered_download_stream; mod unordered_writer; -pub use data_writer::{DataFuture, DataWriter}; +pub use data_writer::DataWriter; pub use download_stream::DownloadStream; pub use sequential_writer::SequentialWriter; pub use unordered_download_stream::UnorderedDownloadStream; diff --git a/xet_data/src/file_reconstruction/data_writer/sequential_writer.rs b/xet_data/src/file_reconstruction/data_writer/sequential_writer.rs index e050eeae9..54e156e5e 100644 --- a/xet_data/src/file_reconstruction/data_writer/sequential_writer.rs +++ b/xet_data/src/file_reconstruction/data_writer/sequential_writer.rs @@ -5,15 +5,15 @@ use std::sync::atomic::{AtomicU64, Ordering}; use bytes::Bytes; use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; -use tokio::sync::oneshot; -use tokio::task::{JoinHandle, JoinSet}; +use tokio::task::JoinHandle; #[cfg(target_family = "wasm")] use tokio_with_wasm::alias as tokio; use xet_client::cas_types::FileRange; use xet_runtime::core::XetContext; use xet_runtime::utils::adjustable_semaphore::AdjustableSemaphorePermit; -use super::super::data_writer::{DataFuture, DataWriter}; +use super::super::data_writer::DataWriter; +use super::super::reconstruction_terms::TermReader; use super::super::run_state::RunState; use super::super::{FileReconstructionError, Result}; use crate::progress_tracking::ItemProgressUpdater; @@ -29,12 +29,12 @@ use crate::progress_tracking::ItemProgressUpdater; // 64 MiB, this effectively limits total number of bytes in iov to 64 MiB * 24 = 1.5 GiB. const WRITEV_MAX_SLICE: usize = 24; -/// Items sent through the sequential writer queue. Each item is either a data -/// chunk (with a oneshot receiver that resolves to the actual bytes) or a +/// Items sent through the sequential writer queue. Each item is either a term +/// (a reader of its bytes, which its xorb block's download task fills) or a /// finish marker indicating no more items will follow. pub(crate) enum SequentialRetrievalItem { Data { - receiver: oneshot::Receiver, + reader: TermReader, permit: Option, }, Finish, @@ -97,34 +97,23 @@ impl SyncWriterThread { // Process the pending item if we have one. match self.pending.take() { - Some(SequentialRetrievalItem::Data { mut receiver, permit }) => { - if should_block { - let data = match receiver.blocking_recv() { - Ok(data) => data, - Err(_) => { - self.run_state.check_error()?; - return Err(FileReconstructionError::InternalWriterError( - "Data sender was dropped before sending data.".to_string(), - )); - }, - }; - Ok(Some((data, permit))) + Some(SequentialRetrievalItem::Data { mut reader, permit }) => { + let data = if should_block { + reader.read_rest_blocking().map(Some) } else { - // Non-blocking: try to receive data. - match receiver.try_recv() { - Ok(data) => Ok(Some((data, permit))), - Err(oneshot::error::TryRecvError::Empty) => { - // Data not ready - put the item back in pending. - self.pending = Some(SequentialRetrievalItem::Data { receiver, permit }); - Ok(None) - }, - Err(oneshot::error::TryRecvError::Closed) => { - self.run_state.check_error()?; - Err(FileReconstructionError::InternalWriterError( - "Data sender was dropped before sending data.".to_string(), - )) - }, - } + reader.try_read_rest() + }; + match data { + Ok(Some(data)) => Ok(Some((data, permit))), + Ok(None) => { + // Data not ready - put the item back in pending. + self.pending = Some(SequentialRetrievalItem::Data { reader, permit }); + Ok(None) + }, + Err(e) => { + self.run_state.check_error()?; + Err(e) + }, } }, Some(SequentialRetrievalItem::Finish) => { @@ -225,16 +214,17 @@ impl SyncWriterThread { } } -/// Writes data sequentially to an output stream from async data futures. -/// Spawns async tasks to resolve futures and a background thread to perform -/// blocking writes, allowing out-of-order future resolution with in-order writes. +/// Writes term data sequentially to an output stream. +/// +/// Terms are queued in order as readers of their xorb blocks; the blocks download concurrently in their own +/// tasks, and a background thread writes each term once all of its bytes are ready. In streaming mode the queue +/// is handed to a [`DownloadStream`](super::DownloadStream) instead of a thread. pub struct SequentialWriter { sender: UnboundedSender, next_position: u64, background_handle: Option>, run_state: Arc, bytes_written: Arc, - active_tasks: JoinSet>, finished: bool, } @@ -249,21 +239,15 @@ impl Drop for SequentialWriter { #[cfg_attr(not(target_family = "wasm"), async_trait::async_trait)] #[cfg_attr(target_family = "wasm", async_trait::async_trait(?Send))] impl DataWriter for SequentialWriter { - /// Sets the source for the next block of data; this is a future that - /// can be executing in the background. This must be the next one sequentially, - /// otherwise it will error out. + /// Queues the next term. It must start where the previous term ended, otherwise this errors out. async fn set_next_term_data_source( &mut self, byte_range: FileRange, permit: Option, - data_future: DataFuture, + reader: TermReader, ) -> Result<()> { self.run_state.check_error()?; - while let Some(result) = self.active_tasks.try_join_next() { - result.map_err(|e| FileReconstructionError::InternalError(format!("Task join error: {e}")))??; - } - if self.finished { return Err(FileReconstructionError::InternalWriterError("Writer has already finished".to_string())); } @@ -276,53 +260,24 @@ impl DataWriter for SequentialWriter { } let expected_size = byte_range.end - byte_range.start; + if reader.len() != expected_size { + return Err(FileReconstructionError::InternalWriterError(format!( + "Data size mismatch: expected {} bytes, got {} bytes", + expected_size, + reader.len() + ))); + } self.next_position = byte_range.end; - let (sender, receiver) = oneshot::channel(); - - if self.sender.send(SequentialRetrievalItem::Data { receiver, permit }).is_err() { + if self.sender.send(SequentialRetrievalItem::Data { reader, permit }).is_err() { self.run_state.check_error()?; return Err(FileReconstructionError::InternalWriterError("Background writer channel closed".to_string())); } - let run_state = self.run_state.clone(); - let task = async move { - let result = async { - run_state.check_error()?; - - let data = data_future.await?; - - if data.len() as u64 != expected_size { - return Err(FileReconstructionError::InternalWriterError(format!( - "Data size mismatch: expected {} bytes, got {} bytes", - expected_size, - data.len() - ))); - } - - if sender.send(data).is_err() { - run_state.check_error()?; - return Err(FileReconstructionError::InternalWriterError( - "Failed to send data: receiver dropped".to_string(), - )); - } - - Ok(()) - } - .await; - - if let Err(ref e) = result { - run_state.set_error(e.clone()); - } - result - }; - - self.active_tasks.spawn(task); - Ok(()) } - /// Wait for the background writer to finish and all tasks to complete. + /// Wait for the background writer to finish. /// Returns the number of bytes written. async fn finish(mut self: Box) -> Result { self.run_state.check_error()?; @@ -340,10 +295,6 @@ impl DataWriter for SequentialWriter { let expected_bytes = self.next_position; - while let Some(result) = self.active_tasks.join_next().await { - result.map_err(|e| FileReconstructionError::InternalError(format!("Task join error: {e}")))??; - } - match self.background_handle.take() { Some(handle) => { handle.await.map_err(|e| { @@ -388,7 +339,6 @@ impl SequentialWriter { background_handle: None, run_state, bytes_written: Arc::new(AtomicU64::new(0)), - active_tasks: JoinSet::new(), finished: false, }; @@ -436,7 +386,6 @@ impl SequentialWriter { background_handle: Some(handle), run_state, bytes_written, - active_tasks: JoinSet::new(), finished: false, }) } @@ -450,6 +399,7 @@ mod tests { use xet_runtime::core::XetContext; use xet_runtime::utils::adjustable_semaphore::AdjustableSemaphore; + use super::super::super::reconstruction_terms::test_utils::{delayed_reader, failing_reader, ready_reader}; use super::*; fn test_context() -> XetContext { @@ -606,8 +556,8 @@ mod tests { } } - fn immediate_future(data: Bytes) -> DataFuture { - Box::pin(async move { Ok(data) }) + fn immediate_future(data: Bytes) -> TermReader { + ready_reader(data) } #[tokio::test] @@ -653,16 +603,10 @@ mod tests { RunState::new_for_test(), ); - // Create futures that resolve with delays - let f0: DataFuture = Box::pin(async { - tokio::time::sleep(Duration::from_millis(50)).await; - Ok(Bytes::from("Hello")) - }); - let f1: DataFuture = Box::pin(async { - tokio::time::sleep(Duration::from_millis(10)).await; - Ok(Bytes::from(" ")) - }); - let f2: DataFuture = Box::pin(async { Ok(Bytes::from("World")) }); + // Create readers whose data arrives with delays + let f0 = delayed_reader("Hello", Duration::from_millis(50)); + let f1 = delayed_reader(" ", Duration::from_millis(10)); + let f2 = ready_reader("World"); writer.set_next_term_data_source(FileRange::new(0, 5), None, f0).await.unwrap(); writer.set_next_term_data_source(FileRange::new(5, 6), None, f1).await.unwrap(); @@ -679,13 +623,10 @@ mod tests { let buffer = std::io::Cursor::new(Vec::new()); let mut writer = SequentialWriter::new(&test_context(), Box::new(buffer), false, RunState::new_for_test()); - writer + let result = writer .set_next_term_data_source(FileRange::new(0, 10), None, immediate_future(Bytes::from("Hello"))) - .await - .unwrap(); - - let result = writer.finish().await; - assert!(result.is_err()); + .await; + assert!(matches!(result, Err(FileReconstructionError::InternalWriterError(_)))); } #[tokio::test] @@ -749,8 +690,7 @@ mod tests { RunState::new_for_test(), ); - let failing_future: DataFuture = - Box::pin(async { Err(FileReconstructionError::InternalError("Simulated future error".to_string())) }); + let failing_future = failing_reader(5, "Simulated download error"); writer .set_next_term_data_source(FileRange::new(0, 5), None, failing_future) @@ -766,13 +706,10 @@ mod tests { let buffer = std::io::Cursor::new(Vec::new()); let mut writer = SequentialWriter::new(&test_context(), Box::new(buffer), false, RunState::new_for_test()); - writer + let result = writer .set_next_term_data_source(FileRange::new(0, 10), None, immediate_future(Bytes::from("Hi"))) - .await - .unwrap(); - - let result = writer.finish().await; - assert!(result.is_err()); + .await; + assert!(matches!(result, Err(FileReconstructionError::InternalWriterError(_)))); } #[tokio::test] @@ -780,13 +717,10 @@ mod tests { let buffer = std::io::Cursor::new(Vec::new()); let mut writer = SequentialWriter::new(&test_context(), Box::new(buffer), false, RunState::new_for_test()); - writer + let result = writer .set_next_term_data_source(FileRange::new(0, 2), None, immediate_future(Bytes::from("Hello World"))) - .await - .unwrap(); - - let result = writer.finish().await; - assert!(result.is_err()); + .await; + assert!(matches!(result, Err(FileReconstructionError::InternalWriterError(_)))); } #[tokio::test] @@ -957,16 +891,10 @@ mod tests { let mut writer = SequentialWriter::new(&test_context(), Box::new(test_writer), true, RunState::new_for_test()); - // Create futures that resolve with different delays - let f0: DataFuture = Box::pin(async { - tokio::time::sleep(Duration::from_millis(30)).await; - Ok(Bytes::from("A")) - }); - let f1: DataFuture = Box::pin(async { - tokio::time::sleep(Duration::from_millis(10)).await; - Ok(Bytes::from("B")) - }); - let f2: DataFuture = Box::pin(async { Ok(Bytes::from("C")) }); + // Create readers whose data arrives with different delays + let f0 = delayed_reader("A", Duration::from_millis(30)); + let f1 = delayed_reader("B", Duration::from_millis(10)); + let f2 = ready_reader("C"); writer.set_next_term_data_source(FileRange::new(0, 1), None, f0).await.unwrap(); writer.set_next_term_data_source(FileRange::new(1, 2), None, f1).await.unwrap(); diff --git a/xet_data/src/file_reconstruction/data_writer/unordered_writer.rs b/xet_data/src/file_reconstruction/data_writer/unordered_writer.rs index d1176467e..9b5757370 100644 --- a/xet_data/src/file_reconstruction/data_writer/unordered_writer.rs +++ b/xet_data/src/file_reconstruction/data_writer/unordered_writer.rs @@ -9,13 +9,15 @@ use tokio_with_wasm::alias as tokio; use xet_client::cas_types::FileRange; use xet_runtime::utils::adjustable_semaphore::AdjustableSemaphorePermit; -use super::super::data_writer::{DataFuture, DataWriter}; +use super::super::data_writer::DataWriter; +use super::super::reconstruction_terms::TermReader; use super::super::run_state::RunState; use super::super::{FileReconstructionError, Result}; -/// A completed term ready for consumption. Contains the byte range indicating -/// where this data belongs in the output file, the actual data bytes, and an -/// optional semaphore permit for backpressure control. +/// Ready data of a term for consumption: the byte range indicating where this +/// data belongs in the output file, the data bytes, and an optional semaphore +/// permit for backpressure control. A term is delivered as one or more of these, +/// as its xorb block downloads. pub(crate) struct CompletedTerm { pub byte_range: FileRange, pub data: Bytes, @@ -43,8 +45,8 @@ impl UnorderedWriterProgress { /// Writer that delivers completed data terms in arbitrary order. /// /// Each call to [`set_next_term_data_source`](DataWriter::set_next_term_data_source) -/// spawns a task (tracked via a [`JoinSet`]) that resolves the data future and -/// sends the result through an [`mpsc`](tokio::sync::mpsc) channel. The consumer +/// spawns a task (tracked via a [`JoinSet`]) that reads the term's bytes as they +/// become ready and sends each piece through an [`mpsc`](tokio::sync::mpsc) channel. The consumer /// (typically an [`UnorderedDownloadStream`](super::unordered_download_stream::UnorderedDownloadStream)) /// reads from the receiver end and gets items in whatever order tasks complete. /// @@ -76,7 +78,7 @@ impl DataWriter for UnorderedWriter { &mut self, byte_range: FileRange, permit: Option, - data_future: DataFuture, + mut reader: TermReader, ) -> Result<()> { self.run_state.check_error()?; @@ -90,6 +92,14 @@ impl DataWriter for UnorderedWriter { } let expected_size = byte_range.end - byte_range.start; + if reader.len() != expected_size { + return Err(FileReconstructionError::InternalWriterError(format!( + "Data size mismatch: expected {} bytes, got {} bytes", + expected_size, + reader.len() + ))); + } + self.progress.terms_in_progress.fetch_add(1, Ordering::Relaxed); self.progress.bytes_in_progress.fetch_add(expected_size, Ordering::Relaxed); @@ -98,44 +108,55 @@ impl DataWriter for UnorderedWriter { let progress = self.progress.clone(); self.task_set.spawn(async move { - let result = async { - run_state.check_error()?; + let mut permit = permit; + let mut bytes_sent = 0u64; - let data = data_future.await?; + let result: Result<()> = async { + run_state.check_error()?; - if data.len() as u64 != expected_size { - return Err(FileReconstructionError::InternalWriterError(format!( - "Data size mismatch: expected {} bytes, got {} bytes", - expected_size, - data.len() - ))); + while let Some(data) = reader.read_next().await? { + let len = data.len() as u64; + let start = byte_range.start + bytes_sent; + bytes_sent += len; + + // Each piece carries its share of the term's buffer permit; the last carries the rest. + let piece_permit = if reader.is_finished() { + permit.take() + } else { + permit.as_mut().and_then(|p| p.split(len)) + }; + progress.bytes_in_progress.fetch_sub(len, Ordering::Relaxed); + + let piece = CompletedTerm { + byte_range: FileRange::new(start, start + len), + data, + permit: piece_permit, + }; + if result_tx.send(Ok(piece)).is_err() { + // The consumer is gone; the reconstruction is being torn down. + break; + } } - - Ok(CompletedTerm { - byte_range, - data, - permit, - }) + Ok(()) } .await; - if let Err(ref e) = result { - run_state.set_error(e.clone()); - } - - let completed_bytes = result.as_ref().map(|t| t.data.len() as u64).unwrap_or(0); - - let _ = result_tx.send(result); - - progress.bytes_in_progress.fetch_sub(expected_size, Ordering::Relaxed); + progress + .bytes_in_progress + .fetch_sub(expected_size - bytes_sent, Ordering::Relaxed); progress.terms_in_progress.fetch_sub(1, Ordering::Release); - if completed_bytes > 0 { - Ok(completed_bytes) - } else { + if let Err(e) = result { run_state.check_error()?; - Ok(0) + // A cancelled reconstruction fails its block downloads; that is not an error of this term. + if run_state.is_cancelled() { + return Ok(bytes_sent); + } + run_state.set_error(e.clone()); + let _ = result_tx.send(Err(e.clone())); + return Err(e); } + Ok(bytes_sent) }); Ok(()) @@ -192,17 +213,15 @@ mod tests { use xet_runtime::utils::adjustable_semaphore::AdjustableSemaphore; + use super::super::super::reconstruction_terms::test_utils::{delayed_reader, failing_reader, ready_reader}; use super::*; - fn immediate_future(data: Bytes) -> DataFuture { - Box::pin(async move { Ok(data) }) + fn immediate_future(data: Bytes) -> TermReader { + ready_reader(data) } - fn delayed_future(data: Bytes, delay: Duration) -> DataFuture { - Box::pin(async move { - tokio::time::sleep(delay).await; - Ok(data) - }) + fn delayed_future(data: Bytes, delay: Duration) -> TermReader { + delayed_reader(data, delay) } /// Drains all results from the receiver, returning data sorted by offset. @@ -284,17 +303,13 @@ mod tests { let run_state = RunState::new_for_test(); let (mut writer, mut rx, _progress) = UnorderedWriter::new_streaming(run_state); - writer + let result = writer .set_next_term_data_source(FileRange::new(0, 10), None, immediate_future(Bytes::from("Hello"))) - .await - .unwrap(); - - let result = writer.finish().await; - assert!(result.is_err()); - - let result = rx.recv().await.unwrap(); - assert!(result.is_err()); + .await; assert!(matches!(result, Err(FileReconstructionError::InternalWriterError(_)))); + + writer.finish().await.unwrap(); + assert!(rx.recv().await.is_none()); } #[tokio::test] @@ -302,8 +317,7 @@ mod tests { let run_state = RunState::new_for_test(); let (mut writer, mut rx, _progress) = UnorderedWriter::new_streaming(run_state); - let failing_future: DataFuture = - Box::pin(async { Err(FileReconstructionError::InternalError("Simulated error".to_string())) }); + let failing_future = failing_reader(5, "Simulated error"); writer .set_next_term_data_source(FileRange::new(0, 5), None, failing_future) @@ -400,8 +414,7 @@ mod tests { let run_state = RunState::new_for_test(); let (mut writer, mut _rx, _progress) = UnorderedWriter::new_streaming(run_state.clone()); - let failing_future: DataFuture = - Box::pin(async { Err(FileReconstructionError::InternalError("fail".to_string())) }); + let failing_future = failing_reader(5, "fail"); writer .set_next_term_data_source(FileRange::new(0, 5), None, failing_future) diff --git a/xet_data/src/file_reconstruction/file_reconstructor.rs b/xet_data/src/file_reconstruction/file_reconstructor.rs index 9ac918e4c..d05378a2f 100644 --- a/xet_data/src/file_reconstruction/file_reconstructor.rs +++ b/xet_data/src/file_reconstruction/file_reconstructor.rs @@ -272,7 +272,7 @@ impl FileReconstructor { async fn run_impl( self, mut data_writer: Box, - run_state: &RunState, + run_state: &Arc, _is_streaming: bool, ) -> std::result::Result { let Self { @@ -401,14 +401,21 @@ impl FileReconstructor { }, }; - let data_future = file_term - .get_data_task( + // Starting a block's download waits for a download permit; doing it here, in term order, makes + // blocks download in file order. + let reader = tokio::select! { + biased; + _ = run_state.cancelled() => { + return run_state.check_run_state().map(|_| 0); + } + result = file_term.start_read( ctx.clone(), client.clone(), run_state.progress_updater().cloned(), chunk_cache.clone(), - ) - .await?; + run_state.clone(), + ) => result?, + }; #[cfg(debug_assertions)] { @@ -423,7 +430,7 @@ impl FileReconstructor { ); data_writer - .set_next_term_data_source(relative_byte_range, Some(buffer_permit), data_future) + .set_next_term_data_source(relative_byte_range, Some(buffer_permit), reader) .await?; run_state.record_new_term(term_size); @@ -528,6 +535,58 @@ mod tests { Ok(data) } + fn new_reconstructor( + client: &Arc, + file_hash: MerkleHash, + byte_range: Option, + config: &ReconstructionConfig, + ) -> FileReconstructor { + let reconstructor = + FileReconstructor::new(&XetContext::default().unwrap(), &(client.clone() as Arc), file_hash) + .with_config(config); + match byte_range { + Some(range) => reconstructor.with_byte_range(range), + None => reconstructor, + } + } + + /// Reconstructs through a `DownloadStream` and returns the concatenated pieces. + async fn reconstruct_to_stream_vec( + client: &Arc, + file_hash: MerkleHash, + byte_range: Option, + config: &ReconstructionConfig, + ) -> Result> { + let mut stream = new_reconstructor(client, file_hash, byte_range, config).reconstruct_to_stream(); + let mut data = Vec::new(); + while let Some(piece) = stream.next().await? { + data.extend_from_slice(&piece); + } + Ok(data) + } + + /// Reconstructs through an `UnorderedDownloadStream` and assembles the pieces by offset, checking that they + /// cover the output exactly once. + async fn reconstruct_to_unordered_stream_vec( + client: &Arc, + file_hash: MerkleHash, + byte_range: Option, + config: &ReconstructionConfig, + ) -> Result> { + let mut stream = new_reconstructor(client, file_hash, byte_range, config).reconstruct_to_unordered_stream(); + let mut pieces = Vec::new(); + while let Some(piece) = stream.next().await? { + pieces.push(piece); + } + pieces.sort_by_key(|(offset, _)| *offset); + let mut data = Vec::new(); + for (offset, piece) in pieces { + assert_eq!(offset, data.len() as u64, "unordered pieces must tile the output"); + data.extend_from_slice(&piece); + } + Ok(data) + } + /// Reconstructs to a file and returns the reconstructed data. /// Creates a temp file, reconstructs to it, then reads the relevant portion back. async fn reconstruct_to_file( @@ -652,6 +711,14 @@ mod tests { let file_specific_result = reconstruct_to_file_at_specific_offset(client, h, None, &config).await.unwrap(); assert_eq!(file_specific_result, *expected, "file_at_specific_offset failed (vectored={use_vectored})"); } + + // Test 5: ordered and unordered streams + let stream_result = reconstruct_to_stream_vec(client, h, None, &base_config).await.unwrap(); + assert_eq!(stream_result, *expected, "stream failed"); + let unordered_result = reconstruct_to_unordered_stream_vec(client, h, None, &base_config) + .await + .unwrap(); + assert_eq!(unordered_result, *expected, "unordered stream failed"); } /// Reconstructs and verifies a byte range using all output methods and vectored/non-vectored writes. @@ -687,6 +754,15 @@ mod tests { .expect("reconstruct_to_file_at_offset_zero should succeed"); assert_eq!(file_offset_result, expected, "file_at_offset failed (vectored={use_vectored})"); } + + // Test 4: ordered and unordered streams + let h = file_contents.file_hash; + let stream_result = reconstruct_to_stream_vec(client, h, Some(range), &base_config).await.unwrap(); + assert_eq!(stream_result, expected, "stream failed"); + let unordered_result = reconstruct_to_unordered_stream_vec(client, h, Some(range), &base_config) + .await + .unwrap(); + assert_eq!(unordered_result, expected, "unordered stream failed"); } // ==================== Full File Reconstruction Tests ==================== @@ -1024,6 +1100,21 @@ mod tests { reconstruct_and_verify_full(&client, &file_contents, test_config()).await; } + #[tokio::test] + async fn test_overlapping_terms_without_exact_cover() { + // Terms [0,3) and [2,5) of one xorb share a block whose exact size the terms can't give. + let (client, file_contents) = setup_test_file(&[(1, (0, 3)), (1, (2, 5)), (1, (1, 4))]).await; + reconstruct_and_verify_full(&client, &file_contents, ReconstructionConfig::default()).await; + let file_len = file_contents.data.len() as u64; + reconstruct_and_verify_range( + &client, + &file_contents, + FileRange::new(file_len / 3 + 7, file_len - 11), + ReconstructionConfig::default(), + ) + .await; + } + #[tokio::test] async fn test_non_contiguous_chunks() { let (client, file_contents) = setup_test_file(&[(1, (0, 2)), (1, (4, 6))]).await; @@ -2032,4 +2123,384 @@ mod tests { } } } // mod server_tests + + /// Streams deliver each block's bytes as they are decompressed, not after the whole block has downloaded. + mod streaming_tests { + use bytes::Bytes; + use tokio::sync::watch; + use xet_client::cas_client::adaptive_concurrency::ConnectionPermit; + use xet_client::cas_client::{ + BlockByteRange, ProgressCallback, ReadAmount, ShardUploadProgressCallback, URLProvider, XorbBlockData, + }; + use xet_client::cas_types::{ + BatchQueryReconstructionResponse, FileChunkHashesResponse, QueryReconstructionResponseV2, + }; + use xet_core_structures::metadata_shard::file_structs::MDBFileInfo; + use xet_core_structures::xorb_object::SerializedXorbObject; + + use super::*; + + /// How `GatedClient` delivers a block. + #[derive(Clone, Copy)] + enum TermDataBehavior { + /// Appends the first chunk, waits until the test opens the gate, then appends the rest. + GateAfterFirstChunk, + /// Appends the first chunk, then fails the download. + FailAfterFirstChunk, + /// Delivers the block as the inner client does, but each transfer progress report takes a while. + DelayProgressReports, + /// Allows one download at a time: a download permit is granted only once the previous block has + /// finished downloading. Records each block's first bytes, in download order, in `downloads`. + OneDownloadAtATime, + } + + /// Wraps a `LocalClient`, changing how blocks are delivered; see `TermDataBehavior`. + struct GatedClient { + inner: Arc, + gate: watch::Receiver, + behavior: TermDataBehavior, + /// Download slots for `OneDownloadAtATime`. + download_slots: Arc, + /// The first bytes of each downloaded block, in download order (`OneDownloadAtATime` only). + downloads: Arc>>, + } + + impl GatedClient { + fn new(inner: Arc, gate: watch::Receiver, behavior: TermDataBehavior) -> Self { + Self { + inner, + gate, + behavior, + download_slots: Arc::new(tokio::sync::Semaphore::new(1)), + downloads: Arc::new(std::sync::Mutex::new(Vec::new())), + } + } + } + + #[async_trait::async_trait] + impl Client for GatedClient { + async fn get_file_reconstruction_info( + &self, + file_hash: &MerkleHash, + ) -> xet_client::error::Result)>> { + self.inner.get_file_reconstruction_info(file_hash).await + } + + async fn get_reconstruction( + &self, + file_id: &MerkleHash, + bytes_range: Option, + ) -> xet_client::error::Result> { + self.inner.get_reconstruction(file_id, bytes_range).await + } + + async fn batch_get_reconstruction( + &self, + file_ids: &[MerkleHash], + ) -> xet_client::error::Result { + self.inner.batch_get_reconstruction(file_ids).await + } + + async fn acquire_download_permit(&self) -> xet_client::error::Result { + if let TermDataBehavior::OneDownloadAtATime = self.behavior { + // Returned by `get_file_term_data` once the download is done. + self.download_slots.acquire().await.unwrap().forget(); + } + self.inner.acquire_download_permit().await + } + + async fn get_file_term_data( + &self, + url_info: Box, + download_permit: ConnectionPermit, + progress_callback: Option, + output: Arc, + ) -> xet_client::error::Result<()> { + if let TermDataBehavior::DelayProgressReports = self.behavior { + // A report made after the last chunk is appended would land after the reconstruction + // completes, failing its progress check. + let delayed: Option = progress_callback.map(|cb| { + Arc::new(move |delta: u64, completed: u64, total: u64| { + std::thread::sleep(Duration::from_millis(100)); + cb(delta, completed, total); + }) as ProgressCallback + }); + return self.inner.get_file_term_data(url_info, download_permit, delayed, output).await; + } + + if let TermDataBehavior::OneDownloadAtATime = self.behavior { + let result = self + .inner + .get_file_term_data(url_info, download_permit, progress_callback, output.clone()) + .await; + let first_bytes = BlockByteRange { + first_chunk: 0, + offset_into_first_chunk: 0, + len: 16, + }; + let prefix = output.try_read(&first_bytes, 0, ReadAmount::All).unwrap().unwrap(); + self.downloads.lock().unwrap().push(prefix); + self.download_slots.add_permits(1); + return result; + } + + let full = Arc::new(XorbBlockData::with_size_bound(output.capacity())); + self.inner + .get_file_term_data(url_info, download_permit, progress_callback, full.clone()) + .await?; + full.finish()?; + let (data, offsets) = full.contents().unwrap(); + + let first_end = offsets[1]; + output.append_chunks(&data[..first_end as usize], &[0, first_end])?; + + match self.behavior { + TermDataBehavior::GateAfterFirstChunk => { + let _ = self.gate.clone().wait_for(|open| *open).await; + }, + TermDataBehavior::FailAfterFirstChunk => { + return Err(xet_client::ClientError::Other("simulated failure after first chunk".into())); + }, + TermDataBehavior::DelayProgressReports | TermDataBehavior::OneDownloadAtATime => { + unreachable!("handled above") + }, + } + + let rest: Vec = offsets[1..].iter().map(|o| o - first_end).collect(); + output.append_chunks(&data[first_end as usize..], &rest) + } + + async fn query_for_global_dedup_shard( + &self, + prefix: &str, + chunk_hash: &MerkleHash, + ) -> xet_client::error::Result> { + self.inner.query_for_global_dedup_shard(prefix, chunk_hash).await + } + + async fn acquire_upload_permit(&self) -> xet_client::error::Result { + self.inner.acquire_upload_permit().await + } + + async fn upload_shard( + &self, + shard_data: Bytes, + upload_permit: ConnectionPermit, + progress_callback: Option, + ) -> xet_client::error::Result> { + self.inner.upload_shard(shard_data, upload_permit, progress_callback).await + } + + async fn upload_xorb( + &self, + prefix: &str, + serialized_xorb_object: SerializedXorbObject, + progress_callback: Option, + upload_permit: ConnectionPermit, + ) -> xet_client::error::Result { + self.inner + .upload_xorb(prefix, serialized_xorb_object, progress_callback, upload_permit) + .await + } + + async fn get_file_chunk_hashes( + &self, + file_id: &MerkleHash, + dirty_ranges: Vec, + ) -> xet_client::error::Result { + self.inner.get_file_chunk_hashes(file_id, dirty_ranges).await + } + } + + /// One term covering 40 chunks of a single xorb, so the whole file is one block. Reconstructs the bytes + /// from `trim.0` to `trim.1` before the end, if given. Returns the gated reconstructor, the gate, and the + /// file contents. + async fn gated_single_block_file( + behavior: TermDataBehavior, + trim: Option<(u64, u64)>, + ) -> (FileReconstructor, watch::Sender, RandomFileContents) { + let (client, file_contents) = setup_test_file(&[(1, (0, 40))]).await; + let (gate_tx, gate_rx) = watch::channel(false); + let gated: Arc = Arc::new(GatedClient::new(client, gate_rx, behavior)); + let mut reconstructor = + FileReconstructor::new(&XetContext::default().unwrap(), &gated, file_contents.file_hash); + if let Some((start, end_trim)) = trim { + let len = file_contents.data.len() as u64; + reconstructor = reconstructor.with_byte_range(FileRange::new(start, len - end_trim)); + } + (reconstructor, gate_tx, file_contents) + } + + const FIRST_BYTES_TIMEOUT: Duration = Duration::from_secs(10); + + #[tokio::test] + async fn test_stream_yields_first_chunk_before_block_completes() { + let (reconstructor, gate, file_contents) = + gated_single_block_file(TermDataBehavior::GateAfterFirstChunk, None).await; + let mut stream = reconstructor.reconstruct_to_stream(); + + // The rest of the block is held back until the stream has returned its first bytes. + let first = tokio::time::timeout(FIRST_BYTES_TIMEOUT, stream.next()) + .await + .expect("the first chunk must be streamed before the rest of its block downloads") + .unwrap() + .unwrap(); + assert!(!first.is_empty() && first.len() < file_contents.data.len()); + assert_eq!(first, file_contents.data[..first.len()]); + + gate.send(true).unwrap(); + let mut data = first.to_vec(); + while let Some(piece) = stream.next().await.unwrap() { + data.extend_from_slice(&piece); + } + assert_eq!(data, file_contents.data); + } + + #[tokio::test] + async fn test_blocking_stream_yields_first_chunk_before_block_completes() { + let (reconstructor, gate, file_contents) = + gated_single_block_file(TermDataBehavior::GateAfterFirstChunk, None).await; + let mut stream = reconstructor.reconstruct_to_stream(); + + let reader = tokio::task::spawn_blocking(move || { + let first = stream.blocking_next().unwrap().unwrap(); + gate.send(true).unwrap(); + let mut data = first.to_vec(); + while let Some(piece) = stream.blocking_next().unwrap() { + data.extend_from_slice(&piece); + } + (first.len(), data) + }); + let (first_len, data) = tokio::time::timeout(FIRST_BYTES_TIMEOUT, reader) + .await + .expect("the first chunk must be streamed before the rest of its block downloads") + .unwrap(); + assert!(first_len < file_contents.data.len()); + assert_eq!(data, file_contents.data); + } + + #[tokio::test] + async fn test_unordered_stream_yields_first_chunk_before_block_completes() { + let (reconstructor, gate, file_contents) = + gated_single_block_file(TermDataBehavior::GateAfterFirstChunk, None).await; + let mut stream = reconstructor.reconstruct_to_unordered_stream(); + + let (offset, first) = tokio::time::timeout(FIRST_BYTES_TIMEOUT, stream.next()) + .await + .expect("the first chunk must be streamed before the rest of its block downloads") + .unwrap() + .unwrap(); + assert_eq!(offset, 0); + assert!(first.len() < file_contents.data.len()); + + gate.send(true).unwrap(); + let mut data = first.to_vec(); + while let Some((offset, piece)) = stream.next().await.unwrap() { + assert_eq!(offset, data.len() as u64); + data.extend_from_slice(&piece); + } + assert_eq!(data, file_contents.data); + } + + #[tokio::test] + async fn test_stream_range_starting_mid_chunk() { + // Start 50 bytes into the first chunk and end 30 bytes before the file does. + let (reconstructor, gate, file_contents) = + gated_single_block_file(TermDataBehavior::GateAfterFirstChunk, Some((50, 30))).await; + let range = FileRange::new(50, file_contents.data.len() as u64 - 30); + let mut stream = reconstructor.reconstruct_to_stream(); + let first = tokio::time::timeout(FIRST_BYTES_TIMEOUT, stream.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(first, file_contents.data[50..50 + first.len()]); + + gate.send(true).unwrap(); + let mut data = first.to_vec(); + while let Some(piece) = stream.next().await.unwrap() { + data.extend_from_slice(&piece); + } + assert_eq!(data, file_contents.data[range.start as usize..range.end as usize]); + } + + #[tokio::test] + async fn test_stream_error_after_partial_block() { + let (reconstructor, _gate, file_contents) = + gated_single_block_file(TermDataBehavior::FailAfterFirstChunk, None).await; + let mut stream = reconstructor.reconstruct_to_stream(); + + // Bytes already delivered stay delivered; the failure surfaces on a later read. + let mut received = Vec::new(); + let err = loop { + match tokio::time::timeout(FIRST_BYTES_TIMEOUT, stream.next()).await.unwrap() { + Ok(Some(piece)) => received.extend_from_slice(&piece), + Ok(None) => panic!("stream must fail, not end"), + Err(err) => break err, + } + }; + assert!(matches!(err, FileReconstructionError::ClientError(_)), "{err:?}"); + assert!(received.len() < file_contents.data.len()); + assert_eq!(received, file_contents.data[..received.len()]); + } + + // Multi-threaded, so the reconstruction can complete while a delayed progress report is pending. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_transfer_progress_complete_when_writing_finishes() { + // Writing to a file asserts (in debug builds) that all transfer bytes were reported by the time the + // last byte is written; a client reporting progress after appending a block's last chunk fails it. + let (reconstructor, _gate, file_contents) = + gated_single_block_file(TermDataBehavior::DelayProgressReports, None).await; + let temp_dir = tempfile::tempdir().unwrap(); + let path = temp_dir.path().join("out.bin"); + let written = reconstructor.reconstruct_to_file(&path, None, true).await.unwrap(); + assert_eq!(written, file_contents.data.len() as u64); + assert_eq!(std::fs::read(&path).unwrap(), file_contents.data); + } + + // Multi-threaded, where the runtime runs spawned tasks in no particular order. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn test_blocks_download_in_file_order() { + // Eight blocks, one per xorb, in file order. + let term_spec: Vec<(u64, (u64, u64))> = (1..=8).map(|xorb| (xorb, (0, 4))).collect(); + let (client, file_contents) = setup_test_file(&term_spec).await; + let (_gate_tx, gate_rx) = watch::channel(false); + let gated = Arc::new(GatedClient::new(client, gate_rx, TermDataBehavior::OneDownloadAtATime)); + let downloads = gated.downloads.clone(); + + let gated: Arc = gated; + let mut stream = FileReconstructor::new(&XetContext::default().unwrap(), &gated, file_contents.file_hash) + .reconstruct_to_stream(); + let mut data = Vec::new(); + while let Some(piece) = tokio::time::timeout(FIRST_BYTES_TIMEOUT, stream.next()).await.unwrap().unwrap() { + data.extend_from_slice(&piece); + } + assert_eq!(data, file_contents.data); + + // The last block is recorded after its data is appended, so the stream can end first. + tokio::time::timeout(FIRST_BYTES_TIMEOUT, async { + while downloads.lock().unwrap().len() < 8 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + + // Each block's first bytes locate it in the file; blocks must have downloaded front to back. + let offsets: Vec = downloads + .lock() + .unwrap() + .iter() + .map(|prefix| { + file_contents + .data + .windows(prefix.len()) + .position(|window| window == prefix.as_ref()) + .unwrap() + }) + .collect(); + assert_eq!(offsets.len(), 8); + assert!(offsets.windows(2).all(|w| w[0] < w[1]), "blocks downloaded out of file order: {offsets:?}"); + } + } // mod streaming_tests } diff --git a/xet_data/src/file_reconstruction/mod.rs b/xet_data/src/file_reconstruction/mod.rs index 5c455e9e4..7627f738d 100644 --- a/xet_data/src/file_reconstruction/mod.rs +++ b/xet_data/src/file_reconstruction/mod.rs @@ -7,4 +7,4 @@ mod run_state; pub use data_writer::{DataWriter, DownloadStream, SequentialWriter, UnorderedDownloadStream, UnorderedWriter}; pub use error::{FileReconstructionError, Result}; pub use file_reconstructor::FileReconstructor; -pub use reconstruction_terms::{FileTerm, ReconstructionTermManager, XorbBlock, XorbBlockData}; +pub use reconstruction_terms::{FileTerm, ReconstructionTermManager, TermReader, XorbBlock}; diff --git a/xet_data/src/file_reconstruction/reconstruction_terms/file_term.rs b/xet_data/src/file_reconstruction/reconstruction_terms/file_term.rs index 0f1f2d3a1..971973eb4 100644 --- a/xet_data/src/file_reconstruction/reconstruction_terms/file_term.rs +++ b/xet_data/src/file_reconstruction/reconstruction_terms/file_term.rs @@ -2,11 +2,7 @@ use std::collections::HashMap; use std::collections::hash_map::Entry; use std::sync::Arc; -use bytes::Bytes; -use tokio::sync::OnceCell; -#[cfg(target_family = "wasm")] -use tokio_with_wasm::alias as tokio; -use xet_client::cas_client::Client; +use xet_client::cas_client::{BlockByteRange, Client}; use xet_client::cas_types::{ChunkRange, FileRange, HttpRange}; use xet_client::chunk_cache::ChunkCache; use xet_core_structures::merklehash::MerkleHash; @@ -14,10 +10,11 @@ use xet_runtime::core::XetContext; use xet_runtime::utils::UniqueId; use super::super::FileReconstructionError; -use super::super::data_writer::DataFuture; use super::super::error::Result; +use super::super::run_state::RunState; use super::retrieval_urls::TermBlockRetrievalURLs; -use super::xorb_block::{XorbBlock, XorbBlockData, XorbReference}; +use super::term_reader::TermReader; +use super::xorb_block::{XorbBlock, XorbReference}; use crate::progress_tracking::ItemProgressUpdater; /// A single term in a file reconstruction, representing a contiguous byte range /// in the output file that maps to a chunk range within a xorb block. @@ -43,49 +40,44 @@ pub struct FileTerm { } impl FileTerm { - pub fn extract_bytes(&self, xorb_block_data: &XorbBlockData) -> Bytes { - let (_, start_byte_offset) = xorb_block_data.chunk_offsets[self.xorb_block_start_index]; - let start_byte_offset = start_byte_offset + self.offset_into_first_range as usize; - let expected_size = (self.byte_range.end - self.byte_range.start) as usize; - let end_byte_offset = start_byte_offset + expected_size; - - xorb_block_data.data.slice(start_byte_offset..end_byte_offset) - } - - /// Get a future that will retrieve and extract the data bytes for this file term. + /// Starts downloading this term's xorb block, unless another term on the block already did, and returns a + /// reader of the term's bytes. /// - /// If the xorb data is already cached, returns a future that immediately resolves (no progress - /// report, since the block was already reported by the term that triggered the download). - /// Otherwise, spawns a task that calls retrieve_data, which uses single-flight to ensure - /// only one download per xorb block (other callers wait without acquiring CAS permits). - pub async fn get_data_task( + /// Waits for a download permit if this term starts the block's download; calling this for terms in file + /// order makes blocks download in file order. The download runs in its own task and fills the block's shared + /// data as chunks are decompressed, so the reader can return the term's first bytes before the rest of the + /// block has arrived. + pub(crate) async fn start_read( &self, ctx: XetContext, client: Arc, progress_updater: Option>, chunk_cache: Option>, - ) -> Result { - // Fast path: data already cached, no need to spawn a task. - if let Some(xorb_block_data) = self.xorb_block.data.get() { - let bytes = self.extract_bytes(xorb_block_data); - return Ok(Box::pin(async move { Ok(bytes) })); - } - - let file_term = self.clone(); - let url_info = self.url_info.clone(); - let xorb_block = self.xorb_block.clone(); - - let task = tokio::task::spawn(async move { - let xorb_block_data = xorb_block - .retrieve_data(ctx, client, url_info, progress_updater, chunk_cache) - .await?; - Ok(file_term.extract_bytes(&xorb_block_data)) - }); - - Ok(Box::pin(async move { task.await? })) + run_state: Arc, + ) -> Result { + self.xorb_block + .start_fetch(ctx, client, self.url_info.clone(), progress_updater, chunk_cache, run_state) + .await?; + + Ok(TermReader::new( + self.xorb_block.data.clone(), + BlockByteRange { + first_chunk: self.xorb_block_start_index, + offset_into_first_chunk: self.offset_into_first_range as usize, + len: (self.byte_range.end - self.byte_range.start) as usize, + }, + )) } } +/// A xorb block being collected from the reconstruction terms, before its references are complete and its data +/// buffer can be sized. +struct PendingXorbBlock { + xorb_hash: MerkleHash, + chunk_ranges: Vec, + references: Vec, +} + /// Intermediate data for a single file term, collected during the first pass of /// `retrieve_file_term_block` before the final `FileTerm` structs are built. /// @@ -134,7 +126,7 @@ pub async fn retrieve_file_term_block( // Parallel vectors indexed by xorb_block_index: // - xorb_blocks: the block metadata (hash, chunk ranges, references) // - xorb_block_retrieval_urls: the download URL and byte ranges for each block - let mut xorb_blocks: Vec = Vec::new(); + let mut xorb_blocks: Vec = Vec::new(); let mut xorb_block_retrieval_urls = Vec::<(String, Vec)>::new(); // Dedup map: (xorb_hash, first_range_chunk_start) -> xorb_block_index. @@ -185,13 +177,10 @@ pub async fn retrieve_file_term_block( let chunk_ranges: Vec = fetch_entry.ranges.iter().map(|r| r.chunks).collect(); let http_ranges: Vec = fetch_entry.ranges.iter().map(|r| r.bytes).collect(); - xorb_blocks.push(XorbBlock { + xorb_blocks.push(PendingXorbBlock { xorb_hash, chunk_ranges, - xorb_block_index: new_index, references: vec![], - uncompressed_size_if_known: None, - data: OnceCell::new(), }); xorb_block_retrieval_urls.push((fetch_entry.url.clone(), http_ranges)); @@ -210,13 +199,10 @@ pub async fn retrieve_file_term_block( Entry::Vacant(entry) => { let new_index = xorb_blocks.len(); - xorb_blocks.push(XorbBlock { + xorb_blocks.push(PendingXorbBlock { xorb_hash, chunk_ranges: vec![range.chunks], - xorb_block_index: new_index, references: vec![], - uncompressed_size_if_known: None, - data: OnceCell::new(), }); xorb_block_retrieval_urls.push((fetch_entry.url.clone(), vec![range.bytes])); @@ -292,14 +278,6 @@ pub async fn retrieve_file_term_block( cur_file_byte_offset += term_byte_size; } - // Sort each block's references by chunk start so that determine_size_if_possible - // can use its forward-chaining DP to check coverage. - for block in &mut xorb_blocks { - block.references.sort_by_key(|r| r.term_chunks.start); - block.uncompressed_size_if_known = - XorbBlock::determine_size_if_possible(&block.chunk_ranges, &block.references); - } - // The last term in the reconstruction may extend beyond the requested range // (e.g. when the query ends mid-chunk). Trim it to the query boundary. if cur_file_byte_offset > query_file_byte_range.end { @@ -333,7 +311,14 @@ pub async fn retrieve_file_term_block( // Second pass: convert the intermediate FileTermEntry data into final FileTerm // structs, now that we can wrap xorb blocks in Arc and share the url_info. - let xorb_blocks_arc: Vec> = xorb_blocks.into_iter().map(Arc::new).collect(); + // Each block's data buffer is sized from all of its references, so blocks are built only now. + let xorb_blocks_arc: Vec> = xorb_blocks + .into_iter() + .enumerate() + .map(|(index, block)| { + XorbBlock::new(block.xorb_hash, block.chunk_ranges, index, block.references).map(Arc::new) + }) + .collect::>()?; let file_terms: Vec = file_term_data .into_iter() @@ -485,12 +470,15 @@ mod tests { // Verify all xorb blocks referenced have valid hashes. assert!(file_contents.xorbs.contains_key(&file_term.xorb_block.xorb_hash)); - // Get the data task and await it. - let data_future = file_term - .get_data_task(ctx.clone(), dyn_client.clone(), None, None) + // Read the term's data in full. + let mut reader = file_term + .start_read(ctx.clone(), dyn_client.clone(), None, None, RunState::new_for_test()) .await .unwrap(); - let data = data_future.await.unwrap(); + let mut data = Vec::new(); + while let Some(piece) = reader.read_next().await.unwrap() { + data.extend_from_slice(&piece); + } // Verify the data size matches the byte range. let expected_size = (file_term.byte_range.end - file_term.byte_range.start) as usize; diff --git a/xet_data/src/file_reconstruction/reconstruction_terms/mod.rs b/xet_data/src/file_reconstruction/reconstruction_terms/mod.rs index 02b9fca66..ec37282ec 100644 --- a/xet_data/src/file_reconstruction/reconstruction_terms/mod.rs +++ b/xet_data/src/file_reconstruction/reconstruction_terms/mod.rs @@ -1,8 +1,12 @@ mod file_term; mod manager; mod retrieval_urls; +mod term_reader; mod xorb_block; pub use file_term::FileTerm; pub use manager::ReconstructionTermManager; -pub use xorb_block::{XorbBlock, XorbBlockData}; +pub use term_reader::TermReader; +#[cfg(test)] +pub(crate) use term_reader::test_utils; +pub use xorb_block::XorbBlock; diff --git a/xet_data/src/file_reconstruction/reconstruction_terms/term_reader.rs b/xet_data/src/file_reconstruction/reconstruction_terms/term_reader.rs new file mode 100644 index 000000000..acd9347b3 --- /dev/null +++ b/xet_data/src/file_reconstruction/reconstruction_terms/term_reader.rs @@ -0,0 +1,146 @@ +use std::sync::Arc; + +use bytes::Bytes; +use xet_client::ClientError; +use xet_client::cas_client::{BlockByteRange, ReadAmount, XorbBlockData}; + +use super::super::error::{FileReconstructionError, Result}; + +/// Reads one file term's bytes from its xorb block's shared data as the block is downloaded. +/// +/// A reader is a position within the term's byte range of the block; it holds no data of its own, and reads are +/// zero-copy views of the block. The block's download task, started when the term was scheduled, fills the data +/// independently of when (or whether) the term is read. If the download fails, every read returns the error. +pub struct TermReader { + data: Arc, + range: BlockByteRange, + /// Bytes of the term already returned. + position: usize, +} + +impl TermReader { + pub(crate) fn new(data: Arc, range: BlockByteRange) -> Self { + Self { + data, + range, + position: 0, + } + } + + /// The term's total length in bytes. + pub fn len(&self) -> u64 { + self.range.len as u64 + } + + /// Whether the term has no bytes. + pub fn is_empty(&self) -> bool { + self.range.len == 0 + } + + /// Whether every byte of the term has been returned. + pub fn is_finished(&self) -> bool { + self.position == self.range.len + } + + /// Returns the rest of the term if all of it is ready, without waiting; `None` if it is not ready yet. + #[cfg(not(target_family = "wasm"))] + pub(crate) fn try_read_rest(&mut self) -> Result> { + let data = self + .data + .try_read(&self.range, self.position, ReadAmount::All) + .map_err(read_error)?; + Ok(data.map(|data| self.advance(data))) + } + + /// Returns the rest of the term, blocking the thread until all of it is ready. + #[cfg(not(target_family = "wasm"))] + pub(crate) fn read_rest_blocking(&mut self) -> Result { + let data = self + .data + .read_blocking(&self.range, self.position, ReadAmount::All) + .map_err(read_error)?; + Ok(self.advance(data)) + } + + /// Returns the term's next ready bytes, waiting until at least one is ready; `None` once the whole term has + /// been returned. + pub(crate) async fn read_next(&mut self) -> Result> { + if self.is_finished() { + return Ok(None); + } + let data = self + .data + .read(&self.range, self.position, ReadAmount::Available) + .await + .map_err(read_error)?; + Ok(Some(self.advance(data))) + } + + /// Blocking version of [`read_next`](Self::read_next). + #[cfg(not(target_family = "wasm"))] + pub(crate) fn read_next_blocking(&mut self) -> Result> { + if self.is_finished() { + return Ok(None); + } + let data = self + .data + .read_blocking(&self.range, self.position, ReadAmount::Available) + .map_err(read_error)?; + Ok(Some(self.advance(data))) + } + + fn advance(&mut self, data: Bytes) -> Bytes { + self.position += data.len(); + debug_assert!(self.position <= self.range.len); + data + } +} + +fn read_error(err: Arc) -> FileReconstructionError { + FileReconstructionError::ClientError(err) +} + +#[cfg(test)] +pub(crate) mod test_utils { + use std::time::Duration; + + use super::*; + + fn whole_range(len: usize) -> BlockByteRange { + BlockByteRange { + first_chunk: 0, + offset_into_first_chunk: 0, + len, + } + } + + /// A reader whose data is already complete. + pub(crate) fn ready_reader(data: impl Into) -> TermReader { + let data: Bytes = data.into(); + let block = Arc::new(XorbBlockData::with_exact_size(data.len())); + block.append_chunks(&data, &[0, data.len() as u32]).unwrap(); + block.finish().unwrap(); + TermReader::new(block, whole_range(data.len())) + } + + /// A reader whose data arrives after `delay`. + pub(crate) fn delayed_reader(data: impl Into, delay: Duration) -> TermReader { + let data: Bytes = data.into(); + let block = Arc::new(XorbBlockData::with_exact_size(data.len())); + let writer = block.clone(); + let len = data.len(); + tokio::spawn(async move { + tokio::time::sleep(delay).await; + writer.append_chunks(&data, &[0, data.len() as u32]).unwrap(); + writer.finish().unwrap(); + }); + TermReader::new(block, whole_range(len)) + } + + /// A reader of `len` bytes whose block download fails with `message`. + pub(crate) fn failing_reader(len: usize, message: &str) -> TermReader { + let block = Arc::new(XorbBlockData::with_exact_size(len)); + block.fail(Arc::new(ClientError::Other(message.to_string()))); + TermReader::new(block, whole_range(len)) + } +} diff --git a/xet_data/src/file_reconstruction/reconstruction_terms/xorb_block.rs b/xet_data/src/file_reconstruction/reconstruction_terms/xorb_block.rs index 699fda8d5..7d2e9912e 100644 --- a/xet_data/src/file_reconstruction/reconstruction_terms/xorb_block.rs +++ b/xet_data/src/file_reconstruction/reconstruction_terms/xorb_block.rs @@ -1,9 +1,13 @@ use std::collections::BTreeMap; use std::sync::Arc; - -use bytes::Bytes; -use tokio::sync::{Mutex, OnceCell}; -use xet_client::cas_client::{Client, ProgressCallback}; +use std::sync::atomic::{AtomicBool, Ordering}; + +use tokio::sync::Mutex; +#[cfg(target_family = "wasm")] +use tokio_with_wasm::alias as tokio; +use xet_client::ClientError; +use xet_client::cas_client::adaptive_concurrency::ConnectionPermit; +use xet_client::cas_client::{Client, ProgressCallback, XorbBlockData}; use xet_client::cas_types::ChunkRange; #[cfg(not(target_family = "wasm"))] use xet_client::cas_types::Key; @@ -12,25 +16,12 @@ use xet_core_structures::merklehash::MerkleHash; use xet_runtime::core::XetContext; use xet_runtime::utils::UniqueId; +use super::super::FileReconstructionError; use super::super::error::Result; +use super::super::run_state::RunState; use super::retrieval_urls::{TermBlockRetrievalURLs, XorbURLProvider}; use crate::progress_tracking::ItemProgressUpdater; -/// Downloaded and decompressed data for a xorb block, including chunk boundary offsets. -/// -/// A single `XorbBlockData` may hold data from multiple disjoint chunk ranges -/// (V2 multi-range fetch). The chunks are concatenated in range order, and -/// `chunk_offsets` maps each chunk index to its byte position within `data`. -pub struct XorbBlockData { - /// Pairs of (chunk_index, byte_offset) mapping each chunk to its start position - /// within `data`. Because the block can span multiple disjoint chunk ranges, - /// storing the chunk index alongside the offset avoids ambiguity. - pub chunk_offsets: Vec<(usize, usize)>, - - /// The concatenated decompressed chunk data for all ranges in this block. - pub data: Bytes, -} - /// A reference from a file term back to the xorb block it belongs to. /// Used by `determine_size_if_possible` to check whether the block's total /// uncompressed size can be inferred from the terms that reference it. @@ -42,12 +33,12 @@ pub struct XorbReference { pub uncompressed_size: usize, } -/// A downloadable xorb block identified by hash and chunk ranges, with cached data. +/// A downloadable xorb block identified by hash and chunk ranges, with its shared data buffer. /// /// A block may contain multiple disjoint chunk ranges from the same xorb (V2 multi-range). -/// Multiple file terms may reference the same block. Downloaded data is cached in `data` -/// so that the first term to request it triggers the download, and subsequent terms -/// reuse the cached result. +/// Multiple file terms may reference the same block. The first term to need the block starts a single +/// download task that appends decompressed chunks to `data`; every term on the block reads its bytes from +/// `data` as they become ready. pub struct XorbBlock { pub xorb_hash: MerkleHash, /// The chunk ranges fetched for this block. For V1 this is a single range; @@ -56,12 +47,13 @@ pub struct XorbBlock { /// Index into the parent `TermBlockRetrievalURLs` for URL lookup. pub xorb_block_index: usize, /// All file-term references covered by this block, sorted by chunk range start. - /// Populated during `retrieve_file_term_block` and used to compute `uncompressed_size_if_known`. pub references: Vec, - /// Expected total decompressed size across all chunk ranges, if it can be determined - /// from the references. Passed to clients as a debug assertion hint. + /// Exact total decompressed size across all chunk ranges, if it can be determined from the references. pub uncompressed_size_if_known: Option, - pub data: OnceCell>, + /// The block's decompressed data, filled by the download task and read by the block's terms. + pub data: Arc, + /// Set by the first term that starts the download, so the block is downloaded once. + fetch_started: AtomicBool, } impl PartialEq for XorbBlock { @@ -74,113 +66,250 @@ impl PartialEq for XorbBlock { impl Eq for XorbBlock {} -/// Builds chunk offset pairs from chunk ranges and a flat byte-offset slice. -fn build_chunk_offsets(chunk_ranges: &[ChunkRange], byte_offsets: &[u32]) -> Vec<(usize, usize)> { - let mut chunk_offsets = Vec::new(); - let mut offset_idx = 0; - for range in chunk_ranges { - for chunk_idx in range.start..range.end { - chunk_offsets.push((chunk_idx as usize, byte_offsets[offset_idx] as usize)); - offset_idx += 1; - } +/// Fails the block's data if the download task ends without finishing it (a panic, or the runtime shutting down), +/// so that readers waiting on the block are woken instead of waiting forever. +struct FailUnfinishedOnDrop(Arc); + +impl Drop for FailUnfinishedOnDrop { + fn drop(&mut self) { + self.0 + .fail(Arc::new(ClientError::Other("xorb block download ended before completing".to_string()))); } - chunk_offsets } impl XorbBlock { - /// Retrieve the xorb block data from the client, caching it for subsequent calls. + /// Creates a block from its chunk ranges and the terms that reference it, sizing its data buffer from the + /// terms' decompressed sizes. + /// + /// The terms give no per-chunk sizes, so the block's exact size is known only when terms sit end to end + /// across it. When terms overlap, the buffer is sized to the smallest sum of terms that covers the block, an + /// upper bound. A block that no set of terms covers is rejected. + pub fn new( + xorb_hash: MerkleHash, + chunk_ranges: Vec, + xorb_block_index: usize, + mut references: Vec, + ) -> Result { + references.sort_by_key(|r| r.term_chunks.start); + let uncompressed_size_if_known = Self::determine_size_if_possible(&chunk_ranges, &references); + let data = match uncompressed_size_if_known { + Some(size) => XorbBlockData::with_exact_size(size), + None => { + let bound = Self::determine_size_bound(&chunk_ranges, &references).ok_or_else(|| { + FileReconstructionError::CorruptedReconstruction(format!( + "terms do not cover xorb block {xorb_hash} chunk ranges {chunk_ranges:?}" + )) + })?; + XorbBlockData::with_size_bound(bound) + }, + }; + + Ok(Self { + xorb_hash, + chunk_ranges, + xorb_block_index, + references, + uncompressed_size_if_known, + data: Arc::new(data), + fetch_started: AtomicBool::new(false), + }) + } + + /// Starts downloading the block into `data` in a background task, unless a term already started it. + /// + /// The download permit is acquired here, before the task is spawned, so that blocks queue for permits in the + /// order their terms are scheduled, which is file order. Acquiring it inside the spawned task would queue blocks + /// in whatever order the runtime happens to run the tasks, and a stream could wait behind several later blocks + /// before its first bytes arrive. /// - /// Uses single-flight: the first caller acquires a CAS download permit and downloads - /// the data; concurrent callers wait on the same result without acquiring permits or - /// duplicating work. If the download fails, the cell remains empty and a later caller - /// can retry. - pub async fn retrieve_data( - self: Arc, + /// On failure the task marks `data` failed, which wakes its readers, and records the error in `run_state` so + /// the reconstruction stops even if no reader is waiting on this block yet. If the reconstruction is cancelled, + /// the download is dropped and `data` is marked failed. The same happens if this call is dropped while waiting + /// for the permit. + pub(crate) async fn start_fetch( + self: &Arc, + ctx: XetContext, + client: Arc, + url_info: Arc, + progress_updater: Option>, + chunk_cache: Option>, + run_state: Arc, + ) -> Result<()> { + if self.fetch_started.swap(true, Ordering::AcqRel) { + return Ok(()); + } + + let fail_guard = FailUnfinishedOnDrop(self.data.clone()); + let permit = match client.acquire_download_permit().await { + Ok(permit) => permit, + Err(err) => { + let err = Arc::new(err); + self.data.fail(err.clone()); + return Err(FileReconstructionError::ClientError(err)); + }, + }; + + let block = self.clone(); + tokio::task::spawn(async move { + let _fail_guard = fail_guard; + + let result = tokio::select! { + biased; + _ = run_state.cancelled() => { + Err(ClientError::Other("reconstruction cancelled".to_string())) + }, + result = block.fetch(ctx, client, url_info, progress_updater, chunk_cache, permit) => result, + }; + + if let Err(err) = result { + let err = Arc::new(err); + // Record the error before waking readers, so that they find it in the run state. + if !run_state.is_cancelled() { + run_state.set_error(FileReconstructionError::ClientError(err.clone())); + } + block.data.fail(err); + } + }); + Ok(()) + } + + /// Fills `data` from the chunk cache or, failing that, from CAS using `permit`, then marks it finished. + async fn fetch( + &self, ctx: XetContext, client: Arc, url_info: Arc, progress_updater: Option>, #[cfg_attr(target_family = "wasm", allow(unused_variables))] chunk_cache: Option>, - ) -> Result> { + permit: ConnectionPermit, + ) -> std::result::Result<(), ClientError> { let xorb_block_index = self.xorb_block_index; - let uncompressed_size_if_known = self.uncompressed_size_if_known; - let chunk_ranges = self.chunk_ranges.clone(); - - self.data - .get_or_try_init(|| async { - // Try the on-disk chunk cache before hitting the network. - // NOTE: cache key uses only the first ChunkRange. This works when each - // XorbBlock has a single range, but will need rework if multi-range - // blocks (multiple disjoint chunk ranges per block) are cached. - // Wasm has no disk-backed ChunkCache; skip the cache read entirely. - #[cfg(not(target_family = "wasm"))] - if let Some(ref cache) = chunk_cache { - let cache_key = Key { - prefix: ctx.config.data.default_prefix.clone(), - hash: self.xorb_hash, - }; - let chunk_range = chunk_ranges.first().copied().unwrap_or_default(); - - if let Ok(Some(cache_range)) = cache.get(&cache_key, &chunk_range).await { + + // NOTE: cache key uses only the first ChunkRange. This works when each + // XorbBlock has a single range, but will need rework if multi-range + // blocks (multiple disjoint chunk ranges per block) are cached. + // Wasm has no disk-backed ChunkCache. + #[cfg(not(target_family = "wasm"))] + let cache_key = Key { + prefix: ctx.config.data.default_prefix.clone(), + hash: self.xorb_hash, + }; + #[cfg(not(target_family = "wasm"))] + let chunk_range = self.chunk_ranges.first().copied().unwrap_or_default(); + + #[cfg(not(target_family = "wasm"))] + let permit = match chunk_cache.as_ref() { + Some(cache) => match cache.get(&cache_key, &chunk_range).await { + Ok(Some(cache_range)) => { + // A cache hit is a local read: free the connection slot for the next block at once. Dropping + // an unused permit reports nothing to the concurrency controller. + drop(permit); + + // A cached range that doesn't fit this block is ignored, and the block is downloaded instead. + // A failed `append_chunks` writes nothing, so the download starts from an empty block. + let fits = self + .uncompressed_size_if_known + .is_none_or(|size| size == cache_range.data.len()); + if fits && self.data.append_chunks(&cache_range.data, &cache_range.offsets).is_ok() { // Report cached bytes as completed so progress tracking stays consistent. if let Some(ref updater) = progress_updater { let (_, _, http_ranges) = url_info.get_retrieval_url(xorb_block_index).await; let transfer_bytes: u64 = http_ranges.iter().map(|r| r.length()).sum(); updater.report_transfer_bytes_completed(transfer_bytes); } - let chunk_offsets = build_chunk_offsets(&chunk_ranges, &cache_range.offsets); - let data = Bytes::from(cache_range.data); - return Ok(Arc::new(XorbBlockData { chunk_offsets, data })); + return self.data.finish(); } + client.acquire_download_permit().await? + }, + _ => permit, + }, + None => permit, + }; + + let url_provider = XorbURLProvider { + ctx: ctx.clone(), + client: client.clone(), + url_info, + xorb_block_index, + last_acquisition_id: Mutex::new(UniqueId::null()), + }; + + // Progress callback reports only transfer (network) bytes during get_file_term_data. + // Decompressed bytes are reported by the data writer when written out. + let progress_callback: Option = progress_updater.as_ref().map(|updater| { + let updater = updater.clone(); + Arc::new(move |delta: u64, _completed: u64, _total: u64| { + updater.report_transfer_bytes_completed(delta); + }) as ProgressCallback + }); + + client + .get_file_term_data(Box::new(url_provider), permit, progress_callback, self.data.clone()) + .await?; + self.data.finish()?; + + // Store in chunk cache (best-effort, non-blocking). + #[cfg(not(target_family = "wasm"))] + if let Some(cache) = chunk_cache + && let Some((data, chunk_byte_offsets)) = self.data.contents() + { + tokio::spawn(async move { + if let Err(err) = cache.put(&cache_key, &chunk_range, &chunk_byte_offsets, &data).await { + tracing::warn!("chunk cache put failed: {err}"); } + }); + } - // Cache miss or no cache configured - download from CAS. - let permit = client.acquire_download_permit().await?; - - let url_provider = XorbURLProvider { - ctx: ctx.clone(), - client: client.clone(), - url_info, - xorb_block_index, - last_acquisition_id: Mutex::new(UniqueId::null()), - }; - - // Progress callback reports only transfer (network) bytes during get_file_term_data. - // Decompressed bytes are reported by the data writer when written to disk. - let progress_callback: Option = progress_updater.as_ref().map(|updater| { - let updater = updater.clone(); - Arc::new(move |delta: u64, _completed: u64, _total: u64| { - updater.report_transfer_bytes_completed(delta); - }) as ProgressCallback - }); - - let (data, chunk_byte_offsets) = client - .get_file_term_data(Box::new(url_provider), permit, progress_callback, uncompressed_size_if_known) - .await?; - - // Store in chunk cache (best-effort, non-blocking). - #[cfg(not(target_family = "wasm"))] - if let Some(cache) = chunk_cache { - let cache_key = Key { - prefix: ctx.config.data.default_prefix.clone(), - hash: self.xorb_hash, - }; - let chunk_range = chunk_ranges.first().copied().unwrap_or_default(); - let data = data.clone(); - let chunk_byte_offsets = chunk_byte_offsets.clone(); - tokio::spawn(async move { - if let Err(err) = cache.put(&cache_key, &chunk_range, &chunk_byte_offsets, &data).await { - tracing::warn!("chunk cache put failed: {err}"); - } - }); - } + Ok(()) + } - let chunk_offsets = build_chunk_offsets(&chunk_ranges, &chunk_byte_offsets); + /// Returns an upper bound on the block's total uncompressed size: the smallest sum of term sizes over a set + /// of terms that together cover every chunk range of the block, allowing terms to overlap. Equals the exact + /// size when terms sit end to end. + /// + /// Same forward pass as [`determine_size_if_possible`](Self::determine_size_if_possible), except a term may + /// extend coverage from any reachable position inside it rather than only from its start. Processing terms by + /// start finds the minimum: a path that uses a term B and then an earlier-starting term A can use A alone + /// from where B started, which covers at least as much for less. + /// + /// Returns `None` if some chunk is covered by no term. The `terms` slice must be sorted by + /// `term_chunks.start`. + pub fn determine_size_bound(xorb_ranges: &[ChunkRange], terms: &[XorbReference]) -> Option { + debug_assert!(terms.windows(2).all(|w| w[0].term_chunks.start <= w[1].term_chunks.start)); - Ok(Arc::new(XorbBlockData { chunk_offsets, data })) - }) - .await - .cloned() + let Some(first_range) = xorb_ranges.first() else { + return Some(0); + }; + + let gap_bridges: BTreeMap = xorb_ranges + .windows(2) + .filter(|pair| pair[0].end < pair[1].start) + .map(|pair| (pair[0].end, pair[1].start)) + .collect(); + + // Covered-up-to position -> smallest accumulated size reaching it. + let mut reachable: BTreeMap = BTreeMap::new(); + reachable.insert(first_range.start, 0); + + for term in terms { + let Some(from) = reachable + .range(term.term_chunks.start..term.term_chunks.end) + .map(|(_, &size)| size) + .min() + else { + continue; + }; + let new_size = from + term.uncompressed_size; + for position in std::iter::once(term.term_chunks.end).chain(gap_bridges.get(&term.term_chunks.end).copied()) + { + reachable + .entry(position) + .and_modify(|size| *size = (*size).min(new_size)) + .or_insert(new_size); + } + } + + reachable.get(&xorb_ranges.last()?.end).copied() } /// Determines the total uncompressed size of the xorb block from the reference terms, @@ -474,4 +603,65 @@ mod tests { let terms = build_refs(&[(ChunkRange::new(0, 3), 300)]); assert_eq!(XorbBlock::determine_size_if_possible(ranges, &terms), None); } + + #[test] + fn test_size_bound_equals_exact_size_when_terms_tile() { + let ranges = &[ChunkRange::new(0, 8)]; + let terms = build_refs(&[ + (ChunkRange::new(0, 3), 300), + (ChunkRange::new(3, 5), 200), + (ChunkRange::new(5, 8), 300), + ]); + assert_eq!(XorbBlock::determine_size_if_possible(ranges, &terms), Some(800)); + assert_eq!(XorbBlock::determine_size_bound(ranges, &terms), Some(800)); + } + + #[test] + fn test_size_bound_with_overlapping_terms() { + // [0,5) and [3,8) overlap on chunks 3 and 4, whose size is unknown. + let ranges = &[ChunkRange::new(0, 8)]; + let terms = build_refs(&[(ChunkRange::new(0, 5), 500), (ChunkRange::new(3, 8), 500)]); + assert_eq!(XorbBlock::determine_size_if_possible(ranges, &terms), None); + assert_eq!(XorbBlock::determine_size_bound(ranges, &terms), Some(1000)); + } + + #[test] + fn test_size_bound_picks_smallest_cover() { + // Covers: [0,8) alone = 900; [0,5) + [4,8) = 500 + 450 = 950; [0,5) + [2,8) = 1100. + let ranges = &[ChunkRange::new(0, 8)]; + let terms = build_refs(&[ + (ChunkRange::new(0, 5), 500), + (ChunkRange::new(0, 8), 900), + (ChunkRange::new(2, 8), 600), + (ChunkRange::new(4, 8), 450), + ]); + assert_eq!(XorbBlock::determine_size_if_possible(ranges, &terms), Some(900)); + assert_eq!(XorbBlock::determine_size_bound(ranges, &terms), Some(900)); + + let terms = build_refs(&[ + (ChunkRange::new(0, 5), 500), + (ChunkRange::new(2, 8), 600), + (ChunkRange::new(4, 8), 450), + ]); + assert_eq!(XorbBlock::determine_size_bound(ranges, &terms), Some(950)); + } + + #[test] + fn test_size_bound_across_disjoint_ranges() { + let ranges = &[ChunkRange::new(0, 4), ChunkRange::new(6, 9)]; + let terms = build_refs(&[ + (ChunkRange::new(0, 3), 300), + (ChunkRange::new(2, 4), 200), + (ChunkRange::new(6, 9), 300), + ]); + assert_eq!(XorbBlock::determine_size_if_possible(ranges, &terms), None); + assert_eq!(XorbBlock::determine_size_bound(ranges, &terms), Some(800)); + } + + #[test] + fn test_size_bound_none_when_a_chunk_is_uncovered() { + let ranges = &[ChunkRange::new(0, 8)]; + let terms = build_refs(&[(ChunkRange::new(0, 3), 300), (ChunkRange::new(4, 8), 400)]); + assert_eq!(XorbBlock::determine_size_bound(ranges, &terms), None); + } } diff --git a/xet_data/src/file_reconstruction/run_state.rs b/xet_data/src/file_reconstruction/run_state.rs index 41edb6ebd..feb80a09e 100644 --- a/xet_data/src/file_reconstruction/run_state.rs +++ b/xet_data/src/file_reconstruction/run_state.rs @@ -111,6 +111,11 @@ impl RunState { } /// Future that resolves when cancelled; for use in `select!`. + /// Whether the reconstruction has been cancelled, either directly or by an error. + pub(crate) fn is_cancelled(&self) -> bool { + self.cancellation_token.is_cancelled() + } + pub(crate) async fn cancelled(&self) { self.cancellation_token.cancelled().await; }