: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(batch-import-worker): stop infinite 1-byte crawl when part is consumed at EOF (#68356)
Eli Reismanf1589a348101
diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rsindex 62d46c7416e8..11f20176d00a 100644--- a/rust/batch-import-worker/src/job/mod.rs+++ b/rust/batch-import-worker/src/job/mod.rs@@ -157,15 +157,20 @@ pub(crate) async fn select_and_fetch_next_chunk(}}- if actual_size == 0 {+ // Streaming sources only learn their size on the read that observes+ // end-of-stream, which is usually also the read that consumed the last+ // bytes - so by the time the size is known here, the offset may already+ // be at (or past) the end. Re-check completion now: fetching again would+ // return an empty chunk, and advancing on one would push the offset past+ // the total, making the part permanently un-finishable.+ if next_part.is_done() {info!(job_id = %job_id,- "No data available for this key: {} try to get the next chunk",- key+ "Part {} (size {}) was fully consumed when its size was discovered, moving on",+ key, actual_size);- next_part.current_offset = actual_size;return Ok(Some((- key.clone(),+ key,Parsed {consumed: 0,data: vec![],@@ -183,13 +188,26 @@ pub(crate) async fn select_and_fetch_next_chunk(.await.context(format!("Fetching part chunk {next_part:?}"))?;+ // `>=` because sources clamp reads to the end of the part, so the final chunk+ // ends exactly at total_size - a strict `>` can never be true and would leave+ // the unconsumed-bytes check below unreachable.let is_last_chunk = match next_part.total_size {- Some(total_size) => next_part.current_offset + next_chunk.len() as u64 > total_size,+ Some(total_size) => next_part.current_offset + next_chunk.len() as u64 >= total_size,None => false,};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.+ 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+ )));+ }+info!(job_id = %job_id, "Fetched part chunk {:?}", next_part);let m_tf = transform.clone();let key_for_error = key.clone();@@ -210,6 +228,16 @@ pub(crate) async fn select_and_fetch_next_chunk(next_part, parsed.consumed);+ // Consuming more bytes than were read is always a parser bug: advancing the+ // offset past real data would silently skip it, or overshoot the end of the+ // part and make it permanently un-finishable.+ if parsed.consumed > chunk_bytes {+ return Err(Error::msg(format!(+ "Parser consumed {} bytes but only {} were read from part {} at offset {}",+ parsed.consumed, chunk_bytes, next_part.key, next_part.current_offset+ )));+ }+// 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!(@@ -1392,6 +1420,197 @@ mod tests {);}+ #[tokio::test]+ async fn test_part_fully_consumed_at_eof_read_completes_without_offset_overshoot() {+ // Streaming sources only learn a part's total size on the read that+ // observes EOF. When that same read fully consumes the remaining bytes,+ // the offset lands exactly at the total while the job still has+ // total_size = None. The next loop iteration must then recognize the+ // part as done — not fetch an empty chunk, "consume" a phantom byte,+ // and push the offset past the total (which makes is_done() unreachable+ // and the job crawl one byte per iteration forever).+ let server = MockServer::start();+ 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;+ 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)));+ // Real newline parser so `consumed` behaves exactly as in production.+ let transform = newline_consumed_transform();++ // Generous iteration budget: a healthy run needs ~(total/chunk + 2)+ // iterations. Far more than that means the loop is stuck.+ let chunk_size = 1024usize;+ let max_iterations = (total_size as usize / chunk_size) + 10;+ let mut completed = false;+ for _ in 0..max_iterations {+ let next = select_and_fetch_next_chunk(+ &state,+ &model,+ &source,+ &transform,+ chunk_size,+ Uuid::now_v7(),+ )+ .await+ .unwrap();++ let offset = state.lock().await.parts[0].current_offset;+ assert!(+ offset <= total_size,+ "part offset {offset} overshot total size {total_size}: the job would crawl forever"+ );++ if next.is_none() {+ completed = true;+ break;+ }+ }++ assert!(+ completed,+ "job did not finish the part within {max_iterations} iterations (offset {} / total {total_size})",+ state.lock().await.parts[0].current_offset+ );+ }++ #[tokio::test]+ async fn test_part_with_trailing_blank_lines_completes() {+ // Data whose final bytes are blank lines must still complete: the blanks+ // are only seen on the EOF read, after which the streaming source has+ // freed the part and can never serve those bytes again.+ let server = MockServer::start();+ let mut body = String::new();+ for i in 0..200 {+ body.push_str(&format!("{{\"event\":\"e{i}\"}}\n"));+ }+ body.push('\n');+ let total_size = body.len() as u64;+ 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();++ let state = Mutex::new(job_state(&keys));+ let model = Mutex::new(dummy_model(job_state(&keys)));+ let transform = newline_consumed_transform();++ let chunk_size = 1024usize;+ let max_iterations = (total_size as usize / chunk_size) + 10;+ let mut completed = false;+ for _ in 0..max_iterations {+ let next = select_and_fetch_next_chunk(+ &state,+ &model,+ &source,+ &transform,+ chunk_size,+ Uuid::now_v7(),+ )+ .await+ .unwrap();+ if next.is_none() {+ completed = true;+ break;+ }+ }++ assert!(completed, "trailing blank lines must not stall the part");+ assert_eq!(state.lock().await.parts[0].current_offset, total_size);+ }++ #[tokio::test]+ async fn test_poisoned_part_with_overshot_offset_self_heals() {+ // A job written by a worker version with the overshoot bug has a part+ // whose stored offset exceeds its total size. On resume that part must+ // be treated as done (its real bytes were all consumed before the+ // phantom crawl began) so the job can move on to the remaining parts.+ let server = MockServer::start();+ let mut body = String::new();+ for i in 0..200 {+ 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(), 2);+ source.prepare_for_job().await.unwrap();+ let keys = source.keys().await.unwrap();+ assert_eq!(keys.len(), 2);++ // Part 1 poisoned as in production: offset way past its recorded total.+ let poisoned = JobState {+ parts: vec![+ PartState {+ key: keys[0].clone(),+ current_offset: 25_328_072,+ total_size: Some(24_441_157),+ },+ PartState {+ key: keys[1].clone(),+ current_offset: 0,+ total_size: None,+ },+ ],+ };+ let state = Mutex::new(poisoned.clone());+ let model = Mutex::new(dummy_model(poisoned));+ let transform = newline_consumed_transform();++ let mut completed = false;+ for _ in 0..20 {+ let next = select_and_fetch_next_chunk(+ &state,+ &model,+ &source,+ &transform,+ 1024,+ Uuid::now_v7(),+ )+ .await+ .unwrap();+ if next.is_none() {+ completed = true;+ break;+ }+ }++ assert!(+ completed,+ "job with an overshot part must skip it and finish the rest"+ );+ let state = state.lock().await;+ assert_eq!(+ state.parts[0].current_offset, 25_328_072,+ "poisoned part must be skipped untouched, not re-read"+ );+ assert_eq!(+ state.parts[1].total_size,+ Some(state.parts[1].current_offset)+ );+ }+#[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.diff --git a/rust/batch-import-worker/src/job/model.rs b/rust/batch-import-worker/src/job/model.rsindex dbb4649302e9..000d7c734f59 100644--- a/rust/batch-import-worker/src/job/model.rs+++ b/rust/batch-import-worker/src/job/model.rs@@ -68,7 +68,10 @@ pub struct PartState {impl PartState {pub fn is_done(&self) -> bool {match self.total_size {- Some(size) => self.current_offset == size,+ // `>=` so a part whose stored offset overshot its total (written by a+ // worker version that kept advancing past the end) still completes on+ // resume instead of being permanently un-finishable.+ Some(size) => self.current_offset >= size,None => false,}}@@ -507,6 +510,28 @@ mod tests {}}+ #[test]+ fn test_part_is_done() {+ // (offset, total, expected). Overshot offsets (recorded by worker versions+ // that advanced past the end of a part) must still count as done, or the+ // part can never complete on resume.+ let cases: [(u64, Option<u64>, bool); 5] = [+ (0, None, false),+ (99, Some(100), false),+ (100, Some(100), true),+ (101, Some(100), true),+ (0, Some(0), true),+ ];+ for (offset, total, expected) in cases {+ let part = PartState {+ key: "k".to_string(),+ current_offset: offset,+ total_size: total,+ };+ assert_eq!(part.is_done(), expected, "offset {offset}, total {total:?}");+ }+ }+#[test]fn test_advance_part_offset_increments_and_returns_new_offset() {let mut state = make_job_state(&[("a", 100), ("b", 0)]);diff --git a/rust/batch-import-worker/src/parse/format.rs b/rust/batch-import-worker/src/parse/format.rsindex 1ae0bbad7c92..f2bd8cf81265 100644--- a/rust/batch-import-worker/src/parse/format.rs+++ b/rust/batch-import-worker/src/parse/format.rs@@ -140,6 +140,16 @@ pub fn newline_delim<T: Send>(inner: impl Fn(&str) -> Result<T, Error> + Sync,) -> impl Fn(Vec<u8>) -> Result<Parsed<Vec<T>>, Error> {move |data: Vec<u8>| {+ // A zero-length chunk (e.g. a read at or past the end of a part) has nothing+ // to consume. Reporting any consumed bytes for it would advance the caller's+ // offset past real data, so it could never converge on the part's end.+ if data.is_empty() {+ return Ok(Parsed {+ data: Vec::new(),+ consumed: 0,+ });+ }+let mut cursor = 0;let mut last_consumed_byte = 0;@@ -170,8 +180,13 @@ pub fn newline_delim<T: Send>(// Sometimes we've split the file on a utf8 character boundary, and the last line is incomplete not just as// a line that can be fed to the inner parser, but as a utf8 string in general. If that's the case, just set// the remainder to be empty, and we can handle it in the next chunk.- let remainder = std::str::from_utf8(&data[last_consumed_byte..]).unwrap_or("");- let remainder = inner(remainder);+ let remainder_str = std::str::from_utf8(&data[last_consumed_byte..]).ok();+ // A blank remainder (e.g. a chunk ending in "\n" or trailing blank lines at the+ // end of a part) has nothing to parse. When blank lines are skippable, count it+ // as consumed so the caller's offset can reach the end of the part - at the end+ // of a stream-decompressed part there is no next chunk to re-read it from.+ let remainder_is_blank = remainder_str.is_some_and(|r| r.trim().is_empty());+ let remainder = remainder_str.map(&inner);let mut output = Vec::with_capacity(lines.len());let intermediate: Vec<_> = lines@@ -198,11 +213,13 @@ pub fn newline_delim<T: Send>(// If we managed to parse the last line, add it too, but if we didn't, assume it's due to this chunk being partway through the file,// and carry on.- if let Ok(parsed) = remainder {+ if let Some(Ok(parsed)) = remainder {output.push(parsed);// -1 because at this point the cursor is pointing at the end of the data,// and we want to point at the last byte we actually consumedlast_validly_consumed_byte = cursor - 1;+ } else if skip_blank_lines && remainder_is_blank {+ last_validly_consumed_byte = cursor - 1;}let parsed = Parsed {@@ -438,6 +455,57 @@ mod tests {assert_eq!(parsed.consumed, 27);}+ #[test]+ fn test_newline_delim_empty_input_consumes_nothing() {+ // An empty chunk (e.g. a streaming source read past EOF) must report zero+ // bytes consumed. Reporting consumed > 0 for empty input makes the job's+ // part offset overshoot the part's total size and the job crawls forever.+ let parsed = json_nd::<TestData>(true)(Vec::new()).unwrap();+ assert!(parsed.data.is_empty());+ assert_eq!(+ parsed.consumed, 0,+ "empty input must consume 0 bytes, got {}",+ parsed.consumed+ );+ }++ #[test]+ fn test_newline_delim_blank_trailing_remainder() {+ // A part's final chunk can end in blank content ("\n", trailing blank+ // lines). With skip_blank_lines the blanks must count as consumed so the+ // offset can reach the end of the part - at the end of a stream-decompressed+ // part there is no next chunk to re-read them from.+ let line = br#"{"id": 1, "name": "test1"}"#;+ for tail in [b"\n\n".as_slice(), b"\n\n\n", b"\n \n"] {+ let mut data = line.to_vec();+ data.extend_from_slice(tail);+ let len = data.len();++ let parsed = json_nd::<TestData>(true)(data).unwrap();+ assert_eq!(parsed.data.len(), 1, "tail {tail:?}");+ assert_eq!(+ parsed.consumed, len,+ "blank tail {tail:?} must be fully consumed"+ );+ }++ // Without skip_blank_lines a blank line is still an error, preserving the+ // "blank lines in input should fail the inner parser" contract.+ let mut data = line.to_vec();+ data.extend_from_slice(b"\n\n");+ assert!(json_nd::<TestData>(false)(data).is_err());++ // An invalid-utf8 tail is not "blank" - it must be left unconsumed for the+ // next chunk, exactly as before.+ let mut data = line.to_vec();+ data.extend_from_slice(b"\n{\"id\": 2, \"name\": \"\xf0\x9f");+ let len = data.len();+ let parsed = json_nd::<TestData>(true)(data).unwrap();+ assert_eq!(parsed.data.len(), 1);+ assert_eq!(parsed.consumed, line.len() + 1);+ assert!(parsed.consumed < len);+ }+#[test]fn test_json_parse_error_has_user_friendly_message() {use crate::error::get_user_message;