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): mixpanel doesnt always send gzipped files (#71141)

Nick Best4b6f42635bab
diff --git a/rust/batch-import-worker/src/extractor/mod.rs b/rust/batch-import-worker/src/extractor/mod.rs
index 80c723ca4b99..c14a6a15e053 100644
--- a/rust/batch-import-worker/src/extractor/mod.rs
+++ b/rust/batch-import-worker/src/extractor/mod.rs
@@ -3,8 +3,8 @@ use flate2::read::GzDecoder;
use serde::{Deserialize, Serialize};
use std::panic::AssertUnwindSafe;
use std::{
- io::Read,
- path::{Path, PathBuf},
+ io::{Read, Seek, SeekFrom},
+ path::PathBuf,
sync::Arc,
};
use tokio::sync::mpsc;
@@ -45,16 +45,17 @@ pub(crate) fn detect_compression_magic(data: &[u8]) -> Option<&'static str> {
.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")
+/// Read the first bytes of `file` into `buf`, rewind to the start, and return
+/// the compression format those bytes identify (if any). `buf` must be at least
+/// as long as the longest entry in [`COMPRESSION_MAGICS`]; a file shorter than a
+/// magic simply does not match it.
+fn sniff_magic(
+ file: &mut std::fs::File,
+ buf: &mut [u8; 8],
+) -> std::io::Result<Option<&'static str>> {
+ let n = file.read(buf)?;
+ file.seek(SeekFrom::Start(0))?;
+ Ok(detect_compression_magic(&buf[..n]))
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -240,11 +241,19 @@ impl PartExtractor for PlainGzipExtractor {
/// 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.
///
+/// The part is dispatched on its magic bytes rather than assumed to be gzip:
+/// export APIs that compress via content negotiation skip compression below a
+/// size threshold (Mixpanel sends bodies <= 1400 bytes uncompressed even when
+/// `Accept-Encoding: gzip` was requested), so a part with no recognized
+/// compression header is streamed as already-plaintext JSONL. A recognized
+/// *non-gzip* compression header is a compression-setting mismatch worth naming
+/// up front, not corruption.
+///
/// `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.
pub(crate) fn run_plain_gzip_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {
- let file = match std::fs::File::open(&raw_file_path) {
+ let mut file = match std::fs::File::open(&raw_file_path) {
Ok(f) => f,
Err(e) => {
let _unused = tx.blocking_send(Err(format!(
@@ -255,13 +264,36 @@ pub(crate) fn run_plain_gzip_producer(raw_file_path: PathBuf, tx: mpsc::Sender<B
}
};
- let mut decoder = GzDecoder::new(file);
+ let mut magic = [0u8; 8];
+ let sniffed = match sniff_magic(&mut file, &mut magic) {
+ Ok(sniffed) => sniffed,
+ Err(e) => {
+ let _unused = tx.blocking_send(Err(format!(
+ "Failed to read gzip file {}: {e}",
+ raw_file_path.display()
+ )));
+ return;
+ }
+ };
+
+ let mut reader: Box<dyn Read> = match sniffed {
+ Some("gzip") => Box::new(GzDecoder::new(file)),
+ Some(fmt) => {
+ let _unused = tx.blocking_send(Err(format!(
+ "The file appears to be {fmt}-compressed, but this import expects gzip \
+ or plaintext - check the source's compression setting."
+ )));
+ return;
+ }
+ None => Box::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) {
+ match reader.read(&mut buffer) {
Ok(0) => break,
Ok(n) => {
produced_any = true;
@@ -271,20 +303,14 @@ pub(crate) fn run_plain_gzip_producer(raw_file_path: PathBuf, tx: mpsc::Sender<B
}
}
Err(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."
+ // In passthrough mode the reader is the plain file, so a read
+ // failure is an I/O problem (permissions, disk), not corruption.
+ let msg = match sniffed {
+ Some("gzip") => format!("Failed to decompress gzip data: {e}"),
+ _ => format!(
+ "Failed to read plaintext file {}: {e}",
+ raw_file_path.display()
),
- None => format!("Failed to decompress gzip data: {e}"),
};
let _unused = tx.blocking_send(Err(msg));
return;
@@ -581,28 +607,52 @@ mod tests {
#[tokio::test]
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] = [
+ // content and leaves empty content untouched — for gzip parts and for
+ // plaintext parts alike. Export APIs that compress via content
+ // negotiation skip gzip below a size threshold (Mixpanel sends bodies
+ // <= 1400 bytes uncompressed even when Accept-Encoding: gzip was
+ // requested), so a plaintext part must decode identically to its
+ // gzipped equivalent instead of failing with "invalid gzip header".
+ // (case name, raw input, gzip the input, expected output)
+ let cases: [(&str, &str, bool, &str); 6] = [
(
- "already terminated",
+ "gzip already terminated",
"line1\nline2\nline3\n",
+ true,
"line1\nline2\nline3\n",
),
(
- "missing trailing newline",
+ "gzip missing trailing newline",
"line1\nline2\nline3",
+ true,
"line1\nline2\nline3\n",
),
- ("empty file", "", ""),
+ ("gzip empty file", "", true, ""),
+ (
+ "plaintext already terminated",
+ "line1\nline2\nline3\n",
+ false,
+ "line1\nline2\nline3\n",
+ ),
+ (
+ "plaintext missing trailing newline",
+ "line1\nline2\nline3",
+ false,
+ "line1\nline2\nline3\n",
+ ),
+ ("plaintext empty file", "", false, ""),
];
- for (name, input, expected) in cases {
+ for (name, input, gzip, expected) in cases {
let temp_dir = TempDir::new()?;
- let gzip_file = temp_dir.path().join("test.gz");
- create_test_gzip_file(input, &gzip_file)?;
+ let part_file = temp_dir.path().join("test.raw");
+ if gzip {
+ create_test_gzip_file(input, &part_file)?;
+ } else {
+ std::fs::write(&part_file, input)?;
+ }
- let mut reader = PlainGzipExtractor.open_reader(gzip_file);
+ let mut reader = PlainGzipExtractor.open_reader(part_file);
let (data, size) = reader.read_to_end_for_test(8192).await;
assert_eq!(
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 d3dcd36c6baf..a8ebd23ca189 100644
--- a/rust/batch-import-worker/src/source/date_range_export.rs
+++ b/rust/batch-import-worker/src/source/date_range_export.rs
@@ -478,10 +478,10 @@ impl DateRangeExportSource {
);
// 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 report 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".
+ // export APIs return this instead of a 404). Report it as an empty part
+ // with its size known immediately - mirroring the 404 branch above and
+ // s3_gzip's zero-byte handling - rather than staging a streaming part
+ // for a file we already know is empty.
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 {
@@ -828,8 +828,8 @@ mod tests {
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".
+ // prepare - mirroring the 404 branch and s3_gzip's zero-byte handling -
+ // not a streaming part.
let server = MockServer::start();
let _mock = server.mock(|when, then| {
when.method(httpmock::Method::GET).path("/export");
diff --git a/rust/batch-import-worker/src/staging/pipeline.rs b/rust/batch-import-worker/src/staging/pipeline.rs
index 0c400a08393d..70d83142c92b 100644
--- a/rust/batch-import-worker/src/staging/pipeline.rs
+++ b/rust/batch-import-worker/src/staging/pipeline.rs
@@ -206,22 +206,18 @@ mod tests {
}
#[tokio::test]
- async fn zero_byte_raw_surfaces_decode_error() {
- // A zero-byte .raw is not a valid gzip stream: the decoder rejects it
- // ("unexpected end of file") and the pipeline must surface that honestly.
- // Sources guarantee this input is unreachable - a zero-byte download is
- // turned into an empty part before any decoder sees it (the 404 branch,
- // s3_gzip's and date_range_export's zero-byte guards) - so an error here
- // means a source-level bug, never a valid empty export.
+ async fn zero_byte_raw_yields_no_bytes() {
+ // A zero-byte .raw has no compression magic, so the producer streams it
+ // as plaintext: an empty part, not a decode error. Sources still guard
+ // zero-byte downloads before any decoder sees them (the 404 branch,
+ // s3_gzip's and date_range_export's zero-byte guards), so this mainly
+ // pins that an empty file can no longer pause a job as spurious
+ // corruption.
let dir = TempDir::new().unwrap();
let raw = dir.path().join("a.raw");
std::fs::write(&raw, b"").unwrap();
- let result = collect(open_plaintext_stream(raw, ExtractorType::PlainGzip, 0)).await;
- assert!(
- result.is_err(),
- "zero-byte input must error, not stage empty"
- );
+ assert_pipeline_output(ExtractorType::PlainGzip, raw, Some(b"")).await;
}
#[tokio::test]