: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
chore(batch-imports): e2e test harness with misbehaving mock export APIs (#69815)
Nick Best3ab3ba0f814e
diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rsindex 284d8b884d61..8176dc95536f 100644--- a/rust/batch-import-worker/src/job/mod.rs+++ b/rust/batch-import-worker/src/job/mod.rs@@ -150,7 +150,7 @@ async fn mirror_part_total(model: &Mutex<JobModel>, key: &str, total: u64) {/// only on the empty-key short-circuit (so the caller skips the success backoff/// reset, matching the original control flow) and `true` otherwise. `None` means/// every part is done.-pub(crate) async fn select_and_fetch_next_chunk(+pub async fn select_and_fetch_next_chunk(state: &Mutex<JobState>,model: &Mutex<JobModel>,source: &dyn DataSource,diff --git a/rust/batch-import-worker/tests/common/harness.rs b/rust/batch-import-worker/tests/common/harness.rsnew file mode 100644index 000000000000..1ccda424b8df--- /dev/null+++ b/rust/batch-import-worker/tests/common/harness.rs@@ -0,0 +1,285 @@+//! In-process harness driving the real batch-import pipeline: a genuine+//! `DateRangeExportSource` (with the production extractor for the provider)+//! pointed at the [`mock_export`](super::mock_export) server, the production+//! JSONL parser and per-provider transform, and the DB-free job fetch loop+//! (`select_and_fetch_next_chunk`).+//!+//! Commits are modeled by the shared `JobState`: the loop advances part offsets+//! in place, exactly as a successfully committed chunk would persist them.+//! [`Harness::restart`] simulates a pod replacement: the source (and with it+//! every prepared key, streaming reader, and staged `.raw` file) is dropped and+//! rebuilt, while the persisted `JobState` survives - the same shape as a+//! deploy landing mid-part in production.++use std::collections::HashMap;+use std::sync::Arc;++use anyhow::Error;+use batch_import_worker::cache::{MockGroupCache, MockIdentifyCache};+use batch_import_worker::extractor::ExtractorType;+use batch_import_worker::job::config::{JobConfig, JobSecrets};+use batch_import_worker::job::model::{JobModel, JobState, JobStatus, PartState};+use batch_import_worker::job::select_and_fetch_next_chunk;+use batch_import_worker::parse::content::amplitude::AmplitudeEvent;+use batch_import_worker::parse::content::mixpanel::MixpanelEvent;+use batch_import_worker::parse::content::TransformContext;+use batch_import_worker::parse::format::{json_nd, skip_geoip, ParserFn};+use batch_import_worker::parse::Parsed;+use batch_import_worker::source::date_range_export::{AuthConfig, DateRangeExportSource};+use batch_import_worker::source::DataSource;+use chrono::{DateTime, TimeZone, Utc};+use common_types::InternallyCapturedEvent;+use rayon::iter::{IntoParallelIterator, ParallelIterator};+use tempfile::TempDir;+use tokio::sync::Mutex;+use uuid::Uuid;++use super::mock_export::{MockExport, Provider};++pub const TEAM_ID: i32 = 42;+pub const TOKEN: &str = "e2e-test-token";++pub struct Harness {+ pub mock: MockExport,+ provider: Provider,+ chunk_size: usize,+ job_id: Uuid,+ staging: TempDir,+ start: DateTime<Utc>,+ end: DateTime<Utc>,+ state: Mutex<JobState>,+ model: Mutex<JobModel>,+ parser: Arc<ParserFn>,+ source: DateRangeExportSource,+ pub emitted: Vec<InternallyCapturedEvent>,+}++/// Outcome of driving the fetch loop.+#[derive(Debug)]+pub enum RunOutcome {+ /// Every part is done.+ Complete,+ /// The requested number of chunks was fetched with work still remaining.+ MoreRemaining,+}++impl Harness {+ /// A harness over `days` consecutive UTC days starting at `start_day`+ /// (`%Y-%m-%d`). One part per day, matching production Mixpanel imports.+ pub async fn new(mock: MockExport, start_day: &str, days: u32, chunk_size: usize) -> Self {+ let provider = mock.provider();+ let date = chrono::NaiveDate::parse_from_str(start_day, "%Y-%m-%d").unwrap();+ let start = Utc+ .from_utc_datetime(&date.and_hms_opt(0, 0, 0).unwrap())+ .to_utc();+ let end = start + chrono::Duration::days(days as i64);++ let staging = TempDir::new().unwrap();+ let job_id = Uuid::now_v7();+ let source = build_source(&mock, provider, staging.path(), start, end);+ source.prepare_for_job().await.unwrap();++ let parts: Vec<PartState> = source+ .keys()+ .await+ .unwrap()+ .into_iter()+ .map(|key| PartState {+ key,+ current_offset: 0,+ total_size: None,+ })+ .collect();+ let job_state = JobState { parts };++ let model = JobModel {+ id: job_id,+ team_id: TEAM_ID,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ lease_id: None,+ leased_until: None,+ status: JobStatus::Running,+ status_message: None,+ display_status_message: None,+ state: Some(job_state.clone()),+ import_config: minimal_job_config(provider),+ secrets: JobSecrets::empty(),+ backoff_attempt: 0,+ backoff_until: None,+ was_leased: false,+ };++ Self {+ provider,+ chunk_size,+ job_id,+ staging,+ start,+ end,+ state: Mutex::new(job_state),+ model: Mutex::new(model),+ parser: Arc::new(build_parser(provider, job_id)),+ source,+ mock,+ emitted: Vec::new(),+ }+ }++ /// Drop and rebuild the source: prepared keys, streaming readers, and staged+ /// `.raw` files are all lost, while the committed `JobState` survives. This+ /// is a pod replacement mid-job.+ pub async fn restart(&mut self) {+ self.source = build_source(+ &self.mock,+ self.provider,+ self.staging.path(),+ self.start,+ self.end,+ );+ self.source.prepare_for_job().await.unwrap();+ }++ /// Fetch and parse up to `max_chunks` chunks, appending emitted events.+ pub async fn run_chunks(&mut self, max_chunks: usize) -> Result<RunOutcome, Error> {+ for _ in 0..max_chunks {+ let next = select_and_fetch_next_chunk(+ &self.state,+ &self.model,+ &self.source,+ &self.parser,+ self.chunk_size,+ self.job_id,+ )+ .await?;+ match next {+ None => return Ok(RunOutcome::Complete),+ Some((_key, parsed, _reset_backoff)) => self.emitted.extend(parsed.data),+ }+ }+ Ok(RunOutcome::MoreRemaining)+ }++ /// Drive the loop until every part is done.+ pub async fn run_to_end(&mut self) -> Result<(), Error> {+ loop {+ if matches!(self.run_chunks(usize::MAX).await?, RunOutcome::Complete) {+ return Ok(());+ }+ }+ }++ /// The committed part states (the harness's stand-in for the DB row).+ pub async fn parts(&self) -> Vec<PartState> {+ self.state.lock().await.parts.clone()+ }+}++fn build_source(+ mock: &MockExport,+ provider: Provider,+ staging: &std::path::Path,+ start: DateTime<Utc>,+ end: DateTime<Utc>,+) -> DateRangeExportSource {+ let extractor = match provider {+ Provider::Mixpanel => ExtractorType::PlainGzip,+ Provider::Amplitude => ExtractorType::ZipGzipJson,+ };+ let auth = match provider {+ Provider::Mixpanel => AuthConfig::MixpanelAuth {+ secret_key: "mock-secret".to_string(),+ },+ Provider::Amplitude => AuthConfig::BasicAuth {+ username: "mock-key".to_string(),+ password: "mock-secret".to_string(),+ },+ };++ DateRangeExportSource::builder(+ mock.export_url(),+ start,+ end,+ 86_400,+ extractor.create_extractor(),+ staging.to_path_buf(),+ )+ .with_query_params("from_date".to_string(), "to_date".to_string())+ .with_date_format("%Y-%m-%d".to_string())+ .with_auth(auth)+ .with_retries(0)+ .with_headers(HashMap::new())+ .build()+ .unwrap()+}++/// Assemble the production parser for `provider` around a hand-built+/// `TransformContext`, mirroring `FormatConfig::get_parser` without its+/// `AppContext` (team-token DB lookup) dependency.+fn build_parser(provider: Provider, job_id: Uuid) -> ParserFn {+ let context = TransformContext {+ team_id: TEAM_ID,+ token: TOKEN.to_string(),+ job_id,+ identify_cache: Arc::new(MockIdentifyCache::new()),+ group_cache: Arc::new(MockGroupCache::new()),+ import_events: true,+ generate_identify_events: true,+ generate_group_identify_events: true,+ };++ match provider {+ Provider::Mixpanel => {+ let format_parse = json_nd::<MixpanelEvent>(true);+ let transform =+ MixpanelEvent::parse_fn(context, false, chrono::Duration::zero(), skip_geoip());+ Box::new(move |data| {+ let parsed = format_parse(data)?;+ let consumed = parsed.consumed;+ let result: Result<Vec<_>, Error> = parsed+ .data+ .into_par_iter()+ .map(&transform)+ .filter_map(|x| x.transpose())+ .collect();+ Ok(Parsed {+ data: result?,+ consumed,+ })+ })+ }+ Provider::Amplitude => {+ let format_parse = json_nd::<AmplitudeEvent>(true);+ let transform = AmplitudeEvent::parse_fn(context, skip_geoip());+ Box::new(move |data| {+ let parsed = format_parse(data)?;+ let consumed = parsed.consumed;+ let result: Result<Vec<Vec<_>>, Error> =+ parsed.data.into_par_iter().map(&transform).collect();+ Ok(Parsed {+ data: result?.into_iter().flatten().collect(),+ consumed,+ })+ })+ }+ }+}++/// The smallest valid `JobConfig`; `select_and_fetch_next_chunk` never reads it,+/// but `JobModel` requires one.+fn minimal_job_config(provider: Provider) -> JobConfig {+ let content = match provider {+ Provider::Mixpanel => serde_json::json!({+ "type": "mixpanel",+ "skip_no_distinct_id": false,+ "timestamp_offset_seconds": null,+ }),+ Provider::Amplitude => serde_json::json!({ "type": "amplitude" }),+ };+ serde_json::from_value(serde_json::json!({+ "source": { "type": "folder", "path": "/unused" },+ "data_format": { "type": "json_lines", "skip_blanks": true, "content": content },+ "sink": { "type": "noop" },+ }))+ .expect("minimal job config must deserialize")+}diff --git a/rust/batch-import-worker/tests/common/mock_export.rs b/rust/batch-import-worker/tests/common/mock_export.rsnew file mode 100644index 000000000000..daf65918e757--- /dev/null+++ b/rust/batch-import-worker/tests/common/mock_export.rs@@ -0,0 +1,397 @@+//! A stateful mock of the Mixpanel / Amplitude raw export APIs.+//!+//! Unlike `httpmock`, this server can vary its response *per download attempt* of+//! the same date range, which is how the real APIs behave: Mixpanel's `/export`+//! gives no byte-stability guarantee between calls (event ordering shifts, late+//! data arrives), and that instability is the root cause of the offset-resume+//! failure class this test suite exists to pin down.+//!+//! Every response body is derived deterministically from `(seed, day, attempt)`,+//! so tests can compute exact ground truth via [`MockExport::expected_events`]+//! and remain reproducible run to run.++use std::collections::HashMap;+use std::io::Write;+use std::sync::{Arc, Mutex};++use axum::extract::{Query, State};+use axum::http::{header, StatusCode};+use axum::response::{IntoResponse, Response};+use axum::routing::get;+use axum::Router;+use chrono::{NaiveDate, Utc};+use flate2::write::GzEncoder;+use flate2::Compression;+use uuid::Uuid;++/// Mirrors `MIXPANEL_INSERT_ID_NAMESPACE` in `src/parse/content/mixpanel.rs`.+/// Duplicated on purpose: the namespace is a compatibility contract (changing it+/// silently breaks dedup against previously imported events), so the tests must+/// fail if it drifts rather than follow the production constant.+const MIXPANEL_INSERT_ID_NAMESPACE: Uuid = Uuid::from_bytes(*b"posthog_mixpanel");++/// Namespace for the deterministic `uuid` field the mock stamps on generated+/// Amplitude events. Purely test-internal.+const AMPLITUDE_TEST_UUID_NAMESPACE: Uuid = Uuid::from_bytes(*b"amplitude_e2e_ns");++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Provider {+ Mixpanel,+ Amplitude,+}++/// How the mock behaves for downloads of one day. Attempts are 1-indexed.+#[derive(Debug, Clone)]+pub enum Behavior {+ /// Byte-stable: every attempt returns identical bytes.+ Stable,+ /// Each attempt returns the same events in a different (seeded) order.+ /// This is the real Mixpanel behavior behind the incident.+ Reorder,+ /// Attempt N returns the day's events plus `extra_per_attempt * (N - 1)`+ /// additional late-arriving events, in stable order.+ LateData { extra_per_attempt: usize },+ /// The first `failures` attempts return 429 with a Retry-After header,+ /// after which the day downloads normally (byte-stable).+ RateLimit {+ failures: u32,+ retry_after_secs: u64,+ },+ /// The day has no data: 404.+ NotFound,+ /// The day has no data: 200 with a zero-byte body.+ EmptyBody,+ /// Valid gzip header, body cut mid-stream.+ TruncatedGzip,+}++/// Ground truth for one generated event, for exactly-once assertions.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct ExpectedEvent {+ pub uuid: Uuid,+ pub name: String,+ pub distinct_id: String,+}++#[derive(Debug, Clone)]+struct GeneratedEvent {+ insert_id: String,+ name: String,+ user: String,+ time: i64,+ pad_len: usize,+}++struct ServerState {+ provider: Provider,+ seed: u64,+ events_per_day: usize,+ behaviors: Mutex<HashMap<String, Behavior>>,+ attempts: Mutex<HashMap<String, u32>>,+}++pub struct MockExport {+ state: Arc<ServerState>,+ addr: std::net::SocketAddr,+ server: tokio::task::JoinHandle<()>,+}++impl Drop for MockExport {+ fn drop(&mut self) {+ self.server.abort();+ }+}++impl MockExport {+ pub async fn start(provider: Provider, seed: u64, events_per_day: usize) -> Self {+ let state = Arc::new(ServerState {+ provider,+ seed,+ events_per_day,+ behaviors: Mutex::new(HashMap::new()),+ attempts: Mutex::new(HashMap::new()),+ });++ let router = Router::new()+ .route("/export", get(handle_export))+ .with_state(state.clone());++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ axum::serve(listener, router).await.unwrap();+ });++ Self {+ state,+ addr,+ server,+ }+ }++ pub fn export_url(&self) -> String {+ format!("http://{}/export", self.addr)+ }++ pub fn provider(&self) -> Provider {+ self.state.provider+ }++ /// Program how downloads of `day` (a `%Y-%m-%d` string, matching the+ /// `from_date` query param) behave. Unprogrammed days are `Stable`.+ pub fn set_behavior(&self, day: &str, behavior: Behavior) {+ self.state+ .behaviors+ .lock()+ .unwrap()+ .insert(day.to_string(), behavior);+ }++ /// How many times `day` has been downloaded (attempts, including 429s).+ pub fn download_count(&self, day: &str) -> u32 {+ *self.state.attempts.lock().unwrap().get(day).unwrap_or(&0)+ }++ /// Ground truth for `day`: the events every successful import of that day+ /// must produce, with the UUIDs the production transforms will assign.+ pub fn expected_events(&self, day: &str) -> Vec<ExpectedEvent> {+ generate_day(self.state.seed, day, self.state.events_per_day)+ .iter()+ .map(|ev| expected_for(self.state.provider, ev))+ .collect()+ }++ /// The unique `(user_id, device_id)` pair count for `day`; with identify+ /// generation enabled, an Amplitude import of the day emits exactly one+ /// `$identify` per pair not already seen by the identify cache.+ pub fn expected_identify_pairs(&self, day: &str) -> usize {+ let events = generate_day(self.state.seed, day, self.state.events_per_day);+ let pairs: std::collections::HashSet<_> = events.iter().map(|ev| ev.user.clone()).collect();+ pairs.len()+ }+}++fn expected_for(provider: Provider, ev: &GeneratedEvent) -> ExpectedEvent {+ let uuid = match provider {+ Provider::Mixpanel => Uuid::new_v5(&MIXPANEL_INSERT_ID_NAMESPACE, ev.insert_id.as_bytes()),+ Provider::Amplitude => amplitude_uuid(ev),+ };+ ExpectedEvent {+ uuid,+ name: ev.name.clone(),+ distinct_id: ev.user.clone(),+ }+}++fn amplitude_uuid(ev: &GeneratedEvent) -> Uuid {+ Uuid::new_v5(&LITUDE_TEST_UUID_NAMESPACE, ev.insert_id.as_bytes())+}++// ---- Deterministic generation ----++fn splitmix64(state: &mut u64) -> u64 {+ *state = state.wrapping_add(0x9e3779b97f4a7c15);+ let mut z = *state;+ z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);+ z ^ (z >> 31)+}++fn day_hash(day: &str) -> u64 {+ day.bytes().fold(0xcbf29ce484222325u64, |h, b| {+ (h ^ b as u64).wrapping_mul(0x100000001b3)+ })+}++fn day_epoch(day: &str) -> i64 {+ NaiveDate::parse_from_str(day, "%Y-%m-%d")+ .unwrap_or_else(|_| panic!("mock received unparseable from_date: {day}"))+ .and_hms_opt(0, 0, 0)+ .unwrap()+ .and_utc()+ .timestamp()+}++const EVENT_NAMES: [&str; 3] = ["Page Load", "Button Click", "Purchase"];+const USER_POOL: usize = 7;++fn generate_day(seed: u64, day: &str, count: usize) -> Vec<GeneratedEvent> {+ let mut rng = seed ^ day_hash(day);+ let epoch = day_epoch(day);+ (0..count)+ .map(|i| {+ let r = splitmix64(&mut rng);+ GeneratedEvent {+ insert_id: format!("ins-{day}-{i}"),+ name: EVENT_NAMES[(r % 3) as usize].to_string(),+ user: format!("user-{}", r % USER_POOL as u64),+ time: epoch + i as i64,+ // Variable line lengths guarantee that a reordered stream+ // misaligns any byte offset taken against a previous order.+ pad_len: (r % 240) as usize,+ }+ })+ .collect()+}++/// Extra events representing late-arriving data for `LateData` attempts.+fn generate_late(seed: u64, day: &str, count: usize) -> Vec<GeneratedEvent> {+ let mut rng = seed ^ day_hash(day) ^ 0x1a7e;+ let epoch = day_epoch(day);+ (0..count)+ .map(|i| {+ let r = splitmix64(&mut rng);+ GeneratedEvent {+ insert_id: format!("ins-late-{day}-{i}"),+ name: EVENT_NAMES[(r % 3) as usize].to_string(),+ user: format!("user-{}", r % USER_POOL as u64),+ time: epoch + 80_000 + i as i64,+ pad_len: (r % 240) as usize,+ }+ })+ .collect()+}++/// Seeded Fisher-Yates. `permutation == 0` leaves the order untouched so+/// `Stable` bodies are identical across attempts.+fn permute(events: &mut [GeneratedEvent], seed: u64, permutation: u64) {+ if permutation == 0 {+ return;+ }+ let mut rng = seed ^ permutation.wrapping_mul(0x9e3779b97f4a7c15);+ for i in (1..events.len()).rev() {+ let j = (splitmix64(&mut rng) % (i as u64 + 1)) as usize;+ events.swap(i, j);+ }+}++// ---- Serialization per provider ----++fn mixpanel_line(ev: &GeneratedEvent) -> String {+ serde_json::json!({+ "event": ev.name,+ "properties": {+ "time": ev.time,+ "distinct_id": ev.user,+ "$insert_id": ev.insert_id,+ "pad": "x".repeat(ev.pad_len),+ }+ })+ .to_string()+}++fn amplitude_line(ev: &GeneratedEvent) -> String {+ let event_time = chrono::DateTime::from_timestamp(ev.time, 0)+ .unwrap()+ .format("%Y-%m-%d %H:%M:%S")+ .to_string();+ serde_json::json!({+ "event_type": ev.name,+ "user_id": ev.user,+ "device_id": format!("dev-{}", ev.user),+ "$insert_id": ev.insert_id,+ "uuid": amplitude_uuid(ev).to_string(),+ "event_time": event_time,+ "amplitude_id": 1,+ "event_properties": { "pad": "x".repeat(ev.pad_len) },+ })+ .to_string()+}++fn gzip(data: &[u8]) -> Vec<u8> {+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());+ encoder.write_all(data).unwrap();+ encoder.finish().unwrap()+}++/// Amplitude exports are a zip of `.json.gz` members; split the day across two+/// members to exercise member ordering and concatenation.+fn amplitude_zip(lines: &[String]) -> Vec<u8> {+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));+ let options = zip::write::SimpleFileOptions::default();+ let mid = lines.len().div_ceil(2);+ for (name, chunk) in [+ ("000.json.gz", &lines[..mid]),+ ("001.json.gz", &lines[mid..]),+ ] {+ zip.start_file(name, options).unwrap();+ zip.write_all(&gzip(chunk.join("\n").as_bytes())).unwrap();+ }+ zip.finish().unwrap().into_inner()+}++fn body_for(state: &ServerState, day: &str, permutation: u64, late_events: usize) -> Vec<u8> {+ let mut events = generate_day(state.seed, day, state.events_per_day);+ events.extend(generate_late(state.seed, day, late_events));+ permute(&mut events, state.seed ^ day_hash(day), permutation);++ match state.provider {+ Provider::Mixpanel => {+ let lines: Vec<String> = events.iter().map(mixpanel_line).collect();+ gzip(lines.join("\n").as_bytes())+ }+ Provider::Amplitude => {+ let lines: Vec<String> = events.iter().map(amplitude_line).collect();+ amplitude_zip(&lines)+ }+ }+}++async fn handle_export(+ State(state): State<Arc<ServerState>>,+ Query(params): Query<HashMap<String, String>>,+) -> Response {+ let Some(day) = params.get("from_date").cloned() else {+ return (StatusCode::BAD_REQUEST, "missing from_date").into_response();+ };++ let attempt = {+ let mut attempts = state.attempts.lock().unwrap();+ let entry = attempts.entry(day.clone()).or_insert(0);+ *entry += 1;+ *entry+ };++ let behavior = state+ .behaviors+ .lock()+ .unwrap()+ .get(&day)+ .cloned()+ .unwrap_or(Behavior::Stable);++ let body = match behavior {+ Behavior::Stable => body_for(&state, &day, 0, 0),+ Behavior::Reorder => body_for(&state, &day, attempt as u64, 0),+ Behavior::LateData { extra_per_attempt } => {+ body_for(&state, &day, 0, extra_per_attempt * (attempt as usize - 1))+ }+ Behavior::RateLimit {+ failures,+ retry_after_secs,+ } => {+ if attempt <= failures {+ return (+ StatusCode::TOO_MANY_REQUESTS,+ [(header::RETRY_AFTER, retry_after_secs.to_string())],+ "rate limited",+ )+ .into_response();+ }+ body_for(&state, &day, 0, 0)+ }+ Behavior::NotFound => return StatusCode::NOT_FOUND.into_response(),+ Behavior::EmptyBody => Vec::new(),+ Behavior::TruncatedGzip => {+ let mut body = body_for(&state, &day, 0, 0);+ body.truncate(body.len() / 2);+ body+ }+ };++ // The `now` timestamp keeps generated timestamps in the past for Amplitude's+ // future-timestamp fallback logic; assert rather than let it drift silently.+ debug_assert!(day_epoch(&day) < Utc::now().timestamp());++ ([(header::CONTENT_TYPE, "application/octet-stream")], body).into_response()+}diff --git a/rust/batch-import-worker/tests/common/mod.rs b/rust/batch-import-worker/tests/common/mod.rsindex ff174c722d3f..7663560a34ba 100644--- a/rust/batch-import-worker/tests/common/mod.rs+++ b/rust/batch-import-worker/tests/common/mod.rs@@ -5,6 +5,9 @@//! hence the crate-wide allow below.#![allow(dead_code)]+pub mod harness;+pub mod mock_export;+use std::io::Write;use aws_config::BehaviorVersion;diff --git a/rust/batch-import-worker/tests/import_pipeline_e2e_test.rs b/rust/batch-import-worker/tests/import_pipeline_e2e_test.rsnew file mode 100644index 000000000000..18b91a8b9015--- /dev/null+++ b/rust/batch-import-worker/tests/import_pipeline_e2e_test.rs@@ -0,0 +1,242 @@+//! End-to-end tests of the batch import pipeline against a mock export API+//! that behaves like the real Mixpanel/Amplitude endpoints - including the ways+//! they misbehave. No external services: the mock server, the source, the+//! parser, and the job fetch loop all run in-process.+//!+//! The central regression here is the offset-resume failure: a pod replacement+//! mid-part forces a re-download, the export API returns the same events in a+//! different byte order, and the committed decompressed-byte offset lands+//! mid-line in the new stream. The job must fail loudly (never silently skip+//! or duplicate data). See `E2E_TEST_PLAN.md`.++use std::collections::{HashMap, HashSet};++use batch_import_worker::error::{get_user_message, is_rate_limited_error};+use common_types::InternallyCapturedEvent;+use uuid::Uuid;++mod common;+use common::harness::{Harness, RunOutcome};+use common::mock_export::{Behavior, ExpectedEvent, MockExport, Provider};++const SEED: u64 = 0x5eed;++/// Split emitted events into (imported events, $identify events) as+/// `(uuid, name, distinct_id)` tuples.+fn split_emitted(events: &[InternallyCapturedEvent]) -> (Vec<ExpectedEvent>, usize) {+ let mut imported = Vec::new();+ let mut identifies = 0;+ for e in events {+ if e.inner.event == "$identify" {+ identifies += 1;+ continue;+ }+ imported.push(ExpectedEvent {+ uuid: e.inner.uuid,+ name: e.inner.event.clone(),+ distinct_id: e.inner.distinct_id.clone(),+ });+ }+ (imported, identifies)+}++/// Assert `emitted` contains every expected event exactly once and nothing else.+fn assert_exactly_once(emitted: &[InternallyCapturedEvent], expected: Vec<ExpectedEvent>) {+ let (imported, _) = split_emitted(emitted);++ let mut counts: HashMap<Uuid, usize> = HashMap::new();+ for ev in &imported {+ *counts.entry(ev.uuid).or_default() += 1;+ }+ let dupes: Vec<_> = counts.iter().filter(|(_, &c)| c > 1).collect();+ assert!(dupes.is_empty(), "duplicated events: {dupes:?}");++ let got: HashSet<ExpectedEvent> = imported.into_iter().collect();+ let want: HashSet<ExpectedEvent> = expected.into_iter().collect();+ let missing: Vec<_> = want.difference(&got).take(3).collect();+ let unexpected: Vec<_> = got.difference(&want).take(3).collect();+ assert!(+ missing.is_empty() && unexpected.is_empty(),+ "emitted set mismatch: {} missing (e.g. {missing:?}), {} unexpected (e.g. {unexpected:?})",+ want.difference(&got).count(),+ got.difference(&want).count(),+ );+}++fn expected_days(mock: &MockExport, days: &[&str]) -> Vec<ExpectedEvent> {+ days.iter().flat_map(|d| mock.expected_events(d)).collect()+}++#[tokio::test]+async fn mixpanel_happy_path_multi_day_multi_chunk() {+ // 1500 events/day at ~150 bytes/line is several 64 KiB chunks per part, so+ // the offset-advance arithmetic is exercised across chunk boundaries.+ let mock = MockExport::start(Provider::Mixpanel, SEED, 1500).await;+ let mut h = Harness::new(mock, "2022-01-24", 3, 64 * 1024).await;++ h.run_to_end().await.expect("import should complete");++ let want = expected_days(&h.mock, &["2022-01-24", "2022-01-25", "2022-01-26"]);+ assert_eq!(want.len(), 4500);+ assert_exactly_once(&h.emitted, want);++ for part in h.parts().await {+ assert!(part.is_done(), "part not done after run: {part:?}");+ }+ // One download per day: no spurious re-preparation.+ for day in ["2022-01-24", "2022-01-25", "2022-01-26"] {+ assert_eq!(h.mock.download_count(day), 1, "day {day}");+ }+}++#[tokio::test]+async fn amplitude_happy_path_with_identify_generation() {+ let mock = MockExport::start(Provider::Amplitude, SEED, 800).await;+ let mut h = Harness::new(mock, "2022-03-01", 2, 64 * 1024).await;++ h.run_to_end().await.expect("import should complete");++ let want = expected_days(&h.mock, &["2022-03-01", "2022-03-02"]);+ assert_exactly_once(&h.emitted, want);++ // Every unique (user_id, device_id) pair produces an $identify, and none is+ // fabricated. The exact count is not asserted: the transform runs in a+ // rayon pool, so the identify cache's check-then-mark can race within a+ // chunk and emit a duplicate $identify - harmless downstream, and the same+ // behavior production has.+ let identify_users: HashSet<String> = h+ .emitted+ .iter()+ .filter(|e| e.inner.event == "$identify")+ .map(|e| e.inner.distinct_id.clone())+ .collect();+ let expected_users: HashSet<String> = h+ .mock+ .expected_events("2022-03-01")+ .into_iter()+ .map(|ev| ev.distinct_id)+ .collect();+ assert_eq!(identify_users, expected_users);+ let (_, identifies) = split_emitted(&h.emitted);+ assert!(identifies >= h.mock.expected_identify_pairs("2022-03-01"));+}++#[tokio::test]+async fn restart_mid_part_with_stable_export_resumes_exactly_once() {+ let mock = MockExport::start(Provider::Mixpanel, SEED, 1500).await;+ let mut h = Harness::new(mock, "2022-01-24", 1, 32 * 1024).await;++ // Consume a couple of chunks, then lose the pod mid-part.+ let outcome = h.run_chunks(2).await.expect("first chunks should parse");+ assert!(matches!(outcome, RunOutcome::MoreRemaining));+ h.restart().await;++ h.run_to_end().await.expect("resume should complete");++ assert_exactly_once(&h.emitted, h.mock.expected_events("2022-01-24"));+ // The restart forced exactly one re-download.+ assert_eq!(h.mock.download_count("2022-01-24"), 2);+}++/// The production incident: a restart mid-part re-downloads the day, the export+/// returns the same events in a different order, and the committed offset lands+/// mid-line in the new byte stream. The job must surface a parse error - not+/// complete while silently skipping whatever moved before the resume offset.+#[tokio::test]+async fn restart_mid_part_with_reordered_export_fails_loudly() {+ let mock = MockExport::start(Provider::Mixpanel, SEED, 1500).await;+ mock.set_behavior("2022-01-24", Behavior::Reorder);+ let mut h = Harness::new(mock, "2022-01-24", 1, 32 * 1024).await;++ let outcome = h.run_chunks(2).await.expect("first chunks should parse");+ assert!(matches!(outcome, RunOutcome::MoreRemaining));+ let emitted_before_restart = h.emitted.len();+ h.restart().await;++ let err = h+ .run_to_end()+ .await+ .expect_err("resuming a byte-offset into a reordered stream must fail");+ let chain = format!("{err:#}");+ assert!(+ chain.contains("Failed to json parse line"),+ "expected the mid-line parse failure, got: {chain}"+ );+ assert!(+ get_user_message(&err).contains("Invalid JSON syntax"),+ "expected the user-facing parse message, got: {}",+ get_user_message(&err)+ );++ // Nothing may have been emitted from the misaligned stream, and nothing+ // emitted so far may be a duplicate or a fabrication.+ assert_eq!(h.emitted.len(), emitted_before_restart);+ let want: HashSet<ExpectedEvent> = h.mock.expected_events("2022-01-24").into_iter().collect();+ let (imported, _) = split_emitted(&h.emitted);+ let got: HashSet<ExpectedEvent> = imported.iter().cloned().collect();+ assert_eq!(got.len(), imported.len(), "duplicates before failure");+ assert!(+ got.is_subset(&want),+ "events emitted that were never generated"+ );+}++#[tokio::test]+async fn rate_limited_download_surfaces_and_then_succeeds() {+ let mock = MockExport::start(Provider::Mixpanel, SEED, 500).await;+ mock.set_behavior(+ "2022-01-24",+ Behavior::RateLimit {+ failures: 1,+ retry_after_secs: 1,+ },+ );+ let mut h = Harness::new(mock, "2022-01-24", 1, 64 * 1024).await;++ // The first attempt surfaces the 429 as a rate-limited error for job-level+ // backoff (the job runner owns the retry, not the source).+ let err = h.run_to_end().await.expect_err("first attempt is a 429");+ assert!(+ is_rate_limited_error(&err),+ "expected a rate-limited error, got: {err:#}"+ );+ assert!(h.emitted.is_empty());++ // The retry (post-backoff in production) completes exactly-once.+ h.run_to_end().await.expect("retry should complete");+ assert_exactly_once(&h.emitted, h.mock.expected_events("2022-01-24"));+ assert_eq!(h.mock.download_count("2022-01-24"), 2);+}++#[tokio::test]+async fn empty_days_complete_without_stalling() {+ let mock = MockExport::start(Provider::Mixpanel, SEED, 500).await;+ // A 404 day and a zero-byte-200 day mixed into a range with real data:+ // both are empty parts, neither may stall or fail the job.+ mock.set_behavior("2022-01-25", Behavior::NotFound);+ mock.set_behavior("2022-01-26", Behavior::EmptyBody);+ let mut h = Harness::new(mock, "2022-01-24", 3, 64 * 1024).await;++ h.run_to_end().await.expect("import should complete");++ assert_exactly_once(&h.emitted, h.mock.expected_events("2022-01-24"));+ for part in h.parts().await {+ assert!(part.is_done(), "part not done: {part:?}");+ }+}++#[tokio::test]+async fn chunk_size_sweep_is_exactly_once_at_every_boundary_shape() {+ // newline_delim's consumed arithmetic is boundary-sensitive (remainder+ // parses, chunks starting exactly on a newline). Sweep chunk sizes that+ // land mid-line, on power-of-two boundaries, and beyond the whole part.+ for chunk_size in [4 * 1024, 8 * 1024 - 1, 64 * 1024, 1 << 20] {+ let mock = MockExport::start(Provider::Mixpanel, SEED, 400).await;+ let mut h = Harness::new(mock, "2022-01-24", 1, chunk_size).await;++ h.run_to_end()+ .await+ .unwrap_or_else(|e| panic!("chunk_size {chunk_size}: {e:#}"));+ assert_exactly_once(&h.emitted, h.mock.expected_events("2022-01-24"));+ }+}