Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(batch-import-worker): stream decompression to bound staging disk (#67149)

Eli Reisman1adc3f382daf
diff --git a/rust/batch-import-worker/src/config.rs b/rust/batch-import-worker/src/config.rs
index bc4a5ae02d9c..7d7218862ae6 100644
--- a/rust/batch-import-worker/src/config.rs
+++ b/rust/batch-import-worker/src/config.rs
@@ -95,6 +95,13 @@ pub struct Config {
// every startup to reclaim space leaked by non-graceful pod terminations.
#[envconfig(from = "STAGING_DIR", default = "/tmp/batch-import-worker")]
pub staging_dir: String,
+
+ // Fail-fast guard: if the staging directory grows past this many bytes while
+ // downloading a part, the job is paused (surfaced to the user) instead of the
+ // pod being evicted under disk pressure. 0 disables the guard. Size this below
+ // the staging volume capacity in deployment.
+ #[envconfig(from = "STAGING_DIR_MAX_BYTES", default = "0")]
+ pub staging_dir_max_bytes: u64,
}
impl Config {
diff --git a/rust/batch-import-worker/src/extractor/mod.rs b/rust/batch-import-worker/src/extractor/mod.rs
index b556fba8c3ab..82c07fbc1c78 100644
--- a/rust/batch-import-worker/src/extractor/mod.rs
+++ b/rust/batch-import-worker/src/extractor/mod.rs
@@ -1,9 +1,10 @@
-use anyhow::{Context, Error};
-use async_trait::async_trait;
+use anyhow::Error;
+use flate2::read::GzDecoder;
use serde::{Deserialize, Serialize};
-use std::{path::Path, path::PathBuf, sync::Arc};
-use tokio::{fs::File, io::AsyncWriteExt};
-use tracing::debug;
+use std::panic::AssertUnwindSafe;
+use std::{io::Read, path::PathBuf, sync::Arc};
+use tokio::sync::mpsc;
+use zip::ZipArchive;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
@@ -22,237 +23,336 @@ impl ExtractorType {
}
}
-#[derive(Clone)]
-pub struct ExtractedPartData {
- pub data_file_path: PathBuf,
- pub data_file_size: usize,
+/// The data source trait reads parts in forward, monotonically increasing byte
+/// ranges. For sources that hand us a compressed file (export endpoints, gzipped
+/// S3 objects), we previously decompressed the whole thing to a second on-disk
+/// file so the range reads could `seek`. That made worst-case disk usage scale
+/// with the *decompressed* size — a single multi-GB compressed export could
+/// expand to tens of GB and exhaust the staging volume.
+///
+/// Instead we stream: a `PartExtractor` opens a [`StreamingReader`] over the
+/// compressed file that decompresses on demand as the job reads forward, so disk
+/// usage is bounded by the compressed `.raw` file alone. Decompression runs on a
+/// dedicated producer thread (off the async runtime) feeding a bounded channel;
+/// the reader keeps only a small carry buffer (~one chunk) of decompressed bytes.
+pub trait PartExtractor: Send + Sync {
+ /// Open a forward streaming reader over the compressed file at `raw_file_path`.
+ fn open_reader(&self, raw_file_path: PathBuf) -> StreamingReader;
}
-// The data source trait requires parts that can be seekable via byte offsets
-// To support data sources that don't have seekable parts by default (export endpoints that return compresed files),
-// we need this extractor that can handle converting whatever content the data source returned into a seekable file
-#[async_trait]
-pub trait PartExtractor: Send + Sync {
- async fn extract_compressed_to_seekable_file(
- &self,
- key: &str,
- file_path: &std::path::Path,
- temp_dir: &std::path::Path,
- ) -> Result<ExtractedPartData, Error>;
+/// Block size the producer thread reads/sends at. Larger blocks keep channel
+/// overhead low for multi-GB files.
+const PRODUCER_BLOCK_SIZE: usize = 64 * 1024;
+/// Bounded channel capacity (in blocks). Caps in-flight decompressed bytes and
+/// applies backpressure to the producer thread, so memory stays bounded.
+const PRODUCER_CHANNEL_CAPACITY: usize = 32;
+
+type Block = Result<Vec<u8>, String>;
+
+/// A decompressed range returned by [`StreamingReader::read_at`].
+pub struct ReadChunk {
+ pub bytes: Vec<u8>,
+ /// The total decompressed size, populated only once end-of-stream has been
+ /// observed. `None` while more data may follow — callers must not treat the
+ /// size as known until this is `Some`.
+ pub total: Option<u64>,
}
-pub struct ZipGzipJsonExtractor;
+/// A forward-only, resumable reader over a decompressed stream.
+///
+/// The decompressed size is discovered lazily (only once the producer hits EOF),
+/// because we never materialize the decompressed data and therefore cannot know
+/// its length up front. Reads must be monotonically non-decreasing in `offset`;
+/// small rewinds within the most recently returned span are supported (the job's
+/// chunker can re-request the tail of a partially-consumed chunk), but seeking
+/// backwards beyond the retained carry buffer is not.
+pub struct StreamingReader {
+ rx: mpsc::Receiver<Block>,
+ /// Decompressed bytes for the half-open range `[carry_start, decoded_end)`.
+ carry: Vec<u8>,
+ carry_start: u64,
+ decoded_end: u64,
+ eof: bool,
+}
-#[async_trait]
-impl PartExtractor for ZipGzipJsonExtractor {
- // This extracts a seekable file from a zip file that contains a bunch of json.gz files
- async fn extract_compressed_to_seekable_file(
- &self,
- key: &str,
- file_path: &Path,
- temp_dir: &Path,
- ) -> Result<ExtractedPartData, Error> {
- let data_file_path = temp_dir.join(format!("{}.data", key.replace(':', "_")));
- let mut output_file = File::create(&data_file_path)
- .await
- .with_context(|| format!("Failed to create data file for key: {key}"))?;
- let mut total_size = 0usize;
-
- let file_entries = tokio::task::spawn_blocking({
- let file_path = file_path.to_path_buf();
- move || -> Result<Vec<String>, Error> {
- use std::fs::File as StdFile;
- use zip::ZipArchive;
-
- let file = StdFile::open(file_path).with_context(|| "Failed to open zip file")?;
- let mut archive = ZipArchive::new(file)
- .with_context(|| "Failed to read and create zip archive")?;
-
- let mut file_names: Vec<String> = (0..archive.len())
- .filter_map(|i| {
- archive.by_index(i).ok().and_then(|file| {
- let name = file.name().to_string();
- if name.ends_with(".json.gz") {
- Some(name)
- } else {
- None
- }
- })
- })
- .collect();
-
- file_names.sort_by(|a, b| natord::compare(a, b));
- Ok(file_names)
+impl StreamingReader {
+ fn spawn<F>(producer: F) -> Self
+ where
+ F: FnOnce(mpsc::Sender<Block>) + Send + 'static,
+ {
+ let (tx, rx) = mpsc::channel(PRODUCER_CHANNEL_CAPACITY);
+ // A dedicated OS thread (not the tokio blocking pool) owns the decoder for
+ // the lifetime of the read. It exits when the receiver is dropped.
+ //
+ // Guard against a producer panic (e.g. an internal flate2/zip panic): without
+ // this, a panic would drop `tx`, and `read_at` would read the closed channel as
+ // a clean EOF and record a truncated part as complete (silent data loss). Convert
+ // the panic into a channel error so `read_at` surfaces it instead.
+ std::thread::spawn(move || {
+ let err_tx = tx.clone();
+ if std::panic::catch_unwind(AssertUnwindSafe(move || producer(tx))).is_err() {
+ let _unused =
+ err_tx.blocking_send(Err("decompression producer thread panicked".to_string()));
}
- })
- .await
- .with_context(|| {
- format!("Failed to extract file entries from zip archive for key: {key}")
- })??;
-
- for file_name in file_entries {
- let start_offset = total_size;
-
- let (tx, mut rx) = tokio::sync::mpsc::channel::<Result<Vec<u8>, Error>>(16);
-
- let decompress_handle = tokio::task::spawn_blocking({
- let file_path = file_path.to_path_buf();
- let file_name = file_name.clone();
-
- move || -> Result<bool, Error> {
- use flate2::read::GzDecoder;
- use std::fs::File as StdFile;
- use std::io::Read;
- use zip::ZipArchive;
-
- let file = StdFile::open(file_path)
- .with_context(|| "Failed to open zip file for decompression")?;
- let mut archive = ZipArchive::new(file)
- .with_context(|| "Failed to read zip archive for decompression")?;
- let zip_file = archive
- .by_name(&file_name)
- .with_context(|| "Failed to find file in zip archive")?;
- let mut decoder = GzDecoder::new(zip_file);
-
- let mut buffer = [0u8; 8192];
- let mut last_byte = None;
-
- loop {
- let bytes_read = decoder
- .read(&mut buffer)
- .with_context(|| "Failed to decompress gzip data from file")?;
- if bytes_read == 0 {
- break;
- }
- if bytes_read > 0 {
- last_byte = Some(buffer[bytes_read - 1]);
- }
-
- if tx.blocking_send(Ok(buffer[..bytes_read].to_vec())).is_err() {
- break;
- }
+ });
+ Self {
+ rx,
+ carry: Vec::new(),
+ carry_start: 0,
+ decoded_end: 0,
+ eof: false,
+ }
+ }
+
+ /// Return decompressed bytes in `[offset, offset + max_len)`, clamped to the
+ /// end of the stream. `offset` must be >= the start of the retained window.
+ pub async fn read_at(&mut self, offset: u64, max_len: usize) -> Result<ReadChunk, Error> {
+ if offset < self.carry_start {
+ return Err(Error::msg(format!(
+ "streaming reader received non-monotonic read: offset {offset} precedes retained window start {}",
+ self.carry_start
+ )));
+ }
+
+ let target = offset.saturating_add(max_len as u64);
+ while !self.eof && self.decoded_end < target {
+ match self.rx.recv().await {
+ Some(Ok(block)) => {
+ self.decoded_end += block.len() as u64;
+ self.carry.extend_from_slice(&block);
+ // Drop everything before `offset` to bound memory to ~one chunk.
+ // Forward-only access guarantees those bytes are never re-read.
+ if self.carry_start < offset {
+ let drop_to = offset.min(self.decoded_end);
+ let drop_len = (drop_to - self.carry_start) as usize;
+ self.carry.drain(0..drop_len);
+ self.carry_start = drop_to;
}
- Ok(last_byte != Some(b'\n'))
}
- });
- let mut file_size = 0usize;
- while let Some(chunk_result) = rx.recv().await {
- let chunk = chunk_result?;
- output_file
- .write_all(&chunk)
- .await
- .with_context(|| "Failed to write decompressed data to file")?;
- file_size += chunk.len();
+ Some(Err(e)) => return Err(Error::msg(e)),
+ None => self.eof = true,
}
+ }
- let needs_newline = decompress_handle
- .await
- .with_context(|| "Failed to decompress file from zip archive")??;
- if needs_newline && file_size > 0 {
- output_file
- .write_all(b"\n")
- .await
- .with_context(|| "Failed to write newline to file")?;
- file_size += 1;
- }
+ let avail_end = self.decoded_end.min(target);
+ let bytes = if avail_end <= offset {
+ Vec::new()
+ } else {
+ let start = (offset - self.carry_start) as usize;
+ let end = (avail_end - self.carry_start) as usize;
+ self.carry[start..end].to_vec()
+ };
+ let total = self.eof.then_some(self.decoded_end);
+ Ok(ReadChunk { bytes, total })
+ }
+}
- total_size += file_size;
- debug!("Processed file: {file_name} from byte {start_offset} to {total_size}");
- }
+pub struct ZipGzipJsonExtractor;
- output_file
- .sync_all()
- .await
- .with_context(|| format!("Failed to sync output file to disk for key: {key}"))?;
- Ok(ExtractedPartData {
- data_file_path,
- data_file_size: total_size,
- })
+impl PartExtractor for ZipGzipJsonExtractor {
+ fn open_reader(&self, raw_file_path: PathBuf) -> StreamingReader {
+ StreamingReader::spawn(move |tx| run_zip_gzip_json_producer(raw_file_path, tx))
}
}
pub struct PlainGzipExtractor;
-#[async_trait]
impl PartExtractor for PlainGzipExtractor {
- async fn extract_compressed_to_seekable_file(
- &self,
- key: &str,
- file_path: &Path,
- temp_dir: &Path,
- ) -> Result<ExtractedPartData, Error> {
- let data_file_path = temp_dir.join(format!("{}.data", key.replace(':', "_")));
- let mut output_file = File::create(&data_file_path)
- .await
- .with_context(|| format!("Failed to create data file for key: {key}"))?;
-
- let (tx, mut rx) = tokio::sync::mpsc::channel::<Result<Vec<u8>, Error>>(16);
-
- let decompress_handle = tokio::task::spawn_blocking({
- let file_path = file_path.to_path_buf();
-
- move || -> Result<bool, Error> {
- use flate2::read::GzDecoder;
- use std::fs::File as StdFile;
- use std::io::Read;
-
- let input_file = StdFile::open(file_path)
- .context("Failed to open gzip file for decompression")?;
- let mut decoder = GzDecoder::new(input_file);
- let mut buffer = [0u8; 8192];
- let mut last_byte = None;
-
- loop {
- let bytes_read = decoder.read(&mut buffer)?;
- if bytes_read == 0 {
- break;
- }
+ fn open_reader(&self, raw_file_path: PathBuf) -> StreamingReader {
+ StreamingReader::spawn(move |tx| run_plain_gzip_producer(raw_file_path, tx))
+ }
+}
- if bytes_read > 0 {
- last_byte = Some(buffer[bytes_read - 1]);
- }
+/// Decompress a single gzip member, streaming blocks to `tx`. Appends a trailing
+/// newline if the decompressed content is non-empty and didn't already end with
+/// one, so the downstream JSONL parser always sees a complete final line.
+///
+/// `GzDecoder` decodes a single gzip member (it stops at the first member's end).
+/// This matches the previous materializing extractor; the export endpoints we
+/// consume emit single-member gzip streams, not concatenated members.
+fn run_plain_gzip_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {
+ let file = match std::fs::File::open(&raw_file_path) {
+ Ok(f) => f,
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!(
+ "Failed to open gzip file {}: {e}",
+ raw_file_path.display()
+ )));
+ return;
+ }
+ };
+
+ let mut decoder = GzDecoder::new(file);
+ let mut buffer = vec![0u8; PRODUCER_BLOCK_SIZE];
+ let mut last_byte: Option<u8> = None;
+ let mut produced_any = false;
+
+ loop {
+ match decoder.read(&mut buffer) {
+ Ok(0) => break,
+ Ok(n) => {
+ produced_any = true;
+ last_byte = Some(buffer[n - 1]);
+ if tx.blocking_send(Ok(buffer[..n].to_vec())).is_err() {
+ return;
+ }
+ }
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!("Failed to decompress gzip data: {e}")));
+ return;
+ }
+ }
+ }
+
+ if produced_any && last_byte != Some(b'\n') {
+ let _unused = tx.blocking_send(Ok(vec![b'\n']));
+ }
+}
+
+/// Decompress every `.json.gz` member of a zip archive in natural-sorted order,
+/// streaming blocks to `tx`. A trailing newline is appended after each non-empty
+/// member that didn't end with one, matching the previous concatenation behavior.
+fn run_zip_gzip_json_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {
+ let file = match std::fs::File::open(&raw_file_path) {
+ Ok(f) => f,
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!(
+ "Failed to open zip file {}: {e}",
+ raw_file_path.display()
+ )));
+ return;
+ }
+ };
- if tx.blocking_send(Ok(buffer[..bytes_read].to_vec())).is_err() {
- break;
+ let mut archive = match ZipArchive::new(file) {
+ Ok(a) => a,
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!("Failed to read zip archive: {e}")));
+ return;
+ }
+ };
+
+ let mut file_names: Vec<String> = (0..archive.len())
+ .filter_map(|i| {
+ archive.by_index(i).ok().and_then(|f| {
+ let name = f.name().to_string();
+ name.ends_with(".json.gz").then_some(name)
+ })
+ })
+ .collect();
+ file_names.sort_by(|a, b| natord::compare(a, b));
+
+ let mut buffer = vec![0u8; PRODUCER_BLOCK_SIZE];
+ for name in file_names {
+ let zip_file = match archive.by_name(&name) {
+ Ok(zf) => zf,
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!(
+ "Failed to find file {name} in zip archive: {e}"
+ )));
+ return;
+ }
+ };
+ let mut decoder = GzDecoder::new(zip_file);
+ let mut last_byte: Option<u8> = None;
+ let mut entry_bytes: u64 = 0;
+
+ loop {
+ match decoder.read(&mut buffer) {
+ Ok(0) => break,
+ Ok(n) => {
+ entry_bytes += n as u64;
+ last_byte = Some(buffer[n - 1]);
+ if tx.blocking_send(Ok(buffer[..n].to_vec())).is_err() {
+ return;
}
}
-
- Ok(last_byte != Some(b'\n'))
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!(
+ "Failed to decompress gzip data from {name}: {e}"
+ )));
+ return;
+ }
}
- });
+ }
- let mut total_size = 0usize;
- while let Some(chunk_result) = rx.recv().await {
- let chunk = chunk_result?;
- output_file
- .write_all(&chunk)
- .await
- .with_context(|| "Failed to write decompressed data to file")?;
- total_size += chunk.len();
+ if entry_bytes > 0 && last_byte != Some(b'\n') && tx.blocking_send(Ok(vec![b'\n'])).is_err()
+ {
+ return;
}
+ }
+}
- let needs_newline = decompress_handle
- .await
- .context("Gzip decompression task panicked")??;
- let final_size = if needs_newline && total_size > 0 {
- output_file
- .write_all(b"\n")
- .await
- .with_context(|| "Failed to write newline to file")?;
- total_size + 1
- } else {
- total_size
- };
+#[cfg(test)]
+fn run_verbatim_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {
+ let mut file = match std::fs::File::open(&raw_file_path) {
+ Ok(f) => f,
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!(
+ "Failed to open file {}: {e}",
+ raw_file_path.display()
+ )));
+ return;
+ }
+ };
+
+ let mut buffer = vec![0u8; PRODUCER_BLOCK_SIZE];
+ loop {
+ match file.read(&mut buffer) {
+ Ok(0) => break,
+ Ok(n) => {
+ if tx.blocking_send(Ok(buffer[..n].to_vec())).is_err() {
+ return;
+ }
+ }
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!("Failed to read file: {e}")));
+ return;
+ }
+ }
+ }
+}
- output_file
- .sync_all()
- .await
- .with_context(|| format!("Failed to sync output file to disk for key: {key}"))?;
+/// Producer that emits one block then panics, to simulate an internal decoder panic.
+#[cfg(test)]
+fn run_panicking_producer(tx: mpsc::Sender<Block>) {
+ let _unused = tx.blocking_send(Ok(b"partial".to_vec()));
+ panic!("simulated producer panic");
+}
- Ok(ExtractedPartData {
- data_file_path,
- data_file_size: final_size,
- })
+#[cfg(test)]
+impl StreamingReader {
+ /// Stream the file at `raw_file_path` verbatim (no decompression, no newline
+ /// normalization). Used by tests that exercise the source plumbing with
+ /// already-plaintext bodies.
+ pub(crate) fn open_verbatim(raw_file_path: PathBuf) -> StreamingReader {
+ StreamingReader::spawn(move |tx| run_verbatim_producer(raw_file_path, tx))
+ }
+
+ /// A reader whose producer panics mid-stream. Used to prove a panic surfaces as an
+ /// error rather than a silently truncated EOF.
+ pub(crate) fn open_panicking() -> StreamingReader {
+ StreamingReader::spawn(run_panicking_producer)
+ }
+
+ /// Drive the reader forward to EOF in `chunk`-sized reads, returning the full
+ /// reconstructed stream and its discovered total size.
+ pub(crate) async fn read_to_end_for_test(&mut self, chunk: usize) -> (Vec<u8>, u64) {
+ let mut out = Vec::new();
+ let mut offset = 0u64;
+ loop {
+ let rc = self.read_at(offset, chunk).await.expect("read_at failed");
+ offset += rc.bytes.len() as u64;
+ out.extend_from_slice(&rc.bytes);
+ if let Some(total) = rc.total {
+ if offset >= total {
+ return (out, total);
+ }
+ } else if rc.bytes.is_empty() {
+ // Not at EOF yet but nothing produced — avoid spinning.
+ return (out, offset);
+ }
+ }
}
}
@@ -263,10 +363,9 @@ mod tests {
use flate2::{write::GzEncoder, Compression};
use std::{fs::File as StdFile, io::Write};
use tempfile::TempDir;
- use tokio::fs;
use zip::{write::SimpleFileOptions, ZipWriter};
- async fn create_test_gzip_file(content: &str, path: &std::path::Path) -> Result<()> {
+ fn create_test_gzip_file(content: &str, path: &std::path::Path) -> Result<()> {
let file = StdFile::create(path)?;
let mut encoder = GzEncoder::new(file, Compression::default());
encoder.write_all(content.as_bytes())?;
@@ -274,7 +373,7 @@ mod tests {
Ok(())
}
- async fn create_test_zip_with_gzip_json(
+ fn create_test_zip_with_gzip_json(
json_files: Vec<(&str, &str)>,
zip_path: &std::path::Path,
) -> Result<()> {
@@ -295,135 +394,111 @@ mod tests {
Ok(())
}
- #[tokio::test]
- async fn test_extractory_type_default() {
+ #[test]
+ fn test_extractory_type_default() {
let default_type = ExtractorType::default();
assert!(matches!(default_type, ExtractorType::PlainGzip));
}
#[tokio::test]
- async fn test_plain_gzip_extractor_simple() -> Result<()> {
- let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- let gzip_file = temp_path.join("test.gz");
- let test_content = "line1\nline2\nline3\n";
- create_test_gzip_file(test_content, &gzip_file).await?;
+ async fn test_plain_gzip_extractor_newline_normalization() -> Result<()> {
+ // The extractor guarantees exactly one trailing newline on non-empty
+ // content and leaves empty content untouched.
+ // (case name, raw input, expected decompressed output)
+ let cases: [(&str, &str, &str); 3] = [
+ (
+ "already terminated",
+ "line1\nline2\nline3\n",
+ "line1\nline2\nline3\n",
+ ),
+ (
+ "missing trailing newline",
+ "line1\nline2\nline3",
+ "line1\nline2\nline3\n",
+ ),
+ ("empty file", "", ""),
+ ];
- let extractor = PlainGzipExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("test_key", &gzip_file, temp_path)
- .await?;
+ for (name, input, expected) in cases {
+ let temp_dir = TempDir::new()?;
+ let gzip_file = temp_dir.path().join("test.gz");
+ create_test_gzip_file(input, &gzip_file)?;
- assert_eq!(result.data_file_size, test_content.len());
- assert!(result.data_file_path.exists());
+ let mut reader = PlainGzipExtractor.open_reader(gzip_file);
+ let (data, size) = reader.read_to_end_for_test(8192).await;
- let extracted_content = fs::read_to_string(&result.data_file_path).await?;
- assert_eq!(extracted_content, test_content);
+ assert_eq!(
+ size as usize,
+ expected.len(),
+ "size mismatch for case: {name}"
+ );
+ assert_eq!(data, expected.as_bytes(), "data mismatch for case: {name}");
+ }
Ok(())
}
#[tokio::test]
- async fn test_plain_gzip_extractor_adds_newline_when_missing() -> Result<()> {
- let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- let gzip_file = temp_path.join("test.gz");
- let test_content = "line1\nline2\nline3"; // No trailing newline
- create_test_gzip_file(test_content, &gzip_file).await?;
-
- let extractor = PlainGzipExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("test_key", &gzip_file, temp_path)
- .await?;
-
- assert_eq!(result.data_file_size, test_content.len() + 1); // +1 for added newline
-
- let extracted_content = fs::read_to_string(&result.data_file_path).await?;
- assert_eq!(extracted_content, format!("{test_content}\n"));
-
- Ok(())
+ async fn test_plain_gzip_extractor_corrupt_midstream_errors() {
+ let temp_dir = TempDir::new().unwrap();
+ let gzip_file = temp_dir.path().join("corrupt.gz");
+ // Write a valid gzip, then truncate it so the header is intact but the
+ // deflate body (and trailer) are incomplete.
+ create_test_gzip_file(&"line\n".repeat(10000), &gzip_file).unwrap();
+ let full = std::fs::read(&gzip_file).unwrap();
+ assert!(full.len() > 50, "compressed fixture should be non-trivial");
+ std::fs::write(&gzip_file, &full[..20]).unwrap();
+
+ // Decoding the truncated stream must surface an error rather than
+ // silently truncating output or panicking.
+ let mut reader = PlainGzipExtractor.open_reader(gzip_file);
+ let result = reader.read_at(0, 8192).await;
+ assert!(result.is_err());
}
- #[tokio::test]
- async fn test_plain_gzip_extractor_empty_file() -> Result<()> {
- let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- let gzip_file = temp_path.join("empty.gz");
- create_test_gzip_file("", &gzip_file).await?;
-
- let extractor = PlainGzipExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("empty_key", &gzip_file, temp_path)
- .await?;
-
- assert_eq!(result.data_file_size, 0);
- assert!(result.data_file_path.exists());
-
- Ok(())
- }
#[tokio::test]
async fn test_zip_gzip_json_extractor_single_file() -> Result<()> {
let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- let zip_file = temp_path.join("test.zip");
+ let zip_file = temp_dir.path().join("test.zip");
let json_content = r#"{"event": "test", "timestamp": 123}
{"event": "test2", "timestamp": 456}"#;
- create_test_zip_with_gzip_json(vec![("data.json.gz", json_content)], &zip_file).await?;
-
- let extractor = ZipGzipJsonExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("zip_test", &zip_file, temp_path)
- .await?;
+ create_test_zip_with_gzip_json(vec![("data.json.gz", json_content)], &zip_file)?;
- assert!(result.data_file_path.exists());
- assert!(result.data_file_size > 0);
-
- let extracted_content = fs::read_to_string(&result.data_file_path).await?;
- assert!(extracted_content.contains("test"));
- assert!(extracted_content.contains("test2"));
+ let mut reader = ZipGzipJsonExtractor.open_reader(zip_file);
+ let (data, size) = reader.read_to_end_for_test(8192).await;
+ assert!(size > 0);
+ let extracted = String::from_utf8(data).unwrap();
+ assert!(extracted.contains("test"));
+ assert!(extracted.contains("test2"));
Ok(())
}
+
#[tokio::test]
async fn test_zip_gzip_json_extractor_multiple_files() -> Result<()> {
let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- let zip_file = temp_path.join("multi.zip");
+ let zip_file = temp_dir.path().join("multi.zip");
let json_files = vec![
("001.json.gz", r#"{"id": 1}"#),
("002.json.gz", r#"{"id": 2}"#),
("003.json.gz", r#"{"id": 3}"#),
];
- create_test_zip_with_gzip_json(json_files, &zip_file).await?;
-
- let extractor = ZipGzipJsonExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("multi_test", &zip_file, temp_path)
- .await?;
+ create_test_zip_with_gzip_json(json_files, &zip_file)?;
- assert!(result.data_file_path.exists());
- assert!(result.data_file_size > 0);
-
- let extracted_content = fs::read_to_string(&result.data_file_path).await?;
- assert!(extracted_content.contains(r#"{"id": 1}"#));
- assert!(extracted_content.contains(r#"{"id": 2}"#));
- assert!(extracted_content.contains(r#"{"id": 3}"#));
+ let mut reader = ZipGzipJsonExtractor.open_reader(zip_file);
+ let (data, _size) = reader.read_to_end_for_test(8192).await;
+ let extracted = String::from_utf8(data).unwrap();
+ // Natural sort keeps members ordered; newline appended after each.
+ assert_eq!(extracted, "{\"id\": 1}\n{\"id\": 2}\n{\"id\": 3}\n");
Ok(())
}
#[tokio::test]
async fn test_zip_gzip_json_extractor_ignores_non_json_gz_files() -> Result<()> {
let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- let zip_file = temp_path.join("mixed.zip");
+ let zip_file = temp_dir.path().join("mixed.zip");
let file = StdFile::create(&zip_file)?;
let mut zip = ZipWriter::new(file);
@@ -442,126 +517,144 @@ mod tests {
zip.finish()?;
- let extractor = ZipGzipJsonExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("mixed_test", &zip_file, temp_path)
- .await?;
-
- let extracted_content = fs::read_to_string(&result.data_file_path).await?;
- assert!(extracted_content.contains("valid json"));
- assert!(!extracted_content.contains("ignore me"));
- assert!(!extracted_content.contains("also ignore"));
-
- Ok(())
- }
- #[tokio::test]
- async fn test_key_sanitization() -> Result<()> {
- let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- let gzip_file = temp_path.join("test.gz");
- create_test_gzip_file("test", &gzip_file).await?;
-
- let extractor = PlainGzipExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("test:key:with:colons", &gzip_file, temp_path)
- .await?;
-
- let expected_filename = "test_key_with_colons.data";
- assert!(result.data_file_path.file_name().unwrap().to_str().unwrap() == expected_filename);
+ let mut reader = ZipGzipJsonExtractor.open_reader(zip_file);
+ let (data, _size) = reader.read_to_end_for_test(8192).await;
+ let extracted = String::from_utf8(data).unwrap();
+ assert!(extracted.contains("valid json"));
+ assert!(!extracted.contains("ignore me"));
+ assert!(!extracted.contains("also ignore"));
Ok(())
}
#[tokio::test]
async fn test_plain_gzip_extractor_nonexistent_file() {
let temp_dir = TempDir::new().unwrap();
- let temp_path = temp_dir.path();
-
- let nonexistent_file = temp_path.join("nonexistent.gz");
- let extractor = PlainGzipExtractor;
-
- let result = extractor
- .extract_compressed_to_seekable_file("test", &nonexistent_file, temp_path)
- .await;
+ let nonexistent_file = temp_dir.path().join("nonexistent.gz");
+ let mut reader = PlainGzipExtractor.open_reader(nonexistent_file);
+ // The open error surfaces on the first read.
+ let result = reader.read_at(0, 8192).await;
assert!(result.is_err());
}
+
#[tokio::test]
async fn test_zip_gzip_extractor_invalid_zip() {
let temp_dir = TempDir::new().unwrap();
- let temp_path = temp_dir.path();
-
- let invalid_zip = temp_path.join("invalid.zip");
- fs::write(&invalid_zip, b"not a zip file").await.unwrap();
-
- let extractor = ZipGzipJsonExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("test", &invalid_zip, temp_path)
- .await;
+ let invalid_zip = temp_dir.path().join("invalid.zip");
+ std::fs::write(&invalid_zip, b"not a zip file").unwrap();
+ let mut reader = ZipGzipJsonExtractor.open_reader(invalid_zip);
+ let result = reader.read_at(0, 8192).await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_zip_gzip_extractor_empty_zip() -> Result<()> {
let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- // Create empty zip
- let zip_file = temp_path.join("empty.zip");
+ let zip_file = temp_dir.path().join("empty.zip");
let file = StdFile::create(&zip_file)?;
let zip = ZipWriter::new(file);
zip.finish()?;
- let extractor = ZipGzipJsonExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("empty_zip", &zip_file, temp_path)
- .await?;
-
- assert_eq!(result.data_file_size, 0);
- assert!(result.data_file_path.exists());
+ let mut reader = ZipGzipJsonExtractor.open_reader(zip_file);
+ let (data, size) = reader.read_to_end_for_test(8192).await;
+ assert_eq!(size, 0);
+ assert!(data.is_empty());
Ok(())
}
+
#[tokio::test]
async fn test_large_file_handling() -> Result<()> {
let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
let large_content = "line\n".repeat(10000);
- let gzip_file = temp_path.join("large.gz");
- create_test_gzip_file(&large_content, &gzip_file).await?;
-
- let extractor = PlainGzipExtractor;
- let result = extractor
- .extract_compressed_to_seekable_file("large_test", &gzip_file, temp_path)
- .await?;
+ let gzip_file = temp_dir.path().join("large.gz");
+ create_test_gzip_file(&large_content, &gzip_file)?;
- assert_eq!(result.data_file_size, large_content.len());
-
- let extracted_content = fs::read_to_string(&result.data_file_path).await?;
- assert_eq!(extracted_content, large_content);
+ // Small read chunk + large content exercises the carry buffer / front-trim.
+ let mut reader = PlainGzipExtractor.open_reader(gzip_file);
+ let (data, size) = reader.read_to_end_for_test(777).await;
+ assert_eq!(size as usize, large_content.len());
+ assert_eq!(data, large_content.as_bytes());
Ok(())
}
#[tokio::test]
- async fn test_trait_usage() -> Result<()> {
+ async fn test_trait_object_usage() -> Result<()> {
let temp_dir = TempDir::new()?;
- let temp_path = temp_dir.path();
-
- let gzip_file = temp_path.join("trait_test.gz");
- create_test_gzip_file("trait test content\n", &gzip_file).await?;
+ let gzip_file = temp_dir.path().join("trait_test.gz");
+ create_test_gzip_file("trait test content\n", &gzip_file)?;
let extractor: Arc<dyn PartExtractor> = Arc::new(PlainGzipExtractor);
- let result = extractor
- .extract_compressed_to_seekable_file("trait_test", &gzip_file, temp_path)
- .await?;
-
- assert!(result.data_file_path.exists());
- assert_eq!(result.data_file_size, "trait test content\n".len());
+ let mut reader = extractor.open_reader(gzip_file);
+ let (data, size) = reader.read_to_end_for_test(8192).await;
+ assert_eq!(size as usize, "trait test content\n".len());
+ assert_eq!(data, b"trait test content\n");
Ok(())
}
+
+ #[tokio::test]
+ async fn test_read_at_clamps_and_reports_total_past_eof() {
+ let temp_dir = TempDir::new().unwrap();
+ let gzip_file = temp_dir.path().join("clamp.gz");
+ create_test_gzip_file("abc\n", &gzip_file).unwrap();
+
+ let mut reader = PlainGzipExtractor.open_reader(gzip_file);
+ // Reading well past the end returns only available bytes + the total.
+ let rc = reader.read_at(0, 1024).await.unwrap();
+ assert_eq!(rc.bytes, b"abc\n");
+ assert_eq!(rc.total, Some(4));
+
+ // A subsequent read at/after EOF returns empty with the known total.
+ let rc = reader.read_at(4, 1024).await.unwrap();
+ assert!(rc.bytes.is_empty());
+ assert_eq!(rc.total, Some(4));
+ }
+
+ #[tokio::test]
+ async fn test_read_at_rejects_backwards_seek() {
+ let temp_dir = TempDir::new().unwrap();
+ let gzip_file = temp_dir.path().join("seek.gz");
+ // Large enough that advancing far forward trims the front of the carry
+ // window, so the retained start moves well past 0.
+ create_test_gzip_file(&"x".repeat(1_000_000), &gzip_file).unwrap();
+
+ let mut reader = PlainGzipExtractor.open_reader(gzip_file);
+ reader.read_at(0, 1024).await.unwrap();
+ reader.read_at(900_000, 1024).await.unwrap();
+ // Seeking back before the (now-trimmed) retained window is rejected.
+ let result = reader.read_at(0, 1024).await;
+ assert!(result.is_err());
+ }
+
+ #[tokio::test]
+ async fn test_producer_panic_surfaces_as_error_not_truncated_eof() {
+ // A producer panic must not be mistaken for a clean end-of-stream, which would
+ // record a truncated part as complete (silent data loss). Drive the reader past
+ // the one block the producer emits before panicking, and require an error.
+ let mut reader = StreamingReader::open_panicking();
+
+ let mut offset = 0u64;
+ loop {
+ match reader.read_at(offset, 4).await {
+ // Expected: the panic is surfaced as a read error.
+ Err(_) => return,
+ Ok(chunk) => {
+ assert!(
+ chunk.total.is_none(),
+ "panic was swallowed as a clean EOF (total={:?})",
+ chunk.total
+ );
+ assert!(
+ !chunk.bytes.is_empty(),
+ "no error and no progress: panic was not surfaced"
+ );
+ offset += chunk.bytes.len() as u64;
+ }
+ }
+ }
+ }
}
diff --git a/rust/batch-import-worker/src/job/config.rs b/rust/batch-import-worker/src/job/config.rs
index 1c7655f82bed..7247672b4d6c 100644
--- a/rust/batch-import-worker/src/job/config.rs
+++ b/rust/batch-import-worker/src/job/config.rs
@@ -195,6 +195,7 @@ impl SourceConfig {
is_restarting: bool,
) -> Result<Box<dyn DataSource>, Error> {
let staging_dir = context.config.staging_dir();
+ let staging_max_bytes = context.config.staging_dir_max_bytes;
match self {
SourceConfig::Folder(config) => Ok(Box::new(config.create_source().await?)),
SourceConfig::UrlList(config) => Ok(Box::new(
@@ -204,11 +205,15 @@ impl SourceConfig {
)),
SourceConfig::S3(config) => Ok(Box::new(config.create_source(secrets).await?)),
SourceConfig::S3Gzip(config) => Ok(Box::new(
- config.create_gzip_source(secrets, staging_dir).await?,
+ config
+ .create_gzip_source(secrets, staging_dir, staging_max_bytes)
+ .await?,
+ )),
+ SourceConfig::DateRangeExport(config) => Ok(Box::new(
+ config
+ .create_source(secrets, staging_dir, staging_max_bytes)
+ .await?,
)),
- SourceConfig::DateRangeExport(config) => {
- Ok(Box::new(config.create_source(secrets, staging_dir).await?))
- }
}
}
}
@@ -423,6 +428,7 @@ impl S3SourceConfig {
&self,
secrets: &JobSecrets,
staging_dir: PathBuf,
+ staging_max_bytes: u64,
) -> Result<GzipS3Source, Error> {
let builder = self.build_s3_config(secrets)?;
let client = aws_sdk_s3::Client::from_conf(builder.build());
@@ -433,6 +439,7 @@ impl S3SourceConfig {
self.prefix.clone(),
ExtractorType::PlainGzip.create_extractor(),
staging_dir,
+ staging_max_bytes,
))
}
}
@@ -441,6 +448,7 @@ impl DateRangeExportSourceConfig {
&self,
secrets: &JobSecrets,
staging_dir: PathBuf,
+ staging_max_bytes: u64,
) -> Result<DateRangeExportSource, Error> {
let auth_config = match &self.auth {
AuthSourceConfig::None => AuthConfig::None,
@@ -540,6 +548,7 @@ impl DateRangeExportSourceConfig {
.with_auth(auth_config)
.with_date_format(self.date_format.clone())
.with_headers(self.headers.clone())
+ .with_staging_max_bytes(staging_max_bytes)
.build()
}
diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rs
index 7b08fe9afe5a..62d46c7416e8 100644
--- a/rust/batch-import-worker/src/job/mod.rs
+++ b/rust/batch-import-worker/src/job/mod.rs
@@ -113,6 +113,142 @@ async fn reset_backoff_after_success(
model.reset_backoff_in_db(&context.db).await
}
+/// DB-free core of [`Job::get_next_chunk`]: pick the next unfinished part, lazily
+/// discover its (decompressed) size, fetch+parse one chunk, and advance the
+/// in-memory part offset. A newly discovered `total_size` is mirrored into the
+/// model in memory only — no DB write happens here, which keeps the fetch/select
+/// loop testable without a database. Per-part staging cleanup is not driven from
+/// here: the source frees each `.raw` on its own EOF read (see
+/// [`crate::source::read_prepared_chunk`]).
+///
+/// Returns the fetched `(key, parsed, reset_backoff)`. `reset_backoff` is `false`
+/// only on the empty-key short-circuit (so the caller skips the success backoff
+/// reset, matching the original control flow) and `true` otherwise. `None` means
+/// every part is done.
+pub(crate) async fn select_and_fetch_next_chunk(
+ state: &Mutex<JobState>,
+ model: &Mutex<JobModel>,
+ source: &dyn DataSource,
+ transform: &Arc<ParserFn>,
+ chunk_size: usize,
+ job_id: Uuid,
+) -> Result<Option<(String, Parsed<Vec<InternallyCapturedEvent>>, bool)>, Error> {
+ let mut state = state.lock().await;
+
+ let Some(next_part) = state.parts.iter_mut().find(|p| !p.is_done()) else {
+ info!(job_id = %job_id, "Found no next part, returning");
+ return Ok(None); // We're done fetching
+ };
+
+ let key = next_part.key.clone();
+ source.prepare_key(&key).await?;
+
+ if next_part.total_size.is_none() {
+ if let Some(actual_size) = source.size(&key).await? {
+ next_part.total_size = Some(actual_size);
+ info!(job_id = %job_id, "Updated total size for key {}: {}", key, actual_size);
+
+ {
+ let mut model = model.lock().await;
+ if let Some(model_state) = &mut model.state {
+ if let Some(model_part) = model_state.parts.iter_mut().find(|p| p.key == key) {
+ model_part.total_size = Some(actual_size);
+ }
+ }
+ }
+
+ if actual_size == 0 {
+ info!(
+ job_id = %job_id,
+ "No data available for this key: {} try to get the next chunk",
+ key
+ );
+ next_part.current_offset = actual_size;
+ return Ok(Some((
+ key.clone(),
+ Parsed {
+ consumed: 0,
+ data: vec![],
+ },
+ false,
+ )));
+ }
+ }
+ }
+
+ info!(job_id = %job_id, "Fetching part chunk {:?}", next_part);
+
+ let next_chunk = source
+ .get_chunk(&next_part.key, next_part.current_offset, chunk_size as u64)
+ .await
+ .context(format!("Fetching part chunk {next_part:?}"))?;
+
+ let is_last_chunk = match next_part.total_size {
+ Some(total_size) => next_part.current_offset + next_chunk.len() as u64 > total_size,
+ None => false,
+ };
+
+ let chunk_bytes = next_chunk.len();
+
+ info!(job_id = %job_id, "Fetched part chunk {:?}", next_part);
+ let m_tf = transform.clone();
+ let key_for_error = key.clone();
+ // This is computationally expensive, so we run it in a blocking task
+ let parsed = tokio::task::spawn_blocking(move || (m_tf)(next_chunk))
+ .await?
+ .map_err(|e| {
+ let inner_msg = get_user_message(&e);
+ e.context(UserError::new(format!(
+ "Parsing data in file '{key_for_error}' failed: {inner_msg}"
+ )))
+ })
+ .context(format!("Processing part chunk {next_part:?}"))?;
+
+ info!(
+ job_id = %job_id,
+ "Parsed part chunk {:?}, consumed {} bytes",
+ next_part, parsed.consumed
+ );
+
+ // If this is the last chunk and we didn't consume all of it, we have leftover unparseable data.
+ if parsed.consumed < chunk_bytes && is_last_chunk {
+ return Err(Error::msg(format!(
+ "Failed to parse data from part {} at offset {} - {} bytes left unconsumed",
+ next_part.key,
+ next_part.current_offset,
+ chunk_bytes - parsed.consumed
+ )));
+ }
+
+ // A single record larger than the read window fills a whole non-final chunk with no
+ // line terminator, so the parser can't advance past it. Without this the loop would
+ // crawl one byte per iteration (and, on the temp-bucket backend, issue a ranged GET
+ // of up to chunk_size per byte). Fail fast with an actionable, non-transient error
+ // that pauses the job.
+ if !is_last_chunk && chunk_bytes == chunk_size && parsed.consumed <= 1 && parsed.data.is_empty()
+ {
+ return Err(Error::from(UserError::new(format!(
+ "A single record in part {} exceeds the maximum chunk size ({chunk_size} bytes) \
+ and cannot be processed; split the oversized record into smaller ones.",
+ next_part.key
+ ))));
+ }
+
+ // If we consumed no bytes and have no parsed data but there was data to consume, something went wrong.
+ // Note: don't error if we have no parsed data but have consumed bytes - invalid events may have been all filtered out
+ if parsed.consumed == 0 && parsed.data.is_empty() && chunk_bytes > 0 {
+ return Err(Error::msg(format!(
+ "Failed to parse any data from part {} at offset {}",
+ next_part.key, next_part.current_offset
+ )));
+ }
+
+ // Update the in-memory part state (the read will be committed to the DB once the write is done)
+ next_part.current_offset += parsed.consumed as u64;
+
+ Ok(Some((key, parsed, true)))
+}
+
pub struct Job {
pub context: Arc<AppContext>,
handle: Handle,
@@ -375,118 +511,28 @@ impl Job {
async fn get_next_chunk(
&self,
) -> Result<Option<(String, Parsed<Vec<InternallyCapturedEvent>>)>, Error> {
- let mut state = self.state.lock().await;
-
- let Some(next_part) = state.parts.iter_mut().find(|p| !p.is_done()) else {
- info!(job_id = %self.job_id, "Found no next part, returning");
+ let Some((key, parsed, reset_backoff)) = select_and_fetch_next_chunk(
+ &self.state,
+ &self.model,
+ self.source.as_ref(),
+ &self.transform,
+ self.chunk_size,
+ self.job_id,
+ )
+ .await?
+ else {
return Ok(None); // We're done fetching
};
- let key = next_part.key.clone();
- self.source.prepare_key(&key).await?;
-
- if next_part.total_size.is_none() {
- if let Some(actual_size) = self.source.size(&key).await? {
- next_part.total_size = Some(actual_size);
- info!(job_id = %self.job_id, "Updated total size for key {}: {}", key, actual_size);
-
- {
- let mut model = self.model.lock().await;
- if let Some(model_state) = &mut model.state {
- if let Some(model_part) =
- model_state.parts.iter_mut().find(|p| p.key == key)
- {
- model_part.total_size = Some(actual_size);
- }
- }
- }
-
- if actual_size == 0 {
- info!(
- job_id = %self.job_id,
- "No data available for this key: {} try to get the next chunk",
- key
- );
- next_part.current_offset = actual_size;
- return Ok(Some((
- key.clone(),
- Parsed {
- consumed: 0,
- data: vec![],
- },
- )));
- }
- }
- }
-
- info!(job_id = %self.job_id, "Fetching part chunk {:?}", next_part);
-
- let next_chunk = self
- .source
- .get_chunk(
- &next_part.key,
- next_part.current_offset,
- self.chunk_size as u64,
- )
- .await
- .context(format!("Fetching part chunk {next_part:?}"))?;
-
- let is_last_chunk = match next_part.total_size {
- Some(total_size) => next_part.current_offset + next_chunk.len() as u64 > total_size,
- None => false,
- };
-
- let chunk_bytes = next_chunk.len();
-
- info!(job_id = %self.job_id, "Fetched part chunk {:?}", next_part);
- let m_tf = self.transform.clone();
- let key_for_error = key.clone();
- // This is computationally expensive, so we run it in a blocking task
- let parsed = tokio::task::spawn_blocking(move || (m_tf)(next_chunk))
- .await?
- .map_err(|e| {
- let inner_msg = get_user_message(&e);
- e.context(UserError::new(format!(
- "Parsing data in file '{key_for_error}' failed: {inner_msg}"
- )))
- })
- .context(format!("Processing part chunk {next_part:?}"))?;
-
- info!(
- job_id = %self.job_id,
- "Parsed part chunk {:?}, consumed {} bytes",
- next_part, parsed.consumed
- );
-
- // If this is the last chunk and we didn't consume all of it, we have leftover unparseable data.
- if parsed.consumed < chunk_bytes && is_last_chunk {
- return Err(Error::msg(format!(
- "Failed to parse data from part {} at offset {} - {} bytes left unconsumed",
- next_part.key,
- next_part.current_offset,
- chunk_bytes - parsed.consumed
- )));
- }
-
- // If we consumed no bytes and have no parsed data but there was data to consume, something went wrong.
- // Note: don't error if we have no parsed data but have consumed bytes - invalid events may have been all filtered out
- if parsed.consumed == 0 && parsed.data.is_empty() && chunk_bytes > 0 {
- return Err(Error::msg(format!(
- "Failed to parse any data from part {} at offset {}",
- next_part.key, next_part.current_offset
- )));
- }
-
- // Update the in-memory part state (the read will be committed to the DB once the write is done)
- next_part.current_offset += parsed.consumed as u64;
-
- let ret_key = key.clone();
- {
+ // The only DB write in this path, kept out of the core above so the
+ // fetch/select/cleanup loop stays testable without a database. Skipped on
+ // the empty-key short-circuit, matching the original control flow.
+ if reset_backoff {
let mut model = self.model.lock().await;
reset_backoff_after_success(self.context.clone(), &mut model).await?;
}
- Ok(Some((ret_key, parsed)))
+ Ok(Some((key, parsed)))
}
async fn do_commit(&self) -> Result<(), Error> {
@@ -1148,4 +1194,304 @@ mod tests {
assert!(handle.is_shutting_down());
}
}
+
+ /// Drives the real DB-free read loop (`select_and_fetch_next_chunk`) against
+ /// the real `DateRangeExportSource` + `PlainGzipExtractor` over `httpmock`, to
+ /// lock the end-to-end staging-cleanup invariant: across a whole run the loop
+ /// alone (without `cleanup_after_job`) leaves no `.raw` behind and never keeps
+ /// more than one part's `.raw` on disk at a time. The source frees each `.raw`
+ /// on its own EOF read (see [`crate::source::read_prepared_chunk`]); the
+ /// decisive read-level proof of that lives in `date_range_export`'s tests.
+ mod staging_cleanup_invariant_tests {
+ use super::*;
+ use crate::extractor::ExtractorType;
+ use crate::source::date_range_export::{AuthConfig, DateRangeExportSource};
+ use chrono::{TimeZone, Utc};
+ use flate2::write::GzEncoder;
+ use flate2::Compression;
+ use std::io::Write;
+ use std::path::{Path, PathBuf};
+ use tempfile::TempDir;
+
+ fn gzip_bytes(data: &[u8]) -> Vec<u8> {
+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
+ encoder.write_all(data).unwrap();
+ encoder.finish().unwrap()
+ }
+
+ /// Build a source spanning `hours` one-hour intervals (one key per hour),
+ /// all served the same gzipped body by the mock.
+ fn build_source(base_url: String, staging: &Path, hours: u32) -> DateRangeExportSource {
+ let start = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();
+ let end = Utc.with_ymd_and_hms(2023, 1, 1, hours, 0, 0).unwrap();
+ DateRangeExportSource::builder(
+ base_url,
+ start,
+ end,
+ 3600,
+ ExtractorType::PlainGzip.create_extractor(),
+ staging.to_path_buf(),
+ )
+ .with_auth(AuthConfig::None)
+ .with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string())
+ .with_headers(HashMap::new())
+ .build()
+ .unwrap()
+ }
+
+ /// A transform that consumes the whole chunk and emits no events. The
+ /// cleanup invariant is about offsets reaching `total` and each `.raw`
+ /// being freed on its EOF read — parsing semantics are irrelevant here, so
+ /// this keeps the loop advancing deterministically by exactly the bytes read.
+ fn consume_all_transform() -> Arc<ParserFn> {
+ Arc::new(Box::new(|bytes: Vec<u8>| {
+ Ok(Parsed {
+ consumed: bytes.len(),
+ data: Vec::new(),
+ })
+ }))
+ }
+
+ /// A transform that runs the real newline parser to compute `consumed`
+ /// (validating each complete line as JSON) but emits no events. This
+ /// reproduces the parser's real boundary behavior — a chunk with no line
+ /// terminator yields `consumed == 1` — which is what the oversized-record
+ /// guard keys on, without standing up the full captured-event pipeline.
+ fn newline_consumed_transform() -> Arc<ParserFn> {
+ Arc::new(Box::new(|bytes: Vec<u8>| {
+ let parser = crate::parse::format::newline_delim(true, |line: &str| {
+ serde_json::from_str::<serde_json::Value>(line)
+ .map(|_| ())
+ .map_err(anyhow::Error::from)
+ });
+ let parsed = parser(bytes)?;
+ Ok(Parsed {
+ consumed: parsed.consumed,
+ data: Vec::new(),
+ })
+ }))
+ }
+
+ fn count_raw_files(dir: &Path) -> usize {
+ let mut count = 0;
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(d) = stack.pop() {
+ let Ok(entries) = std::fs::read_dir(&d) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path: PathBuf = entry.path();
+ if path.is_dir() {
+ stack.push(path);
+ } else if path.extension().and_then(|e| e.to_str()) == Some("raw") {
+ count += 1;
+ }
+ }
+ }
+ count
+ }
+
+ fn dummy_model(state: JobState) -> JobModel {
+ JobModel {
+ id: Uuid::now_v7(),
+ team_id: 1,
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ lease_id: None,
+ leased_until: None,
+ status: model::JobStatus::Running,
+ status_message: None,
+ display_status_message: None,
+ state: Some(state),
+ import_config: config::JobConfig {
+ source: config::SourceConfig::Folder(config::FolderSourceConfig {
+ path: "/tmp".to_string(),
+ }),
+ data_format: crate::parse::format::FormatConfig::JsonLines {
+ skip_blanks: true,
+ content: crate::parse::content::ContentType::Captured,
+ },
+ sink: config::SinkConfig::NoOp,
+ import_events: true,
+ generate_identify_events: false,
+ generate_group_identify_events: false,
+ },
+ secrets: config::JobSecrets {
+ secrets: HashMap::new(),
+ },
+ backoff_attempt: 0,
+ backoff_until: None,
+ was_leased: false,
+ }
+ }
+
+ fn job_state(keys: &[String]) -> JobState {
+ JobState {
+ parts: keys
+ .iter()
+ .map(|key| PartState {
+ key: key.clone(),
+ current_offset: 0,
+ total_size: None,
+ })
+ .collect(),
+ }
+ }
+
+ #[tokio::test]
+ async fn test_single_part_raw_cleaned_up_by_read_loop_without_job_cleanup() {
+ let server = MockServer::start();
+ let mut body = String::new();
+ for i in 0..2000 {
+ body.push_str(&format!("{{\"event\":\"e{i}\"}}\n"));
+ }
+ let _mock = server.mock(|when, then| {
+ when.method(Method::GET).path("/export");
+ then.status(200).body(gzip_bytes(body.as_bytes()));
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = build_source(server.url("/export"), staging.path(), 1);
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ assert_eq!(keys.len(), 1);
+
+ let state = Mutex::new(job_state(&keys));
+ let model = Mutex::new(dummy_model(job_state(&keys)));
+ let transform = consume_all_transform();
+
+ // Small chunk so the loop takes several passes before EOF.
+ let mut peak_raw = 0;
+ loop {
+ let next = select_and_fetch_next_chunk(
+ &state,
+ &model,
+ &source,
+ &transform,
+ 1024,
+ Uuid::now_v7(),
+ )
+ .await
+ .unwrap();
+ peak_raw = peak_raw.max(count_raw_files(staging.path()));
+ if next.is_none() {
+ break;
+ }
+ }
+
+ // The loop alone (no cleanup_after_job) must have deleted the .raw:
+ // the source frees it on the EOF read.
+ assert_eq!(
+ count_raw_files(staging.path()),
+ 0,
+ "the read loop must delete the part's .raw once it is fully read, without cleanup_after_job"
+ );
+ assert_eq!(
+ peak_raw, 1,
+ "exactly one .raw should exist while the part is in flight"
+ );
+ }
+
+ #[tokio::test]
+ async fn test_record_larger_than_chunk_size_fails_fast() {
+ // A single JSON record with no interior newline, larger than the read window.
+ // Without the guard the loop would crawl one byte per iteration forever.
+ let server = MockServer::start();
+ let huge_record = format!("{{\"event\":\"{}\"}}", "x".repeat(5000));
+ assert!(!huge_record.contains('\n'));
+ let _mock = server.mock(|when, then| {
+ when.method(Method::GET).path("/export");
+ then.status(200).body(gzip_bytes(huge_record.as_bytes()));
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = build_source(server.url("/export"), staging.path(), 1);
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+
+ let state = Mutex::new(job_state(&keys));
+ let model = Mutex::new(dummy_model(job_state(&keys)));
+ let transform = newline_consumed_transform();
+
+ // Read window (1024) is far smaller than the 5000-byte record.
+ let result = select_and_fetch_next_chunk(
+ &state,
+ &model,
+ &source,
+ &transform,
+ 1024,
+ Uuid::now_v7(),
+ )
+ .await;
+
+ let err = result.expect_err("oversized record must fail fast, not crawl");
+ // Actionable, user-facing message so the job pauses (not a transient retry).
+ let user_msg = crate::error::get_user_message(&err);
+ assert!(
+ user_msg.contains("exceeds the maximum chunk size"),
+ "unexpected message: {user_msg}"
+ );
+ assert!(!crate::error::is_rate_limited_error(&err));
+ assert!(!crate::error::is_timeout_error(&err));
+ assert!(!crate::error::is_transient_network_error(&err));
+ assert!(!crate::error::is_transient_server_error(&err));
+ }
+
+ #[tokio::test]
+ async fn test_multi_part_peak_staging_bounded_to_one_part() {
+ let server = MockServer::start();
+ let mut body = String::new();
+ for i in 0..2000 {
+ body.push_str(&format!("{{\"event\":\"e{i}\"}}\n"));
+ }
+ let _mock = server.mock(|when, then| {
+ when.method(Method::GET).path("/export");
+ then.status(200).body(gzip_bytes(body.as_bytes()));
+ });
+
+ let staging = TempDir::new().unwrap();
+ // Two one-hour intervals -> two keys processed back to back.
+ let source = build_source(server.url("/export"), staging.path(), 2);
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ assert_eq!(keys.len(), 2);
+
+ let state = Mutex::new(job_state(&keys));
+ let model = Mutex::new(dummy_model(job_state(&keys)));
+ let transform = consume_all_transform();
+
+ // Two invariants across the whole run:
+ // - peak coexisting .raw files stays at 1 (each part's .raw is freed
+ // on its EOF read, before the next part is read), and
+ // - after the loop, zero .raw remain — cleaned by the loop alone,
+ // including the last part (which has no later prepare-time sweep).
+ let mut peak_raw = 0;
+ loop {
+ let next = select_and_fetch_next_chunk(
+ &state,
+ &model,
+ &source,
+ &transform,
+ 1024,
+ Uuid::now_v7(),
+ )
+ .await
+ .unwrap();
+ peak_raw = peak_raw.max(count_raw_files(staging.path()));
+ if next.is_none() {
+ break;
+ }
+ }
+
+ assert_eq!(
+ peak_raw, 1,
+ "peak staging must be bounded to a single part's .raw; coexisting raws means a completed part was not cleaned up"
+ );
+ assert_eq!(
+ count_raw_files(staging.path()),
+ 0,
+ "all parts' .raw files must be cleaned up by the read loop alone"
+ );
+ }
+ }
}
diff --git a/rust/batch-import-worker/src/metrics.rs b/rust/batch-import-worker/src/metrics.rs
index f8b2d0e4d6a9..b87eab73cb37 100644
--- a/rust/batch-import-worker/src/metrics.rs
+++ b/rust/batch-import-worker/src/metrics.rs
@@ -3,6 +3,7 @@ pub const BACKOFF_DELAY_SECONDS: &str = "batch_import_backoff_delay_seconds";
pub const UNPAUSE_TOTAL: &str = "batch_import_unpause_total";
pub const STAGING_SWEEP_REMOVED: &str = "batch_import_staging_sweep_removed_total";
pub const STAGING_DIR_BYTES: &str = "batch_import_staging_dir_bytes";
+pub const STAGING_GUARD_TRIPPED: &str = "batch_import_staging_guard_tripped_total";
pub const ACTIVE_JOBS: &str = "batch_import_active_jobs";
use metrics::{counter, gauge, histogram};
@@ -24,6 +25,10 @@ pub fn staging_dir_bytes(bytes: f64) {
gauge!(STAGING_DIR_BYTES).set(bytes);
}
+pub fn staging_guard_tripped() {
+ counter!(STAGING_GUARD_TRIPPED).increment(1);
+}
+
/// Number of batch import jobs currently needing a worker (queued and in-flight).
/// Reported by every replica off the shared Postgres queue; the KEDA autoscaler
/// collapses the per-pod duplicates with `max()` to drive replica count.
diff --git a/rust/batch-import-worker/src/source/date_range_export.rs b/rust/batch-import-worker/src/source/date_range_export.rs
index 90de2501c4ef..c5d6628199bd 100644
--- a/rust/batch-import-worker/src/source/date_range_export.rs
+++ b/rust/batch-import-worker/src/source/date_range_export.rs
@@ -6,16 +6,13 @@ use chrono::{DateTime, Duration as ChronoDuration, Utc};
use reqwest::header::HeaderMap;
use reqwest::{Client, Error as ReqwestError};
use tempfile::TempDir;
-use tokio::{
- fs::File,
- io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
- sync::Mutex,
-};
+use tokio::{fs::File, io::AsyncWriteExt, sync::Mutex};
use tracing::{debug, info, warn};
-use super::DataSource;
+use super::{read_prepared_chunk, remove_prepared_key, DataSource, PreparedPart};
use crate::error::{RateLimitedError, ToUserError};
-use crate::extractor::{ExtractedPartData, PartExtractor};
+use crate::extractor::PartExtractor;
+use crate::staging::StagingGuard;
// Extract a user friendly error message
// from status code of request to the export source endpoint
@@ -90,6 +87,7 @@ pub struct DateRangeExportSourceBuilder {
auth_config: AuthConfig,
date_format: String,
headers: HashMap<String, String>,
+ staging_max_bytes: u64,
}
impl DateRangeExportSourceBuilder {
@@ -116,9 +114,15 @@ impl DateRangeExportSourceBuilder {
auth_config: AuthConfig::None,
date_format: "%Y-%m-%dT%H:%M:%SZ".to_string(),
headers: HashMap::new(),
+ staging_max_bytes: 0,
}
}
+ pub fn with_staging_max_bytes(mut self, staging_max_bytes: u64) -> Self {
+ self.staging_max_bytes = staging_max_bytes;
+ self
+ }
+
pub fn with_query_params(mut self, start_qp: String, end_qp: String) -> Self {
self.start_qp = start_qp;
self.end_qp = end_qp;
@@ -186,6 +190,7 @@ impl DateRangeExportSourceBuilder {
retry_delay: self.retry_delay,
extractor: self.extractor,
staging_dir: self.staging_dir,
+ staging_max_bytes: self.staging_max_bytes,
temp_dir: Arc::new(Mutex::new(None)),
prepared_keys: Arc::new(Mutex::new(HashMap::new())),
})
@@ -205,8 +210,9 @@ pub struct DateRangeExportSource {
pub start_qp: String,
pub end_qp: String,
staging_dir: PathBuf,
+ staging_max_bytes: u64,
temp_dir: Arc<Mutex<Option<TempDir>>>,
- prepared_keys: Arc<Mutex<HashMap<String, ExtractedPartData>>>,
+ prepared_keys: Arc<Mutex<HashMap<String, PreparedPart>>>,
auth_config: AuthConfig,
date_format: String,
headers: HashMap<String, String>,
@@ -306,10 +312,12 @@ impl DateRangeExportSource {
// To support exporting directly from sources that do not provide a byte seekable interface, we need to create
// that byte seekable interface ourselves
- // This method streams the data from the source into a temp file on disk via 8kb buffers,
- // then uses an extractor to convert the compressed/separated data into a single file that
- // can be read/seeked through via byte offsets
- async fn download_and_prepare_part_data(&self, key: &str) -> Result<ExtractedPartData, Error> {
+ // This method streams the compressed data from the source into a temp `.raw`
+ // file on disk, then opens a streaming decoder over it. The compressed file is
+ // kept and decompressed on demand as the job reads forward, so disk usage is
+ // bounded by the compressed size rather than the (potentially much larger)
+ // decompressed size.
+ async fn download_and_prepare_part_data(&self, key: &str) -> Result<PreparedPart, Error> {
let (start, end) = self
.interval_from_key(key)
.ok_or_else(|| Error::msg("Invalid interval key"))?;
@@ -331,7 +339,7 @@ impl DateRangeExportSource {
key: &str,
start: DateTime<Utc>,
end: DateTime<Utc>,
- ) -> Result<ExtractedPartData, Error> {
+ ) -> Result<PreparedPart, Error> {
// All date range export APIs (Mixpanel, Amplitude, etc.) use inclusive date ranges,
// meaning both start and end dates/times are included in the results. Our intervals
// are created as semi-open [start, end), so we subtract one interval unit from the
@@ -390,16 +398,7 @@ impl DateRangeExportSource {
key
);
tokio::time::sleep(Duration::from_secs(2)).await;
- let temp_dir = self.get_temp_dir_path().await?;
-
- let empty_data_file_path = temp_dir.join(format!("{}.data", key.replace(':', "_")));
- let empty_file = File::create(&empty_data_file_path).await?;
- empty_file.sync_all().await?;
-
- return Ok(ExtractedPartData {
- data_file_path: empty_data_file_path,
- data_file_size: 0,
- });
+ return Ok(PreparedPart::empty());
}
if response.status().as_u16() == 429 {
@@ -423,6 +422,11 @@ impl DateRangeExportSource {
let temp_dir = self.get_temp_dir_path().await?;
+ // Pause the job if staging is already over budget (e.g. leftover from a
+ // prior part) before we add to it, and again as the `.raw` grows.
+ let mut guard = StagingGuard::new(self.staging_dir.clone(), self.staging_max_bytes);
+ guard.check().await?;
+
let raw_file_path = temp_dir.join(format!("{}.raw", key.replace(':', "_")));
let mut raw_file = File::create(&raw_file_path)
.await
@@ -442,6 +446,7 @@ impl DateRangeExportSource {
)
})?;
total_bytes += chunk.len();
+ guard.record(chunk.len() as u64).await?;
}
raw_file.sync_all().await.with_context(|| {
@@ -450,6 +455,10 @@ impl DateRangeExportSource {
raw_file_path.display()
)
})?;
+ // Final check once the whole `.raw` is on disk: the per-chunk `record` calls are
+ // throttled, so a part smaller than the check interval could otherwise exceed the
+ // limit without ever being measured. This enforces the limit at the part boundary.
+ guard.check().await?;
info!(
"Streamed {} bytes to file {} for key: {}",
total_bytes,
@@ -457,27 +466,15 @@ impl DateRangeExportSource {
key
);
- let extracted_part = self
- .extractor
- .extract_compressed_to_seekable_file(key, &raw_file_path, temp_dir.as_path())
- .await
- .with_context(|| {
- format!("Failed to extract compressed to seekable file for key: {key}")
- })?;
-
- if let Err(e) = tokio::fs::remove_file(&raw_file_path).await {
- warn!(
- "Failed to remove raw file {0}: {e}",
- raw_file_path.display()
- );
- }
+ // Keep the `.raw` file and decompress on demand as the job reads forward.
+ let reader = self.extractor.open_reader(raw_file_path.clone());
info!(
- "Extracted part key: {} with {} total bytes",
- key, extracted_part.data_file_size
+ "Prepared key {} ({total_bytes} compressed bytes, streaming decode)",
+ key
);
- Ok(extracted_part)
+ Ok(PreparedPart::streaming(raw_file_path, reader))
}
async fn get_chunk_from_prepared_key(
@@ -486,48 +483,7 @@ impl DateRangeExportSource {
offset: u64,
size: u64,
) -> Result<Vec<u8>, Error> {
- let extracted_part = {
- let prepared_keys = self.prepared_keys.lock().await;
- prepared_keys
- .get(key)
- .ok_or_else(|| Error::msg(format!("Key not prepared: {key}")))?
- .clone()
- };
-
- if extracted_part.data_file_size == 0 {
- return Ok(Vec::new());
- }
-
- let total_size = extracted_part.data_file_size as u64;
- if offset >= total_size {
- return Ok(Vec::new());
- }
-
- let end_offset = std::cmp::min(offset + size, total_size);
- let read_size = (end_offset - offset) as usize;
-
- let mut file = File::open(extracted_part.data_file_path)
- .await
- .with_context(|| format!("Failed to open extracted data file for key: {key}"))?;
- file.seek(std::io::SeekFrom::Start(offset))
- .await
- .with_context(|| {
- format!("Failed to seek to offset {offset} in extracted data file for key: {key}")
- })?;
- let mut buffer = vec![0u8; read_size];
- file.read_exact(&mut buffer).await.with_context(|| {
- format!(
- "Failed to read exact {read_size} bytes from extracted data file for key: {key}"
- )
- })?;
-
- if end_offset == total_size {
- if let Err(e) = self.cleanup_key(key).await {
- warn!("Failed to cleanup key {key}: {e:?}");
- }
- }
-
- Ok(buffer)
+ read_prepared_chunk(&self.prepared_keys, key, offset, size).await
}
}
@@ -543,12 +499,7 @@ impl DataSource for DateRangeExportSource {
async fn size(&self, key: &str) -> Result<Option<u64>, Error> {
let prepared_keys = self.prepared_keys.lock().await;
- if let Some(extracted_part) = prepared_keys.get(key) {
- let total_bytes = extracted_part.data_file_size as u64;
- Ok(Some(total_bytes))
- } else {
- Ok(None)
- }
+ Ok(prepared_keys.get(key).and_then(|part| part.total_size))
}
async fn get_chunk(&self, key: &str, offset: u64, size: u64) -> Result<Vec<u8>, Error> {
@@ -624,11 +575,11 @@ impl DataSource for DateRangeExportSource {
}
}
- let extracted_part = self.download_and_prepare_part_data(key).await?;
+ let prepared_part = self.download_and_prepare_part_data(key).await?;
{
let mut prepared_keys = self.prepared_keys.lock().await;
- prepared_keys.insert(key.to_string(), extracted_part);
+ prepared_keys.insert(key.to_string(), prepared_part);
}
Ok(())
@@ -636,18 +587,7 @@ impl DataSource for DateRangeExportSource {
// Should be called after we've read the last of a key/part into memory and attempt to commit it
async fn cleanup_key(&self, key: &str) -> Result<(), Error> {
- let extracted_part = {
- let mut prepared_keys = self.prepared_keys.lock().await;
- prepared_keys.remove(key)
- };
-
- if let Some(extracted_part) = extracted_part {
- if let Err(e) = tokio::fs::remove_file(&extracted_part.data_file_path).await {
- warn!("Failed to remove temp file for key {}: {}", key, e);
- } else {
- debug!("Cleaned up key: {}", key);
- }
- }
+ remove_prepared_key(&self.prepared_keys, key).await;
Ok(())
}
@@ -659,34 +599,59 @@ impl DataSource for DateRangeExportSource {
#[cfg(test)]
mod tests {
use super::*;
- use crate::extractor::ExtractedPartData;
+ use crate::extractor::StreamingReader;
use chrono::{TimeZone, Utc};
use httpmock::MockServer;
use std::path::Path;
use tempfile::TempDir;
- use tokio::fs;
+ /// Test extractor that streams the downloaded body back verbatim (no
+ /// decompression, no newline normalization), so assertions can compare
+ /// against the exact plaintext body served by the mock server.
struct MockExtractor;
- #[async_trait]
impl PartExtractor for MockExtractor {
- async fn extract_compressed_to_seekable_file(
- &self,
- _key: &str,
- raw_file_path: &Path,
- temp_dir: &Path,
- ) -> Result<ExtractedPartData, Error> {
- let data_file_path = temp_dir.join(format!(
- "{}.data",
- raw_file_path.file_stem().unwrap().to_string_lossy()
- ));
- fs::copy(raw_file_path, &data_file_path).await?;
- let metadata = fs::metadata(&data_file_path).await?;
- Ok(ExtractedPartData {
- data_file_path,
- data_file_size: metadata.len() as usize,
- })
+ fn open_reader(&self, raw_file_path: PathBuf) -> StreamingReader {
+ StreamingReader::open_verbatim(raw_file_path)
+ }
+ }
+
+ /// Read a key to completion through the public source API in `chunk`-sized
+ /// forward reads, returning the reconstructed bytes. Mirrors how the job's
+ /// chunker consumes a key (monotonic offsets), and drives lazy size discovery.
+ async fn read_key_to_end(source: &DateRangeExportSource, key: &str, chunk: u64) -> Vec<u8> {
+ let mut out = Vec::new();
+ let mut offset = 0u64;
+ loop {
+ let bytes = source.get_chunk(key, offset, chunk).await.unwrap();
+ if bytes.is_empty() {
+ break;
+ }
+ offset += bytes.len() as u64;
+ out.extend_from_slice(&bytes);
}
+ out
+ }
+
+ /// Count `.raw` staging files anywhere under `dir`. Peak/residual `.raw` count
+ /// is how we assert staging disk is freed (see the free-on-EOF tests below).
+ fn count_raw_files(dir: &Path) -> usize {
+ let mut count = 0;
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(d) = stack.pop() {
+ let Ok(entries) = std::fs::read_dir(&d) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ stack.push(path);
+ } else if path.extension().and_then(|e| e.to_str()) == Some("raw") {
+ count += 1;
+ }
+ }
+ }
+ count
}
const TEST_DATA: &str = r#"{"event": "test1", "timestamp": "2023-01-01T00:00:00Z"}
@@ -799,9 +764,11 @@ mod tests {
source.prepare_key(key).await.unwrap();
- let size = source.size(key).await.unwrap();
- assert!(size.is_some());
- assert_eq!(size.unwrap(), TEST_DATA.len() as u64);
+ // Size is discovered lazily: unknown until the stream has been read to EOF.
+ assert_eq!(source.size(key).await.unwrap(), None);
+
+ let data = read_key_to_end(&source, key, 8).await;
+ assert_eq!(data, TEST_DATA.as_bytes());
source.cleanup_after_job().await.unwrap();
}
@@ -951,12 +918,14 @@ mod tests {
let file_size = TEST_DATA.len() as u64;
- let chunk = source.get_chunk(key, file_size + 100, 10).await.unwrap();
- assert!(chunk.is_empty());
-
+ // Reads are forward-only. A window that straddles EOF returns just the
+ // available tail; a subsequent read at EOF returns empty.
let chunk = source.get_chunk(key, file_size - 5, 20).await.unwrap();
assert_eq!(chunk.len(), 5);
+ let chunk = source.get_chunk(key, file_size, 10).await.unwrap();
+ assert!(chunk.is_empty());
+
source.cleanup_after_job().await.unwrap();
}
@@ -1066,11 +1035,14 @@ mod tests {
source.prepare_key(key).await.unwrap();
- assert!(source.size(key).await.unwrap().is_some());
+ // The key is prepared and readable.
+ let chunk = source.get_chunk(key, 0, 8).await.unwrap();
+ assert!(!chunk.is_empty());
source.cleanup_key(key).await.unwrap();
- assert!(source.size(key).await.unwrap().is_none());
+ // After cleanup the key is torn down, so reading it errors.
+ assert!(source.get_chunk(key, 0, 8).await.is_err());
source.cleanup_after_job().await.unwrap();
}
@@ -1099,27 +1071,98 @@ mod tests {
}
#[tokio::test]
- async fn test_reading_entire_file_cleans_up_key() {
+ async fn test_reading_entire_file_frees_raw_and_keeps_size() {
let server = MockServer::start();
let _mock = server.mock(|when, then| {
when.method(httpmock::Method::GET).path("/export");
then.status(200).body(TEST_DATA);
});
- let _staging = TempDir::new().unwrap();
- let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());
+ let staging = TempDir::new().unwrap();
+ let source = create_test_source(server.url("/export"), 3600, staging.path().to_path_buf());
+ source.prepare_for_job().await.unwrap();
+
+ let keys = source.keys().await.unwrap();
+ let key = &keys[0];
+
+ source.prepare_key(key).await.unwrap();
+ assert_eq!(
+ count_raw_files(staging.path()),
+ 1,
+ "prepared key stages one .raw"
+ );
+
+ // Reading the key to completion reconstructs the body, and the source frees
+ // the compressed `.raw` on the EOF read — no `cleanup_after_job` needed.
+ let data = read_key_to_end(&source, key, 8).await;
+ assert_eq!(data, TEST_DATA.as_bytes());
+ assert_eq!(
+ count_raw_files(staging.path()),
+ 0,
+ "the .raw must be deleted once the key is fully read"
+ );
+
+ // The bookkeeping entry is retained so the now-known size is still reportable.
+ assert_eq!(
+ source.size(key).await.unwrap(),
+ Some(TEST_DATA.len() as u64)
+ );
+
+ source.cleanup_after_job().await.unwrap();
+ }
+
+ /// Robustness proof for the hex-security finding / the A1 class of regression:
+ /// staging cleanup happens on the EOF read itself, so a caller that consumes
+ /// the final chunk and immediately treats the part as done (issuing no further
+ /// read) still frees the `.raw`. A single read larger than the body reaches EOF
+ /// in one shot; we assert the file is gone without any terminal `offset>=total`
+ /// read, and that the retained entry keeps `prepare_key` from re-downloading it.
+ #[tokio::test]
+ async fn test_raw_freed_on_single_eof_read_without_terminal_read() {
+ let server = MockServer::start();
+ let mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(TEST_DATA);
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = create_test_source(server.url("/export"), 3600, staging.path().to_path_buf());
source.prepare_for_job().await.unwrap();
let keys = source.keys().await.unwrap();
let key = &keys[0];
source.prepare_key(key).await.unwrap();
+ assert_eq!(mock.hits(), 1);
+ assert_eq!(count_raw_files(staging.path()), 1);
- let file_size = source.size(key).await.unwrap().unwrap();
+ // One read past the end returns the whole body and reaches EOF.
+ let bytes = source
+ .get_chunk(key, 0, TEST_DATA.len() as u64 + 4096)
+ .await
+ .unwrap();
+ assert_eq!(bytes, TEST_DATA.as_bytes());
- let _chunk = source.get_chunk(key, 0, file_size).await.unwrap();
+ // Cleanup fired on that read alone — no second (terminal) get_chunk issued.
+ assert_eq!(
+ count_raw_files(staging.path()),
+ 0,
+ "the .raw must be freed on the EOF read, without a terminal read"
+ );
+ assert_eq!(
+ source.size(key).await.unwrap(),
+ Some(TEST_DATA.len() as u64)
+ );
- assert!(source.size(key).await.unwrap().is_none());
+ // The retained entry keeps prepare_key a no-op, so the freed file is not
+ // re-downloaded (which would re-stage the .raw we just reclaimed).
+ source.prepare_key(key).await.unwrap();
+ assert_eq!(
+ mock.hits(),
+ 1,
+ "prepare_key must not re-download a freed key"
+ );
+ assert_eq!(count_raw_files(staging.path()), 0);
source.cleanup_after_job().await.unwrap();
}
diff --git a/rust/batch-import-worker/src/source/mod.rs b/rust/batch-import-worker/src/source/mod.rs
index fc9211c43972..e4795ec770dd 100644
--- a/rust/batch-import-worker/src/source/mod.rs
+++ b/rust/batch-import-worker/src/source/mod.rs
@@ -1,5 +1,11 @@
use anyhow::Error;
use async_trait::async_trait;
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Arc;
+use tokio::sync::Mutex;
+
+use crate::extractor::StreamingReader;
pub mod date_range_export;
pub mod folder;
@@ -7,6 +13,116 @@ pub mod s3;
pub mod s3_gzip;
pub mod url_list;
+/// Per-key state for sources that download a compressed `.raw` file and
+/// stream-decompress it on demand (see [`crate::extractor::StreamingReader`]).
+///
+/// Disk usage is bounded by the compressed file: there is no decompressed
+/// `.data` copy. The decompressed size is discovered lazily — it is only known
+/// once the reader reaches end-of-stream — so `total_size` stays `None` until
+/// the job has read the whole key.
+pub(crate) struct PreparedPart {
+ /// The compressed file backing this key. `None` for empty keys (404 /
+ /// zero-byte objects) and once the key has been streamed to EOF, when the
+ /// file is deleted and this is cleared (see [`read_prepared_chunk`]).
+ pub raw_file_path: Option<PathBuf>,
+ /// Forward streaming reader over the compressed file. `None` for empty keys
+ /// and once the key has been fully read (the reader is dropped at EOF).
+ pub reader: Option<Arc<Mutex<StreamingReader>>>,
+ /// Total decompressed size, known only after EOF. Always `Some(0)` for empty.
+ pub total_size: Option<u64>,
+}
+
+impl PreparedPart {
+ pub(crate) fn empty() -> Self {
+ Self {
+ raw_file_path: None,
+ reader: None,
+ total_size: Some(0),
+ }
+ }
+
+ pub(crate) fn streaming(raw_file_path: PathBuf, reader: StreamingReader) -> Self {
+ Self {
+ raw_file_path: Some(raw_file_path),
+ reader: Some(Arc::new(Mutex::new(reader))),
+ total_size: None,
+ }
+ }
+}
+
+/// Read a forward range from a prepared, stream-decompressed key.
+///
+/// Reads are forward-only and monotonic, matching the job's chunker. On the read
+/// that reaches end-of-stream, the discovered total size is recorded (so
+/// [`DataSource::size`] can return it) and the compressed backing file is freed
+/// immediately: the reader is dropped (stopping the producer thread) and the
+/// `.raw` deleted, since a forward-only stream never re-reads it. The bookkeeping
+/// entry is kept with `reader: None` so `size()` still reports the total and
+/// `prepare_key` stays a no-op. Cleanup therefore happens on the EOF read itself
+/// and never depends on a later terminal read or on how the caller drives reads.
+pub(crate) async fn read_prepared_chunk(
+ prepared_keys: &Mutex<HashMap<String, PreparedPart>>,
+ key: &str,
+ offset: u64,
+ size: u64,
+) -> Result<Vec<u8>, Error> {
+ let reader = {
+ let map = prepared_keys.lock().await;
+ let part = map
+ .get(key)
+ .ok_or_else(|| Error::msg(format!("Key not prepared: {key}")))?;
+ match &part.reader {
+ // Empty key, or a key already streamed to EOF and freed: nothing left
+ // to read. Idempotent — we leave the tiny reader-less entry in place
+ // (dropped by cleanup_after_job) so behavior can't depend on the
+ // caller's read pattern.
+ None => return Ok(Vec::new()),
+ Some(reader) => reader.clone(),
+ }
+ };
+
+ let chunk = reader.lock().await.read_at(offset, size as usize).await?;
+
+ let mut raw_to_delete = None;
+ if let Some(total) = chunk.total {
+ let mut map = prepared_keys.lock().await;
+ if let Some(part) = map.get_mut(key) {
+ part.total_size = Some(total);
+ // EOF reached with the final bytes in hand. A forward-only stream
+ // never reads this file again, so free it now instead of waiting for
+ // a terminal offset>=total read; keep the reader-less entry so size()
+ // still reports `total` and prepare_key stays a no-op.
+ part.reader = None;
+ raw_to_delete = part.raw_file_path.take();
+ }
+ }
+
+ // Delete the compressed file outside the map lock.
+ if let Some(raw) = raw_to_delete {
+ if let Err(e) = tokio::fs::remove_file(&raw).await {
+ tracing::warn!("Failed to remove raw file for key {key}: {e}");
+ }
+ }
+
+ Ok(chunk.bytes)
+}
+
+/// Remove a prepared key, dropping its reader (which stops the producer thread)
+/// and deleting the backing compressed file.
+pub(crate) async fn remove_prepared_key(
+ prepared_keys: &Mutex<HashMap<String, PreparedPart>>,
+ key: &str,
+) {
+ let removed = { prepared_keys.lock().await.remove(key) };
+ if let Some(part) = removed {
+ if let Some(raw) = part.raw_file_path {
+ if let Err(e) = tokio::fs::remove_file(&raw).await {
+ tracing::warn!("Failed to remove raw file for key {key}: {e}");
+ }
+ }
+ }
+}
+
#[async_trait]
pub trait DataSource: Sync + Send {
async fn keys(&self) -> Result<Vec<String>, Error>;
diff --git a/rust/batch-import-worker/src/source/s3_gzip.rs b/rust/batch-import-worker/src/source/s3_gzip.rs
index 6cc196dec809..b7db69956efe 100644
--- a/rust/batch-import-worker/src/source/s3_gzip.rs
+++ b/rust/batch-import-worker/src/source/s3_gzip.rs
@@ -7,14 +7,15 @@ use async_trait::async_trait;
use aws_sdk_s3::Client as S3Client;
use tempfile::TempDir;
use tokio::sync::Mutex;
-use tokio::{fs::File, io::AsyncReadExt, io::AsyncSeekExt, io::AsyncWriteExt};
+use tokio::{fs::File, io::AsyncWriteExt};
use tracing::{debug, info, warn};
use crate::error::ToUserError;
-use crate::extractor::{ExtractedPartData, PartExtractor};
+use crate::extractor::PartExtractor;
+use crate::staging::StagingGuard;
use super::s3::extract_user_friendly_error;
-use super::DataSource;
+use super::{read_prepared_chunk, remove_prepared_key, DataSource, PreparedPart};
fn sanitize_key_for_path(key: &str) -> String {
key.replace(['/', ':'], "_")
@@ -30,8 +31,9 @@ pub struct GzipS3Source {
prefix: String,
extractor: Arc<dyn PartExtractor>,
staging_dir: PathBuf,
+ staging_max_bytes: u64,
temp_dir: Arc<Mutex<Option<TempDir>>>,
- prepared_keys: Arc<Mutex<HashMap<String, ExtractedPartData>>>,
+ prepared_keys: Arc<Mutex<HashMap<String, PreparedPart>>>,
}
impl GzipS3Source {
@@ -41,6 +43,7 @@ impl GzipS3Source {
prefix: String,
extractor: Arc<dyn PartExtractor>,
staging_dir: PathBuf,
+ staging_max_bytes: u64,
) -> Self {
Self {
client,
@@ -48,6 +51,7 @@ impl GzipS3Source {
prefix,
extractor,
staging_dir,
+ staging_max_bytes,
temp_dir: Arc::new(Mutex::new(None)),
prepared_keys: Arc::new(Mutex::new(HashMap::new())),
}
@@ -68,48 +72,7 @@ impl GzipS3Source {
offset: u64,
size: u64,
) -> Result<Vec<u8>, Error> {
- let extracted_part = {
- let prepared_keys = self.prepared_keys.lock().await;
- prepared_keys
- .get(key)
- .ok_or_else(|| Error::msg(format!("Key not prepared: {key}")))?
- .clone()
- };
-
- if extracted_part.data_file_size == 0 {
- return Ok(Vec::new());
- }
-
- let total_size = extracted_part.data_file_size as u64;
- if offset >= total_size {
- return Ok(Vec::new());
- }
-
- let end_offset = std::cmp::min(offset + size, total_size);
- let read_size = (end_offset - offset) as usize;
-
- let mut file = File::open(&extracted_part.data_file_path)
- .await
- .with_context(|| format!("Failed to open extracted data file for key: {key}"))?;
- file.seek(std::io::SeekFrom::Start(offset))
- .await
- .with_context(|| {
- format!("Failed to seek to offset {offset} in extracted data file for key: {key}")
- })?;
- let mut buffer = vec![0u8; read_size];
- file.read_exact(&mut buffer).await.with_context(|| {
- format!(
- "Failed to read exact {read_size} bytes from extracted data file for key: {key}"
- )
- })?;
-
- if end_offset == total_size {
- if let Err(e) = self.cleanup_key(key).await {
- warn!("Failed to cleanup key {key}: {e:?}");
- }
- }
-
- Ok(buffer)
+ read_prepared_chunk(&self.prepared_keys, key, offset, size).await
}
}
@@ -156,11 +119,7 @@ impl DataSource for GzipS3Source {
async fn size(&self, key: &str) -> Result<Option<u64>, Error> {
let prepared_keys = self.prepared_keys.lock().await;
- if let Some(extracted_part) = prepared_keys.get(key) {
- Ok(Some(extracted_part.data_file_size as u64))
- } else {
- Ok(None)
- }
+ Ok(prepared_keys.get(key).and_then(|part| part.total_size))
}
async fn get_chunk(&self, key: &str, offset: u64, size: u64) -> Result<Vec<u8>, Error> {
@@ -232,6 +191,11 @@ impl DataSource for GzipS3Source {
let temp_dir = self.get_temp_dir_path().await?;
let safe_key = sanitize_key_for_path(key);
+ // Pause the job if staging is already over budget before we add to it,
+ // and again as the `.raw` grows.
+ let mut guard = StagingGuard::new(self.staging_dir.clone(), self.staging_max_bytes);
+ guard.check().await?;
+
let raw_file_path = temp_dir.join(format!("{}.raw", safe_key));
let mut raw_file = File::create(&raw_file_path)
.await
@@ -249,6 +213,7 @@ impl DataSource for GzipS3Source {
format!("Failed to write raw file: {}", raw_file_path.display())
})?;
total_bytes += chunk.len() as u64;
+ guard.record(chunk.len() as u64).await?;
}
raw_file
@@ -265,68 +230,44 @@ impl DataSource for GzipS3Source {
);
}
- let empty_data_file_path = temp_dir.join(format!("{}.data", safe_key));
- let empty_file = File::create(&empty_data_file_path)
- .await
- .with_context(|| format!("Failed to create empty data file for key: {key}"))?;
- empty_file.sync_all().await?;
-
- let extracted_part = ExtractedPartData {
- data_file_path: empty_data_file_path,
- data_file_size: 0,
- };
let mut prepared_keys = self.prepared_keys.lock().await;
- prepared_keys.insert(key.to_string(), extracted_part);
+ prepared_keys.insert(key.to_string(), PreparedPart::empty());
info!("Prepared key {} (empty object)", key);
return Ok(());
}
+ // Final check once the whole `.raw` is on disk: the per-chunk `record` calls are
+ // throttled, so a part smaller than the check interval could otherwise exceed the
+ // limit without ever being measured. This enforces the limit at the part boundary.
+ guard.check().await?;
+
debug!(
- "Streamed {total_bytes} bytes to {} for key: {key}",
+ "Streamed {total_bytes} compressed bytes to {} for key: {key}",
raw_file_path.display()
);
- let extracted_part = self
- .extractor
- .extract_compressed_to_seekable_file(&safe_key, &raw_file_path, &temp_dir)
- .await
- .with_context(|| {
- format!("Failed to extract compressed to seekable file for key: {key}")
- })?;
-
- if let Err(e) = tokio::fs::remove_file(&raw_file_path).await {
- warn!(
- "Failed to remove raw file {}: {e:?}",
- raw_file_path.display()
- );
- }
-
+ // Open a streaming decoder over the compressed file; we keep the `.raw`
+ // on disk and decompress on demand rather than materializing a `.data`
+ // copy, bounding disk usage to the compressed size.
+ let reader = self.extractor.open_reader(raw_file_path.clone());
{
let mut prepared_keys = self.prepared_keys.lock().await;
- prepared_keys.insert(key.to_string(), extracted_part.clone());
+ prepared_keys.insert(
+ key.to_string(),
+ PreparedPart::streaming(raw_file_path, reader),
+ );
}
info!(
- "Prepared key {} ({} bytes decompressed)",
- key, extracted_part.data_file_size
+ "Prepared key {} ({total_bytes} compressed bytes, streaming decode)",
+ key
);
Ok(())
}
async fn cleanup_key(&self, key: &str) -> Result<(), Error> {
- let extracted_part = {
- let mut prepared_keys = self.prepared_keys.lock().await;
- prepared_keys.remove(key)
- };
-
- if let Some(extracted_part) = extracted_part {
- if let Err(e) = tokio::fs::remove_file(&extracted_part.data_file_path).await {
- warn!("Failed to remove temp file for key {}: {}", key, e);
- } else {
- debug!("Cleaned up key: {}", key);
- }
- }
+ remove_prepared_key(&self.prepared_keys, key).await;
Ok(())
}
}
diff --git a/rust/batch-import-worker/src/staging.rs b/rust/batch-import-worker/src/staging.rs
index 1304564f2336..02c91d314808 100644
--- a/rust/batch-import-worker/src/staging.rs
+++ b/rust/batch-import-worker/src/staging.rs
@@ -1,7 +1,84 @@
-use std::path::Path;
+use std::path::{Path, PathBuf};
use anyhow::{Context, Error};
-use tracing::{debug, info, warn};
+use tracing::{info, warn};
+
+use crate::error::UserError;
+
+/// Default amount of freshly-written data between staging-size checks. Stat-ing
+/// the whole staging tree is O(files), so we only re-measure after this much has
+/// been written, bounding overshoot to roughly this value plus one download chunk.
+const DEFAULT_GUARD_CHECK_INTERVAL_BYTES: u64 = 256 * 1024 * 1024;
+
+/// Fail-fast guard against unbounded staging growth.
+///
+/// Sources that download large parts call [`StagingGuard::check`] before starting
+/// (to catch staging that is already over budget from earlier work) and
+/// [`StagingGuard::record`] as they write. If staging exceeds the configured
+/// limit the job is paused via a [`UserError`] instead of the pod being evicted
+/// under disk pressure (which loses all progress and restart-loops). A limit of
+/// `0` disables the guard.
+pub struct StagingGuard {
+ staging_dir: PathBuf,
+ max_bytes: u64,
+ check_interval: u64,
+ since_check: u64,
+}
+
+impl StagingGuard {
+ pub fn new(staging_dir: PathBuf, max_bytes: u64) -> Self {
+ Self {
+ staging_dir,
+ max_bytes,
+ check_interval: DEFAULT_GUARD_CHECK_INTERVAL_BYTES,
+ since_check: 0,
+ }
+ }
+
+ fn enabled(&self) -> bool {
+ self.max_bytes > 0
+ }
+
+ /// Record `written` freshly-staged bytes and re-check the staging size once
+ /// enough has accumulated since the last check. Cheap to call per chunk.
+ pub async fn record(&mut self, written: u64) -> Result<(), Error> {
+ if !self.enabled() {
+ return Ok(());
+ }
+ self.since_check = self.since_check.saturating_add(written);
+ if self.since_check < self.check_interval {
+ return Ok(());
+ }
+ self.since_check = 0;
+ self.check().await
+ }
+
+ /// Measure staging usage now and fail if it exceeds the limit.
+ pub async fn check(&self) -> Result<(), Error> {
+ if !self.enabled() {
+ return Ok(());
+ }
+ let used = staging_dir_bytes(&self.staging_dir).await;
+ if used > self.max_bytes {
+ crate::metrics::staging_guard_tripped();
+ const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
+ let used_gib = used as f64 / GIB;
+ let limit_gib = self.max_bytes as f64 / GIB;
+ let user_msg = format!(
+ "Staging disk limit exceeded ({used_gib:.1} GiB used, limit {limit_gib:.1} GiB). \
+ This import part is too large to process on a single worker -- split the import \
+ into smaller date ranges or parts."
+ );
+ return Err(Error::msg(format!(
+ "staging dir {} at {used} bytes exceeds limit {}",
+ self.staging_dir.display(),
+ self.max_bytes
+ ))
+ .context(UserError::new(user_msg)));
+ }
+ Ok(())
+ }
+}
/// Ensure the staging directory exists, creating it if necessary.
pub async fn ensure_staging_dir(path: &Path) -> Result<(), Error> {
@@ -81,8 +158,11 @@ pub async fn sweep_staging_dir(path: &Path) -> Result<u64, Error> {
pub async fn staging_dir_bytes(path: &Path) -> u64 {
match compute_dir_size(path).await {
Ok(bytes) => bytes,
+ // Fail open: a stat failure must not block imports. Log at warn! so a
+ // persistent failure (EACCES, the path vanishing) is operator-visible
+ // rather than silently disabling the guard.
Err(e) => {
- debug!("Failed to compute staging dir size: {e}");
+ warn!("Failed to compute staging dir size, treating as 0: {e}");
0
}
}
@@ -192,4 +272,75 @@ mod tests {
let bytes = staging_dir_bytes(&staging).await;
assert_eq!(bytes, 0);
}
+
+ #[tokio::test]
+ async fn test_staging_guard_disabled_never_trips() {
+ let root = TempDir::new().unwrap();
+ ensure_staging_dir(root.path()).await.unwrap();
+ tokio::fs::write(root.path().join("big"), vec![0u8; 10_000])
+ .await
+ .unwrap();
+
+ // max_bytes == 0 disables the guard regardless of usage.
+ let mut guard = StagingGuard::new(root.path().to_path_buf(), 0);
+ guard.check().await.unwrap();
+ guard.record(1_000_000_000).await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn test_staging_guard_check_trips_over_limit_with_user_message() {
+ use crate::error::get_user_message;
+
+ let root = TempDir::new().unwrap();
+ ensure_staging_dir(root.path()).await.unwrap();
+ tokio::fs::write(root.path().join("big"), vec![0u8; 4096])
+ .await
+ .unwrap();
+
+ let guard = StagingGuard::new(root.path().to_path_buf(), 1024);
+ let err = guard.check().await.unwrap_err();
+ // Surfaces an actionable user-facing message (so the job pauses, not evicts),
+ // reported in GiB rather than raw bytes.
+ let msg = get_user_message(&err);
+ assert!(msg.contains("Staging disk limit exceeded"));
+ assert!(
+ msg.contains("GiB"),
+ "expected GiB-formatted message, got: {msg}"
+ );
+
+ // Under-limit passes.
+ let ok_guard = StagingGuard::new(root.path().to_path_buf(), 1024 * 1024);
+ ok_guard.check().await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn test_staging_guard_fail_open_on_stat_error() {
+ // Point the guard at a file, not a directory, so read_dir fails. The
+ // guard must fail open (Ok, treating usage as 0) rather than erroring or
+ // panicking -- a stat failure must never block imports.
+ let root = TempDir::new().unwrap();
+ let not_a_dir = root.path().join("regular-file");
+ tokio::fs::write(&not_a_dir, b"data").await.unwrap();
+
+ let guard = StagingGuard::new(not_a_dir, 1024);
+ guard.check().await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn test_staging_guard_record_throttles_until_interval() {
+ let root = TempDir::new().unwrap();
+ ensure_staging_dir(root.path()).await.unwrap();
+ tokio::fs::write(root.path().join("big"), vec![0u8; 4096])
+ .await
+ .unwrap();
+
+ // Already over the limit, but record() only re-measures after the check
+ // interval of newly-recorded bytes has accumulated.
+ let mut guard = StagingGuard::new(root.path().to_path_buf(), 1024);
+ guard.check_interval = 1_000_000;
+
+ guard.record(500_000).await.unwrap(); // below interval -> no measurement
+ let tripped = guard.record(600_000).await; // crosses interval -> measures
+ assert!(tripped.is_err());
+ }
}
diff --git a/rust/batch-import-worker/tests/common/mod.rs b/rust/batch-import-worker/tests/common/mod.rs
index 6bad67f63acf..ff174c722d3f 100644
--- a/rust/batch-import-worker/tests/common/mod.rs
+++ b/rust/batch-import-worker/tests/common/mod.rs
@@ -1,8 +1,24 @@
-//! Shared test utilities for MinIO/S3 integration tests.
+//! Shared test utilities for the batch-import integration tests.
+//!
+//! Each integration test file is its own crate and pulls this in via `mod
+//! common;`, so a helper used by only some of them looks "dead" to the others —
+//! hence the crate-wide allow below.
+#![allow(dead_code)]
+
+use std::io::Write;
use aws_config::BehaviorVersion;
use aws_sdk_s3::config::Region;
use aws_sdk_s3::Client as AwsS3Client;
+use flate2::write::GzEncoder;
+use flate2::Compression;
+
+/// Gzip-compress `data` with default compression (single member).
+pub fn gzip_bytes(data: &[u8]) -> Vec<u8> {
+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
+ encoder.write_all(data).unwrap();
+ encoder.finish().unwrap()
+}
pub const MINIO_ENDPOINT: &str = "http://localhost:19000";
pub const MINIO_ACCESS_KEY: &str = "object_storage_root_user";
diff --git a/rust/batch-import-worker/tests/date_range_export_streaming_test.rs b/rust/batch-import-worker/tests/date_range_export_streaming_test.rs
new file mode 100644
index 000000000000..0b0ca6b54e2b
--- /dev/null
+++ b/rust/batch-import-worker/tests/date_range_export_streaming_test.rs
@@ -0,0 +1,260 @@
+//! Dependency-free integration tests for the streaming-decompression path of the
+//! date range export source. These exercise the real `PlainGzipExtractor` (not a
+//! mock) end-to-end through the public `DataSource` interface, asserting the
+//! properties that matter for the critical batch-import path:
+//!
+//! - reconstruction: the decompressed stream read in small forward chunks equals
+//! the original body (with the trailing-newline guarantee),
+//! - resume: a fresh source instance (simulating a pod restart) can resume from a
+//! persisted decompressed offset and reconstruct the remainder exactly,
+//! - disk bounding: reading never materializes a decompressed `.data` file, so
+//! staging disk usage stays bounded by the compressed `.raw` size even when the
+//! content decompresses to something far larger.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+
+use batch_import_worker::extractor::ExtractorType;
+use batch_import_worker::source::date_range_export::{AuthConfig, DateRangeExportSource};
+use batch_import_worker::source::DataSource;
+use chrono::{TimeZone, Utc};
+use httpmock::MockServer;
+use tempfile::TempDir;
+
+mod common;
+use common::gzip_bytes;
+
+/// Build a single-interval source pointed at `base_url`, staging under `staging`.
+fn build_source(base_url: String, staging: &Path) -> DateRangeExportSource {
+ let start = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();
+ let end = Utc.with_ymd_and_hms(2023, 1, 1, 1, 0, 0).unwrap();
+ DateRangeExportSource::builder(
+ base_url,
+ start,
+ end,
+ 3600,
+ ExtractorType::PlainGzip.create_extractor(),
+ staging.to_path_buf(),
+ )
+ .with_auth(AuthConfig::None)
+ .with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string())
+ .with_headers(HashMap::new())
+ .build()
+ .unwrap()
+}
+
+/// Consume a key forward from `start_offset` in `chunk`-sized reads until the
+/// stream ends (an empty chunk), returning the concatenated bytes.
+async fn read_forward(
+ source: &DateRangeExportSource,
+ key: &str,
+ start_offset: u64,
+ chunk: u64,
+) -> Vec<u8> {
+ let mut out = Vec::new();
+ let mut offset = start_offset;
+ loop {
+ let bytes = source
+ .get_chunk(key, offset, chunk)
+ .await
+ .expect("get_chunk");
+ if bytes.is_empty() {
+ break;
+ }
+ offset += bytes.len() as u64;
+ out.extend_from_slice(&bytes);
+ }
+ out
+}
+
+fn list_files_with_ext(dir: &Path, ext: &str) -> Vec<PathBuf> {
+ let mut out = Vec::new();
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(d) = stack.pop() {
+ let Ok(entries) = std::fs::read_dir(&d) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ stack.push(path);
+ } else if path.extension().and_then(|e| e.to_str()) == Some(ext) {
+ out.push(path);
+ }
+ }
+ }
+ out
+}
+
+fn staging_total_bytes(dir: &Path) -> u64 {
+ let mut total = 0u64;
+ let mut stack = vec![dir.to_path_buf()];
+ while let Some(d) = stack.pop() {
+ let Ok(entries) = std::fs::read_dir(&d) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ stack.push(path);
+ } else if let Ok(meta) = entry.metadata() {
+ total += meta.len();
+ }
+ }
+ }
+ total
+}
+
+#[tokio::test]
+async fn test_streaming_reconstructs_full_body() {
+ let server = MockServer::start();
+ // Distinct JSONL lines so a misordered/duplicated stream would be detectable;
+ // body ends with a newline so the decompressed output equals the body exactly.
+ let mut body = String::new();
+ for i in 0..5000 {
+ body.push_str(&format!(
+ "{{\"event\":\"e{i}\",\"properties\":{{\"idx\":{i}}}}}\n"
+ ));
+ }
+ let gz = gzip_bytes(body.as_bytes());
+ let _mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(gz);
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = build_source(server.url("/export"), staging.path());
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ let key = &keys[0];
+ source.prepare_key(key).await.unwrap();
+
+ // Small chunk size exercises the carry buffer across many reads.
+ let reconstructed = read_forward(&source, key, 0, 1024).await;
+ assert_eq!(reconstructed, body.as_bytes());
+
+ source.cleanup_after_job().await.unwrap();
+}
+
+#[tokio::test]
+async fn test_streaming_resumes_from_offset_after_restart() {
+ let server = MockServer::start();
+ let mut body = String::new();
+ for i in 0..5000 {
+ body.push_str(&format!("line-{i}-{}\n", "x".repeat(20)));
+ }
+ let gz = gzip_bytes(body.as_bytes());
+ let _mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(gz);
+ });
+
+ let staging = TempDir::new().unwrap();
+
+ // First instance: read roughly the first half, tracking the decompressed
+ // offset the job would persist in PartState.current_offset.
+ let resume_offset;
+ let mut prefix = Vec::new();
+ {
+ let source = build_source(server.url("/export"), staging.path());
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ let key = &keys[0];
+ source.prepare_key(key).await.unwrap();
+
+ let half = (body.len() / 2) as u64;
+ let mut offset = 0u64;
+ while offset < half {
+ let bytes = source.get_chunk(key, offset, 777).await.unwrap();
+ assert!(
+ !bytes.is_empty(),
+ "did not expect EOF before the halfway mark"
+ );
+ offset += bytes.len() as u64;
+ prefix.extend_from_slice(&bytes);
+ }
+ resume_offset = offset;
+ source.cleanup_after_job().await.unwrap();
+ }
+
+ assert!(resume_offset > 0 && (resume_offset as usize) < body.len());
+
+ // Second instance (fresh, as after a pod restart): resume from the persisted
+ // offset and read the remainder.
+ let suffix;
+ {
+ let source = build_source(server.url("/export"), staging.path());
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ let key = &keys[0];
+ source.prepare_key(key).await.unwrap();
+
+ suffix = read_forward(&source, key, resume_offset, 999).await;
+ source.cleanup_after_job().await.unwrap();
+ }
+
+ let mut combined = prefix;
+ combined.extend_from_slice(&suffix);
+ assert_eq!(
+ combined,
+ body.as_bytes(),
+ "prefix + resumed suffix must reconstruct the full body with no gap or overlap"
+ );
+}
+
+#[tokio::test]
+async fn test_streaming_does_not_materialize_decompressed_file() {
+ let server = MockServer::start();
+ // Highly compressible: ~4 MiB decompressed from a few KiB compressed.
+ let body = "A".repeat(4 * 1024 * 1024) + "\n";
+ let gz = gzip_bytes(body.as_bytes());
+ let compressed_len = gz.len() as u64;
+ assert!(
+ compressed_len < (body.len() as u64) / 10,
+ "test setup expects strong compression"
+ );
+
+ let _mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(gz);
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = build_source(server.url("/export"), staging.path());
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ let key = &keys[0];
+ source.prepare_key(key).await.unwrap();
+
+ // After prepare: the compressed .raw exists, no decompressed .data file does,
+ // and staging is bounded by the compressed size (not the decompressed size).
+ assert_eq!(
+ list_files_with_ext(staging.path(), "raw").len(),
+ 1,
+ "expected the compressed .raw to be retained"
+ );
+ assert!(
+ list_files_with_ext(staging.path(), "data").is_empty(),
+ "streaming must not materialize a decompressed .data file"
+ );
+
+ // Read part of the (large) decompressed stream, then re-check: still no .data,
+ // and staging stays close to the compressed size rather than ballooning toward
+ // the multi-MiB decompressed size.
+ source.get_chunk(key, 0, 64 * 1024).await.unwrap();
+ source.get_chunk(key, 64 * 1024, 64 * 1024).await.unwrap();
+ assert!(
+ list_files_with_ext(staging.path(), "data").is_empty(),
+ "streaming must not materialize a decompressed .data file mid-read"
+ );
+ assert!(
+ staging_total_bytes(staging.path()) < (body.len() as u64) / 4,
+ "staging disk usage must stay bounded by the compressed size, not the decompressed size"
+ );
+
+ // Fully consume to confirm correctness, then clean up.
+ let rest = read_forward(&source, key, 128 * 1024, 256 * 1024).await;
+ assert_eq!(128 * 1024 + rest.len(), body.len());
+
+ source.cleanup_after_job().await.unwrap();
+}
diff --git a/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs b/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs
index fe9fca8482f0..6e6119e1c98a 100644
--- a/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs
+++ b/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs
@@ -13,18 +13,15 @@ use batch_import_worker::{
source::DataSource,
};
use common_types::{InternallyCapturedEvent, RawEvent};
-use flate2::write::GzEncoder;
-use flate2::Compression;
use std::collections::HashSet;
-use std::io::Write;
use std::sync::Arc;
use tempfile::NamedTempFile;
use uuid::Uuid;
mod common;
use common::{
- cleanup_bucket, create_minio_client, ensure_bucket_exists, MINIO_ACCESS_KEY, MINIO_ENDPOINT,
- MINIO_SECRET_KEY,
+ cleanup_bucket, create_minio_client, ensure_bucket_exists, gzip_bytes, MINIO_ACCESS_KEY,
+ MINIO_ENDPOINT, MINIO_SECRET_KEY,
};
const TEST_BUCKET: &str = "batch-import-test";
@@ -45,12 +42,6 @@ fn make_captured_event(i: u32) -> String {
.to_string()
}
-fn gzip_bytes(data: &[u8]) -> Vec<u8> {
- let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
- encoder.write_all(data).unwrap();
- encoder.finish().unwrap()
-}
-
#[tokio::test]
async fn test_s3_gzip_minio_integration() {
let client = match create_minio_client().await.list_buckets().send().await {
@@ -117,7 +108,7 @@ async fn test_s3_gzip_minio_integration() {
let _staging = tempfile::TempDir::new().expect("create staging dir");
let source = s3_config
- .create_gzip_source(&secrets, _staging.path().to_path_buf())
+ .create_gzip_source(&secrets, _staging.path().to_path_buf(), 0)
.await
.expect("create gzip source");
source.prepare_for_job().await.expect("prepare for job");
@@ -159,16 +150,21 @@ async fn test_s3_gzip_minio_integration() {
let mut all_events: Vec<InternallyCapturedEvent> = Vec::new();
for key in &keys {
source.prepare_key(key).await.expect("prepare_key");
- let size = source.size(key).await.expect("size").expect("size some");
+ // Streaming sources discover size lazily, so consume forward until the
+ // reader returns an empty chunk (end of stream) rather than reading up to
+ // a known size.
let mut offset = 0u64;
- while offset < size {
+ loop {
let chunk = source
.get_chunk(key, offset, CHUNK_SIZE)
.await
.expect("get_chunk");
+ if chunk.is_empty() {
+ break;
+ }
let parsed = parser(chunk).expect("parse chunk");
- all_events.extend(parsed.data);
offset += parsed.consumed as u64;
+ all_events.extend(parsed.data);
}
}
diff --git a/rust/batch-import-worker/tests/staging_guard_test.rs b/rust/batch-import-worker/tests/staging_guard_test.rs
new file mode 100644
index 000000000000..e86bab0c477a
--- /dev/null
+++ b/rust/batch-import-worker/tests/staging_guard_test.rs
@@ -0,0 +1,117 @@
+//! Dependency-free integration test for the fail-fast staging disk guard wired
+//! into the date range export source. It proves that when the staging directory
+//! is already over the configured byte budget, preparing a key returns an error
+//! carrying an actionable user-facing message (so the job pauses cleanly instead
+//! of the pod being evicted under disk pressure). A limit of 0 leaves the guard
+//! disabled and downloads proceed normally.
+
+use std::collections::HashMap;
+use std::path::Path;
+
+use batch_import_worker::extractor::ExtractorType;
+use batch_import_worker::source::date_range_export::{AuthConfig, DateRangeExportSource};
+use batch_import_worker::source::DataSource;
+use chrono::{TimeZone, Utc};
+use httpmock::MockServer;
+use tempfile::TempDir;
+
+fn build_source(base_url: String, staging: &Path, staging_max_bytes: u64) -> DateRangeExportSource {
+ let start = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();
+ let end = Utc.with_ymd_and_hms(2023, 1, 1, 1, 0, 0).unwrap();
+ DateRangeExportSource::builder(
+ base_url,
+ start,
+ end,
+ 3600,
+ ExtractorType::PlainGzip.create_extractor(),
+ staging.to_path_buf(),
+ )
+ .with_auth(AuthConfig::None)
+ .with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string())
+ .with_headers(HashMap::new())
+ .with_staging_max_bytes(staging_max_bytes)
+ .build()
+ .unwrap()
+}
+
+#[tokio::test]
+async fn test_prepare_key_pauses_when_staging_over_budget() {
+ let server = MockServer::start();
+ let _mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(vec![0u8; 1024]);
+ });
+
+ let staging = TempDir::new().unwrap();
+ // Pre-fill staging well above the 1 KiB limit (simulates leftover from prior
+ // work / a sibling part). The guard measures the whole staging tree.
+ std::fs::write(staging.path().join("preexisting.bin"), vec![0u8; 64 * 1024]).unwrap();
+
+ let source = build_source(server.url("/export"), staging.path(), 1024);
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ let key = &keys[0];
+
+ let err = source
+ .prepare_key(key)
+ .await
+ .expect_err("prepare_key must fail when staging is over budget");
+ // The error chain carries the actionable UserError so the job pauses with it.
+ let chain = format!("{err:#}");
+ assert!(
+ chain.contains("Staging disk limit exceeded"),
+ "expected user-facing staging-limit message, got: {chain}"
+ );
+}
+
+#[tokio::test]
+async fn test_prepare_key_pauses_when_single_part_exceeds_budget() {
+ // Staging starts empty (so the pre-download check passes at 0 bytes), and the
+ // downloaded part alone exceeds the limit while staying far below the guard's
+ // per-chunk check interval (256 MiB) -- so only the post-download check can catch
+ // it. Proves the limit is enforced at the part boundary, not just at download start.
+ let server = MockServer::start();
+ let _mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(vec![0u8; 1024]);
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = build_source(server.url("/export"), staging.path(), 512);
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ let key = &keys[0];
+
+ let err = source
+ .prepare_key(key)
+ .await
+ .expect_err("prepare_key must fail when the part alone exceeds the budget");
+ let chain = format!("{err:#}");
+ assert!(
+ chain.contains("Staging disk limit exceeded"),
+ "expected user-facing staging-limit message, got: {chain}"
+ );
+}
+
+#[tokio::test]
+async fn test_prepare_key_succeeds_when_guard_disabled() {
+ let server = MockServer::start();
+ let _mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(vec![0u8; 1024]);
+ });
+
+ let staging = TempDir::new().unwrap();
+ std::fs::write(staging.path().join("preexisting.bin"), vec![0u8; 64 * 1024]).unwrap();
+
+ // max_bytes == 0 disables the guard: the same over-budget staging is fine.
+ let source = build_source(server.url("/export"), staging.path(), 0);
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+ let key = &keys[0];
+
+ source
+ .prepare_key(key)
+ .await
+ .expect("prepare_key must succeed when the guard is disabled");
+}