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): latch stream decode errors, empty-part zero-byte bodies (#68417)

Eli Reisman5a547ddc307d
diff --git a/rust/batch-import-worker/src/extractor/mod.rs b/rust/batch-import-worker/src/extractor/mod.rs
index 82c07fbc1c78..0cd31c2f73dc 100644
--- a/rust/batch-import-worker/src/extractor/mod.rs
+++ b/rust/batch-import-worker/src/extractor/mod.rs
@@ -73,6 +73,12 @@ pub struct StreamingReader {
carry_start: u64,
decoded_end: u64,
eof: bool,
+ /// A decode/producer error, latched so every subsequent read keeps failing.
+ /// The producer thread exits after sending an error, and without the latch a
+ /// retried read would see the closed channel as a clean EOF and report the
+ /// partially decoded length as the stream total - callers that retry reads
+ /// would then treat a truncated stream as complete (silent data loss).
+ error: Option<String>,
}
impl StreamingReader {
@@ -101,12 +107,16 @@ impl StreamingReader {
carry_start: 0,
decoded_end: 0,
eof: false,
+ error: None,
}
}
/// 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 let Some(e) = &self.error {
+ return Err(Error::msg(e.clone()));
+ }
if offset < self.carry_start {
return Err(Error::msg(format!(
"streaming reader received non-monotonic read: offset {offset} precedes retained window start {}",
@@ -129,7 +139,10 @@ impl StreamingReader {
self.carry_start = drop_to;
}
}
- Some(Err(e)) => return Err(Error::msg(e)),
+ Some(Err(e)) => {
+ self.error = Some(e.clone());
+ return Err(Error::msg(e));
+ }
None => self.eof = true,
}
}
@@ -455,6 +468,47 @@ mod tests {
assert!(result.is_err());
}
+ #[tokio::test]
+ async fn test_decode_error_is_latched_across_reads() {
+ // Once a decode error is delivered, every subsequent read must keep
+ // returning it. The producer thread exits after sending the error, so a
+ // naive re-read would see the closed channel as a clean EOF and report the
+ // partially decoded length as the stream total - callers that retry reads
+ // (the sources' get_chunk retry loops) would then record a truncated part
+ // as complete: silent data loss.
+ let temp_dir = TempDir::new().unwrap();
+ let gzip_file = temp_dir.path().join("corrupt.gz");
+ // Large content so plenty of blocks decode successfully before the
+ // truncation point - the dangerous shape, since decoded_end is well past
+ // zero when the error arrives.
+ create_test_gzip_file(&"line\n".repeat(100_000), &gzip_file).unwrap();
+ let full = std::fs::read(&gzip_file).unwrap();
+ std::fs::write(&gzip_file, &full[..full.len() - 5]).unwrap();
+
+ let mut reader = PlainGzipExtractor.open_reader(gzip_file);
+
+ // Drive forward until the decode error surfaces (some reads succeed first).
+ let mut offset = 0u64;
+ while let Ok(chunk) = reader.read_at(offset, 8192).await {
+ assert!(
+ chunk.total.is_none(),
+ "truncated stream must never report a total"
+ );
+ assert!(!chunk.bytes.is_empty(), "no progress and no error");
+ offset += chunk.bytes.len() as u64;
+ }
+
+ // The error must be sticky: re-reads (at the same or an earlier retained
+ // offset) return the error again, never a clean EOF with a bogus total.
+ for _ in 0..2 {
+ let retry = reader.read_at(offset, 8192).await;
+ assert!(
+ retry.is_err(),
+ "retried read after a decode error must keep erroring, not report EOF"
+ );
+ }
+ }
+
#[tokio::test]
async fn test_zip_gzip_json_extractor_single_file() -> Result<()> {
let temp_dir = TempDir::new()?;
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 c5d6628199bd..2ebd9535fdf4 100644
--- a/rust/batch-import-worker/src/source/date_range_export.rs
+++ b/rust/batch-import-worker/src/source/date_range_export.rs
@@ -466,6 +466,22 @@ impl DateRangeExportSource {
key
);
+ // A 200 with a zero-byte body is an export interval with no data (some
+ // export APIs return this instead of a 404). It is not a decodable gzip
+ // stream, so treat it as an empty part - mirroring the 404 branch above
+ // and s3_gzip's zero-byte handling - rather than handing the decoder an
+ // empty file it would reject as "unexpected end of file".
+ if total_bytes == 0 {
+ info!("No data available for key: {} (empty response body)", key);
+ if let Err(e) = tokio::fs::remove_file(&raw_file_path).await {
+ warn!(
+ "Failed to remove empty raw file {}: {e}",
+ raw_file_path.display()
+ );
+ }
+ return Ok(PreparedPart::empty());
+ }
+
// Keep the `.raw` file and decompress on demand as the job reads forward.
let reader = self.extractor.open_reader(raw_file_path.clone());
@@ -681,6 +697,103 @@ mod tests {
.unwrap()
}
+ /// A source decoding real gzip (the production PlainGzip extractor), for tests
+ /// that exercise decode failures and empty bodies end to end.
+ fn create_gzip_source(base_url: String, staging_dir: PathBuf) -> 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,
+ crate::extractor::ExtractorType::PlainGzip.create_extractor(),
+ staging_dir,
+ )
+ .with_auth(AuthConfig::None)
+ .with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string())
+ .with_headers(HashMap::new())
+ .build()
+ .unwrap()
+ }
+
+ #[tokio::test]
+ async fn test_corrupt_gzip_errors_instead_of_silently_truncating() {
+ // A gzip that decodes some blocks then fails mid-stream. get_chunk's retry
+ // loop must surface the decode error - not have a retried read observe the
+ // dead producer's closed channel as a clean EOF, record the partial decode
+ // length as the part's total size, and let the job commit a truncated part
+ // as complete (silent data loss).
+ let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ std::io::Write::write_all(&mut gz, "line\n".repeat(100_000).as_bytes()).unwrap();
+ let mut body = gz.finish().unwrap();
+ body.truncate(body.len() - 5);
+
+ let server = MockServer::start();
+ let _mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(body.clone());
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = create_gzip_source(server.url("/export"), staging.path().to_path_buf());
+ source.prepare_for_job().await.unwrap();
+ let key = source.keys().await.unwrap().remove(0);
+ source.prepare_key(&key).await.unwrap();
+
+ // Read forward exactly like the job's chunker until the source reports
+ // either an error (correct) or end-of-part (must not happen).
+ let mut offset = 0u64;
+ let outcome = loop {
+ match source.get_chunk(&key, offset, 64 * 1024).await {
+ Ok(chunk) if chunk.is_empty() => break Ok(()),
+ Ok(chunk) => offset += chunk.len() as u64,
+ Err(e) => break Err(e),
+ }
+ };
+
+ assert!(
+ outcome.is_err(),
+ "mid-stream decode failure must error the read, not end the part early"
+ );
+ assert_eq!(
+ source.size(&key).await.unwrap(),
+ None,
+ "a truncated decode must never be recorded as the part's total size"
+ );
+ }
+
+ #[tokio::test]
+ async fn test_empty_200_body_is_an_empty_part_by_design() {
+ // A 200 with a zero-byte body (an export day with no events, without gzip
+ // framing) must become an empty part with its size known immediately after
+ // prepare - mirroring the 404 branch and s3_gzip's zero-byte handling - not
+ // a streaming part whose first read hits "unexpected end of file".
+ let server = MockServer::start();
+ let _mock = server.mock(|when, then| {
+ when.method(httpmock::Method::GET).path("/export");
+ then.status(200).body(Vec::<u8>::new());
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = create_gzip_source(server.url("/export"), staging.path().to_path_buf());
+ source.prepare_for_job().await.unwrap();
+ let key = source.keys().await.unwrap().remove(0);
+ source.prepare_key(&key).await.unwrap();
+
+ assert_eq!(
+ source.size(&key).await.unwrap(),
+ Some(0),
+ "empty body must prepare as an empty part with a known size"
+ );
+ assert!(source.get_chunk(&key, 0, 1024).await.unwrap().is_empty());
+ assert_eq!(
+ count_raw_files(staging.path()),
+ 0,
+ "the zero-byte .raw must not be kept"
+ );
+ }
+
#[tokio::test]
async fn test_interval_generation() {
let server = MockServer::start();