: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): detect still-compressed import data with disambiguated errors (#68741)
Eli Reisman559fd7989ee4
diff --git a/rust/batch-import-worker/src/extractor/mod.rs b/rust/batch-import-worker/src/extractor/mod.rsindex 0cd31c2f73dc..2ac156cdca31 100644--- a/rust/batch-import-worker/src/extractor/mod.rs+++ b/rust/batch-import-worker/src/extractor/mod.rs@@ -2,10 +2,61 @@ use anyhow::Error;use flate2::read::GzDecoder;use serde::{Deserialize, Serialize};use std::panic::AssertUnwindSafe;-use std::{io::Read, path::PathBuf, sync::Arc};+use std::{+ io::Read,+ path::{Path, PathBuf},+ sync::Arc,+};use tokio::sync::mpsc;use zip::ZipArchive;+/// Magic-byte prefixes of the compression formats we might be handed by mistake.+/// Each entry maps a constant header prefix to the format name.+///+/// A newline-delimited JSON import only ever expects plaintext JSON, whose values+/// begin with `{ [ " -`, a digit, `t`/`f`/`n`, or whitespace. None of the first+/// bytes below (`0x1f 0x28 0x50 0x42 0xfd 0x78`) collide with those, so a match at+/// the *start of a part* is an unambiguous "still compressed" signal rather than a+/// coincidence - see [`detect_compression_magic`].+const COMPRESSION_MAGICS: &[(&[u8], &str)] = &[+ (&[0x1f, 0x8b], "gzip"),+ (&[0x28, 0xb5, 0x2f, 0xfd], "zstd"),+ (&[0x50, 0x4b, 0x03, 0x04], "zip"),+ (&[0x50, 0x4b, 0x05, 0x06], "zip"), // empty archive+ (&[0x50, 0x4b, 0x07, 0x08], "zip"), // spanned archive+ (&[0x42, 0x5a, 0x68], "bzip2"),+ (&[0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00], "xz"),+ // zlib streams start with CM/CINFO byte 0x78 followed by an FLG byte chosen so+ // that (CMF*256 + FLG) % 31 == 0. These four FLG values cover the compression+ // levels every common zlib encoder emits.+ (&[0x78, 0x01], "zlib"),+ (&[0x78, 0x5e], "zlib"),+ (&[0x78, 0x9c], "zlib"),+ (&[0x78, 0xda], "zlib"),+];++/// Return the name of the compression format whose magic bytes prefix `data`, or+/// `None` if `data` does not start with a recognized compression header. Data+/// shorter than a candidate prefix simply does not match it.+pub(crate) fn detect_compression_magic(data: &[u8]) -> Option<&'static str> {+ COMPRESSION_MAGICS+ .iter()+ .find(|(magic, _)| data.starts_with(magic))+ .map(|(_, name)| *name)+}++/// Peek the first bytes of `path` and, if they are a recognized *non-gzip*+/// compression header, return that format's name. Used to enrich a gzip decode+/// failure: a real gzip that fails to decode is genuine corruption, but a zstd /+/// zip / xz / ... file reaching the gzip extractor is a compression-setting+/// mismatch worth naming. Best-effort - any IO error yields `None`.+fn peek_non_gzip_compression(path: &Path) -> Option<&'static str> {+ let mut buf = [0u8; 8];+ let mut file = std::fs::File::open(path).ok()?;+ let n = file.read(&mut buf).ok()?;+ detect_compression_magic(&buf[..n]).filter(|&fmt| fmt != "gzip")+}+#[derive(Debug, Clone, Serialize, Deserialize, Default)]#[serde(rename_all = "snake_case")]pub enum ExtractorType {@@ -211,7 +262,22 @@ fn run_plain_gzip_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {}}Err(e) => {- let _unused = tx.blocking_send(Err(format!("Failed to decompress gzip data: {e}")));+ // A decode failure before any output is usually a wrong-format file+ // (e.g. a zstd/zip/xz object reaching the gzip extractor), not a+ // corrupt gzip. Sniff the raw header and, if it is another known+ // format, name it so the pause message is actionable.+ let msg = match (!produced_any)+ .then(|| peek_non_gzip_compression(&raw_file_path))+ .flatten()+ {+ Some(fmt) => format!(+ "Failed to decompress gzip data: {e}. The file appears to be \+ {fmt}-compressed, but this import expects gzip - check the source's \+ compression setting."+ ),+ None => format!("Failed to decompress gzip data: {e}"),+ };+ let _unused = tx.blocking_send(Err(msg));return;}}@@ -413,6 +479,96 @@ mod tests {assert!(matches!(default_type, ExtractorType::PlainGzip));}+ #[test]+ fn test_detect_compression_magic_positive() {+ // Real headers emitted by each encoder must be recognized by name.+ let cases: [(&[u8], &str); 8] = [+ (&[0x1f, 0x8b, 0x08, 0x00], "gzip"),+ (&[0x28, 0xb5, 0x2f, 0xfd, 0x00], "zstd"),+ (b"PK\x03\x04rest", "zip"),+ (b"PK\x05\x06", "zip"),+ (b"BZh9blah", "bzip2"),+ (&[0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00, 0x00], "xz"),+ (&[0x78, 0x9c, 0xcb, 0x48], "zlib"),+ (&[0x78, 0xda, 0x01], "zlib"),+ ];+ for (bytes, expected) in cases {+ assert_eq!(+ detect_compression_magic(bytes),+ Some(expected),+ "bytes {bytes:02x?} should be detected as {expected}"+ );+ }+ }++ #[test]+ fn test_detect_compression_magic_negative() {+ // Plaintext JSONL and other non-magic inputs must never be flagged: this is+ // what keeps the offset-0 job-loop guard from ever tripping on real data.+ let cases: [&[u8]; 7] = [+ b"{\"event\":\"x\"}\n", // bare JSON object line+ b"[1,2,3]\n", // JSON array line+ &[0xef, 0xbb, 0xbf, b'{'], // UTF-8 BOM then JSON+ &[0x1f], // gzip first byte only - too short to match+ &[0x78], // zlib first byte only - too short to match+ &[0xff, 0xff, 0xff], // invalid-utf8 binary that is not a magic+ b"", // empty+ ];+ for bytes in cases {+ assert_eq!(+ detect_compression_magic(bytes),+ None,+ "bytes {bytes:02x?} must not be detected as compression"+ );+ }+ }++ #[tokio::test]+ async fn test_plain_gzip_producer_enriches_wrong_format_error() {+ // A zstd file reaching the gzip extractor is a compression-setting mismatch,+ // not corruption. The decode error must name the actual format so the pause+ // message is actionable, instead of a bare "failed to decompress" string.+ let temp_dir = TempDir::new().unwrap();+ let zstd_file = temp_dir.path().join("actually.zst");+ // A minimal zstd magic-led body is enough: GzDecoder rejects it at the header.+ std::fs::write(&zstd_file, [0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x01, 0x02, 0x03]).unwrap();++ let mut reader = PlainGzipExtractor.open_reader(zstd_file);+ let Err(err) = reader.read_at(0, 8192).await else {+ panic!("a zstd file must not decode as gzip");+ };+ let msg = format!("{err:#}");+ assert!(+ msg.contains("zstd"),+ "decode error should name the detected format, got: {msg}"+ );+ assert!(+ msg.contains("gzip"),+ "decode error should state the expected format, got: {msg}"+ );+ }++ #[tokio::test]+ async fn test_plain_gzip_producer_does_not_mislabel_corrupt_gzip() {+ // A genuinely corrupt gzip (valid header, truncated body) is corruption, not a+ // format mismatch - the error must stay generic and never claim another format.+ let temp_dir = TempDir::new().unwrap();+ let gzip_file = temp_dir.path().join("corrupt.gz");+ create_test_gzip_file(&"line\n".repeat(10000), &gzip_file).unwrap();+ let full = std::fs::read(&gzip_file).unwrap();+ std::fs::write(&gzip_file, &full[..20]).unwrap();++ let mut reader = PlainGzipExtractor.open_reader(gzip_file);+ let Err(err) = reader.read_at(0, 8192).await else {+ panic!("truncated gzip must error");+ };+ let msg = format!("{err:#}");+ assert!(+ !msg.contains("zstd") && !msg.contains("compression setting"),+ "corrupt gzip must not be mislabeled as a format mismatch, got: {msg}"+ );+ }+#[tokio::test]async fn test_plain_gzip_extractor_newline_normalization() -> Result<()> {// The extractor guarantees exactly one trailing newline on non-emptydiff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rsindex 866243d25bda..a35687c95035 100644--- a/rust/batch-import-worker/src/job/mod.rs+++ b/rust/batch-import-worker/src/job/mod.rs@@ -17,6 +17,7 @@ use crate::{extract_retry_after_from_error, get_user_message, is_rate_limited_error, is_timeout_error,is_transient_network_error, is_transient_server_error, UserError,},+ extractor::detect_compression_magic,job::{backoff::format_backoff_messages, config::SinkConfig},parse::{format::ParserFn, Parsed},source::DataSource,@@ -254,6 +255,28 @@ pub(crate) async fn select_and_fetch_next_chunk()));}+ // A part that still *begins* with a known compression magic can never be+ // parsed as newline-delimited JSON: the file is compressed a second time, or+ // the source/extractor's compression setting does not match the file. Only the+ // start of a part is decisive - mid-file chunks can coincidentally begin with+ // these bytes - so this is gated on offset 0. Fail fast with an actionable,+ // non-transient error (a UserError pauses the job) instead of letting the+ // parser emit a confusing "invalid utf-8" failure or crawl one byte at a time.+ if next_part.current_offset == 0 {+ if let Some(fmt) = detect_compression_magic(&next_chunk) {+ let internal = Error::msg(format!(+ "part {} begins with {fmt} magic bytes at offset 0 ({chunk_bytes} bytes read)",+ next_part.key+ ));+ return Err(internal.context(UserError::new(format!(+ "Part {} begins with {fmt}-compressed data where newline-delimited JSON was \+ expected - the file may be compressed twice, or the import's compression \+ setting doesn't match the file.",+ next_part.key+ ))));+ }+ }+info!(job_id = %job_id, "Fetched part chunk {:?}", next_part);let m_tf = transform.clone();let key_for_error = key.clone();@@ -1796,6 +1819,165 @@ mod tests {}}+ /// A part whose first bytes are a known compression magic is still compressed+ /// (double-compression, or a source/extractor whose compression setting does+ /// not match the file). The loop must fail fast at part offset 0 with an+ /// actionable, non-transient error - never crawl or emit a confusing utf-8+ /// parse failure. The guard sits in the shared loop, so one streaming source+ /// (post-decompression double-gzip) and one plain verbatim source (a gzip file+ /// on a non-decompressing source) together prove it covers every source shape.+ mod compression_magic_guard_tests {+ use super::staging_cleanup_invariant_tests::{+ build_source_with_extractor, dummy_model, gzip_bytes, job_state,+ newline_consumed_transform,+ };+ use super::*;+ use crate::extractor::ExtractorType;+ use crate::source::folder::FolderSource;+ use tempfile::TempDir;++ fn assert_non_transient(err: &Error) {+ 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_double_gzipped_part_detected_at_offset_zero() {+ // gzip(gzip(jsonl)): the extractor strips the outer gzip, so the+ // plaintext stream *starts* with the inner gzip magic. The guard must+ // catch it at offset 0 and pause with the double-compression message.+ let server = MockServer::start();+ let mut inner = String::new();+ for i in 0..50 {+ inner.push_str(&format!("{{\"event\":\"e{i}\"}}\n"));+ }+ let double = gzip_bytes(&gzip_bytes(inner.as_bytes()));+ let _mock = server.mock(|when, then| {+ when.method(Method::GET).path("/export");+ then.status(200).body(double);+ });++ 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 state = Mutex::new(job_state(&keys));+ let model = Mutex::new(dummy_model(job_state(&keys)));+ let transform = newline_consumed_transform();++ let err = select_and_fetch_next_chunk(+ &state,+ &model,+ &source,+ &transform,+ 1024,+ Uuid::now_v7(),+ )+ .await+ .expect_err("double-gzipped data must be rejected at offset 0");++ let user_msg = crate::error::get_user_message(&err);+ assert!(+ user_msg.contains("compressed twice") && user_msg.contains("gzip"),+ "unexpected user message: {user_msg}"+ );+ assert!(+ format!("{err:#}").contains("offset 0"),+ "internal chain should record the offset, got: {err:#}"+ );+ assert_non_transient(&err);+ // The guard fires before advancing, so nothing is consumed.+ assert_eq!(state.lock().await.parts[0].current_offset, 0);+ }++ #[tokio::test]+ async fn test_plain_source_serving_gzip_file_detected_at_offset_zero() {+ // The reverse misconfiguration: a gzipped file handed to a plain+ // (verbatim, non-decompressing) source. The raw gzip magic is the first+ // thing the loop reads, so the same offset-0 guard must catch it.+ let staging = TempDir::new().unwrap();+ let gz = gzip_bytes(b"{\"event\":\"x\"}\n");+ std::fs::write(staging.path().join("data.jsonl"), &gz).unwrap();++ let source = FolderSource::new(staging.path().to_str().unwrap().to_string())+ .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 err = select_and_fetch_next_chunk(+ &state,+ &model,+ &source,+ &transform,+ 1024,+ Uuid::now_v7(),+ )+ .await+ .expect_err("a gzip file on a plain source must be rejected at offset 0");++ let user_msg = crate::error::get_user_message(&err);+ assert!(+ user_msg.contains("compressed") && user_msg.contains("gzip"),+ "unexpected user message: {user_msg}"+ );+ assert_non_transient(&err);+ }++ #[tokio::test]+ async fn test_non_magic_binary_still_yields_parse_error() {+ // Bucket 3: non-magic invalid-utf8 content is corrupt data, not+ // compression. The guard must NOT fire; the pre-existing utf-8 parse+ // error must surface unchanged, proving the guard does not over-claim.+ let staging = TempDir::new().unwrap();+ // 0xff is not a compression-magic first byte; the trailing newline forms+ // a complete line that fails utf-8 validation - the pre-existing path.+ std::fs::write(staging.path().join("data.jsonl"), [0xff, 0x28, 0xff, b'\n']).unwrap();++ let source = FolderSource::new(staging.path().to_str().unwrap().to_string())+ .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 err = select_and_fetch_next_chunk(+ &state,+ &model,+ &source,+ &transform,+ 1024,+ Uuid::now_v7(),+ )+ .await+ .expect_err("invalid-utf8 binary must still fail");++ let full = format!("{err:#}");+ assert!(+ full.contains("utf8") || full.contains("Failed to parse"),+ "expected the pre-existing parse error, got: {full}"+ );+ assert!(+ !crate::error::get_user_message(&err).contains("compressed twice"),+ "non-magic data must not be mislabeled as double-compression: {full}"+ );+ assert_non_transient(&err);+ }+ }+/// 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