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): complete empty parts instead of pausing on no-data (#68410)

Eli Reismanc3539b1e6f72
diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rs
index 11f20176d00a..866243d25bda 100644
--- a/rust/batch-import-worker/src/job/mod.rs
+++ b/rust/batch-import-worker/src/job/mod.rs
@@ -113,6 +113,17 @@ async fn reset_backoff_after_success(
model.reset_backoff_in_db(&context.db).await
}
+/// Mirror a part's discovered total size into the model state, which is what
+/// gets persisted to the DB on the next part commit.
+async fn mirror_part_total(model: &Mutex<JobModel>, key: &str, total: u64) {
+ 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(total);
+ }
+ }
+}
+
/// 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
@@ -147,15 +158,7 @@ pub(crate) async fn select_and_fetch_next_chunk(
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);
- }
- }
- }
+ mirror_part_total(model, &key, actual_size).await;
// Streaming sources only learn their size on the read that observes
// end-of-stream, which is usually also the read that consumed the last
@@ -198,13 +201,56 @@ pub(crate) async fn select_and_fetch_next_chunk(
let chunk_bytes = next_chunk.len();
- // An empty chunk before the known end of the part means the source has nothing
- // more to give at this offset (e.g. a stream already read to EOF). No further
- // iteration can make progress, so fail rather than loop.
+ // An empty chunk before the part looks finished means the source hit
+ // end-of-stream at or before this offset. For streaming sources the size is
+ // only discoverable on the read that observes EOF - which for an empty part
+ // (a day with no events: an empty 200 body, a gzip of nothing, a zip with no
+ // data members) or a resume at a not-yet-persisted EOF is this very read. So
+ // re-consult the size now: if the source's own view confirms everything was
+ // consumed, the part is complete. Anything else (a ranged source serving
+ // empty bodies mid-part, a stream that shrank below the recorded total) can
+ // never make progress, so fail rather than loop.
if chunk_bytes == 0 && !is_last_chunk {
- return Err(Error::msg(format!(
- "Source returned no data for part {} at offset {} before the end of the part",
- next_part.key, next_part.current_offset
+ let refreshed_size = source.size(&key).await?;
+ let confirmed_complete = refreshed_size.is_some_and(|actual| {
+ let total_consistent = next_part.total_size.is_none_or(|t| t == actual);
+ total_consistent && next_part.current_offset >= actual
+ });
+
+ if !confirmed_complete {
+ return Err(Error::msg(format!(
+ "Source returned no data for part {} at offset {} before the end of the part",
+ next_part.key, next_part.current_offset
+ )));
+ }
+
+ let actual_size = refreshed_size.expect("confirmed_complete implies the size is known");
+ if next_part.current_offset > actual_size {
+ // A resumed offset past the stream's end: the export shrank between
+ // downloads. Everything the source can serve was already consumed,
+ // so completing is the only non-stranding option - but it deserves
+ // a loud trace, since the tail of the previous download's data may
+ // not exist in this download at all.
+ warn!(
+ job_id = %job_id,
+ "Part {} resumed at offset {} past the stream end {}; marking complete",
+ key, next_part.current_offset, actual_size
+ );
+ }
+ next_part.total_size = Some(actual_size);
+ mirror_part_total(model, &key, actual_size).await;
+ info!(
+ job_id = %job_id,
+ "Part {} (size {}) has no data left to read at offset {}, marking complete",
+ key, actual_size, next_part.current_offset
+ );
+ return Ok(Some((
+ key,
+ Parsed {
+ consumed: 0,
+ data: vec![],
+ },
+ false,
)));
}
@@ -1241,15 +1287,20 @@ mod tests {
use std::path::{Path, PathBuf};
use tempfile::TempDir;
- fn gzip_bytes(data: &[u8]) -> Vec<u8> {
+ pub(super) 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 {
+ /// all served the same body by the mock, decoded with `extractor`.
+ pub(super) fn build_source_with_extractor(
+ base_url: String,
+ staging: &Path,
+ hours: u32,
+ extractor: ExtractorType,
+ ) -> 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(
@@ -1257,7 +1308,7 @@ mod tests {
start,
end,
3600,
- ExtractorType::PlainGzip.create_extractor(),
+ extractor.create_extractor(),
staging.to_path_buf(),
)
.with_auth(AuthConfig::None)
@@ -1267,6 +1318,10 @@ mod tests {
.unwrap()
}
+ fn build_source(base_url: String, staging: &Path, hours: u32) -> DateRangeExportSource {
+ build_source_with_extractor(base_url, staging, hours, ExtractorType::PlainGzip)
+ }
+
/// 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
@@ -1285,7 +1340,7 @@ mod tests {
/// 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> {
+ pub(super) 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)
@@ -1319,7 +1374,34 @@ mod tests {
count
}
- fn dummy_model(state: JobState) -> JobModel {
+ /// Drive `select_and_fetch_next_chunk` until it reports all parts done,
+ /// up to `max_iterations`. Returns whether it completed within budget.
+ pub(super) async fn drive_loop_to_completion(
+ state: &Mutex<JobState>,
+ model: &Mutex<JobModel>,
+ source: &dyn DataSource,
+ transform: &Arc<ParserFn>,
+ chunk_size: usize,
+ max_iterations: usize,
+ ) -> Result<bool, Error> {
+ for _ in 0..max_iterations {
+ let next = select_and_fetch_next_chunk(
+ state,
+ model,
+ source,
+ transform,
+ chunk_size,
+ Uuid::now_v7(),
+ )
+ .await?;
+ if next.is_none() {
+ return Ok(true);
+ }
+ }
+ Ok(false)
+ }
+
+ pub(super) fn dummy_model(state: JobState) -> JobModel {
JobModel {
id: Uuid::now_v7(),
team_id: 1,
@@ -1353,7 +1435,7 @@ mod tests {
}
}
- fn job_state(keys: &[String]) -> JobState {
+ pub(super) fn job_state(keys: &[String]) -> JobState {
JobState {
parts: keys
.iter()
@@ -1713,4 +1795,233 @@ mod tests {
);
}
}
+
+ /// Streaming sources discover a part's decompressed size only on the read
+ /// that observes end-of-stream. When that stream turns out to be empty (or
+ /// already fully consumed at the resume offset), the first read returns an
+ /// empty chunk before the job has ever seen a size - which must complete the
+ /// part, not pause the job as "source returned no data". These tests pin
+ /// every empty-stream shape plus the error path for genuinely broken sources.
+ mod empty_part_completion_tests {
+ use super::staging_cleanup_invariant_tests::{
+ build_source_with_extractor, drive_loop_to_completion, dummy_model, gzip_bytes,
+ job_state, newline_consumed_transform,
+ };
+ use super::*;
+ use crate::extractor::ExtractorType;
+ use std::io::Write;
+ use tempfile::TempDir;
+ use zip::{write::SimpleFileOptions, ZipWriter};
+
+ /// A zip archive with no `.json.gz` members - the Amplitude-shaped
+ /// equivalent of an empty export (decompresses to zero bytes).
+ fn zip_without_json_members() -> Vec<u8> {
+ let mut zip = ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ zip.start_file("readme.txt", SimpleFileOptions::default())
+ .unwrap();
+ zip.write_all(b"no data for this day").unwrap();
+ zip.finish().unwrap().into_inner()
+ }
+
+ /// Empty exports come in several shapes, all decompressing to zero
+ /// bytes: a raw empty 200 body (Mixpanel day with no events), a valid
+ /// gzip of empty content, and a zip with no data members. Each must
+ /// complete the part exactly like the pre-streaming code did.
+ #[tokio::test]
+ async fn test_empty_export_completes_part() {
+ let cases: [(&str, Vec<u8>, ExtractorType); 3] = [
+ ("empty 200 body", Vec::new(), ExtractorType::PlainGzip),
+ (
+ "gzip of empty content",
+ gzip_bytes(b""),
+ ExtractorType::PlainGzip,
+ ),
+ (
+ "zip with no json members",
+ zip_without_json_members(),
+ ExtractorType::ZipGzipJson,
+ ),
+ ];
+
+ for (name, body, extractor) in cases {
+ let server = MockServer::start();
+ let _mock = server.mock(|when, then| {
+ when.method(Method::GET).path("/export");
+ then.status(200).body(body);
+ });
+
+ let staging = TempDir::new().unwrap();
+ let source = build_source_with_extractor(
+ server.url("/export"),
+ staging.path(),
+ 1,
+ extractor,
+ );
+ 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();
+
+ let completed =
+ drive_loop_to_completion(&state, &model, &source, &transform, 1024, 10)
+ .await
+ .unwrap_or_else(|e| panic!("case '{name}' errored: {e:#}"));
+
+ assert!(completed, "case '{name}' did not complete the empty part");
+ let state = state.lock().await;
+ assert_eq!(state.parts[0].current_offset, 0, "case '{name}'");
+ assert_eq!(
+ state.parts[0].total_size,
+ Some(0),
+ "case '{name}' must record the discovered size so the DB state is terminal"
+ );
+ // The mirrored model state is what gets persisted on commit.
+ let model = model.lock().await;
+ assert_eq!(
+ model.state.as_ref().unwrap().parts[0].total_size,
+ Some(0),
+ "case '{name}' must mirror the size into the model"
+ );
+ }
+ }
+
+ /// A job can crash after committing the offset of a part's final chunk
+ /// but before the next iteration discovered (and persisted) the size.
+ /// On resume the re-downloaded stream EOFs exactly at the stored offset:
+ /// the first read is empty with total_size still None, and the part must
+ /// complete. If the re-downloaded data is instead *smaller* than the
+ /// stored offset (non-byte-stable export), everything available was
+ /// already consumed, so the part must also complete rather than strand
+ /// the job on an unresolvable error.
+ #[tokio::test]
+ async fn test_resume_at_or_past_eof_with_unknown_total_completes() {
+ let mut body = String::new();
+ for i in 0..200 {
+ body.push_str(&format!("{{\"event\":\"e{i}\"}}\n"));
+ }
+ let total_size = body.len() as u64;
+
+ for (name, resume_offset) in [
+ ("resume exactly at EOF", total_size),
+ ("resume past a shrunk export", total_size + 1000),
+ ] {
+ let server = MockServer::start();
+ 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_with_extractor(
+ server.url("/export"),
+ staging.path(),
+ 1,
+ ExtractorType::PlainGzip,
+ );
+ source.prepare_for_job().await.unwrap();
+ let keys = source.keys().await.unwrap();
+
+ let resumed = JobState {
+ parts: vec![PartState {
+ key: keys[0].clone(),
+ current_offset: resume_offset,
+ total_size: None,
+ }],
+ };
+ let state = Mutex::new(resumed.clone());
+ let model = Mutex::new(dummy_model(resumed));
+ let transform = newline_consumed_transform();
+
+ let completed =
+ drive_loop_to_completion(&state, &model, &source, &transform, 1024, 10)
+ .await
+ .unwrap_or_else(|e| panic!("case '{name}' errored: {e:#}"));
+
+ assert!(completed, "case '{name}' did not complete");
+ let state = state.lock().await;
+ assert_eq!(
+ state.parts[0].total_size,
+ Some(total_size),
+ "case '{name}' must record the size discovered on resume"
+ );
+ assert_eq!(
+ state.parts[0].current_offset, resume_offset,
+ "case '{name}' must not rewind or advance the stored offset"
+ );
+ }
+ }
+
+ /// A source that reports a fixed size but serves empty chunks - the
+ /// "genuinely broken source" shape (e.g. a ranged HTTP server returning
+ /// empty 200s mid-part, or a stream that shrank to a size that no longer
+ /// matches the part's recorded total). These must still pause the job
+ /// loudly, proving the empty-part completion path did not neuter the
+ /// no-progress guard.
+ struct EmptyChunkSource {
+ reported_size: Option<u64>,
+ }
+
+ #[async_trait]
+ impl DataSource for EmptyChunkSource {
+ async fn keys(&self) -> Result<Vec<String>, Error> {
+ Ok(vec!["part".to_string()])
+ }
+
+ async fn size(&self, _key: &str) -> Result<Option<u64>, Error> {
+ Ok(self.reported_size)
+ }
+
+ async fn get_chunk(
+ &self,
+ _key: &str,
+ _offset: u64,
+ _size: u64,
+ ) -> Result<Vec<u8>, Error> {
+ Ok(Vec::new())
+ }
+ }
+
+ #[tokio::test]
+ async fn test_empty_chunk_before_end_of_part_still_errors() {
+ // (case, part state total, part offset, source-reported size)
+ let cases: [(&str, Option<u64>, u64, Option<u64>); 3] = [
+ // Ranged source serving empty bodies mid-part.
+ ("empty chunk below known size", Some(1000), 400, Some(1000)),
+ // Stream ended early relative to what the source itself reports.
+ ("source size past offset", None, 400, Some(1000)),
+ // Stored total disagrees with what the source now reports.
+ (
+ "shrunk source with recorded total",
+ Some(1000),
+ 400,
+ Some(400),
+ ),
+ ];
+
+ for (name, part_total, offset, reported_size) in cases {
+ let source = EmptyChunkSource { reported_size };
+ let part_state = JobState {
+ parts: vec![PartState {
+ key: "part".to_string(),
+ current_offset: offset,
+ total_size: part_total,
+ }],
+ };
+ let state = Mutex::new(part_state.clone());
+ let model = Mutex::new(dummy_model(part_state));
+ let transform = newline_consumed_transform();
+
+ let result =
+ drive_loop_to_completion(&state, &model, &source, &transform, 1024, 5).await;
+
+ let err = result.unwrap_err();
+ assert!(
+ format!("{err:#}").contains("returned no data"),
+ "case '{name}' expected the no-data error, got: {err:#}"
+ );
+ }
+ }
+ }
}