: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
feat(batch-import): add StagingBackend trait + local-disk backend (#67569)
Eli Reismanc5ef29f46847
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.ymlindex 0a87ef6912fc..7f0e38d6a0de 100644--- a/.github/workflows/ci-rust.yml+++ b/.github/workflows/ci-rust.yml@@ -320,12 +320,15 @@ jobs:- name: Setup main repo and dependenciesenv:COMPOSE_FILE: ../docker-compose.dev.yml:../docker-compose.profiles.yml- COMPOSE_PROFILES: etcd+ # `replay` boots SeaweedFS (S3 API on :8333), required by the+ # batch-import-worker temp-bucket integration tests, which fail+ # rather than skip when the store is down in CI.+ COMPOSE_PROFILES: etcd,replayWAIT_FOR_DOCKER_LAUNCH_RETRIES: 3WAIT_FOR_DOCKER_LAUNCH_RETRY_DELAY: 10run: |../bin/ci-wait-for-docker launch --down- ../bin/ci-wait-for-docker wait+ ../bin/ci-wait-for-docker wait seaweedfsecho "127.0.0.1 db redis7 kafka clickhouse clickhouse-coordinator objectstorage seaweedfs temporal" | sudo tee -a /etc/hostsdiff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 6bfd20669012..fee16b217d9e 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1309,6 +1309,7 @@ dependencies = ["mockito","moka","natord",+ "object_store","posthog-rs","rayon","rdkafka",diff --git a/rust/batch-import-worker/Cargo.toml b/rust/batch-import-worker/Cargo.tomlindex 2ae75235055b..b93c7045b9e5 100644--- a/rust/batch-import-worker/Cargo.toml+++ b/rust/batch-import-worker/Cargo.toml@@ -33,6 +33,7 @@ reqwest = { workspace = true }aws-config = { workspace = true }aws-sdk-s3 = { workspace = true }aws-smithy-http-client = { workspace = true }+object_store = { version = "0.13.0", features = ["aws"] }rdkafka = { workspace = true }rayon = "1.10.0"celes = "=2.4.0"diff --git a/rust/batch-import-worker/src/config.rs b/rust/batch-import-worker/src/config.rsindex 7d7218862ae6..ddda09cf7cc5 100644--- a/rust/batch-import-worker/src/config.rs+++ b/rust/batch-import-worker/src/config.rs@@ -102,6 +102,95 @@ pub struct Config {// the staging volume capacity in deployment.#[envconfig(from = "STAGING_DIR_MAX_BYTES", default = "0")]pub staging_dir_max_bytes: u64,++ // Where compressed sources stage decompressed part plaintext: `local_disk`+ // (default, per-pod disk) or `temp_bucket` (internal S3). Selects the+ // StagingBackend; nothing branches on it until routing lands.+ #[envconfig(from = "STAGING_BACKEND", default = "local_disk")]+ pub staging_backend: String,++ // Internal S3 "temp bucket" used when STAGING_BACKEND=temp_bucket. Empty+ // string means unset. TEMP_BUCKET_NAME is required in that mode.+ #[envconfig(from = "TEMP_BUCKET_NAME", default = "")]+ pub temp_bucket_name: String,+ // Custom S3 endpoint for local dev / CI (SeaweedFS: http://localhost:8333 with+ // bucket `posthog`, any credentials, and TEMP_BUCKET_FORCE_PATH_STYLE=true).+ #[envconfig(from = "TEMP_BUCKET_ENDPOINT", default = "")]+ pub temp_bucket_endpoint: String,+ #[envconfig(from = "TEMP_BUCKET_REGION", default = "")]+ pub temp_bucket_region: String,+ #[envconfig(from = "TEMP_BUCKET_PREFIX", default = "batch-import-staging/")]+ pub temp_bucket_prefix: String,++ // Explicit S3 credentials for local dev / CI without IAM (production uses the+ // standard AWS chain: IRSA web-identity). Both must be set to take effect.+ #[envconfig(from = "TEMP_BUCKET_ACCESS_KEY_ID", default = "")]+ pub temp_bucket_access_key_id: String,+ #[envconfig(from = "TEMP_BUCKET_SECRET_ACCESS_KEY", default = "")]+ pub temp_bucket_secret_access_key: String,++ // Path-style object URLs (required by S3-compatible dev stores like SeaweedFS).+ #[envconfig(from = "TEMP_BUCKET_FORCE_PATH_STYLE", default = "false")]+ pub temp_bucket_force_path_style: bool,++ // Timeout for a single S3 request attempt, including body transfer. Must be+ // large enough for a full CHUNK_SIZE (~100 MB) ranged GET on a slow path.+ #[envconfig(from = "TEMP_BUCKET_ATTEMPT_TIMEOUT_SECS", default = "120")]+ pub temp_bucket_attempt_timeout_secs: u64,++ // Total time budget for an S3 operation across all client-level retries.+ #[envconfig(from = "TEMP_BUCKET_OPERATION_TIMEOUT_SECS", default = "600")]+ pub temp_bucket_operation_timeout_secs: u64,++ // Client-level retries per S3 operation (job-level backoff retries on top).+ #[envconfig(from = "TEMP_BUCKET_MAX_RETRIES", default = "3")]+ pub temp_bucket_max_retries: usize,++ // Concurrent in-flight requests to the temp bucket per job client.+ #[envconfig(from = "TEMP_BUCKET_MAX_CONCURRENT_REQUESTS", default = "16")]+ pub temp_bucket_max_concurrent_requests: usize,++ // Multipart upload part size when staging a part. S3 assembles the numbered+ // parts into one object; part size bounds the maximum staged object size+ // (part_size x 10,000 parts — the AWS multipart limit) and the upload's+ // memory footprint (part_size x (concurrency + 1) buffered in RAM).+ // 64 MiB => 640 GiB max staged part at ~320 MiB peak RAM. Must be within+ // S3's 5 MiB..5 GiB part-size bounds.+ #[envconfig(from = "TEMP_BUCKET_UPLOAD_PART_SIZE_BYTES", default = "67108864")]+ pub temp_bucket_upload_part_size_bytes: u64,++ // Concurrent in-flight part uploads while staging. Staging throughput is+ // producer-bound (origin download + gzip decode), so a small window suffices+ // to keep uploads fully overlapped.+ #[envconfig(from = "TEMP_BUCKET_UPLOAD_CONCURRENCY", default = "4")]+ pub temp_bucket_upload_concurrency: usize,++ // Per-part decompressed-byte ceiling enforced by the fetch+decompress pipeline+ // (decompression-bomb / cost guard). Breaching it pauses the job with an+ // actionable error rather than staging unbounded plaintext.+ //+ // 0 means "no operator-configured ceiling", NOT unlimited: in temp_bucket mode+ // an implicit ceiling just below the S3 multipart wall always applies (see+ // `effective_plaintext_ceiling`), so an oversized part pauses with the+ // actionable message instead of an opaque multipart failure. The local+ // streaming path has no wall and stays unlimited when this is 0.+ #[envconfig(from = "STAGED_PLAINTEXT_MAX_BYTES", default = "0")]+ pub staged_plaintext_max_bytes: u64,+}++/// S3 multipart uploads are capped at 10,000 parts (AWS hard limit).+const S3_MAX_MULTIPART_PARTS: u64 = 10_000;+/// S3 part-size bounds: 5 MiB minimum (except the last part), 5 GiB maximum.+const S3_MIN_PART_SIZE_BYTES: u64 = 5 * 1024 * 1024;+const S3_MAX_PART_SIZE_BYTES: u64 = 5 * 1024 * 1024 * 1024;+/// S3 single-object size cap.+const S3_MAX_OBJECT_BYTES: u64 = 5 * 1024 * 1024 * 1024 * 1024;++/// Which staging backend a job's compressed sources use.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum StagingBackendKind {+ LocalDisk,+ TempBucket,}impl Config {@@ -120,6 +209,87 @@ impl Config {PathBuf::from(&self.staging_dir)}+ /// Resolve and validate the configured staging backend. Fails fast when+ /// `temp_bucket` is selected without a bucket name, with upload knobs outside+ /// S3's multipart bounds, or on an unknown value.+ pub fn staging_backend(&self) -> Result<StagingBackendKind, anyhow::Error> {+ match self.staging_backend.as_str() {+ "local_disk" => Ok(StagingBackendKind::LocalDisk),+ "temp_bucket" => {+ if self.temp_bucket_name.trim().is_empty() {+ return Err(anyhow::Error::msg(+ "STAGING_BACKEND=temp_bucket requires TEMP_BUCKET_NAME to be set",+ ));+ }+ if !(S3_MIN_PART_SIZE_BYTES..=S3_MAX_PART_SIZE_BYTES)+ .contains(&self.temp_bucket_upload_part_size_bytes)+ {+ // Sub-5MiB parts are rejected by S3 on every multi-part stage;+ // catch the misconfiguration before any job work starts.+ return Err(anyhow::Error::msg(format!(+ "TEMP_BUCKET_UPLOAD_PART_SIZE_BYTES={} outside S3 part-size bounds \+ ({S3_MIN_PART_SIZE_BYTES}..={S3_MAX_PART_SIZE_BYTES})",+ self.temp_bucket_upload_part_size_bytes+ )));+ }+ if self.temp_bucket_upload_concurrency == 0 {+ return Err(anyhow::Error::msg(+ "TEMP_BUCKET_UPLOAD_CONCURRENCY must be >= 1",+ ));+ }+ Ok(StagingBackendKind::TempBucket)+ }+ other => Err(anyhow::Error::msg(format!(+ "Unknown STAGING_BACKEND '{other}' (expected 'local_disk' or 'temp_bucket')"+ ))),+ }+ }++ /// The largest object the temp bucket can hold with the configured part size:+ /// S3 caps multipart uploads at 10,000 parts and objects at 5 TiB.+ fn temp_bucket_object_wall_bytes(&self) -> u64 {+ std::cmp::min(+ self.temp_bucket_upload_part_size_bytes+ .saturating_mul(S3_MAX_MULTIPART_PARTS),+ S3_MAX_OBJECT_BYTES,+ )+ }++ /// Effective per-part decompressed-byte ceiling in temp_bucket mode.+ ///+ /// Always non-zero: an implicit ceiling at 95% of the S3 multipart wall applies+ /// even when `STAGED_PLAINTEXT_MAX_BYTES=0`, so an oversized part always pauses+ /// with the actionable "split the import" message and can never reach the wall's+ /// opaque multipart failure. An operator-configured ceiling only tightens it.+ pub fn effective_plaintext_ceiling(&self) -> u64 {+ let implicit = self.temp_bucket_object_wall_bytes() / 100 * 95;+ if self.staged_plaintext_max_bytes > 0 {+ std::cmp::min(self.staged_plaintext_max_bytes, implicit)+ } else {+ implicit+ }+ }++ /// Optional custom S3 endpoint (local dev / SeaweedFS). `None` when unset.+ pub fn temp_bucket_endpoint(&self) -> Option<&str> {+ let e = self.temp_bucket_endpoint.trim();+ (!e.is_empty()).then_some(e)+ }++ /// Optional S3 region override. `None` when unset.+ pub fn temp_bucket_region(&self) -> Option<&str> {+ let r = self.temp_bucket_region.trim();+ (!r.is_empty()).then_some(r)+ }++ /// Explicit S3 credentials (local dev / CI). `None` unless both parts are set;+ /// production relies on the standard AWS chain (IRSA) instead.+ pub fn temp_bucket_credentials(&self) -> Option<(&str, &str)> {+ let key = self.temp_bucket_access_key_id.trim();+ let secret = self.temp_bucket_secret_access_key.trim();+ (!key.is_empty() && !secret.is_empty()).then_some((key, secret))+ }+pub fn backoff_policy(&self) -> BackoffPolicy {BackoffPolicy::new(std::time::Duration::from_secs(self.backoff_initial_seconds),@@ -195,4 +365,134 @@ mod tests {assert_eq!(p.max_delay.as_secs(), 3600);assert!((p.multiplier - 2.0).abs() < f64::EPSILON);}++ #[test]+ fn test_staging_backend_defaults_to_local_disk() {+ let config = Config::init_from_env().unwrap();+ assert_eq!(config.staging_backend, "local_disk");+ assert_eq!(+ config.staging_backend().unwrap(),+ StagingBackendKind::LocalDisk+ );+ assert_eq!(config.staged_plaintext_max_bytes, 0);+ assert_eq!(config.temp_bucket_prefix, "batch-import-staging/");+ assert_eq!(config.temp_bucket_endpoint(), None);+ assert_eq!(config.temp_bucket_region(), None);+ }++ fn config_for_backend(backend: &str, bucket: &str) -> Config {+ let mut config = Config::init_from_env().unwrap();+ config.staging_backend = backend.to_string();+ config.temp_bucket_name = bucket.to_string();+ config+ }++ #[test]+ fn test_staging_backend_temp_bucket_requires_name() {+ let config = config_for_backend("temp_bucket", "");+ let err = config.staging_backend().unwrap_err().to_string();+ assert!(err.contains("TEMP_BUCKET_NAME"), "unexpected error: {err}");+ }++ #[test]+ fn test_staging_backend_temp_bucket_ok_with_name() {+ let config = config_for_backend("temp_bucket", "my-bucket");+ assert_eq!(+ config.staging_backend().unwrap(),+ StagingBackendKind::TempBucket+ );+ }++ #[test]+ fn test_staging_backend_unknown_value_errors() {+ let config = config_for_backend("nfs", "");+ let err = config.staging_backend().unwrap_err().to_string();+ assert!(+ err.contains("Unknown STAGING_BACKEND"),+ "unexpected error: {err}"+ );+ }++ #[test]+ fn test_temp_bucket_endpoint_and_region_optional() {+ let mut config = Config::init_from_env().unwrap();+ config.temp_bucket_endpoint = " ".to_string();+ config.temp_bucket_region = "".to_string();+ assert_eq!(config.temp_bucket_endpoint(), None);+ assert_eq!(config.temp_bucket_region(), None);++ config.temp_bucket_endpoint = "http://localhost:8333".to_string();+ config.temp_bucket_region = "us-east-1".to_string();+ assert_eq!(config.temp_bucket_endpoint(), Some("http://localhost:8333"));+ assert_eq!(config.temp_bucket_region(), Some("us-east-1"));+ }++ #[test]+ fn test_temp_bucket_credentials_require_both_parts() {+ let mut config = Config::init_from_env().unwrap();+ assert_eq!(config.temp_bucket_credentials(), None);+ config.temp_bucket_access_key_id = "key".to_string();+ assert_eq!(config.temp_bucket_credentials(), None);+ config.temp_bucket_secret_access_key = "secret".to_string();+ assert_eq!(config.temp_bucket_credentials(), Some(("key", "secret")));+ }++ #[test]+ fn test_upload_knob_validation_bounds() {+ // Sub-5MiB parts are rejected by S3 on multi-part stages; >5GiB is the S3+ // part-size maximum; concurrency 0 would deadlock the writer. Each must+ // fail fast at config resolution — but only in temp_bucket mode, where the+ // knobs are actually consumed.+ let cases: Vec<(u64, usize, &str)> = vec![+ (4 * 1024 * 1024, 4, "TEMP_BUCKET_UPLOAD_PART_SIZE_BYTES"),+ (+ 6 * 1024 * 1024 * 1024,+ 4,+ "TEMP_BUCKET_UPLOAD_PART_SIZE_BYTES",+ ),+ (64 * 1024 * 1024, 0, "TEMP_BUCKET_UPLOAD_CONCURRENCY"),+ ];+ for (part_size, concurrency, expected) in cases {+ let mut config = config_for_backend("temp_bucket", "my-bucket");+ config.temp_bucket_upload_part_size_bytes = part_size;+ config.temp_bucket_upload_concurrency = concurrency;+ let err = config.staging_backend().unwrap_err().to_string();+ assert!(+ err.contains(expected),+ "part_size={part_size} concurrency={concurrency}: unexpected error: {err}"+ );++ let mut local = config_for_backend("local_disk", "");+ local.temp_bucket_upload_part_size_bytes = part_size;+ local.temp_bucket_upload_concurrency = concurrency;+ assert_eq!(+ local.staging_backend().unwrap(),+ StagingBackendKind::LocalDisk,+ "local_disk mode must not validate unused upload knobs"+ );+ }+ }++ #[test]+ fn test_effective_plaintext_ceiling_is_always_below_the_wall() {+ let mut config = config_for_backend("temp_bucket", "my-bucket");++ // Defaults: 64 MiB parts -> 640 GiB wall -> implicit ceiling at 95%.+ let wall: u64 = 64 * 1024 * 1024 * 10_000;+ assert_eq!(config.effective_plaintext_ceiling(), wall / 100 * 95);++ // An operator ceiling only tightens the implicit one...+ config.staged_plaintext_max_bytes = 1_000_000;+ assert_eq!(config.effective_plaintext_ceiling(), 1_000_000);++ // ...and can never loosen it past the wall.+ config.staged_plaintext_max_bytes = u64::MAX;+ assert_eq!(config.effective_plaintext_ceiling(), wall / 100 * 95);++ // Maximum part size: the wall clamps at S3's 5 TiB object cap.+ config.staged_plaintext_max_bytes = 0;+ config.temp_bucket_upload_part_size_bytes = 5 * 1024 * 1024 * 1024;+ let object_cap: u64 = 5 * 1024 * 1024 * 1024 * 1024;+ assert_eq!(config.effective_plaintext_ceiling(), object_cap / 100 * 95);+ }}diff --git a/rust/batch-import-worker/src/error/mod.rs b/rust/batch-import-worker/src/error/mod.rsindex 16f5185bbe2d..ff08f0993edb 100644--- a/rust/batch-import-worker/src/error/mod.rs+++ b/rust/batch-import-worker/src/error/mod.rs@@ -36,6 +36,17 @@ pub fn get_user_message(error: &anyhow::Error) -> String {}}+/// Attach a public-facing message only when the chain doesn't already carry one, so a+/// specific message deeper in the stack (e.g. the plaintext-ceiling breach) is never+/// shadowed by a generic wrapper added higher up.+pub fn ensure_user_message(error: anyhow::Error, msg: impl Into<String>) -> anyhow::Error {+ if error.downcast_ref::<UserError>().is_some() {+ error+ } else {+ error.context(UserError::new(msg))+ }+}+#[derive(Error, Debug)]#[error("Rate limited")]pub struct RateLimitedError {@@ -125,6 +136,66 @@ pub fn is_transient_server_error(error: &anyhow::Error) -> bool {})}+/// Returns true if the error chain contains a *transient* `object_store` (temp-bucket+/// S3) failure that outlived the client's internal retries: 429/5xx responses,+/// timeouts, and transport-level errors. Everything else — 401/403 (IAM), 404, other+/// 4xx, config errors — is deliberately NOT transient: job-level backoff can retry+/// without limit (`BACKOFF_MAX_ATTEMPTS=0`), so misclassifying a permanent failure+/// here would retry it forever instead of pausing visibly. Unknown shapes therefore+/// default to "not transient" (pause), the fail-safe direction.+pub fn is_transient_object_store_error(error: &anyhow::Error) -> bool {+ for cause in error.chain() {+ if let Some(ose) = cause.downcast_ref::<object_store::Error>() {+ return match ose {+ // Everything object_store couldn't map to a specific (permanent)+ // variant: 429/5xx after retries, timeouts, transport failures —+ // and also unmapped 4xx, which the helper filters back out.+ object_store::Error::Generic { source, .. } => {+ object_store_generic_is_transient(source.as_ref())+ }+ // Tokio task join failure inside the store: process-local, retryable.+ object_store::Error::JoinError { .. } => true,+ // NotFound / PermissionDenied / Unauthenticated / Precondition /+ // AlreadyExists / config errors: permanent, pause.+ _ => false,+ };+ }+ }+ false+}++/// Classify the source chain under `object_store::Error::Generic`.+///+/// Transport-level failures (timeout, connect, reset) surface as a public+/// `object_store::client::HttpError` in the chain and are transient by construction.+/// HTTP-status failures keep the status only in the retry error's message+/// ("Server returned non-2xx status code: <status>..."), because the retry error+/// type is not public API; 429/5xx are transient, other statuses are not. An S3+/// error body on a 200 ("Server returned error response: ...", e.g. InternalError /+/// SlowDown) is transient — object_store retries those for the same reason. If the+/// message format changes in an object_store upgrade, classification degrades to+/// "not transient" (a visible pause), never to an infinite retry.+fn object_store_generic_is_transient(source: &(dyn std::error::Error + 'static)) -> bool {+ let mut messages = String::new();+ let mut cur: Option<&(dyn std::error::Error + 'static)> = Some(source);+ while let Some(err) = cur {+ if err+ .downcast_ref::<object_store::client::HttpError>()+ .is_some()+ {+ return true;+ }+ messages.push_str(&err.to_string());+ messages.push('\n');+ cur = err.source();+ }+ if let Some(idx) = messages.find("status code: ") {+ let status = &messages[idx + "status code: ".len()..];+ return status.starts_with('5') || status.starts_with("429");+ }+ messages.contains("Server returned error response")+}+#[cfg(test)]mod tests {use super::*;@@ -418,4 +489,138 @@ mod tests {);}}++ /// Build a real object_store S3 client against a mock endpoint with client-level+ /// retries disabled, so tests classify the genuine error shapes the production+ /// client produces (not synthetic strings that could drift from the crate).+ fn object_store_against(url: &str) -> object_store::aws::AmazonS3 {+ use object_store::aws::AmazonS3Builder;+ AmazonS3Builder::new()+ .with_bucket_name("test-bucket")+ .with_endpoint(url)+ .with_region("us-east-1")+ .with_allow_http(true)+ .with_virtual_hosted_style_request(false)+ .with_access_key_id("k")+ .with_secret_access_key("s")+ .with_retry(object_store::RetryConfig {+ max_retries: 0,+ retry_timeout: std::time::Duration::from_secs(5),+ ..Default::default()+ })+ .build()+ .unwrap()+ }++ async fn object_store_error_for_status(status: u16) -> anyhow::Error {+ use object_store::ObjectStoreExt;+ let server = MockServer::start();+ let _mock = server.mock(|when, then| {+ when.any_request();+ then.status(status);+ });+ let store = object_store_against(&server.base_url());+ let err = store+ .get(&object_store::path::Path::from("k.data"))+ .await+ .unwrap_err();+ anyhow::Error::from(err).context("Failed to read staged object for key: k")+ }++ #[tokio::test]+ async fn test_object_store_5xx_and_429_are_transient() {+ // A throttle/outage that outlives the client's internal retries must reach+ // job-level backoff, not a pause: with real jobs this is the difference+ // between self-healing and a support ticket.+ for status in [500, 502, 503, 504, 429] {+ let err = object_store_error_for_status(status).await;+ assert!(+ is_transient_object_store_error(&err),+ "expected transient for {status}: {err:#}"+ );+ }+ }++ #[tokio::test]+ async fn test_object_store_permanent_errors_pause_not_retry() {+ // 401/403 (IAM misconfig), 404, and other 4xx must never classify as+ // transient: job backoff retries without limit, so a misclassified+ // permanent error would retry invisibly forever instead of pausing.+ for status in [401, 403, 404, 400] {+ let err = object_store_error_for_status(status).await;+ assert!(+ !is_transient_object_store_error(&err),+ "expected permanent for {status}: {err:#}"+ );+ }+ }++ #[tokio::test]+ async fn test_object_store_timeout_and_connect_errors_are_transient() {+ use object_store::ObjectStoreExt;++ // Request timeout: server delays past the client timeout.+ let server = MockServer::start();+ let _mock = server.mock(|when, then| {+ when.any_request();+ then.status(200)+ .delay(std::time::Duration::from_millis(500));+ });+ let store = {+ use object_store::aws::AmazonS3Builder;+ AmazonS3Builder::new()+ .with_bucket_name("test-bucket")+ .with_endpoint(server.base_url())+ .with_region("us-east-1")+ .with_allow_http(true)+ .with_virtual_hosted_style_request(false)+ .with_access_key_id("k")+ .with_secret_access_key("s")+ .with_client_options(+ object_store::ClientOptions::new()+ .with_timeout(std::time::Duration::from_millis(50)),+ )+ .with_retry(object_store::RetryConfig {+ max_retries: 0,+ retry_timeout: std::time::Duration::from_secs(5),+ ..Default::default()+ })+ .build()+ .unwrap()+ };+ let err = anyhow::Error::from(+ store+ .get(&object_store::path::Path::from("k.data"))+ .await+ .unwrap_err(),+ );+ assert!(+ is_transient_object_store_error(&err),+ "timeout must be transient: {err:#}"+ );++ // Transport error: nothing listens on the target port.+ let store = object_store_against("http://127.0.0.1:1");+ let err = anyhow::Error::from(+ store+ .get(&object_store::path::Path::from("k.data"))+ .await+ .unwrap_err(),+ );+ assert!(+ is_transient_object_store_error(&err),+ "connect failure must be transient: {err:#}"+ );+ }++ #[test]+ fn test_ensure_user_message_never_shadows_a_specific_one() {+ let specific = anyhow::Error::msg("root").context(UserError::new("specific message"));+ let wrapped = ensure_user_message(specific, "generic message");+ assert_eq!(get_user_message(&wrapped), "specific message");++ let bare = anyhow::Error::msg("root");+ let wrapped = ensure_user_message(bare, "generic message");+ assert_eq!(get_user_message(&wrapped), "generic message");+ }}diff --git a/rust/batch-import-worker/src/extractor/mod.rs b/rust/batch-import-worker/src/extractor/mod.rsindex 2ac156cdca31..80c723ca4b99 100644--- a/rust/batch-import-worker/src/extractor/mod.rs+++ b/rust/batch-import-worker/src/extractor/mod.rs@@ -98,7 +98,31 @@ const PRODUCER_BLOCK_SIZE: usize = 64 * 1024;/// applies backpressure to the producer thread, so memory stays bounded.const PRODUCER_CHANNEL_CAPACITY: usize = 32;-type Block = Result<Vec<u8>, String>;+pub(crate) type Block = Result<Vec<u8>, String>;++/// Spawn a decompression producer on a dedicated OS thread (not the tokio blocking+/// pool — the decoder owns the thread for the lifetime of the read) feeding a bounded+/// channel. The thread exits when the receiver is dropped.+///+/// Guards against a producer panic (e.g. an internal flate2/zip panic): without this, a+/// panic would drop `tx` and consumers would read the closed channel as a clean EOF,+/// recording a truncated part as complete (silent data loss). The panic is converted+/// into a channel error instead. Shared by [`StreamingReader`] and the staging+/// pipeline so both consumers get identical bytes and identical panic semantics.+pub(crate) fn spawn_producer_thread<F>(producer: F) -> mpsc::Receiver<Block>+where+ F: FnOnce(mpsc::Sender<Block>) + Send + 'static,+{+ let (tx, rx) = mpsc::channel(PRODUCER_CHANNEL_CAPACITY);+ std::thread::spawn(move || {+ let err_tx = tx.clone();+ if std::panic::catch_unwind(AssertUnwindSafe(move || producer(tx))).is_err() {+ let _unused =+ err_tx.blocking_send(Err("decompression producer thread panicked".to_string()));+ }+ });+ rx+}/// A decompressed range returned by [`StreamingReader::read_at`].pub struct ReadChunk {@@ -137,23 +161,8 @@ impl StreamingReader {whereF: FnOnce(mpsc::Sender<Block>) + Send + 'static,{- let (tx, rx) = mpsc::channel(PRODUCER_CHANNEL_CAPACITY);- // A dedicated OS thread (not the tokio blocking pool) owns the decoder for- // the lifetime of the read. It exits when the receiver is dropped.- //- // Guard against a producer panic (e.g. an internal flate2/zip panic): without- // this, a panic would drop `tx`, and `read_at` would read the closed channel as- // a clean EOF and record a truncated part as complete (silent data loss). Convert- // the panic into a channel error so `read_at` surfaces it instead.- std::thread::spawn(move || {- let err_tx = tx.clone();- if std::panic::catch_unwind(AssertUnwindSafe(move || producer(tx))).is_err() {- let _unused =- err_tx.blocking_send(Err("decompression producer thread panicked".to_string()));- }- });Self {- rx,+ rx: spawn_producer_thread(producer),carry: Vec::new(),carry_start: 0,decoded_end: 0,@@ -234,7 +243,7 @@ impl PartExtractor for PlainGzipExtractor {/// `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.-fn run_plain_gzip_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {+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) {Ok(f) => f,Err(e) => {@@ -291,7 +300,7 @@ fn run_plain_gzip_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {/// Decompress every `.json.gz` member of a zip archive in natural-sorted order,/// streaming blocks to `tx`. A trailing newline is appended after each non-empty/// member that didn't end with one, matching the previous concatenation behavior.-fn run_zip_gzip_json_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {+pub(crate) fn run_zip_gzip_json_producer(raw_file_path: PathBuf, tx: mpsc::Sender<Block>) {let file = match std::fs::File::open(&raw_file_path) {Ok(f) => f,Err(e) => {diff --git a/rust/batch-import-worker/src/job/config.rs b/rust/batch-import-worker/src/job/config.rsindex 7247672b4d6c..c7f0084e5063 100644--- a/rust/batch-import-worker/src/job/config.rs+++ b/rust/batch-import-worker/src/job/config.rs@@ -8,7 +8,10 @@ use fernet::MultiFernet;use serde::{Deserialize, Serialize};use serde_json::Value;+use uuid::Uuid;+use crate::{+ config::StagingBackendKind,context::AppContext,emit::{capture::CaptureEmitter, kafka::KafkaEmitter, Emitter, FileEmitter, NoOpEmitter,@@ -22,8 +25,9 @@ use crate::{s3::S3Source,s3_gzip::GzipS3Source,url_list::UrlList,- DataSource,+ DataSource, RemoteStaging,},+ staging::{StagingBackend, TempBucketBackend},};use super::model::JobModel;@@ -193,9 +197,26 @@ impl SourceConfig {secrets: &JobSecrets,context: Arc<AppContext>,is_restarting: bool,+ job_id: Uuid,) -> Result<Box<dyn DataSource>, Error> {let staging_dir = context.config.staging_dir();let staging_max_bytes = context.config.staging_dir_max_bytes;+ // The effective ceiling is always non-zero in temp-bucket mode: it caps the+ // decompressed part size just below the S3 multipart wall so an oversized+ // part pauses with the actionable message instead of an opaque S3 error.+ // Irrelevant in local mode (no RemoteStaging is constructed).+ let staged_plaintext_max_bytes = context.config.effective_plaintext_ceiling();+ // Fail fast on invalid staging config (e.g. temp_bucket without a bucket name)+ // before any source work starts. Only the compressed sources stage plaintext,+ // so only they receive the backend.+ let staging_backend: Option<Arc<dyn StagingBackend>> =+ match context.config.staging_backend()? {+ StagingBackendKind::LocalDisk => None,+ StagingBackendKind::TempBucket => Some(Arc::new(+ TempBucketBackend::from_config(&context.config, format!("job-{job_id}"))+ .await?,+ )),+ };match self {SourceConfig::Folder(config) => Ok(Box::new(config.create_source().await?)),SourceConfig::UrlList(config) => Ok(Box::new(@@ -206,12 +227,24 @@ impl SourceConfig {SourceConfig::S3(config) => Ok(Box::new(config.create_source(secrets).await?)),SourceConfig::S3Gzip(config) => Ok(Box::new(config- .create_gzip_source(secrets, staging_dir, staging_max_bytes)+ .create_gzip_source(+ secrets,+ staging_dir,+ staging_max_bytes,+ staging_backend,+ staged_plaintext_max_bytes,+ ).await?,)),SourceConfig::DateRangeExport(config) => Ok(Box::new(config- .create_source(secrets, staging_dir, staging_max_bytes)+ .create_source(+ secrets,+ staging_dir,+ staging_max_bytes,+ staging_backend,+ staged_plaintext_max_bytes,+ ).await?,)),}@@ -429,10 +462,18 @@ impl S3SourceConfig {secrets: &JobSecrets,staging_dir: PathBuf,staging_max_bytes: u64,+ staging_backend: Option<Arc<dyn StagingBackend>>,+ staged_plaintext_max_bytes: u64,) -> Result<GzipS3Source, Error> {let builder = self.build_s3_config(secrets)?;let client = aws_sdk_s3::Client::from_conf(builder.build());+ let remote_staging = staging_backend.map(|backend| RemoteStaging {+ backend,+ extractor_type: ExtractorType::PlainGzip,+ max_plaintext_bytes: staged_plaintext_max_bytes,+ });+Ok(GzipS3Source::new(client,self.bucket.clone(),@@ -440,6 +481,7 @@ impl S3SourceConfig {ExtractorType::PlainGzip.create_extractor(),staging_dir,staging_max_bytes,+ remote_staging,))}}@@ -449,6 +491,8 @@ impl DateRangeExportSourceConfig {secrets: &JobSecrets,staging_dir: PathBuf,staging_max_bytes: u64,+ staging_backend: Option<Arc<dyn StagingBackend>>,+ staged_plaintext_max_bytes: u64,) -> Result<DateRangeExportSource, Error> {let auth_config = match &self.auth {AuthSourceConfig::None => AuthConfig::None,@@ -534,6 +578,12 @@ impl DateRangeExportSourceConfig {let extractor = self.extractor_type.create_extractor();+ let remote_staging = staging_backend.map(|backend| RemoteStaging {+ backend,+ extractor_type: self.extractor_type.clone(),+ max_plaintext_bytes: staged_plaintext_max_bytes,+ });+DateRangeExportSource::builder(self.base_url.clone(),self.start,@@ -549,6 +599,7 @@ impl DateRangeExportSourceConfig {.with_date_format(self.date_format.clone()).with_headers(self.headers.clone()).with_staging_max_bytes(staging_max_bytes)+ .with_remote_staging(remote_staging).build()}diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rsindex a35687c95035..a1532032e949 100644--- a/rust/batch-import-worker/src/job/mod.rs+++ b/rust/batch-import-worker/src/job/mod.rs@@ -15,7 +15,8 @@ use crate::{emit::Emitter,error::{extract_retry_after_from_error, get_user_message, is_rate_limited_error, is_timeout_error,- is_transient_network_error, is_transient_server_error, UserError,+ is_transient_network_error, is_transient_object_store_error, is_transient_server_error,+ UserError,},extractor::detect_compression_magic,job::{backoff::format_backoff_messages, config::SinkConfig},@@ -86,6 +87,18 @@ fn decide_on_error(status_msg,display_msg,}+ } else if is_transient_object_store_error(err) {+ // Temp-bucket staging I/O that outlived the S3 client's internal retries+ // (throttling, 5xx, timeouts, transport). Backoff and retry rather than+ // pausing a customer job over infrastructure weather.+ let delay = policy.next_delay(current_attempt);+ let (status_msg, display_msg) =+ format_backoff_messages(current_date_range, delay, "Temporary storage error");+ ErrorHandlingDecision::Backoff {+ delay,+ status_msg,+ display_msg,+ }} else {// Use the full error chain for developer-facing messagelet error_msg = match current_date_range {@@ -324,9 +337,15 @@ pub(crate) async fn select_and_fetch_next_chunk(// that pauses the job.if !is_last_chunk && chunk_bytes == chunk_size && parsed.consumed <= 1 && parsed.data.is_empty(){- return Err(Error::from(UserError::new(format!(- "A single record in part {} exceeds the maximum chunk size ({chunk_size} bytes) \- and cannot be processed; split the oversized record into smaller ones.",+ // Public message stays free of internal tuning values (chunk_size); the root+ // error carries them for status_message and logs.+ return Err(Error::msg(format!(+ "single record exceeds chunk_size={chunk_size} in part {} at offset {}",+ next_part.key, next_part.current_offset+ ))+ .context(UserError::new(format!(+ "A single record in part {} is too large to process. Split the oversized \+ record into smaller records and re-run this date range or file.",next_part.key))));}@@ -346,6 +365,38 @@ pub(crate) async fn select_and_fetch_next_chunk(Ok(Some((key, parsed, true)))}+/// Free a committed part's staging once it is fully consumed, best-effort.+///+/// Called from `do_commit` after `complete_commit` persists the advanced offsets. Checks+/// the *persisted* model view (not the in-memory fetch state, which runs one iteration+/// ahead) so staging is only freed for parts whose completion is durable. Failures are+/// logged and counted, never propagated: a missed delete leaks only transient storage,+/// reclaimed by `cleanup_after_job` and (for the temp bucket) the bucket TTL.+pub(crate) async fn cleanup_committed_part_if_done(+ source: &dyn DataSource,+ model: &Mutex<JobModel>,+ key: &str,+) {+ let part_done = {+ let model = model.lock().await;+ model+ .state+ .as_ref()+ .and_then(|state| state.parts.iter().find(|p| p.key == key))+ .is_some_and(|part| part.is_done())+ };+ if !part_done {+ return;+ }+ match source.cleanup_key(key).await {+ Ok(()) => crate::metrics::part_cleanup("ok"),+ Err(e) => {+ warn!("Failed to clean up staging for committed part {key}: {e:#}");+ crate::metrics::part_cleanup("error");+ }+ }+}+pub struct Job {pub context: Arc<AppContext>,handle: Handle,@@ -394,7 +445,7 @@ impl Job {let source = model.import_config.source- .construct(&model.secrets, context.clone(), is_restarting)+ .construct(&model.secrets, context.clone(), is_restarting, model.id).await.with_context(|| "Failed to construct data source for job".to_string())?;@@ -476,9 +527,12 @@ impl Job {if let Err(e) = next_commit {// If we fail to commit, we just log and bail out - the job will be paused if it needs to be,- // but this pod should restart, in case it's sink is in some bad state+ // but this pod should restart, in case it's sink is in some bad state.+ // The failure is sink-side and the offset was rolled back, so keep the+ // staged remote data: the resume re-reads the byte-identical chunk+ // instead of re-downloading from an origin that may have changed.error!("Failed to commit chunk: {:?}", e);- if let Err(cleanup_err) = self.source.cleanup_after_job().await {+ if let Err(cleanup_err) = self.source.release_job_resources().await {warn!("Failed to cleanup after commit failure: {:?}", cleanup_err);}return Err(e);@@ -495,9 +549,9 @@ impl Job {return Ok(None);}Err(e) => {- if let Err(e) = self.source.cleanup_after_job().await {- warn!("Failed to cleanup after job: {:?}", e);- }+ // Cleanup is deferred until after classification below: transient+ // interruptions keep remote staging for the resume to attach to,+ // while source-side pauses sweep it for a clean re-download.let user_facing_error_message = get_user_message(&e);let current_date_range = {let state = self.state.lock().await;@@ -526,6 +580,12 @@ impl Job {status_msg,display_msg,} => {+ // Transient (or transient-persisted, below): keep staged+ // remote parts so the resume attaches without re-hitting an+ // origin that is likely still rate-limited or flaky.+ if let Err(cleanup_err) = self.source.release_job_resources().await {+ warn!("Failed to release job resources: {:?}", cleanup_err);+ }if should_pause_due_to_max_attempts(next_attempt,self.context.config.backoff_max_attempts,@@ -577,6 +637,12 @@ impl Job {error_msg,display_msg,} => {+ // Source-side pause: a human intervenes and may fix the+ // source file in place, so sweep staged data — the resume+ // must re-download a clean copy, never attach to a stale one.+ if let Err(cleanup_err) = self.source.cleanup_after_job().await {+ warn!("Failed to cleanup after job: {:?}", cleanup_err);+ }let mut model = self.model.lock().await;error!(job_id = %model.id,@@ -674,6 +740,20 @@ impl Job {info!(job_id = %self.job_id, "Finishing PG part commit");self.complete_commit().await?;info!(job_id = %self.job_id, "Committed part {} consumed {} bytes", key, parsed.consumed);++ // The committed part may now be fully consumed: free its staging eagerly and only+ // after its offsets are durable. Safe against concurrent reads: the in-memory state+ // marked this part done no later than the iteration before this commit (offsets+ // advance at fetch time, and the completion short-circuits - size-discovery and+ // empty-chunk - mark a part done in the same iteration that produces their+ // synthetic zero-consumed checkpoint), so the read loop can never re-select it.+ // Those synthetic checkpoints can make the hook fire a second time for a part+ // whose data commit already cleaned up; cleanup_key is idempotent, so the double+ // call is a tolerated no-op rather than a correctness issue. A rollback or a crash+ // between the two commit stages returns/aborts before reaching this point,+ // preserving the staged data for the byte-identical re-read on resume.+ cleanup_committed_part_if_done(self.source.as_ref(), &self.model, &key).await;+info!(job_id = %self.job_id, "Sleeping for {:?}", to_sleep);tokio::select! {_ = tokio::time::sleep(to_sleep) => {},@@ -948,6 +1028,74 @@ mod tests {}}+ /// Build the real object_store error a temp-bucket read/stage produces for the+ /// given S3 response status (client-level retries disabled for speed).+ async fn object_store_error_with_status(status: u16) -> Error {+ use object_store::ObjectStoreExt;+ let server = MockServer::start();+ let _mock = server.mock(|when, then| {+ when.any_request();+ then.status(status);+ });+ let store = object_store::aws::AmazonS3Builder::new()+ .with_bucket_name("b")+ .with_endpoint(server.base_url())+ .with_region("us-east-1")+ .with_allow_http(true)+ .with_virtual_hosted_style_request(false)+ .with_access_key_id("k")+ .with_secret_access_key("s")+ .with_retry(object_store::RetryConfig {+ max_retries: 0,+ retry_timeout: std::time::Duration::from_secs(5),+ ..Default::default()+ })+ .build()+ .unwrap();+ let err = store+ .get(&object_store::path::Path::from("k.data"))+ .await+ .unwrap_err();+ Error::from(err).context("Failed to read staged object for key: k")+ }++ fn policy_for_test() -> crate::job::backoff::BackoffPolicy {+ crate::job::backoff::BackoffPolicy::new(+ std::time::Duration::from_secs(60),+ 2.0,+ std::time::Duration::from_secs(3600),+ )+ }++ #[tokio::test]+ async fn test_decide_on_error_backoff_for_transient_storage_error() {+ // A temp-bucket 503 that outlived the S3 client's internal retries must+ // reach job backoff, not pause a customer job over infrastructure weather.+ let err = object_store_error_with_status(503).await;+ let decision = decide_on_error(&err, None, policy_for_test(), 0, "unused");+ match decision {+ ErrorHandlingDecision::Backoff { status_msg, .. } => {+ assert!(+ status_msg.contains("Temporary storage error"),+ "unexpected status: {status_msg}"+ );+ }+ other => panic!("expected backoff for storage 503, got {other:?}"),+ }+ }++ #[tokio::test]+ async fn test_decide_on_error_pause_for_permanent_storage_error() {+ // 403 (IAM misconfig) must pause visibly: with unlimited backoff attempts,+ // classifying it transient would retry it invisibly forever.+ let err = object_store_error_with_status(403).await;+ let decision = decide_on_error(&err, None, policy_for_test(), 0, "Storage error");+ assert!(+ matches!(decision, ErrorHandlingDecision::Pause { .. }),+ "expected pause for storage 403, got {decision:?}"+ );+ }+#[tokio::test]async fn test_retry_after_overrides_backoff() {let server = MockServer::start();@@ -1318,11 +1466,13 @@ mod tests {/// Build a source spanning `hours` one-hour intervals (one key per hour),/// all served the same body by the mock, decoded with `extractor`.- pub(super) fn build_source_with_extractor(+ /// `remote` selects temp-bucket staging; `None` is the local streaming path.+ pub(super) fn build_source_with(base_url: String,staging: &Path,hours: u32,extractor: ExtractorType,+ remote: Option<crate::source::RemoteStaging>,) -> 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();@@ -1337,12 +1487,22 @@ mod tests {.with_auth(AuthConfig::None).with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string()).with_headers(HashMap::new())+ .with_remote_staging(remote).build().unwrap()}+ pub(super) fn build_source_with_extractor(+ base_url: String,+ staging: &Path,+ hours: u32,+ extractor: ExtractorType,+ ) -> DateRangeExportSource {+ build_source_with(base_url, staging, hours, extractor, None)+ }+fn build_source(base_url: String, staging: &Path, hours: u32) -> DateRangeExportSource {- build_source_with_extractor(base_url, staging, hours, ExtractorType::PlainGzip)+ build_source_with(base_url, staging, hours, ExtractorType::PlainGzip, None)}/// A transform that consumes the whole chunk and emits no events. The@@ -1749,16 +1909,26 @@ mod tests {.await;let err = result.expect_err("oversized record must fail fast, not crawl");- // Actionable, user-facing message so the job pauses (not a transient retry).+ // Actionable, user-facing message so the job pauses (not a transient retry),+ // free of internal tuning values; the internal chain keeps chunk_size.let user_msg = crate::error::get_user_message(&err);assert!(- user_msg.contains("exceeds the maximum chunk size"),+ user_msg.contains("too large to process"),"unexpected message: {user_msg}");+ assert!(+ !user_msg.contains("chunk_size") && !user_msg.contains("1024"),+ "public message must not leak internal tuning values: {user_msg}"+ );+ assert!(+ format!("{err:#}").contains("chunk_size=1024"),+ "internal chain must carry the limit detail: {err:#}"+ );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));+ assert!(!crate::error::is_transient_object_store_error(&err));}#[tokio::test]@@ -1817,6 +1987,341 @@ mod tests {"all parts' .raw files must be cleaned up by the read loop alone");}++ /// The real read loop over a remote-staged (temp-bucket) source: parts stage on+ /// first touch, sizes are known immediately (no lazy-size pass), every part+ /// completes with the parser consuming real newline-delimited records, and no+ /// `.raw` survives staging (deleted right after a successful ingest).+ #[tokio::test]+ async fn test_remote_staged_source_completes_all_parts_through_read_loop() {+ use crate::source::RemoteStaging;+ use crate::staging::TempBucketBackend;+ use object_store::memory::InMemory;++ let server = MockServer::start();+ let mut body = String::new();+ for i in 0..500 {+ 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 remote = RemoteStaging {+ backend: Arc::new(TempBucketBackend::new(+ Arc::new(InMemory::new()),+ "staging/",+ "job-LOOP",+ )),+ extractor_type: ExtractorType::PlainGzip,+ max_plaintext_bytes: 0,+ };+ let source = build_source_with(+ server.url("/export"),+ staging.path(),+ 2,+ ExtractorType::PlainGzip,+ Some(remote),+ );+ source.prepare_for_job().await.unwrap();+ let keys = source.keys().await.unwrap();+ assert_eq!(keys.len(), 2);++ let state = Mutex::new(job_state(&keys));+ let model = Mutex::new(dummy_model(job_state(&keys)));+ // Real newline parser: proves record reassembly across chunk boundaries+ // works over ranged backend reads, not just a consume-everything stub.+ let transform = newline_consumed_transform();++ loop {+ let next = select_and_fetch_next_chunk(+ &state,+ &model,+ &source,+ &transform,+ 1024,+ Uuid::now_v7(),+ )+ .await+ .unwrap();+ // A successful stage never leaves a .raw behind.+ assert_eq!(count_raw_files(staging.path()), 0);+ if next.is_none() {+ break;+ }+ }++ let final_state = state.lock().await;+ for part in &final_state.parts {+ assert!(part.is_done(), "part {} must complete", part.key);+ assert_eq!(part.total_size, Some(body.len() as u64));+ }+ }++ /// Wraps a source to observe (and optionally fail) `cleanup_key` calls, so the+ /// post-commit hook's exactly-once / best-effort behavior is observable.+ struct SpySource<S> {+ inner: S,+ cleanup_calls: std::sync::atomic::AtomicUsize,+ fail_cleanup: bool,+ }++ impl<S> SpySource<S> {+ fn new(inner: S, fail_cleanup: bool) -> Self {+ Self {+ inner,+ cleanup_calls: std::sync::atomic::AtomicUsize::new(0),+ fail_cleanup,+ }+ }++ fn cleanups(&self) -> usize {+ self.cleanup_calls.load(std::sync::atomic::Ordering::SeqCst)+ }+ }++ #[async_trait::async_trait]+ impl<S: DataSource> DataSource for SpySource<S> {+ async fn keys(&self) -> Result<Vec<String>, Error> {+ self.inner.keys().await+ }+ async fn size(&self, key: &str) -> Result<Option<u64>, Error> {+ self.inner.size(key).await+ }+ async fn get_chunk(&self, key: &str, offset: u64, size: u64) -> Result<Vec<u8>, Error> {+ self.inner.get_chunk(key, offset, size).await+ }+ async fn prepare_key(&self, key: &str) -> Result<(), Error> {+ self.inner.prepare_key(key).await+ }+ async fn prepare_for_job(&self) -> Result<(), Error> {+ self.inner.prepare_for_job().await+ }+ async fn cleanup_after_job(&self) -> Result<(), Error> {+ self.inner.cleanup_after_job().await+ }+ async fn cleanup_key(&self, key: &str) -> Result<(), Error> {+ self.cleanup_calls+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ if self.fail_cleanup {+ return Err(Error::msg("simulated cleanup failure"));+ }+ self.inner.cleanup_key(key).await+ }+ }++ fn remote_staging_for(+ store: Arc<object_store::memory::InMemory>,+ ) -> crate::source::RemoteStaging {+ crate::source::RemoteStaging {+ backend: Arc::new(crate::staging::TempBucketBackend::new(+ store, "staging/", "job-HOOK",+ )),+ extractor_type: ExtractorType::PlainGzip,+ max_plaintext_bytes: 0,+ }+ }++ /// Drive the real fetch loop over a remote source, mirroring do_commit's+ /// post-complete sequence per checkpoint: persist the offset advance to the model,+ /// then invoke the hook. Returns the spy so callers can assert cleanup counts.+ async fn run_loop_with_hook(+ source: &SpySource<DateRangeExportSource>,+ keys: &[String],+ ) -> (Mutex<JobModel>, usize) {+ let state = Mutex::new(job_state(keys));+ let model = Mutex::new(dummy_model(job_state(keys)));+ let transform = newline_consumed_transform();+ let mut commits = 0usize;+ loop {+ let next = select_and_fetch_next_chunk(+ &state,+ &model,+ source,+ &transform,+ 1024,+ Uuid::now_v7(),+ )+ .await+ .unwrap();+ let Some((key, parsed, _)) = next else { break };+ {+ let mut model = model.lock().await;+ model+ .state+ .as_mut()+ .unwrap()+ .advance_part_offset(&key, parsed.consumed as u64)+ .unwrap();+ }+ cleanup_committed_part_if_done(source, &model, &key).await;+ commits += 1;+ }+ (model, commits)+ }++ #[tokio::test]+ async fn test_post_commit_hook_frees_each_remote_part_exactly_once() {+ let server = MockServer::start();+ let mut body = String::new();+ for i in 0..500 {+ 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 store = Arc::new(object_store::memory::InMemory::new());+ let remote = remote_staging_for(Arc::clone(&store));+ let backend = Arc::clone(&remote.backend);+ let source = SpySource::new(+ build_source_with(+ server.url("/export"),+ staging.path(),+ 2,+ ExtractorType::PlainGzip,+ Some(remote),+ ),+ false,+ );+ source.prepare_for_job().await.unwrap();+ let keys = source.keys().await.unwrap();++ let (_model, commits) = run_loop_with_hook(&source, &keys).await;++ // Multiple commits per part (small chunk size), but exactly one cleanup per+ // part: the hook fires only on the commit that makes the part done.+ assert!(commits > keys.len(), "expected multiple commits per part");+ assert_eq!(source.cleanups(), keys.len());+ for key in &keys {+ assert_eq!(+ backend.size(key).await.unwrap(),+ None,+ "staged object for a committed part must be deleted"+ );+ }+ }++ #[tokio::test]+ async fn test_post_commit_hook_preserves_staging_until_part_is_done() {+ // Encodes the rollback / crash-between-commit-stages guarantee: the hook only+ // fires for a durably-done part, so a part mid-flight (or with its offset+ // reverted) keeps its staged object for the byte-identical re-read.+ let server = MockServer::start();+ let body = b"{\"event\":\"a\"}\n{\"event\":\"b\"}\n";+ let _mock = server.mock(|when, then| {+ when.method(Method::GET).path("/export");+ then.status(200).body(gzip_bytes(body));+ });++ let staging = TempDir::new().unwrap();+ let store = Arc::new(object_store::memory::InMemory::new());+ let remote = remote_staging_for(Arc::clone(&store));+ let backend = Arc::clone(&remote.backend);+ let source = SpySource::new(+ build_source_with(+ server.url("/export"),+ staging.path(),+ 1,+ ExtractorType::PlainGzip,+ Some(remote),+ ),+ false,+ );+ source.prepare_for_job().await.unwrap();+ let key = source.keys().await.unwrap().remove(0);+ source.prepare_key(&key).await.unwrap();++ let model = Mutex::new(dummy_model(job_state(std::slice::from_ref(&key))));+ {+ let mut model = model.lock().await;+ let state = model.state.as_mut().unwrap();+ state.parts[0].total_size = Some(body.len() as u64);+ // Partially consumed (e.g. after a rollback reverted a later advance).+ state.parts[0].current_offset = 14;+ }++ cleanup_committed_part_if_done(&source, &model, &key).await;+ assert_eq!(+ source.cleanups(),+ 0,+ "hook must not fire for a part mid-flight"+ );+ assert_eq!(+ backend.size(&key).await.unwrap(),+ Some(body.len() as u64),+ "staged object must survive for the re-read"+ );+ }++ #[tokio::test]+ async fn test_post_commit_hook_cleanup_failure_is_best_effort() {+ let server = MockServer::start();+ let body = b"{\"event\":\"a\"}\n";+ let _mock = server.mock(|when, then| {+ when.method(Method::GET).path("/export");+ then.status(200).body(gzip_bytes(body));+ });++ let staging = TempDir::new().unwrap();+ let store = Arc::new(object_store::memory::InMemory::new());+ let remote = remote_staging_for(Arc::clone(&store));+ let source = SpySource::new(+ build_source_with(+ server.url("/export"),+ staging.path(),+ 1,+ ExtractorType::PlainGzip,+ Some(remote),+ ),+ true, // cleanup_key always fails+ );+ source.prepare_for_job().await.unwrap();+ let keys = source.keys().await.unwrap();++ // The loop must run to completion despite every cleanup failing.+ let (_model, _commits) = run_loop_with_hook(&source, &keys).await;+ assert_eq!(source.cleanups(), 1, "hook attempted the cleanup");+ }++ #[tokio::test]+ async fn test_post_commit_hook_empty_part_cleanup_is_no_op() {+ let server = MockServer::start();+ let _mock = server.mock(|when, then| {+ when.method(Method::GET).path("/export");+ then.status(404);+ });++ let staging = TempDir::new().unwrap();+ let store = Arc::new(object_store::memory::InMemory::new());+ let remote = remote_staging_for(Arc::clone(&store));+ let backend = Arc::clone(&remote.backend);+ let source = SpySource::new(+ build_source_with(+ server.url("/export"),+ staging.path(),+ 1,+ ExtractorType::PlainGzip,+ Some(remote),+ ),+ false,+ );+ source.prepare_for_job().await.unwrap();+ let keys = source.keys().await.unwrap();++ let (model, _commits) = run_loop_with_hook(&source, &keys).await;++ // The empty part commits to done (0 == 0), the hook fires, and the delete of+ // the (empty) staged object succeeds; a second invocation is a no-op.+ assert_eq!(source.cleanups(), 1);+ assert_eq!(backend.size(&keys[0]).await.unwrap(), None);+ cleanup_committed_part_if_done(&source, &model, &keys[0]).await;+ assert_eq!(source.cleanups(), 2, "double cleanup is tolerated");+ }}/// A part whose first bytes are a known compression magic is still compressed@@ -1997,7 +2502,7 @@ mod tests {/// 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> {+ pub(super) 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();@@ -2206,4 +2711,216 @@ mod tests {}}}++ /// Remote (temp-bucket) staging must satisfy the same read-loop contracts the+ /// local streaming path is pinned to above and in `empty_part_completion_tests`:+ /// empty exports complete, trailing blank lines complete, and parts already done+ /// (including offsets overshot by a past worker bug) are skipped without ever+ /// touching the origin or the backend. All drive the real+ /// `select_and_fetch_next_chunk` loop over a temp-bucket-staged source.+ mod remote_read_loop_parity_tests {+ use super::empty_part_completion_tests::zip_without_json_members;+ use super::staging_cleanup_invariant_tests::{+ build_source_with, drive_loop_to_completion, dummy_model, gzip_bytes, job_state,+ newline_consumed_transform,+ };+ use super::*;+ use crate::extractor::ExtractorType;+ use crate::source::RemoteStaging;+ use crate::staging::{StagingBackend, TempBucketBackend};+ use object_store::memory::InMemory;+ use tempfile::TempDir;++ fn remote_staging(store: Arc<InMemory>) -> (RemoteStaging, Arc<TempBucketBackend>) {+ let backend = Arc::new(TempBucketBackend::new(store, "staging/", "job-PARITY"));+ let backend_dyn: Arc<dyn StagingBackend> = backend.clone();+ (+ RemoteStaging {+ backend: backend_dyn,+ extractor_type: ExtractorType::PlainGzip,+ max_plaintext_bytes: 0,+ },+ backend,+ )+ }++ /// Remote counterpart of `test_empty_export_completes_part`: every empty+ /// export shape stages an empty object and completes the part.+ #[tokio::test]+ async fn test_remote_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 (mut remote, backend) = remote_staging(Arc::new(InMemory::new()));+ remote.extractor_type = extractor.clone();+ let source = build_source_with(+ server.url("/export"),+ staging.path(),+ 1,+ extractor,+ Some(remote),+ );+ 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}'");+ // The empty object is durably staged: a resume attaches to it+ // instead of re-downloading from the origin.+ assert_eq!(+ backend.size(&keys[0]).await.unwrap(),+ Some(0),+ "case '{name}' must stage an empty object"+ );+ }+ }++ /// Remote counterpart of `test_part_with_trailing_blank_lines_completes`:+ /// blank trailing content in the staged bytes is consumed over ranged+ /// backend reads exactly as over the local stream.+ #[tokio::test]+ async fn test_remote_part_with_trailing_blank_lines_completes() {+ 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 (remote, _backend) = remote_staging(Arc::new(InMemory::new()));+ let source = build_source_with(+ server.url("/export"),+ staging.path(),+ 1,+ ExtractorType::PlainGzip,+ Some(remote),+ );+ 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,+ (total_size as usize / 1024) + 10,+ )+ .await+ .unwrap();++ assert!(completed, "trailing blank lines must not stall the part");+ assert_eq!(state.lock().await.parts[0].current_offset, total_size);+ }++ /// Remote counterpart of `test_poisoned_part_with_overshot_offset_self_heals`:+ /// a part whose stored offset overshot its total (a past worker bug) is+ /// skipped as done without being staged or re-downloaded - `is_done` is+ /// checked before any prepare work, so the poisoned part costs nothing.+ #[tokio::test]+ async fn test_remote_poisoned_part_skipped_without_staging() {+ 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 (remote, backend) = remote_staging(Arc::new(InMemory::new()));+ let source = build_source_with(+ server.url("/export"),+ staging.path(),+ 2,+ ExtractorType::PlainGzip,+ Some(remote),+ );+ source.prepare_for_job().await.unwrap();+ let keys = source.keys().await.unwrap();+ assert_eq!(keys.len(), 2);++ 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 completed = drive_loop_to_completion(&state, &model, &source, &transform, 1024, 20)+ .await+ .unwrap();++ assert!(completed, "job with an overshot part must finish the rest");+ let state = state.lock().await;+ assert_eq!(+ state.parts[0].current_offset, 25_328_072,+ "poisoned part must be skipped untouched"+ );+ assert_eq!(state.parts[1].total_size, Some(body.len() as u64));+ assert_eq!(+ backend.size(&keys[0]).await.unwrap(),+ None,+ "poisoned part must never be staged"+ );+ assert_eq!(+ mock.hits(),+ 1,+ "only the healthy part may hit the origin (one download)"+ );+ }+ }}diff --git a/rust/batch-import-worker/src/main.rs b/rust/batch-import-worker/src/main.rsindex a0679ab6bf14..fd1315dfc02a 100644--- a/rust/batch-import-worker/src/main.rs+++ b/rust/batch-import-worker/src/main.rs@@ -218,9 +218,12 @@ pub async fn main() -> Result<(), Error> {while let Some(job) = next_step {if job_handle.is_shutting_down() {- info!("Shutting down, cleaning up in-flight job before dropping");- if let Err(e) = job.source.cleanup_after_job().await {- warn!("Failed to cleanup job source on shutdown: {e:?}");+ // Keep remote staging on shutdown (deploys included): the pod+ // that re-claims the job attaches to staged parts instead of+ // re-downloading. Local temp files are still freed.+ info!("Shutting down, releasing in-flight job resources before dropping");+ if let Err(e) = job.source.release_job_resources().await {+ warn!("Failed to release job source resources on shutdown: {e:?}");}break;}diff --git a/rust/batch-import-worker/src/metrics.rs b/rust/batch-import-worker/src/metrics.rsindex b87eab73cb37..009ddefe7a2f 100644--- a/rust/batch-import-worker/src/metrics.rs+++ b/rust/batch-import-worker/src/metrics.rs@@ -5,6 +5,14 @@ pub const STAGING_SWEEP_REMOVED: &str = "batch_import_staging_sweep_removed_totapub const STAGING_DIR_BYTES: &str = "batch_import_staging_dir_bytes";pub const STAGING_GUARD_TRIPPED: &str = "batch_import_staging_guard_tripped_total";pub const ACTIVE_JOBS: &str = "batch_import_active_jobs";+pub const TEMP_BUCKET_STAGE_BYTES: &str = "batch_import_temp_bucket_stage_bytes";+pub const TEMP_BUCKET_STAGE_DURATION_SECONDS: &str =+ "batch_import_temp_bucket_stage_duration_seconds";+pub const TEMP_BUCKET_READ_DURATION_SECONDS: &str =+ "batch_import_temp_bucket_read_duration_seconds";+pub const STAGED_PLAINTEXT_CEILING_TRIPPED: &str =+ "batch_import_staged_plaintext_ceiling_tripped_total";+pub const PART_CLEANUP_TOTAL: &str = "batch_import_part_cleanup_total";use metrics::{counter, gauge, histogram};@@ -35,3 +43,25 @@ pub fn staging_guard_tripped() {pub fn active_jobs(count: f64) {gauge!(ACTIVE_JOBS).set(count);}++/// Record a completed temp-bucket part upload: total bytes staged and wall-clock duration.+pub fn temp_bucket_part_staged(bytes: u64, duration_secs: f64) {+ histogram!(TEMP_BUCKET_STAGE_BYTES).record(bytes as f64);+ histogram!(TEMP_BUCKET_STAGE_DURATION_SECONDS).record(duration_secs);+}++/// Record the latency of a single ranged GET against the temp bucket.+pub fn temp_bucket_read(duration_secs: f64) {+ histogram!(TEMP_BUCKET_READ_DURATION_SECONDS).record(duration_secs);+}++/// Count a part that breached STAGED_PLAINTEXT_MAX_BYTES and paused the job.+pub fn staged_plaintext_ceiling_tripped() {+ counter!(STAGED_PLAINTEXT_CEILING_TRIPPED).increment(1);+}++/// Count post-commit staging cleanup of a completed part, by outcome ("ok" / "error").+/// A failed cleanup leaks only transient storage (reclaimed by job cleanup / bucket TTL).+pub fn part_cleanup(outcome: &'static str) {+ counter!(PART_CLEANUP_TOTAL, "outcome" => outcome).increment(1);+}diff --git a/rust/batch-import-worker/src/source/date_range_export.rs b/rust/batch-import-worker/src/source/date_range_export.rsindex 2ebd9535fdf4..0031be9dbfeb 100644--- a/rust/batch-import-worker/src/source/date_range_export.rs+++ b/rust/batch-import-worker/src/source/date_range_export.rs@@ -9,7 +9,7 @@ use tempfile::TempDir;use tokio::{fs::File, io::AsyncWriteExt, sync::Mutex};use tracing::{debug, info, warn};-use super::{read_prepared_chunk, remove_prepared_key, DataSource, PreparedPart};+use super::{read_prepared_chunk, remove_prepared_key, DataSource, PreparedPart, RemoteStaging};use crate::error::{RateLimitedError, ToUserError};use crate::extractor::PartExtractor;use crate::staging::StagingGuard;@@ -88,6 +88,7 @@ pub struct DateRangeExportSourceBuilder {date_format: String,headers: HashMap<String, String>,staging_max_bytes: u64,+ remote_staging: Option<RemoteStaging>,}impl DateRangeExportSourceBuilder {@@ -115,6 +116,7 @@ impl DateRangeExportSourceBuilder {date_format: "%Y-%m-%dT%H:%M:%SZ".to_string(),headers: HashMap::new(),staging_max_bytes: 0,+ remote_staging: None,}}@@ -123,6 +125,14 @@ impl DateRangeExportSourceBuilder {self}+ /// Stage decompressed part plaintext in a remote backend (temp bucket) instead of+ /// serving reads from the local streaming machinery. `None` (default) keeps the+ /// local path unchanged.+ pub fn with_remote_staging(mut self, remote_staging: Option<RemoteStaging>) -> Self {+ self.remote_staging = remote_staging;+ self+ }+pub fn with_query_params(mut self, start_qp: String, end_qp: String) -> Self {self.start_qp = start_qp;self.end_qp = end_qp;@@ -191,6 +201,7 @@ impl DateRangeExportSourceBuilder {extractor: self.extractor,staging_dir: self.staging_dir,staging_max_bytes: self.staging_max_bytes,+ remote_staging: self.remote_staging,temp_dir: Arc::new(Mutex::new(None)),prepared_keys: Arc::new(Mutex::new(HashMap::new())),})@@ -211,6 +222,7 @@ pub struct DateRangeExportSource {pub end_qp: String,staging_dir: PathBuf,staging_max_bytes: u64,+ remote_staging: Option<RemoteStaging>,temp_dir: Arc<Mutex<Option<TempDir>>>,prepared_keys: Arc<Mutex<HashMap<String, PreparedPart>>>,auth_config: AuthConfig,@@ -312,12 +324,12 @@ impl DateRangeExportSource {// To support exporting directly from sources that do not provide a byte seekable interface, we need to create// that byte seekable interface ourselves- // This method streams the compressed data from the source into a temp `.raw`- // file on disk, then opens a streaming decoder over it. The compressed file is- // kept and decompressed on demand as the job reads forward, so disk usage is- // bounded by the compressed size rather than the (potentially much larger)- // decompressed size.- async fn download_and_prepare_part_data(&self, key: &str) -> Result<PreparedPart, Error> {+ // This method streams the compressed data from the source into a temp `.raw` file on+ // disk and returns its path (`None` for an empty part, e.g. a 404 interval). What+ // happens to the `.raw` depends on the staging mode: the local path opens a streaming+ // decoder over it (disk bounded by compressed size); the remote path ingests it into+ // the temp bucket and deletes it.+ async fn download_part_raw(&self, key: &str) -> Result<Option<(PathBuf, u64)>, Error> {let (start, end) = self.interval_from_key(key).ok_or_else(|| Error::msg("Invalid interval key"))?;@@ -330,16 +342,15 @@ impl DateRangeExportSource {info!("Downloading and preparing key: {}", key);// Let errors (including 429 wrapped as RateLimitedError) bubble up to job-level backoff- self.download_and_prepare_part_data_inner(key, start, end)- .await+ self.download_part_raw_inner(key, start, end).await}- async fn download_and_prepare_part_data_inner(+ async fn download_part_raw_inner(&self,key: &str,start: DateTime<Utc>,end: DateTime<Utc>,- ) -> Result<PreparedPart, Error> {+ ) -> Result<Option<(PathBuf, u64)>, Error> {// All date range export APIs (Mixpanel, Amplitude, etc.) use inclusive date ranges,// meaning both start and end dates/times are included in the results. Our intervals// are created as semi-open [start, end), so we subtract one interval unit from the@@ -398,7 +409,7 @@ impl DateRangeExportSource {key);tokio::time::sleep(Duration::from_secs(2)).await;- return Ok(PreparedPart::empty());+ return Ok(None);}if response.status().as_u16() == 429 {@@ -468,7 +479,7 @@ 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 treat it as an empty part - mirroring the 404 branch above+ // 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".if total_bytes == 0 {@@ -479,18 +490,10 @@ impl DateRangeExportSource {raw_file_path.display());}- return Ok(PreparedPart::empty());+ return Ok(None);}- // Keep the `.raw` file and decompress on demand as the job reads forward.- let reader = self.extractor.open_reader(raw_file_path.clone());-- info!(- "Prepared key {} ({total_bytes} compressed bytes, streaming decode)",- key- );-- Ok(PreparedPart::streaming(raw_file_path, reader))+ Ok(Some((raw_file_path, total_bytes as u64)))}async fn get_chunk_from_prepared_key(@@ -501,6 +504,27 @@ impl DateRangeExportSource {) -> Result<Vec<u8>, Error> {read_prepared_chunk(&self.prepared_keys, key, offset, size).await}++ /// Free pod-local state: prepared readers/`.raw` files and the job temp dir.+ /// Clear refs first, then explicitly `close()` the temp dir to surface removal+ /// errors. Never touches remote staging.+ async fn cleanup_local_resources(&self) {+ {+ let mut prepared_keys = self.prepared_keys.lock().await;+ prepared_keys.clear();+ }+ {+ let mut temp_dir_guard = self.temp_dir.lock().await;+ if let Some(temp_dir) = temp_dir_guard.take() {+ let path = temp_dir.path().to_path_buf();+ if let Err(e) = temp_dir.close() {+ warn!("Failed to remove temp directory {}: {e}", path.display());+ } else {+ debug!("Cleaned up temp directory: {}", path.display());+ }+ }+ }+ }}#[async_trait]@@ -514,11 +538,17 @@ impl DataSource for DateRangeExportSource {}async fn size(&self, key: &str) -> Result<Option<u64>, Error> {+ if let Some(remote) = &self.remote_staging {+ return remote.backend.size(key).await;+ }let prepared_keys = self.prepared_keys.lock().await;Ok(prepared_keys.get(key).and_then(|part| part.total_size))}async fn get_chunk(&self, key: &str, offset: u64, size: u64) -> Result<Vec<u8>, Error> {+ if let Some(remote) = &self.remote_staging {+ return remote.read_chunk(key, offset, size).await;+ }let mut retries = self.retries;loop {match self.get_chunk_from_prepared_key(key, offset, size).await {@@ -560,29 +590,35 @@ impl DataSource for DateRangeExportSource {}async fn cleanup_after_job(&self) -> Result<(), Error> {- // Clear refs then explicitly close() the temp dir to surface removal errors- {- let mut prepared_keys = self.prepared_keys.lock().await;- prepared_keys.clear();- }- {- let mut temp_dir_guard = self.temp_dir.lock().await;- if let Some(temp_dir) = temp_dir_guard.take() {- let path = temp_dir.path().to_path_buf();- if let Err(e) = temp_dir.close() {- warn!("Failed to remove temp directory {}: {e}", path.display());- } else {- debug!("Cleaned up temp directory: {}", path.display());- }- }+ // Terminal: sweep any staged objects this job left in the remote backend+ // (best-effort; the bucket TTL is the final backstop), then release local+ // resources.+ if let Some(remote) = &self.remote_staging {+ remote.sweep_job().await;}+ self.cleanup_local_resources().await;debug!("Job cleanup complete");Ok(())}+ async fn release_job_resources(&self) -> Result<(), Error> {+ // Transient interruption: keep staged remote objects for the resume to+ // re-attach to; free only pod-local disk and in-memory state (the disk is+ // shared with whatever job this pod claims next).+ self.cleanup_local_resources().await;+ debug!("Job resources released (remote staging kept for resume)");+ Ok(())+ }+// We call this every time we process a chunk from a key/part// So this needs to be idempotent/a no-op when the key/part is already preparedasync fn prepare_key(&self, key: &str) -> Result<(), Error> {+ if let Some(remote) = &self.remote_staging {+ return remote+ .prepare_key(key, || self.download_part_raw(key))+ .await;+ }+{let prepared_keys = self.prepared_keys.lock().await;if prepared_keys.contains_key(key) {@@ -591,7 +627,15 @@ impl DataSource for DateRangeExportSource {}}- let prepared_part = self.download_and_prepare_part_data(key).await?;+ let prepared_part = match self.download_part_raw(key).await? {+ None => PreparedPart::empty(),+ Some((raw_file_path, total_bytes)) => {+ // Keep the `.raw` file and decompress on demand as the job reads forward.+ let reader = self.extractor.open_reader(raw_file_path.clone());+ info!("Prepared key {key} ({total_bytes} compressed bytes, streaming decode)");+ PreparedPart::streaming(raw_file_path, reader)+ }+ };{let mut prepared_keys = self.prepared_keys.lock().await;@@ -603,6 +647,9 @@ impl DataSource for DateRangeExportSource {// Should be called after we've read the last of a key/part into memory and attempt to commit itasync fn cleanup_key(&self, key: &str) -> Result<(), Error> {+ if let Some(remote) = &self.remote_staging {+ return remote.backend.cleanup_key(key).await;+ }remove_prepared_key(&self.prepared_keys, key).await;Ok(())}@@ -1530,3 +1577,463 @@ mod tests {source.cleanup_after_job().await.unwrap();}}++/// Remote (temp-bucket) staging mode: the source ingests each downloaded part into a+/// StagingBackend via the decompress pipeline and serves reads from it. These tests use+/// the real backend over `object_store::memory::InMemory` and real gzip bodies over+/// httpmock, exercising the exact production code path minus the network store.+#[cfg(test)]+mod remote_staging_tests {+ use super::*;+ use crate::extractor::ExtractorType;+ use crate::staging::TempBucketBackend;+ use chrono::{TimeZone, Utc};+ use flate2::{write::GzEncoder, Compression};+ use httpmock::{Mock, MockServer};+ use object_store::memory::InMemory;+ use object_store::ObjectStore;+ use std::io::Write;+ use std::path::Path;+ use tempfile::TempDir;++ const BODY: &[u8] = b"{\"event\":\"a\"}\n{\"event\":\"b\"}\n{\"event\":\"c\"}\n";++ fn gzip(data: &[u8]) -> Vec<u8> {+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());+ encoder.write_all(data).unwrap();+ encoder.finish().unwrap()+ }++ fn mock_export<'a>(server: &'a MockServer, body: &[u8]) -> Mock<'a> {+ let gz = gzip(body);+ server.mock(move |when, then| {+ when.method(httpmock::Method::GET).path("/export");+ then.status(200).body(gz.clone());+ })+ }++ fn remote_staging(+ store: Arc<dyn ObjectStore>,+ max_plaintext_bytes: u64,+ ) -> Option<RemoteStaging> {+ Some(RemoteStaging {+ backend: Arc::new(TempBucketBackend::new(store, "staging/", "job-TEST")),+ extractor_type: ExtractorType::PlainGzip,+ max_plaintext_bytes,+ })+ }++ /// One-hour-interval source over `hours` keys, staging remotely into `store`+ /// (or locally when `remote` is None), decoding real gzip.+ fn build_source(+ base_url: String,+ staging: &Path,+ hours: u32,+ remote: Option<RemoteStaging>,+ ) -> 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(+ base_url,+ start,+ end,+ 3600,+ ExtractorType::PlainGzip.create_extractor(),+ staging.to_path_buf(),+ )+ .with_auth(AuthConfig::None)+ .with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string())+ .with_headers(HashMap::new())+ .with_remote_staging(remote)+ .build()+ .unwrap()+ }++ /// Read a key back through `get_chunk` in small record-misaligned slices.+ async fn read_all(source: &DateRangeExportSource, key: &str, slice: u64) -> Vec<u8> {+ let total = source.size(key).await.unwrap().expect("size must be known");+ let mut out = Vec::new();+ let mut offset = 0u64;+ while offset < total {+ let chunk = source.get_chunk(key, offset, slice).await.unwrap();+ assert!(!chunk.is_empty(), "read stalled before total");+ offset += chunk.len() as u64;+ out.extend_from_slice(&chunk);+ }+ out+ }++ #[tokio::test]+ async fn remote_round_trip_multi_part_byte_identical_to_local() {+ let server = MockServer::start();+ let _mock = mock_export(&server, BODY);+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());++ let remote_src = build_source(+ server.url("/export"),+ staging.path(),+ 2,+ remote_staging(Arc::clone(&store), 0),+ );+ remote_src.prepare_for_job().await.unwrap();+ let keys = remote_src.keys().await.unwrap();+ assert_eq!(keys.len(), 2);++ // Local-mode source over the same origin is the byte-identity reference.+ let local_staging = TempDir::new().unwrap();+ let local_src = build_source(server.url("/export"), local_staging.path(), 2, None);+ local_src.prepare_for_job().await.unwrap();++ for key in &keys {+ remote_src.prepare_key(key).await.unwrap();+ local_src.prepare_key(key).await.unwrap();++ // Size is known immediately after remote staging (no lazy-size pass).+ assert_eq!(remote_src.size(key).await.unwrap(), Some(BODY.len() as u64));++ let remote_bytes = read_all(&remote_src, key, 7).await;+ assert_eq!(remote_bytes, BODY);+ // Local streaming mode discovers size lazily; drive it with the same slices.+ let mut local_bytes = Vec::new();+ let mut offset = 0u64;+ loop {+ let chunk = local_src.get_chunk(key, offset, 7).await.unwrap();+ if chunk.is_empty() {+ break;+ }+ offset += chunk.len() as u64;+ local_bytes.extend_from_slice(&chunk);+ }+ assert_eq!(remote_bytes, local_bytes, "backends must be byte-identical");++ // The .raw is deleted right after a successful stage: staging disk holds+ // nothing for this part while it is being read.+ assert_eq!(count_raw_files_in(staging.path()), 0);+ }+ }++ fn count_raw_files_in(dir: &Path) -> usize {+ let mut count = 0;+ let mut stack = vec![dir.to_path_buf()];+ while let Some(d) = stack.pop() {+ let Ok(entries) = std::fs::read_dir(&d) else {+ continue;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ stack.push(path);+ } else if path.extension().and_then(|e| e.to_str()) == Some("raw") {+ count += 1;+ }+ }+ }+ count+ }++ #[tokio::test]+ async fn remote_resume_attaches_without_redownload() {+ let server = MockServer::start();+ let mock = mock_export(&server, BODY);+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());++ let src_a = build_source(+ server.url("/export"),+ staging.path(),+ 1,+ remote_staging(Arc::clone(&store), 0),+ );+ src_a.prepare_for_job().await.unwrap();+ let key = &src_a.keys().await.unwrap()[0];+ src_a.prepare_key(key).await.unwrap();+ assert_eq!(mock.hits(), 1);++ // A fresh source (simulating a pod restart: empty in-memory state) over the same+ // backend store must attach via head and never re-hit the origin.+ let staging_b = TempDir::new().unwrap();+ let src_b = build_source(+ server.url("/export"),+ staging_b.path(),+ 1,+ remote_staging(Arc::clone(&store), 0),+ );+ src_b.prepare_for_job().await.unwrap();+ src_b.prepare_key(key).await.unwrap();+ assert_eq!(mock.hits(), 1, "resume must not re-download from origin");+ assert_eq!(src_b.size(key).await.unwrap(), Some(BODY.len() as u64));+ assert_eq!(read_all(&src_b, key, 7).await, BODY);+ }++ #[tokio::test]+ async fn flip_mid_part_resumes_byte_identical_from_offset() {+ // The no-Postgres-migration guarantee: a part half-read under local staging can+ // be resumed at the same byte offset under temp-bucket staging (and vice versa)+ // because both decode the identical plaintext stream.+ let server = MockServer::start();+ let _mock = mock_export(&server, BODY);++ // Read a prefix under local streaming mode.+ let local_staging = TempDir::new().unwrap();+ let local_src = build_source(server.url("/export"), local_staging.path(), 1, None);+ local_src.prepare_for_job().await.unwrap();+ let key = &local_src.keys().await.unwrap()[0];+ local_src.prepare_key(key).await.unwrap();+ let offset = 17u64; // deliberately mid-record+ let prefix = local_src.get_chunk(key, 0, offset).await.unwrap();+ assert_eq!(prefix.len() as u64, offset);++ // Flip: a fresh remote-mode source resumes from the persisted offset.+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let remote_src = build_source(+ server.url("/export"),+ staging.path(),+ 1,+ remote_staging(store, 0),+ );+ remote_src.prepare_for_job().await.unwrap();+ remote_src.prepare_key(key).await.unwrap();+ let suffix = remote_src+ .get_chunk(key, offset, BODY.len() as u64)+ .await+ .unwrap();++ let mut reassembled = prefix;+ reassembled.extend_from_slice(&suffix);+ assert_eq!(reassembled, BODY, "no gap or overlap across the flip");+ }++ #[tokio::test]+ async fn flip_back_to_local_mid_part_resumes_byte_identical_from_offset() {+ // The rollback direction of the flip guarantee: a part half-read under+ // temp-bucket staging resumes at the same persisted byte offset under local+ // streaming mode (STAGING_BACKEND flipped back), because both modes decode+ // the identical plaintext stream.+ let server = MockServer::start();+ let _mock = mock_export(&server, BODY);++ // Read a prefix under temp-bucket mode.+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let remote_src = build_source(+ server.url("/export"),+ staging.path(),+ 1,+ remote_staging(store, 0),+ );+ remote_src.prepare_for_job().await.unwrap();+ let key = &remote_src.keys().await.unwrap()[0];+ remote_src.prepare_key(key).await.unwrap();+ let offset = 17u64; // deliberately mid-record+ let prefix = remote_src.get_chunk(key, 0, offset).await.unwrap();+ assert_eq!(prefix.len() as u64, offset);++ // Flip back: a fresh local-mode source resumes from the persisted offset.+ let local_staging = TempDir::new().unwrap();+ let local_src = build_source(server.url("/export"), local_staging.path(), 1, None);+ local_src.prepare_for_job().await.unwrap();+ local_src.prepare_key(key).await.unwrap();+ let suffix = local_src+ .get_chunk(key, offset, BODY.len() as u64)+ .await+ .unwrap();++ let mut reassembled = prefix;+ reassembled.extend_from_slice(&suffix);+ assert_eq!(+ reassembled, BODY,+ "no gap or overlap across the rollback flip"+ );+ }++ #[tokio::test]+ async fn remote_empty_part_stages_empty_object_and_skips_redownload() {+ let server = MockServer::start();+ let mock = server.mock(|when, then| {+ when.method(httpmock::Method::GET).path("/export");+ then.status(404);+ });+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let src = build_source(+ server.url("/export"),+ staging.path(),+ 1,+ remote_staging(store, 0),+ );+ src.prepare_for_job().await.unwrap();+ let key = &src.keys().await.unwrap()[0];++ src.prepare_key(key).await.unwrap();+ assert_eq!(src.size(key).await.unwrap(), Some(0));+ assert!(src.get_chunk(key, 0, 100).await.unwrap().is_empty());++ // The staged empty object makes prepare_key idempotent: no second origin hit.+ src.prepare_key(key).await.unwrap();+ assert_eq!(mock.hits(), 1);+ }++ #[tokio::test]+ async fn remote_ceiling_breach_pauses_and_stages_nothing() {+ let server = MockServer::start();+ let _mock = mock_export(&server, BODY);+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let src = build_source(+ server.url("/export"),+ staging.path(),+ 1,+ remote_staging(Arc::clone(&store), 16), // ceiling far below BODY.len()+ );+ src.prepare_for_job().await.unwrap();+ let key = &src.keys().await.unwrap()[0];++ let err = src.prepare_key(key).await.unwrap_err();+ // Public message is actionable with no internal config names; the env-var+ // detail lives in the internal chain for status_message/logs.+ let user_msg = crate::error::get_user_message(&err);+ assert!(+ user_msg.contains("Split the import"),+ "unexpected message: {user_msg}"+ );+ assert!(+ !user_msg.contains("STAGED_PLAINTEXT_MAX_BYTES"),+ "public message must not leak env var names: {user_msg}"+ );+ assert!(+ format!("{err:#}").contains("STAGED_PLAINTEXT_MAX_BYTES=16"),+ "internal chain must carry the limit detail: {err:#}"+ );+ // Failed-stage atomicity: no readable object was published.+ assert_eq!(src.size(key).await.unwrap(), None);+ // And the downloaded .raw is not left behind on the failure path (a paused job+ // must not hold staging disk while awaiting resume).+ assert_eq!(+ count_raw_files_in(staging.path()),+ 0,+ "a failed stage must not leak the downloaded .raw"+ );+ }++ #[tokio::test]+ async fn remote_cleanup_key_and_job_sweep() {+ let server = MockServer::start();+ let _mock = mock_export(&server, BODY);+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let src = build_source(+ server.url("/export"),+ staging.path(),+ 2,+ remote_staging(Arc::clone(&store), 0),+ );+ src.prepare_for_job().await.unwrap();+ let keys = src.keys().await.unwrap();++ src.prepare_key(&keys[0]).await.unwrap();+ src.prepare_key(&keys[1]).await.unwrap();++ // cleanup_key removes exactly one part; double-delete is a no-op.+ src.cleanup_key(&keys[0]).await.unwrap();+ assert_eq!(src.size(&keys[0]).await.unwrap(), None);+ assert_eq!(src.size(&keys[1]).await.unwrap(), Some(BODY.len() as u64));+ src.cleanup_key(&keys[0]).await.unwrap();++ // cleanup_after_job sweeps the remainder.+ src.cleanup_after_job().await.unwrap();+ let fresh = build_source(+ server.url("/export"),+ staging.path(),+ 2,+ remote_staging(store, 0),+ );+ assert_eq!(fresh.size(&keys[1]).await.unwrap(), None);+ }++ #[tokio::test]+ async fn release_job_resources_keeps_staged_parts_for_resume() {+ // The transient-interruption path (backoff / sink rollback / shutdown):+ // local resources are freed but staged remote parts survive, so the resume+ // re-attaches — no origin re-hit — and re-reads byte-identical data at any+ // offset (the property a sink-rollback retry depends on).+ let server = MockServer::start();+ let mock = mock_export(&server, BODY);+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let src = build_source(+ server.url("/export"),+ staging.path(),+ 1,+ remote_staging(Arc::clone(&store), 0),+ );+ src.prepare_for_job().await.unwrap();+ let key = src.keys().await.unwrap().remove(0);+ src.prepare_key(&key).await.unwrap();+ assert_eq!(mock.hits(), 1);+ let before = src.get_chunk(&key, 5, 12).await.unwrap();++ src.release_job_resources().await.unwrap();++ // Staged object survived; the job temp dir did not.+ assert_eq!(src.size(&key).await.unwrap(), Some(BODY.len() as u64));+ assert_eq!(+ std::fs::read_dir(staging.path()).unwrap().count(),+ 0,+ "local job temp dir must be freed"+ );++ // A fresh source (the resuming pod) attaches without re-downloading and+ // re-reads the identical bytes at the same offset.+ let staging_b = TempDir::new().unwrap();+ let resumed = build_source(+ server.url("/export"),+ staging_b.path(),+ 1,+ remote_staging(store, 0),+ );+ resumed.prepare_for_job().await.unwrap();+ resumed.prepare_key(&key).await.unwrap();+ assert_eq!(mock.hits(), 1, "resume must not re-hit the origin");+ assert_eq!(resumed.get_chunk(&key, 5, 12).await.unwrap(), before);+ }++ #[tokio::test]+ async fn cleanup_after_job_forces_clean_redownload_on_resume() {+ // The source-pause path: a human may fix the source file in place, so the+ // sweep guarantees the resume re-downloads a clean copy — attaching to a+ // stale staged copy of a corrupt file would just re-fail the job.+ let server = MockServer::start();+ let mock = mock_export(&server, BODY);+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let src = build_source(+ server.url("/export"),+ staging.path(),+ 1,+ remote_staging(Arc::clone(&store), 0),+ );+ src.prepare_for_job().await.unwrap();+ let key = src.keys().await.unwrap().remove(0);+ src.prepare_key(&key).await.unwrap();+ assert_eq!(mock.hits(), 1);++ src.cleanup_after_job().await.unwrap();++ let staging_b = TempDir::new().unwrap();+ let resumed = build_source(+ server.url("/export"),+ staging_b.path(),+ 1,+ remote_staging(store, 0),+ );+ resumed.prepare_for_job().await.unwrap();+ resumed.prepare_key(&key).await.unwrap();+ assert_eq!(+ mock.hits(),+ 2,+ "resume after a terminal sweep must re-download from origin"+ );+ }+}diff --git a/rust/batch-import-worker/src/source/mod.rs b/rust/batch-import-worker/src/source/mod.rsindex e4795ec770dd..ad34df9340ec 100644--- a/rust/batch-import-worker/src/source/mod.rs+++ b/rust/batch-import-worker/src/source/mod.rs@@ -1,11 +1,16 @@-use anyhow::Error;-use async_trait::async_trait;use std::collections::HashMap;+use std::future::Future;use std::path::PathBuf;use std::sync::Arc;+use std::time::Duration;++use anyhow::Error;+use async_trait::async_trait;use tokio::sync::Mutex;+use tracing::{debug, info, warn};-use crate::extractor::StreamingReader;+use crate::extractor::{ExtractorType, StreamingReader};+use crate::staging::{open_plaintext_stream, PlaintextStream, StagingBackend};pub mod date_range_export;pub mod folder;@@ -13,6 +18,146 @@ pub mod s3;pub mod s3_gzip;pub mod url_list;+/// Remote (temp-bucket) staging for a compressed source, selected by+/// `STAGING_BACKEND=temp_bucket`. Bundles the backend with how this source's parts+/// decompress, so a downloaded `.raw` can be ingested in one call.+///+/// When present, a source stages each part's decompressed plaintext in the backend and+/// serves `size`/`get_chunk`/`cleanup_key` from it, bypassing the local+/// [`PreparedPart`]/[`StreamingReader`] machinery. When absent (`local_disk`, the+/// default), the local streaming path below is used unchanged.+#[derive(Clone)]+pub struct RemoteStaging {+ pub backend: Arc<dyn StagingBackend>,+ pub extractor_type: ExtractorType,+ /// Per-part decompressed-byte ceiling forwarded to the pipeline (0 = disabled).+ pub max_plaintext_bytes: u64,+}++/// Read retries against the staging backend, mirroring the local prepared-chunk+/// retry behavior both compressed sources have always used.+const REMOTE_READ_RETRIES: usize = 3;++impl RemoteStaging {+ /// `DataSource::prepare_key` delegation for a compressed source: attach if the+ /// part is already staged (cached size, or `head` on a cold process — multipart+ /// atomicity guarantees no torn part is ever visible), otherwise run the source's+ /// download and ingest the result. Idempotent, matching the job loop's+ /// call-every-iteration contract.+ pub(crate) async fn prepare_key<F, Fut>(&self, key: &str, download: F) -> Result<(), Error>+ where+ F: FnOnce() -> Fut,+ Fut: Future<Output = Result<Option<(PathBuf, u64)>, Error>>,+ {+ // Guarantee a public-facing message on the staging legs of this path (attach+ // check + ingest) without shadowing more specific ones (ceiling breach, rate+ // limits). Download errors keep their own source-specific messages.+ let staging_user_msg = || {+ format!(+ "Preparing import data for part {key} failed. The job retries temporary \+ storage errors automatically; if it stays paused, resume it to retry, \+ and if it keeps failing the source file may be corrupt — re-export it \+ or split it and run the remainder as a separate job."+ )+ };+ match self.backend.size(key).await {+ Ok(Some(_)) => {+ debug!("Key already staged remotely: {}", key);+ return Ok(());+ }+ Ok(None) => {}+ Err(e) => return Err(crate::error::ensure_user_message(e, staging_user_msg())),+ }+ let downloaded = download().await?;+ let size = self+ .stage_downloaded(key, downloaded.map(|(path, _)| path))+ .await+ .map_err(|e| crate::error::ensure_user_message(e, staging_user_msg()))?;+ info!(key, size, "Staged key remotely (decompressed bytes)");+ Ok(())+ }++ /// `DataSource::get_chunk` delegation: a ranged, side-effect-free read with the+ /// same small retry loop the sources use for local prepared-chunk reads (the+ /// backend's S3 client retries transient failures internally as well).+ pub(crate) async fn read_chunk(+ &self,+ key: &str,+ offset: u64,+ size: u64,+ ) -> Result<Vec<u8>, Error> {+ let mut retries = REMOTE_READ_RETRIES;+ loop {+ match self.backend.read(key, offset, size).await {+ Ok(chunk) => return Ok(chunk),+ Err(e) => {+ if retries == 0 {+ return Err(crate::error::ensure_user_message(+ e,+ format!(+ "Reading staged import data for part {key} failed. The job \+ retries temporary storage errors automatically; if it stays \+ paused, resume it to continue from where it left off."+ ),+ ));+ }+ warn!(+ key,+ offset, "Error reading staged chunk: {e:?}, remaining retries: {retries}"+ );+ tokio::time::sleep(Duration::from_secs(1)).await;+ retries -= 1;+ }+ }+ }+ }++ /// `DataSource::cleanup_after_job` delegation: sweep this job's staged objects,+ /// best-effort (the bucket TTL is the final backstop).+ pub(crate) async fn sweep_job(&self) {+ if let Err(e) = self.backend.cleanup_job().await {+ warn!("Failed to clean up remote staging after job: {e:#}");+ }+ }++ /// Ingest a downloaded part into the backend and return its decompressed size.+ /// `raw_file_path: None` means an empty part (404 / zero-byte object): an empty+ /// object is staged so `size()` reports `Some(0)` and resume skips re-download.+ /// The `.raw` is deleted after a successful stage (its bytes now live remotely).+ pub(crate) async fn stage_downloaded(+ &self,+ key: &str,+ raw_file_path: Option<PathBuf>,+ ) -> Result<u64, Error> {+ match raw_file_path {+ None => {+ self.backend+ .stage_part(+ key,+ PlaintextStream::from_chunks(Vec::<bytes::Bytes>::new()),+ )+ .await+ }+ Some(raw) => {+ let stream = open_plaintext_stream(+ raw.clone(),+ self.extractor_type.clone(),+ self.max_plaintext_bytes,+ );+ let result = self.backend.stage_part(key, stream).await;+ // The `.raw` is single-use: on success its bytes now live remotely; on+ // failure the retry re-downloads from origin (the backend has no object,+ // so prepare_key won't attach). Remove it either way so a failed or paused+ // job doesn't hold staging disk or trip the staging guard on resume.+ if let Err(e) = tokio::fs::remove_file(&raw).await {+ warn!("Failed to remove staged raw file {}: {e}", raw.display());+ }+ result+ }+ }+ }+}+/// Per-key state for sources that download a compressed `.raw` file and/// stream-decompress it on demand (see [`crate::extractor::StreamingReader`]).///@@ -142,10 +287,25 @@ pub trait DataSource: Sync + Send {async fn prepare_for_job(&self) -> Result<(), Error> {Ok(())}++ /// Terminal cleanup: reclaim everything, including durable remote staging.+ /// Called when the job completes, and on source-side pauses — a human may fix+ /// the source file in place before resuming, so the resume must re-download a+ /// clean copy rather than attach to a stale staged one.async fn cleanup_after_job(&self) -> Result<(), Error> {Ok(())}+ /// Transient-interruption cleanup: release per-process resources (local temp+ /// files, in-memory state) but keep durable remote staging, so a resumed job+ /// re-attaches to staged parts instead of re-hitting the origin. Called on+ /// transient backoff, sink commit rollback (the retried chunk then re-reads+ /// byte-identical staged data), and graceful shutdown (the re-claiming pod+ /// attaches). Defaults to full cleanup for sources with no remote staging.+ async fn release_job_resources(&self) -> Result<(), Error> {+ self.cleanup_after_job().await+ }+fn get_date_range_for_key(&self, _key: &str) -> Option<String> {None}diff --git a/rust/batch-import-worker/src/source/s3_gzip.rs b/rust/batch-import-worker/src/source/s3_gzip.rsindex b7db69956efe..7f1b12ecb4f8 100644--- a/rust/batch-import-worker/src/source/s3_gzip.rs+++ b/rust/batch-import-worker/src/source/s3_gzip.rs@@ -15,7 +15,7 @@ use crate::extractor::PartExtractor;use crate::staging::StagingGuard;use super::s3::extract_user_friendly_error;-use super::{read_prepared_chunk, remove_prepared_key, DataSource, PreparedPart};+use super::{read_prepared_chunk, remove_prepared_key, DataSource, PreparedPart, RemoteStaging};fn sanitize_key_for_path(key: &str) -> String {key.replace(['/', ':'], "_")@@ -32,6 +32,7 @@ pub struct GzipS3Source {extractor: Arc<dyn PartExtractor>,staging_dir: PathBuf,staging_max_bytes: u64,+ remote_staging: Option<RemoteStaging>,temp_dir: Arc<Mutex<Option<TempDir>>>,prepared_keys: Arc<Mutex<HashMap<String, PreparedPart>>>,}@@ -44,6 +45,7 @@ impl GzipS3Source {extractor: Arc<dyn PartExtractor>,staging_dir: PathBuf,staging_max_bytes: u64,+ remote_staging: Option<RemoteStaging>,) -> Self {Self {client,@@ -52,6 +54,7 @@ impl GzipS3Source {extractor,staging_dir,staging_max_bytes,+ remote_staging,temp_dir: Arc::new(Mutex::new(None)),prepared_keys: Arc::new(Mutex::new(HashMap::new())),}@@ -74,6 +77,102 @@ impl GzipS3Source {) -> Result<Vec<u8>, Error> {read_prepared_chunk(&self.prepared_keys, key, offset, size).await}++ /// Free pod-local state: prepared readers/`.raw` files and the job temp dir.+ /// Clear refs first, then explicitly `close()` the temp dir to surface removal+ /// errors. Never touches remote staging.+ async fn cleanup_local_resources(&self) {+ {+ let mut prepared_keys = self.prepared_keys.lock().await;+ prepared_keys.clear();+ }+ {+ let mut temp_dir_guard = self.temp_dir.lock().await;+ if let Some(temp_dir) = temp_dir_guard.take() {+ let path = temp_dir.path().to_path_buf();+ if let Err(e) = temp_dir.close() {+ warn!("Failed to remove temp directory {}: {e}", path.display());+ } else {+ debug!("Cleaned up temp directory: {}", path.display());+ }+ }+ }+ }++ /// Stream the compressed object into a temp `.raw` file and return its path, or+ /// `None` for a zero-byte object (the empty `.raw` is removed). The staging guard is+ /// checked before the download, throttled as the file grows, and once more at the+ /// part boundary.+ async fn download_object_raw(&self, key: &str) -> Result<Option<(PathBuf, u64)>, Error> {+ let get = self+ .client+ .get_object()+ .bucket(&self.bucket)+ .key(key)+ .send()+ .await+ .or_else(|sdk_error| {+ let friendly_msg =+ extract_user_friendly_error(&sdk_error, &self.bucket, "get object");+ Err(sdk_error).user_error(friendly_msg)+ })?;++ let temp_dir = self.get_temp_dir_path().await?;+ let safe_key = sanitize_key_for_path(key);++ // Pause the job if staging is already over budget before we add to it,+ // and again as the `.raw` grows.+ let mut guard = StagingGuard::new(self.staging_dir.clone(), self.staging_max_bytes);+ guard.check().await?;++ let raw_file_path = temp_dir.join(format!("{}.raw", safe_key));+ let mut raw_file = File::create(&raw_file_path)+ .await+ .with_context(|| format!("Failed to create raw file: {}", raw_file_path.display()))?;++ let mut stream = get.body;+ let mut total_bytes: u64 = 0;+ while let Some(chunk) = stream.try_next().await.with_context(|| {+ format!(+ "Failed to read body data from S3 object s3://{0}/{key}",+ self.bucket,+ )+ })? {+ raw_file.write_all(&chunk).await.with_context(|| {+ format!("Failed to write raw file: {}", raw_file_path.display())+ })?;+ total_bytes += chunk.len() as u64;+ guard.record(chunk.len() as u64).await?;+ }++ raw_file+ .sync_all()+ .await+ .with_context(|| format!("Failed to sync raw file: {}", raw_file_path.display()))?;+ drop(raw_file);++ if total_bytes == 0 {+ if let Err(e) = tokio::fs::remove_file(&raw_file_path).await {+ warn!(+ "Failed to remove empty raw file {}: {e}",+ raw_file_path.display()+ );+ }+ return Ok(None);+ }++ // Final check once the whole `.raw` is on disk: the per-chunk `record` calls are+ // throttled, so a part smaller than the check interval could otherwise exceed the+ // limit without ever being measured. This enforces the limit at the part boundary.+ guard.check().await?;++ debug!(+ "Streamed {total_bytes} compressed bytes to {} for key: {key}",+ raw_file_path.display()+ );++ Ok(Some((raw_file_path, total_bytes)))+ }}#[async_trait]@@ -118,11 +217,17 @@ impl DataSource for GzipS3Source {}async fn size(&self, key: &str) -> Result<Option<u64>, Error> {+ if let Some(remote) = &self.remote_staging {+ return remote.backend.size(key).await;+ }let prepared_keys = self.prepared_keys.lock().await;Ok(prepared_keys.get(key).and_then(|part| part.total_size))}async fn get_chunk(&self, key: &str, offset: u64, size: u64) -> Result<Vec<u8>, Error> {+ if let Some(remote) = &self.remote_staging {+ return remote.read_chunk(key, offset, size).await;+ }self.get_chunk_from_prepared_key(key, offset, size).await}@@ -147,26 +252,33 @@ impl DataSource for GzipS3Source {}async fn cleanup_after_job(&self) -> Result<(), Error> {- {- let mut prepared_keys = self.prepared_keys.lock().await;- prepared_keys.clear();- }- {- let mut temp_dir_guard = self.temp_dir.lock().await;- if let Some(temp_dir) = temp_dir_guard.take() {- let path = temp_dir.path().to_path_buf();- if let Err(e) = temp_dir.close() {- warn!("Failed to remove temp directory {}: {e}", path.display());- } else {- debug!("Cleaned up temp directory: {}", path.display());- }- }+ // Terminal: sweep any staged objects this job left in the remote backend+ // (best-effort; the bucket TTL is the final backstop), then release local+ // resources.+ if let Some(remote) = &self.remote_staging {+ remote.sweep_job().await;}+ self.cleanup_local_resources().await;debug!("Job cleanup complete");Ok(())}+ async fn release_job_resources(&self) -> Result<(), Error> {+ // Transient interruption: keep staged remote objects for the resume to+ // re-attach to; free only pod-local disk and in-memory state (the disk is+ // shared with whatever job this pod claims next).+ self.cleanup_local_resources().await;+ debug!("Job resources released (remote staging kept for resume)");+ Ok(())+ }+async fn prepare_key(&self, key: &str) -> Result<(), Error> {+ if let Some(remote) = &self.remote_staging {+ return remote+ .prepare_key(key, || self.download_object_raw(key))+ .await;+ }+{let prepared_keys = self.prepared_keys.lock().await;if prepared_keys.contains_key(key) {@@ -175,100 +287,205 @@ impl DataSource for GzipS3Source {}}- let get = self- .client- .get_object()- .bucket(&self.bucket)- .key(key)- .send()- .await- .or_else(|sdk_error| {- let friendly_msg =- extract_user_friendly_error(&sdk_error, &self.bucket, "get object");- Err(sdk_error).user_error(friendly_msg)- })?;+ let prepared_part = match self.download_object_raw(key).await? {+ None => {+ info!("Prepared key {} (empty object)", key);+ PreparedPart::empty()+ }+ Some((raw_file_path, total_bytes)) => {+ // Open a streaming decoder over the compressed file; we keep the `.raw`+ // on disk and decompress on demand rather than materializing a `.data`+ // copy, bounding disk usage to the compressed size.+ let reader = self.extractor.open_reader(raw_file_path.clone());+ info!("Prepared key {key} ({total_bytes} compressed bytes, streaming decode)");+ PreparedPart::streaming(raw_file_path, reader)+ }+ };- let temp_dir = self.get_temp_dir_path().await?;- let safe_key = sanitize_key_for_path(key);+ {+ let mut prepared_keys = self.prepared_keys.lock().await;+ prepared_keys.insert(key.to_string(), prepared_part);+ }- // Pause the job if staging is already over budget before we add to it,- // and again as the `.raw` grows.- let mut guard = StagingGuard::new(self.staging_dir.clone(), self.staging_max_bytes);- guard.check().await?;+ Ok(())+ }- let raw_file_path = temp_dir.join(format!("{}.raw", safe_key));- let mut raw_file = File::create(&raw_file_path)- .await- .with_context(|| format!("Failed to create raw file: {}", raw_file_path.display()))?;+ async fn cleanup_key(&self, key: &str) -> Result<(), Error> {+ if let Some(remote) = &self.remote_staging {+ return remote.backend.cleanup_key(key).await;+ }+ remove_prepared_key(&self.prepared_keys, key).await;+ Ok(())+ }+}- let mut stream = get.body;- let mut total_bytes: u64 = 0;- while let Some(chunk) = stream.try_next().await.with_context(|| {- format!(- "Failed to read body data from S3 object s3://{0}/{key}",- self.bucket,- )- })? {- raw_file.write_all(&chunk).await.with_context(|| {- format!("Failed to write raw file: {}", raw_file_path.display())- })?;- total_bytes += chunk.len() as u64;- guard.record(chunk.len() as u64).await?;+/// Remote (temp-bucket) staging mode for the S3 gzip source, held to the same contract+/// as the date-range source: the origin is a real aws-sdk S3 client pointed at an+/// httpmock endpoint (GetObject only — these tests address parts by key, as the job+/// loop does), and the backend is the real one over `object_store::memory::InMemory`.+#[cfg(test)]+mod remote_staging_tests {+ use super::*;+ use crate::extractor::ExtractorType;+ use crate::source::RemoteStaging;+ use crate::staging::TempBucketBackend;+ use aws_config::BehaviorVersion;+ use aws_sdk_s3::config::{Credentials, Region};+ use flate2::{write::GzEncoder, Compression};+ use httpmock::{Mock, MockServer};+ use object_store::memory::InMemory;+ use object_store::ObjectStore;+ use std::io::Write;+ use std::path::Path;+ use tempfile::TempDir;++ const BUCKET: &str = "customer-bucket";+ const KEY: &str = "exports/2024/events-0001.jsonl.gz";++ /// Realistic captured-event JSONL: multiple records whose boundaries don't align+ /// with the small read slices used below.+ fn realistic_body() -> Vec<u8> {+ let mut body = Vec::new();+ for i in 0..40u32 {+ let line = serde_json::json!({+ "event": "$pageview",+ "distinct_id": format!("user-{i}"),+ "timestamp": format!("2024-01-{:02}T12:00:00Z", (i % 28) + 1),+ "uuid": uuid::Uuid::now_v7().to_string(),+ "properties": { "idx": i, "$browser": "Firefox" }+ })+ .to_string();+ body.extend_from_slice(line.as_bytes());+ body.push(b'\n');}+ body+ }- raw_file- .sync_all()- .await- .with_context(|| format!("Failed to sync raw file: {}", raw_file_path.display()))?;- drop(raw_file);+ fn gzip(data: &[u8]) -> Vec<u8> {+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());+ encoder.write_all(data).unwrap();+ encoder.finish().unwrap()+ }- if total_bytes == 0 {- if let Err(e) = tokio::fs::remove_file(&raw_file_path).await {- warn!(- "Failed to remove empty raw file {}: {e}",- raw_file_path.display()- );- }+ /// Mock the S3 GetObject request the aws-sdk client issues for `KEY`+ /// (path-style: GET /{bucket}/{key}).+ fn mock_get_object<'a>(server: &'a MockServer, gz: &[u8]) -> Mock<'a> {+ let body = gz.to_vec();+ server.mock(move |when, then| {+ when.method(httpmock::Method::GET)+ .path(format!("/{BUCKET}/{KEY}"));+ then.status(200).body(body.clone());+ })+ }- let mut prepared_keys = self.prepared_keys.lock().await;- prepared_keys.insert(key.to_string(), PreparedPart::empty());- info!("Prepared key {} (empty object)", key);- return Ok(());- }+ async fn aws_client_for(server: &MockServer) -> aws_sdk_s3::Client {+ let config = aws_config::defaults(BehaviorVersion::latest())+ .endpoint_url(server.base_url())+ .region(Region::new("us-east-1"))+ .credentials_provider(Credentials::new("k", "s", None, None, "test"))+ .load()+ .await;+ let s3_config = aws_sdk_s3::config::Builder::from(&config)+ .force_path_style(true)+ .build();+ aws_sdk_s3::Client::from_conf(s3_config)+ }- // Final check once the whole `.raw` is on disk: the per-chunk `record` calls are- // throttled, so a part smaller than the check interval could otherwise exceed the- // limit without ever being measured. This enforces the limit at the part boundary.- guard.check().await?;+ async fn build_source(+ server: &MockServer,+ staging: &Path,+ store: Arc<dyn ObjectStore>,+ ) -> GzipS3Source {+ GzipS3Source::new(+ aws_client_for(server).await,+ BUCKET.to_string(),+ "exports/".to_string(),+ ExtractorType::PlainGzip.create_extractor(),+ staging.to_path_buf(),+ 0,+ Some(RemoteStaging {+ backend: Arc::new(TempBucketBackend::new(store, "staging/", "job-S3GZ")),+ extractor_type: ExtractorType::PlainGzip,+ max_plaintext_bytes: 0,+ }),+ )+ }- debug!(- "Streamed {total_bytes} compressed bytes to {} for key: {key}",- raw_file_path.display()- );+ #[tokio::test]+ async fn remote_round_trip_resume_and_lifecycle() {+ let body = realistic_body();+ let server = MockServer::start();+ let mock = mock_get_object(&server, &gzip(&body));+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());- // Open a streaming decoder over the compressed file; we keep the `.raw`- // on disk and decompress on demand rather than materializing a `.data`- // copy, bounding disk usage to the compressed size.- let reader = self.extractor.open_reader(raw_file_path.clone());- {- let mut prepared_keys = self.prepared_keys.lock().await;- prepared_keys.insert(- key.to_string(),- PreparedPart::streaming(raw_file_path, reader),- );- }+ let src = build_source(&server, staging.path(), Arc::clone(&store)).await;+ src.prepare_for_job().await.unwrap();- info!(- "Prepared key {} ({total_bytes} compressed bytes, streaming decode)",- key+ // Stage on first touch; size known immediately; prepare_key idempotent.+ src.prepare_key(KEY).await.unwrap();+ src.prepare_key(KEY).await.unwrap();+ assert_eq!(+ mock.hits(),+ 1,+ "second prepare_key must attach, not re-download");+ assert_eq!(src.size(KEY).await.unwrap(), Some(body.len() as u64));- Ok(())+ // Record-misaligned ranged reads reconstruct the body exactly.+ let mut out = Vec::new();+ let mut offset = 0u64;+ loop {+ let chunk = src.get_chunk(KEY, offset, 97).await.unwrap();+ if chunk.is_empty() {+ break;+ }+ offset += chunk.len() as u64;+ out.extend_from_slice(&chunk);+ }+ assert_eq!(out, body);++ // Transient-interruption release keeps the staged part: a fresh source+ // (resuming pod) attaches with no origin re-hit.+ src.release_job_resources().await.unwrap();+ let staging_b = TempDir::new().unwrap();+ let resumed = build_source(&server, staging_b.path(), Arc::clone(&store)).await;+ resumed.prepare_for_job().await.unwrap();+ resumed.prepare_key(KEY).await.unwrap();+ assert_eq!(mock.hits(), 1, "resume must not re-hit the origin");+ assert_eq!(resumed.get_chunk(KEY, 10, 25).await.unwrap(), &body[10..35]);++ // Per-part delete is idempotent; the terminal sweep forces a clean+ // re-download on the next attempt (the fixed-source-after-pause guarantee).+ resumed.cleanup_key(KEY).await.unwrap();+ assert_eq!(resumed.size(KEY).await.unwrap(), None);+ resumed.cleanup_key(KEY).await.unwrap();+ resumed.prepare_key(KEY).await.unwrap();+ assert_eq!(mock.hits(), 2, "after delete, prepare_key re-downloads");+ resumed.cleanup_after_job().await.unwrap();+ let staging_c = TempDir::new().unwrap();+ let fresh = build_source(&server, staging_c.path(), store).await;+ assert_eq!(fresh.size(KEY).await.unwrap(), None);}- async fn cleanup_key(&self, key: &str) -> Result<(), Error> {- remove_prepared_key(&self.prepared_keys, key).await;- Ok(())+ #[tokio::test]+ async fn remote_zero_byte_object_stages_empty_part() {+ let server = MockServer::start();+ let mock = mock_get_object(&server, b"");+ let staging = TempDir::new().unwrap();+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());++ let src = build_source(&server, staging.path(), store).await;+ src.prepare_for_job().await.unwrap();+ src.prepare_key(KEY).await.unwrap();++ // A zero-byte origin object stages an empty part: size reports Some(0) (the+ // job loop's done-empty short-circuit), reads are empty, and the staged+ // marker makes prepare_key idempotent with no second origin hit.+ assert_eq!(src.size(KEY).await.unwrap(), Some(0));+ assert!(src.get_chunk(KEY, 0, 100).await.unwrap().is_empty());+ src.prepare_key(KEY).await.unwrap();+ assert_eq!(mock.hits(), 1);}}diff --git a/rust/batch-import-worker/src/staging/backend.rs b/rust/batch-import-worker/src/staging/backend.rsnew file mode 100644index 000000000000..4fb56d39ec89--- /dev/null+++ b/rust/batch-import-worker/src/staging/backend.rs@@ -0,0 +1,527 @@+use std::collections::HashMap;+use std::path::PathBuf;++use anyhow::{Context, Error};+use async_trait::async_trait;+use bytes::Bytes;+use tokio::fs::File;+use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};+use tokio::sync::{mpsc, Mutex};+use tokio::task::JoinHandle;+use tracing::warn;+use uuid::Uuid;++/// A forward, on-demand stream of decompressed plaintext blocks for a single part.+///+/// Produced by the shared fetch+decompress pipeline (added in a later change) and+/// consumed by a [`StagingBackend`] in `stage_part`. Decoupling the producer from+/// the backend is what lets both the local-disk and temp-bucket backends persist the+/// exact same byte stream, so a part's byte offsets stay valid across backends.+pub struct PlaintextStream {+ rx: mpsc::Receiver<Result<Bytes, Error>>,+ // The producer task, if this stream owns one. Awaited on channel EOF so a producer+ // panic surfaces as a stream error instead of being mistaken for a clean end-of-stream+ // (which would silently truncate the staged part).+ producer: Option<JoinHandle<()>>,+}++impl PlaintextStream {+ /// Wrap a receiver of decompressed blocks with no owned producer. The caller is+ /// responsible for the sender side (tests, manual channels).+ pub fn new(rx: mpsc::Receiver<Result<Bytes, Error>>) -> Self {+ Self { rx, producer: None }+ }++ /// Wrap a receiver alongside the producer task feeding it, so a producer panic is+ /// detected at EOF and reported rather than swallowed.+ pub(crate) fn from_producer(+ rx: mpsc::Receiver<Result<Bytes, Error>>,+ producer: JoinHandle<()>,+ ) -> Self {+ Self {+ rx,+ producer: Some(producer),+ }+ }++ /// Pull the next block, or `None` once the producer has finished cleanly. If the+ /// channel closes without the producer sending an error, the owned producer handle is+ /// awaited: a panic (or cancellation) is surfaced as an error so the consumer does not+ /// treat a crashed producer as a complete stream.+ pub async fn next(&mut self) -> Option<Result<Bytes, Error>> {+ if let Some(item) = self.rx.recv().await {+ return Some(item);+ }+ match self.producer.take() {+ Some(handle) => match handle.await {+ Ok(()) => None,+ Err(join_err) => Some(Err(Error::msg(format!(+ "decompression task terminated abnormally: {join_err}"+ )))),+ },+ None => None,+ }+ }++ /// Build a stream from in-memory blocks, feeding them through a bounded channel+ /// on a background task. Mirrors the real producer shape; handy for tests and for+ /// callers that already hold the full plaintext.+ pub fn from_chunks<I>(chunks: I) -> Self+ where+ I: IntoIterator<Item = Bytes> + Send + 'static,+ I::IntoIter: Send,+ {+ let (tx, rx) = mpsc::channel(16);+ let handle = tokio::spawn(async move {+ for chunk in chunks {+ if tx.send(Ok(chunk)).await.is_err() {+ break;+ }+ }+ });+ Self::from_producer(rx, handle)+ }+}++/// Where a compressed source's decompressed part plaintext is staged so the job loop+/// can read it back by byte offset.+///+/// The two compressed sources (`date_range_export`, `s3_gzip`) delegate their+/// `prepare_key`/`size`/`get_chunk`/`cleanup_key` here. Implementations must satisfy the+/// job-loop contract: `read` is idempotent and side-effect-free (reads past EOF return+/// short/empty rather than erroring), and staging a key is atomic — a partially staged+/// key must not be observable via `size`/`read`.+#[async_trait]+pub trait StagingBackend: Send + Sync {+ /// Reclaim all staging for the job. Best-effort: failures are logged, not fatal.+ async fn cleanup_job(&self) -> Result<(), Error> {+ Ok(())+ }++ /// Consume the decompressed plaintext for `key` and persist it, returning the total+ /// byte size. Must be atomic: on error, no readable staging is left behind.+ async fn stage_part(&self, key: &str, plaintext: PlaintextStream) -> Result<u64, Error>;++ /// Total staged size in bytes, or `None` if the key is not staged.+ async fn size(&self, key: &str) -> Result<Option<u64>, Error>;++ /// Read up to `size` bytes starting at `offset`. Reads at/after EOF return empty;+ /// reads that overrun EOF return the available prefix. Never mutates staging.+ async fn read(&self, key: &str, offset: u64, size: u64) -> Result<Vec<u8>, Error>;++ /// Delete the staging for a single key. Must no-op (not error) if already absent.+ async fn cleanup_key(&self, key: &str) -> Result<(), Error>;+}++/// Make a key safe to use as a filename / object suffix. Matches the existing sources'+/// `:`-replacement and additionally neutralizes path separators so nested S3 keys stay+/// a single flat name.+///+/// Invariant: callers stage one source per job, so all keys within a job share a single+/// style (date-range keys or S3 paths) and stay distinct after sanitization. This does not+/// guarantee global injectivity — `a:b` and `a/b` both map to `a_b` — so do not mix key+/// styles under one backend instance.+pub(crate) fn sanitize_key(key: &str) -> String {+ key.replace([':', '/'], "_")+}++/// Write a plaintext stream to `path`, fsync, and return the byte count. Used by+/// `LocalDiskBackend::stage_part` against a temp path so the caller can rename atomically.+async fn stage_to_file(+ path: &std::path::Path,+ plaintext: &mut PlaintextStream,+ key: &str,+) -> Result<u64, Error> {+ let mut file = File::create(path)+ .await+ .with_context(|| format!("Failed to create data file for key: {key}"))?;++ let mut total: u64 = 0;+ while let Some(block) = plaintext.next().await {+ let block = block.with_context(|| format!("Failed to decompress part for key: {key}"))?;+ file.write_all(&block)+ .await+ .with_context(|| format!("Failed to write staged data for key: {key}"))?;+ total += block.len() as u64;+ }++ file.sync_all()+ .await+ .with_context(|| format!("Failed to sync staged data for key: {key}"))?;+ Ok(total)+}++/// Stages part plaintext as a `.data` file under a per-job directory, reading it back with+/// seek + `read_exact`.+///+/// This is the byte-identity reference/oracle the temp-bucket backend is validated against+/// — it is exercised only by tests and is NOT reachable from any `STAGING_BACKEND` value.+/// With `STAGING_BACKEND=local_disk` (default) sources use the streaming `.raw` machinery+/// (disk bounded by compressed size); routing through this materializing backend would+/// regress disk usage to decompressed size.+pub struct LocalDiskBackend {+ job_dir: PathBuf,+ // Sizes recorded at stage time, mirroring the sources' in-memory prepared-key map.+ // Reads fall back to stat-ing the file so a resumed process can attach without a+ // prior `stage_part`.+ sizes: Mutex<HashMap<String, u64>>,+}++impl LocalDiskBackend {+ /// `job_dir` is the per-job staging directory (e.g. `{staging_dir}/job-{id}`).+ pub fn new(job_dir: PathBuf) -> Self {+ Self {+ job_dir,+ sizes: Mutex::new(HashMap::new()),+ }+ }++ fn data_path(&self, key: &str) -> PathBuf {+ self.job_dir.join(format!("{}.data", sanitize_key(key)))+ }+}++#[async_trait]+impl StagingBackend for LocalDiskBackend {+ async fn cleanup_job(&self) -> Result<(), Error> {+ if let Err(e) = tokio::fs::remove_dir_all(&self.job_dir).await {+ if e.kind() != std::io::ErrorKind::NotFound {+ warn!(+ "Failed to remove staging dir {}: {e}",+ self.job_dir.display()+ );+ }+ }+ self.sizes.lock().await.clear();+ Ok(())+ }++ async fn stage_part(&self, key: &str, mut plaintext: PlaintextStream) -> Result<u64, Error> {+ tokio::fs::create_dir_all(&self.job_dir)+ .await+ .with_context(|| format!("Failed to create staging dir: {}", self.job_dir.display()))?;++ // Stage to a unique temp file, then atomically rename to the key path only after a+ // successful sync. A failure mid-write leaves the partial at the temp path, never at+ // the observable key path, so `size`/`read` can't see a truncated part.+ let final_path = self.data_path(key);+ let tmp_path =+ self.job_dir+ .join(format!("{}.{}.partial", sanitize_key(key), Uuid::now_v7()));++ let total = match stage_to_file(&tmp_path, &mut plaintext, key).await {+ Ok(total) => total,+ Err(e) => {+ if let Err(cleanup_err) = tokio::fs::remove_file(&tmp_path).await {+ if cleanup_err.kind() != std::io::ErrorKind::NotFound {+ warn!(+ "Failed to remove partial staged file {}: {cleanup_err}",+ tmp_path.display()+ );+ }+ }+ return Err(e);+ }+ };++ tokio::fs::rename(&tmp_path, &final_path)+ .await+ .with_context(|| format!("Failed to publish staged data for key: {key}"))?;++ self.sizes.lock().await.insert(key.to_string(), total);+ Ok(total)+ }++ async fn size(&self, key: &str) -> Result<Option<u64>, Error> {+ if let Some(size) = self.sizes.lock().await.get(key).copied() {+ return Ok(Some(size));+ }+ match tokio::fs::metadata(self.data_path(key)).await {+ Ok(meta) => Ok(Some(meta.len())),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),+ Err(e) => {+ Err(Error::from(e)+ .context(format!("Failed to stat staged data file for key: {key}")))+ }+ }+ }++ async fn read(&self, key: &str, offset: u64, size: u64) -> Result<Vec<u8>, Error> {+ let total_size = match self.size(key).await? {+ Some(s) => s,+ None => return Err(Error::msg(format!("Key not staged: {key}"))),+ };++ if total_size == 0 || offset >= total_size {+ return Ok(Vec::new());+ }++ let end_offset = std::cmp::min(offset + size, total_size);+ let read_size = (end_offset - offset) as usize;++ let mut file = File::open(self.data_path(key))+ .await+ .with_context(|| format!("Failed to open staged data file for key: {key}"))?;+ file.seek(std::io::SeekFrom::Start(offset))+ .await+ .with_context(|| format!("Failed to seek to offset {offset} for key: {key}"))?;+ let mut buffer = vec![0u8; read_size];+ file.read_exact(&mut buffer)+ .await+ .with_context(|| format!("Failed to read {read_size} bytes for key: {key}"))?;+ Ok(buffer)+ }++ async fn cleanup_key(&self, key: &str) -> Result<(), Error> {+ if let Err(e) = tokio::fs::remove_file(self.data_path(key)).await {+ if e.kind() != std::io::ErrorKind::NotFound {+ return Err(Error::from(e)+ .context(format!("Failed to remove staged data file for key: {key}")));+ }+ }+ self.sizes.lock().await.remove(key);+ Ok(())+ }+}++/// Convenience for callers that hold a full plaintext buffer (tests, and any future+/// non-streaming producer): stage it and return the recorded size.+#[cfg(test)]+pub(crate) async fn stage_bytes(+ backend: &dyn StagingBackend,+ key: &str,+ data: &[u8],+) -> Result<u64, Error> {+ let stream = PlaintextStream::from_chunks(vec![Bytes::copy_from_slice(data)]);+ backend.stage_part(key, stream).await+}++/// Prove a backend's reads reconstruct the staged bytes exactly across arbitrary,+/// record-misaligned offsets — the property the job loop relies on when it re-reads a+/// partial trailing record. Stages `body`, reads it back in tiny (7-byte) slices whose+/// boundaries do not align with record boundaries, asserts the concatenation equals+/// `body`, and asserts a single read spanning more than one slice returns the exact span.+///+/// Shared across backends so both `LocalDiskBackend` and `TempBucketBackend` are held to+/// the identical read contract.+///+/// A multi-record JSONL body whose record boundaries do not fall on the read-slice+/// boundaries used by [`assert_reads_reconstruct`], so both backends are exercised with+/// the same fixture.+#[cfg(test)]+pub(crate) const TEST_RECORD_BODY: &[u8] = b"{\"id\":1}\n{\"id\":2}\n{\"id\":3}\n{\"id\":4}\n";++#[cfg(test)]+pub(crate) async fn assert_reads_reconstruct(backend: &dyn StagingBackend, key: &str, body: &[u8]) {+ let size = stage_bytes(backend, key, body).await.unwrap();+ assert_eq!(size, body.len() as u64);++ // Reassemble via small, deliberately record-misaligned reads.+ const SLICE: u64 = 7;+ let mut reconstructed = Vec::with_capacity(body.len());+ let mut offset = 0u64;+ loop {+ let chunk = backend.read(key, offset, SLICE).await.unwrap();+ if chunk.is_empty() {+ break;+ }+ assert!(+ chunk.len() as u64 <= SLICE,+ "read returned more than requested"+ );+ reconstructed.extend_from_slice(&chunk);+ offset += chunk.len() as u64;+ }+ assert_eq!(+ reconstructed, body,+ "misaligned reads must reconstruct the body"+ );++ // A single read wider than a slice returns exactly the requested span.+ if body.len() >= 20 {+ let span = backend.read(key, 5, 15).await.unwrap();+ assert_eq!(span, &body[5..20]);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::Path;+ use tempfile::TempDir;++ fn backend(root: &Path) -> LocalDiskBackend {+ LocalDiskBackend::new(root.join("job-TEST"))+ }++ #[tokio::test]+ async fn stage_then_read_slices_match() {+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ let body = b"line one\nline two\nline three\n";+ let size = stage_bytes(&be, "2024-01-01", body).await.unwrap();+ assert_eq!(size, body.len() as u64);+ assert_eq!(+ be.size("2024-01-01").await.unwrap(),+ Some(body.len() as u64)+ );++ // Full read.+ assert_eq!(be.read("2024-01-01", 0, 1000).await.unwrap(), body);+ // Mid-slice.+ assert_eq!(be.read("2024-01-01", 9, 8).await.unwrap(), b"line two");+ // Overrun EOF returns the available prefix.+ let tail = be.read("2024-01-01", 18, 1000).await.unwrap();+ assert_eq!(tail, b"line three\n");+ // Read at EOF is empty, not an error.+ assert!(be+ .read("2024-01-01", body.len() as u64, 10)+ .await+ .unwrap()+ .is_empty());+ }++ #[tokio::test]+ async fn producer_panic_surfaces_as_error_not_clean_eof() {+ // A producer that panics (mirrors a flate2/zip internal panic) must not look like a+ // clean EOF — otherwise the consumer would stage a silently truncated part.+ let (tx, rx) = mpsc::channel::<Result<Bytes, Error>>(4);+ let handle = tokio::task::spawn_blocking(move || {+ let _tx = tx; // hold the sender so the channel closes only on unwind+ panic!("simulated decoder panic");+ });+ let mut stream = PlaintextStream::from_producer(rx, handle);++ let mut saw_error = false;+ while let Some(item) = stream.next().await {+ if item.is_err() {+ saw_error = true;+ }+ }+ assert!(saw_error, "a producer panic must surface as a stream error");+ }++ #[tokio::test]+ async fn multi_chunk_stream_is_concatenated_in_order() {+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ let stream = PlaintextStream::from_chunks(vec![+ Bytes::from_static(b"aaa"),+ Bytes::from_static(b"bbb"),+ Bytes::from_static(b"ccc"),+ ]);+ let size = be.stage_part("k", stream).await.unwrap();+ assert_eq!(size, 9);+ assert_eq!(be.read("k", 0, 9).await.unwrap(), b"aaabbbccc");+ }++ #[tokio::test]+ async fn empty_part_reports_zero_and_reads_empty() {+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ let size = stage_bytes(&be, "empty", b"").await.unwrap();+ assert_eq!(size, 0);+ assert_eq!(be.size("empty").await.unwrap(), Some(0));+ assert!(be.read("empty", 0, 100).await.unwrap().is_empty());+ }++ #[tokio::test]+ async fn size_none_and_read_errors_for_unstaged_key() {+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ assert_eq!(be.size("missing").await.unwrap(), None);+ assert!(be.read("missing", 0, 10).await.is_err());+ }++ #[tokio::test]+ async fn size_attaches_to_existing_file_without_stage_part() {+ // Simulates a resumed process: the .data file exists on disk but the in-memory+ // size map is empty. size()/read() must recover from the file.+ let root = TempDir::new().unwrap();+ let job_dir = root.path().join("job-TEST");+ tokio::fs::create_dir_all(&job_dir).await.unwrap();+ let body = b"resumed body\n";+ tokio::fs::write(job_dir.join(format!("{}.data", sanitize_key("k1"))), body)+ .await+ .unwrap();++ let be = LocalDiskBackend::new(job_dir);+ assert_eq!(be.size("k1").await.unwrap(), Some(body.len() as u64));+ assert_eq!(be.read("k1", 0, 1000).await.unwrap(), body);+ }++ #[tokio::test]+ async fn failed_stage_leaves_no_observable_key() {+ // A mid-stream error must not publish a partial file: size() stays None and no+ // .data appears at the key path (only, transiently, a .partial temp that is removed).+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ let (tx, rx) = mpsc::channel(4);+ tx.send(Ok(Bytes::from_static(b"partial data")))+ .await+ .unwrap();+ tx.send(Err(anyhow::anyhow!("decode blew up")))+ .await+ .unwrap();+ drop(tx);++ let result = be.stage_part("k", PlaintextStream::new(rx)).await;+ assert!(result.is_err());+ assert_eq!(be.size("k").await.unwrap(), None);+ assert!(be.read("k", 0, 10).await.is_err());++ // No leftover files under the job dir (partial temp cleaned up, no key file).+ let mut entries = tokio::fs::read_dir(root.path().join("job-TEST"))+ .await+ .unwrap();+ assert!(entries.next_entry().await.unwrap().is_none());+ }++ #[tokio::test]+ async fn misaligned_reads_reconstruct_body() {+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ assert_reads_reconstruct(&be, "k", TEST_RECORD_BODY).await;+ }++ #[tokio::test]+ async fn restage_overwrites_atomically() {+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ stage_bytes(&be, "k", b"first version").await.unwrap();+ let size = stage_bytes(&be, "k", b"second").await.unwrap();+ assert_eq!(size, 6);+ assert_eq!(be.read("k", 0, 100).await.unwrap(), b"second");+ }++ #[tokio::test]+ async fn cleanup_key_is_idempotent() {+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ stage_bytes(&be, "k", b"data").await.unwrap();+ be.cleanup_key("k").await.unwrap();+ assert_eq!(be.size("k").await.unwrap(), None);+ // Second delete of an absent key is a no-op, not an error.+ be.cleanup_key("k").await.unwrap();+ }++ #[tokio::test]+ async fn cleanup_job_removes_all_staging() {+ let root = TempDir::new().unwrap();+ let be = backend(root.path());+ stage_bytes(&be, "a", b"aaa").await.unwrap();+ stage_bytes(&be, "b", b"bbb").await.unwrap();+ be.cleanup_job().await.unwrap();+ assert_eq!(be.size("a").await.unwrap(), None);+ assert_eq!(be.size("b").await.unwrap(), None);+ // Idempotent: cleaning an already-removed job dir is fine.+ be.cleanup_job().await.unwrap();+ }++ #[tokio::test]+ async fn sanitize_key_neutralizes_separators() {+ assert_eq!(sanitize_key("2024-01-01:00"), "2024-01-01_00");+ assert_eq!(sanitize_key("path/to/key"), "path_to_key");+ assert_eq!(sanitize_key("a:b/c"), "a_b_c");+ }+}diff --git a/rust/batch-import-worker/src/staging.rs b/rust/batch-import-worker/src/staging/mod.rssimilarity index 98%rename from rust/batch-import-worker/src/staging.rsrename to rust/batch-import-worker/src/staging/mod.rsindex 02c91d314808..24b418d51dde 100644--- a/rust/batch-import-worker/src/staging.rs+++ b/rust/batch-import-worker/src/staging/mod.rs@@ -5,6 +5,15 @@ use tracing::{info, warn};use crate::error::UserError;+pub mod backend;+pub mod pipeline;+pub mod s3_client;+pub mod temp_bucket;++pub use backend::{LocalDiskBackend, PlaintextStream, StagingBackend};+pub use pipeline::open_plaintext_stream;+pub use temp_bucket::TempBucketBackend;+/// Default amount of freshly-written data between staging-size checks. Stat-ing/// the whole staging tree is O(files), so we only re-measure after this much has/// been written, bounding overshoot to roughly this value plus one download chunk.diff --git a/rust/batch-import-worker/src/staging/pipeline.rs b/rust/batch-import-worker/src/staging/pipeline.rsnew file mode 100644index 000000000000..0c400a08393d--- /dev/null+++ b/rust/batch-import-worker/src/staging/pipeline.rs@@ -0,0 +1,352 @@+use std::path::PathBuf;++use anyhow::Error;+use bytes::Bytes;+use tokio::sync::mpsc;++use crate::error::UserError;+use crate::extractor::{+ run_plain_gzip_producer, run_zip_gzip_json_producer, spawn_producer_thread, ExtractorType,+};++use super::backend::PlaintextStream;++// Bounded adapter channel depth: backpressure caps in-flight decompressed bytes.+const CHANNEL_CAPACITY: usize = 16;++/// Open a forward, on-demand decompression stream over a compressed `.raw` file.+///+/// This reuses the exact producers behind [`crate::extractor::StreamingReader`]+/// (`run_plain_gzip_producer` / `run_zip_gzip_json_producer`), so the emitted plaintext is+/// byte-identical to what the streaming read path decodes — same single-member+/// `GzDecoder` semantics, same natural-sort member ordering, same trailing-newline+/// normalization — by construction, not by parallel implementation. That identity is what+/// keeps a part's byte offsets valid across staging backends.+///+/// The producer runs on a dedicated OS thread (via the shared, panic-guarded+/// [`spawn_producer_thread`]); a small async adapter task converts its blocks and applies+/// the ceiling.+///+/// `max_plaintext_bytes` is a per-part decompressed-byte ceiling (0 = disabled): if the+/// emitted plaintext exceeds it, the stream yields a user-facing error that pauses the+/// job instead of staging unbounded output. This is a decompression-bomb / cost guard,+/// not a disk guard.+pub fn open_plaintext_stream(+ raw_path: PathBuf,+ extractor: ExtractorType,+ max_plaintext_bytes: u64,+) -> PlaintextStream {+ let block_rx = match extractor {+ ExtractorType::PlainGzip => {+ spawn_producer_thread(move |tx| run_plain_gzip_producer(raw_path, tx))+ }+ ExtractorType::ZipGzipJson => {+ spawn_producer_thread(move |tx| run_zip_gzip_json_producer(raw_path, tx))+ }+ };++ let (tx, rx) = mpsc::channel(CHANNEL_CAPACITY);+ // Attach the adapter handle so a panic in the adapter itself is surfaced as a stream+ // error at EOF instead of masquerading as a clean end-of-stream. Producer-thread+ // panics are already converted to channel errors by spawn_producer_thread.+ let handle = tokio::spawn(adapt_blocks(block_rx, tx, max_plaintext_bytes));+ PlaintextStream::from_producer(rx, handle)+}++/// Forward producer blocks to the plaintext channel, converting `Block` errors into+/// `anyhow` errors and enforcing the decompressed-byte ceiling at this single choke point.+async fn adapt_blocks(+ mut block_rx: mpsc::Receiver<crate::extractor::Block>,+ tx: mpsc::Sender<Result<Bytes, Error>>,+ max_plaintext_bytes: u64,+) {+ let mut total: u64 = 0;+ while let Some(block) = block_rx.recv().await {+ match block {+ Ok(block) => {+ total += block.len() as u64;+ if max_plaintext_bytes > 0 && total > max_plaintext_bytes {+ let _unused = tx+ .send(Err(plaintext_ceiling_error(total, max_plaintext_bytes)))+ .await;+ return;+ }+ if tx.send(Ok(Bytes::from(block))).await.is_err() {+ return;+ }+ }+ Err(msg) => {+ let _unused = tx.send(Err(Error::msg(msg))).await;+ return;+ }+ }+ }+}++/// Build the ceiling-breach error (classifies as Pause). Returned once the running+/// plaintext total exceeds a non-zero limit.+///+/// Two channels, per the worker's error convention: the `UserError` context is the+/// public, actionable message (no internal config names — the limit may be operator-set+/// or derived, and either way the remedy is the same); the root error carries the+/// internal detail for `status_message` and logs.+fn plaintext_ceiling_error(total: u64, max_plaintext_bytes: u64) -> Error {+ crate::metrics::staged_plaintext_ceiling_tripped();+ const GIB: f64 = (1024 * 1024 * 1024) as f64;+ let user_msg = format!(+ "Import part decompressed to {:.2} GiB, exceeding the {:.2} GiB maximum for a \+ single part. Split the import into smaller date ranges (direct imports) or \+ smaller files (S3 imports) and run them as separate jobs.",+ total as f64 / GIB,+ max_plaintext_bytes as f64 / GIB,+ );+ Error::msg(format!(+ "staged plaintext exceeded ceiling: {total} bytes > STAGED_PLAINTEXT_MAX_BYTES={max_plaintext_bytes}"+ ))+ .context(UserError::new(user_msg))+}++#[cfg(test)]+mod tests {+ use super::*;+ use flate2::{write::GzEncoder, Compression};+ use std::fs::File as StdFile;+ use std::io::Write;+ use tempfile::TempDir;+ use zip::{write::SimpleFileOptions, ZipWriter};++ fn write_gzip(content: &[u8], path: &std::path::Path) {+ let file = StdFile::create(path).unwrap();+ let mut encoder = GzEncoder::new(file, Compression::default());+ encoder.write_all(content).unwrap();+ encoder.finish().unwrap();+ }++ fn write_zip_of_gzip(members: &[(&str, &[u8])], path: &std::path::Path) {+ let file = StdFile::create(path).unwrap();+ let mut zip = ZipWriter::new(file);+ for (name, content) in members {+ zip.start_file(*name, SimpleFileOptions::default()).unwrap();+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());+ encoder.write_all(content).unwrap();+ let compressed = encoder.finish().unwrap();+ zip.write_all(&compressed).unwrap();+ }+ zip.finish().unwrap();+ }++ async fn collect(mut stream: PlaintextStream) -> Result<Vec<u8>, Error> {+ let mut out = Vec::new();+ while let Some(block) = stream.next().await {+ out.extend_from_slice(&block?);+ }+ Ok(out)+ }++ /// Bytes the streaming read path decodes for the same file — the oracle the pipeline+ /// must reproduce exactly (both consume the same producers; this locks the adapter).+ async fn reader_oracle(extractor: ExtractorType, raw_path: &std::path::Path) -> Vec<u8> {+ let mut reader = extractor+ .create_extractor()+ .open_reader(raw_path.to_path_buf());+ let (bytes, total) = reader.read_to_end_for_test(8192).await;+ assert_eq!(bytes.len() as u64, total);+ bytes+ }++ /// Assert the pipeline matches both the streaming reader and, when provided, an+ /// explicit expected byte string (so the oracle is not purely self-referential).+ async fn assert_pipeline_output(+ extractor: ExtractorType,+ raw_path: PathBuf,+ expected: Option<&[u8]>,+ ) {+ let oracle = reader_oracle(extractor.clone(), &raw_path).await;+ if let Some(expected) = expected {+ assert_eq!(oracle, expected, "oracle must match explicit fixture");+ }+ let actual = collect(open_plaintext_stream(raw_path, extractor, 0))+ .await+ .unwrap();+ assert_eq!(actual, oracle);+ }++ #[tokio::test]+ async fn plain_gzip_with_trailing_newline_matches_reader() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.raw");+ write_gzip(b"line1\nline2\nline3\n", &raw);+ assert_pipeline_output(+ ExtractorType::PlainGzip,+ raw,+ Some(b"line1\nline2\nline3\n"),+ )+ .await;+ }++ #[tokio::test]+ async fn plain_gzip_without_trailing_newline_appends_one() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.raw");+ write_gzip(b"line1\nline2\nline3", &raw);+ assert_pipeline_output(+ ExtractorType::PlainGzip,+ raw,+ Some(b"line1\nline2\nline3\n"),+ )+ .await;+ }++ #[tokio::test]+ async fn empty_gzip_yields_no_bytes_and_no_newline() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.raw");+ write_gzip(b"", &raw);+ assert_pipeline_output(ExtractorType::PlainGzip, raw, Some(b"")).await;+ }++ #[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.+ 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"+ );+ }++ #[tokio::test]+ async fn zip_with_no_json_gz_members_yields_no_bytes() {+ // An archive with no data members decompresses to nothing: an empty part,+ // not an error and not a stall.+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.zip");+ let file = StdFile::create(&raw).unwrap();+ let mut zip = ZipWriter::new(file);+ zip.start_file("readme.txt", SimpleFileOptions::default())+ .unwrap();+ zip.write_all(b"no data for this export").unwrap();+ zip.finish().unwrap();++ assert_pipeline_output(ExtractorType::ZipGzipJson, raw, Some(b"")).await;+ }++ #[tokio::test]+ async fn large_plain_gzip_matches_reader() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.raw");+ // Many producer blocks; no explicit fixture needed, reader oracle suffices.+ write_gzip("line\n".repeat(100_000).as_bytes(), &raw);+ assert_pipeline_output(ExtractorType::PlainGzip, raw, None).await;+ }++ #[tokio::test]+ async fn zip_multi_member_preserves_natsort_order_and_per_member_newlines() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.zip");+ // Out of natural order in the archive; members 001 and 010 need appended newlines.+ write_zip_of_gzip(+ &[+ ("010.json.gz", b"{\"id\":10}"),+ ("002.json.gz", b"{\"id\":2}\n"),+ ("001.json.gz", b"{\"id\":1}"),+ ],+ &raw,+ );+ assert_pipeline_output(+ ExtractorType::ZipGzipJson,+ raw,+ Some(b"{\"id\":1}\n{\"id\":2}\n{\"id\":10}\n"),+ )+ .await;+ }++ #[tokio::test]+ async fn zip_ignores_non_json_gz_members() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.zip");+ let file = StdFile::create(&raw).unwrap();+ let mut zip = ZipWriter::new(file);+ zip.start_file("data.json.gz", SimpleFileOptions::default())+ .unwrap();+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());+ encoder.write_all(b"valid json").unwrap();+ let compressed = encoder.finish().unwrap();+ zip.write_all(&compressed).unwrap();+ zip.start_file("readme.txt", SimpleFileOptions::default())+ .unwrap();+ zip.write_all(b"ignore me").unwrap();+ zip.finish().unwrap();++ assert_pipeline_output(ExtractorType::ZipGzipJson, raw, Some(b"valid json\n")).await;+ }++ #[tokio::test]+ async fn truncated_gzip_surfaces_error_not_silent_truncation() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.raw");+ write_gzip(b"some content that will be cut off midstream", &raw);+ // Chop the gzip trailer/body so decoding fails partway.+ let full = std::fs::read(&raw).unwrap();+ std::fs::write(&raw, &full[..full.len() - 5]).unwrap();++ let result = collect(open_plaintext_stream(raw, ExtractorType::PlainGzip, 0)).await;+ assert!(result.is_err(), "truncated gzip must surface an error");+ }++ #[tokio::test]+ async fn ceiling_breach_yields_pause_classified_user_error() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.raw");+ write_gzip("x".repeat(100_000).as_bytes(), &raw);++ let err = collect(open_plaintext_stream(raw, ExtractorType::PlainGzip, 1024))+ .await+ .unwrap_err();++ // Actionable public message survives in the chain (so the job pauses, not+ // retries), is GiB-formatted, and leaks no internal config names.+ let user_msg = crate::error::get_user_message(&err);+ assert!(user_msg.contains("GiB"), "unexpected message: {user_msg}");+ assert!(+ user_msg.contains("Split the import"),+ "unexpected message: {user_msg}"+ );+ assert!(+ !user_msg.contains("STAGED_PLAINTEXT_MAX_BYTES"),+ "public message must not leak env var names: {user_msg}"+ );+ // The internal chain keeps the config detail for status_message/logs.+ let internal = format!("{err:#}");+ assert!(+ internal.contains("STAGED_PLAINTEXT_MAX_BYTES=1024"),+ "internal chain must carry the limit detail: {internal}"+ );+ // Not classified as a transient/retryable 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 ceiling_disabled_with_zero_never_trips() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("a.raw");+ // Newline-terminated so nothing is appended and the length is exact.+ write_gzip("y\n".repeat(25_000).as_bytes(), &raw);+ let actual = collect(open_plaintext_stream(raw, ExtractorType::PlainGzip, 0))+ .await+ .unwrap();+ assert_eq!(actual.len(), 50_000);+ }+}diff --git a/rust/batch-import-worker/src/staging/s3_client.rs b/rust/batch-import-worker/src/staging/s3_client.rsnew file mode 100644index 000000000000..a81458c25ee8--- /dev/null+++ b/rust/batch-import-worker/src/staging/s3_client.rs@@ -0,0 +1,85 @@+use std::sync::Arc;+use std::time::Duration;++use anyhow::{Context, Result};+use object_store::aws::AmazonS3Builder;+use object_store::limit::LimitStore;+use object_store::{ClientOptions, ObjectStore};+use tracing::{debug, info};++use crate::config::Config;++/// Build the `object_store` client for the temp bucket from config, following the+/// kafka-deduplicator checkpoint client pattern (the repo standard for S3 access).+///+/// Credential priority:+/// 1. Explicit credentials from config (local dev / CI against SeaweedFS)+/// 2. IRSA via `AWS_WEB_IDENTITY_TOKEN_FILE` + `AWS_ROLE_ARN` (EKS production)+/// 3. Default AWS credential chain (env vars, config files, IMDS)+///+/// Timeouts and retries are config-driven: the attempt timeout must fit a full+/// CHUNK_SIZE (~100 MB) ranged GET, and client-level retries are kept small because+/// job-level backoff retries on top. The store is wrapped in a `LimitStore` to cap+/// concurrent requests per job client.+///+/// Deliberately NOT validated eagerly here: the client is built per job, and a+/// `Job::new` failure pauses the job without transient-error classification — an+/// eager bucket probe would turn an S3 blip into a paused customer job. The first+/// HEAD/PUT of part 1 validates seconds later on a path with proper classification+/// (blip -> backoff, misconfig -> clear pause).+pub async fn create_temp_bucket_store(config: &Config) -> Result<Arc<dyn ObjectStore>> {+ let mut builder = AmazonS3Builder::from_env()+ .with_bucket_name(&config.temp_bucket_name)+ .with_client_options(+ ClientOptions::new()+ .with_timeout(Duration::from_secs(config.temp_bucket_attempt_timeout_secs)),+ )+ .with_retry(object_store::RetryConfig {+ max_retries: config.temp_bucket_max_retries,+ retry_timeout: Duration::from_secs(config.temp_bucket_operation_timeout_secs),+ ..Default::default()+ });++ if let Some(region) = config.temp_bucket_region() {+ builder = builder.with_region(region);+ }++ // Custom endpoint for local dev / CI (SeaweedFS).+ if let Some(endpoint) = config.temp_bucket_endpoint() {+ builder = builder.with_endpoint(endpoint);+ if endpoint.starts_with("http://") {+ builder = builder.with_allow_http(true);+ }+ }++ // Explicit credentials override env (local dev / CI without IAM).+ if let Some((access_key, secret_key)) = config.temp_bucket_credentials() {+ info!("Temp bucket: using explicit S3 credentials from config");+ builder = builder+ .with_access_key_id(access_key)+ .with_secret_access_key(secret_key);+ } else if std::env::var("AWS_WEB_IDENTITY_TOKEN_FILE").is_ok()+ && std::env::var("AWS_ROLE_ARN").is_ok()+ {+ info!("Temp bucket: using IRSA credentials (AWS_WEB_IDENTITY_TOKEN_FILE + AWS_ROLE_ARN)");+ } else {+ debug!("Temp bucket: using default AWS credential chain");+ }++ // Path-style object URLs (required by S3-compatible dev stores like SeaweedFS).+ if config.temp_bucket_force_path_style {+ builder = builder.with_virtual_hosted_style_request(false);+ }++ let store = builder.build().with_context(|| {+ format!(+ "Failed to build temp-bucket S3 client for bucket '{}'",+ config.temp_bucket_name+ )+ })?;++ Ok(Arc::new(LimitStore::new(+ store,+ config.temp_bucket_max_concurrent_requests,+ )))+}diff --git a/rust/batch-import-worker/src/staging/temp_bucket.rs b/rust/batch-import-worker/src/staging/temp_bucket.rsnew file mode 100644index 000000000000..7c67b3dd328b--- /dev/null+++ b/rust/batch-import-worker/src/staging/temp_bucket.rs@@ -0,0 +1,503 @@+use std::collections::HashMap;+use std::sync::Arc;+use std::time::Instant;++use anyhow::{Context, Error};+use async_trait::async_trait;+use futures_util::StreamExt;+use object_store::buffered::BufWriter;+use object_store::path::Path as ObjectPath;+use object_store::{ObjectStore, ObjectStoreExt};+use tokio::io::AsyncWriteExt;+use tokio::sync::Mutex;+use tracing::warn;++use crate::config::Config;+use crate::metrics;++use super::backend::{sanitize_key, PlaintextStream, StagingBackend};+use super::s3_client::create_temp_bucket_store;++/// Multipart part size for staging uploads. Each part is buffered in memory, and S3+/// caps a multipart upload at 10,000 parts, so this bounds both the upload's RAM+/// footprint (part_size x (concurrency + 1)) and the maximum staged object size+/// (part_size x 10,000). 64 MiB => 640 GiB max part. Config-overridable.+const DEFAULT_UPLOAD_PART_SIZE_BYTES: usize = 64 * 1024 * 1024;+/// In-flight part uploads while staging. Staging throughput is producer-bound+/// (origin download + gzip decode), so a small window keeps uploads fully+/// overlapped without multiplying memory. Config-overridable.+const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;++/// Stages part plaintext as an object in an internal S3 "temp bucket", reading it back+/// with ranged GETs. Layout: `{prefix}{job_id}/{sanitized_key}.data`.+///+/// A part is written via a multipart-capable `BufWriter` that only completes the upload on+/// full success, so a failed ingest leaves no readable object — `head`/`read` never observe+/// a torn part. That atomicity is what makes head-based resume (skip re-ingest when a+/// completed object already exists) safe.+pub struct TempBucketBackend {+ store: Arc<dyn ObjectStore>,+ // Normalized to end with '/'.+ prefix: String,+ job_id: String,+ upload_part_size: usize,+ upload_concurrency: usize,+ // Sizes recorded at stage time; on a cold process they are recovered via `head`.+ sizes: Mutex<HashMap<String, u64>>,+}++impl TempBucketBackend {+ /// Construct from an existing store (used by tests with in-memory / dev stores).+ pub fn new(+ store: Arc<dyn ObjectStore>,+ prefix: impl Into<String>,+ job_id: impl Into<String>,+ ) -> Self {+ let mut prefix = prefix.into();+ if !prefix.is_empty() && !prefix.ends_with('/') {+ prefix.push('/');+ }+ Self {+ store,+ prefix,+ job_id: job_id.into(),+ upload_part_size: DEFAULT_UPLOAD_PART_SIZE_BYTES,+ upload_concurrency: DEFAULT_UPLOAD_CONCURRENCY,+ sizes: Mutex::new(HashMap::new()),+ }+ }++ /// Override the multipart upload geometry (part size bounds the max staged object+ /// size at part_size x 10,000; concurrency bounds upload memory). Used by+ /// `from_config` and by tests that force many small parts.+ pub fn with_upload_tuning(mut self, part_size: usize, concurrency: usize) -> Self {+ self.upload_part_size = part_size;+ self.upload_concurrency = concurrency;+ self+ }++ /// Construct from config, building the S3 client from the standard credential chain.+ pub async fn from_config(config: &Config, job_id: impl Into<String>) -> Result<Self, Error> {+ let store = create_temp_bucket_store(config).await?;+ Ok(+ Self::new(store, config.temp_bucket_prefix.clone(), job_id).with_upload_tuning(+ config.temp_bucket_upload_part_size_bytes as usize,+ config.temp_bucket_upload_concurrency,+ ),+ )+ }++ fn object_path(&self, key: &str) -> ObjectPath {+ ObjectPath::from(format!(+ "{}{}/{}.data",+ self.prefix,+ self.job_id,+ sanitize_key(key)+ ))+ }++ fn job_prefix(&self) -> ObjectPath {+ ObjectPath::from(format!("{}{}/", self.prefix, self.job_id))+ }+}++#[async_trait]+impl StagingBackend for TempBucketBackend {+ async fn cleanup_job(&self) -> Result<(), Error> {+ let prefix = self.job_prefix();+ let mut stream = self.store.list(Some(&prefix));+ while let Some(item) = stream.next().await {+ match item {+ Ok(meta) => {+ if let Err(e) = self.store.delete(&meta.location).await {+ warn!("Failed to delete staged object {}: {e}", meta.location);+ }+ }+ Err(e) => warn!("Failed to list staged objects under {prefix}: {e}"),+ }+ }+ self.sizes.lock().await.clear();+ Ok(())+ }++ async fn stage_part(&self, key: &str, mut plaintext: PlaintextStream) -> Result<u64, Error> {+ let path = self.object_path(key);+ let mut writer =+ BufWriter::with_capacity(Arc::clone(&self.store), path, self.upload_part_size)+ .with_max_concurrency(self.upload_concurrency);+ let started = Instant::now();++ let mut total: u64 = 0;+ while let Some(block) = plaintext.next().await {+ match block {+ Ok(block) => {+ if let Err(e) = writer.write_all(&block).await {+ abort_quietly(&mut writer, key).await;+ return Err(Error::from(e)+ .context(format!("Failed to write staged data for key: {key}")));+ }+ total += block.len() as u64;+ }+ Err(e) => {+ // Decode/ceiling error from the pipeline: abort so no readable object+ // is left, and preserve the (possibly user-facing) error chain.+ abort_quietly(&mut writer, key).await;+ return Err(e.context(format!("Failed to stage part for key: {key}")));+ }+ }+ }++ // shutdown() completes the multipart upload — the object becomes visible only here.+ writer+ .shutdown()+ .await+ .with_context(|| format!("Failed to complete staged upload for key: {key}"))?;++ self.sizes.lock().await.insert(key.to_string(), total);+ metrics::temp_bucket_part_staged(total, started.elapsed().as_secs_f64());+ Ok(total)+ }++ async fn size(&self, key: &str) -> Result<Option<u64>, Error> {+ if let Some(size) = self.sizes.lock().await.get(key).copied() {+ return Ok(Some(size));+ }+ match self.store.head(&self.object_path(key)).await {+ Ok(meta) => {+ // Cache the recovered size so a resumed job doesn't re-head the same+ // object on every prepare_key/read iteration. Invalidated by+ // cleanup_key/cleanup_job and by a NotFound read (object deleted+ // out-of-band, e.g. bucket TTL on a long-paused job).+ self.sizes.lock().await.insert(key.to_string(), meta.size);+ Ok(Some(meta.size))+ }+ Err(object_store::Error::NotFound { .. }) => Ok(None),+ Err(e) => {+ Err(Error::from(e).context(format!("Failed to head staged object for key: {key}")))+ }+ }+ }++ async fn read(&self, key: &str, offset: u64, size: u64) -> Result<Vec<u8>, Error> {+ let total_size = match self.size(key).await? {+ Some(s) => s,+ None => return Err(Error::msg(format!("Key not staged: {key}"))),+ };++ if total_size == 0 || offset >= total_size {+ return Ok(Vec::new());+ }++ let end_offset = std::cmp::min(offset + size, total_size);+ let started = Instant::now();+ match self+ .store+ .get_range(&self.object_path(key), offset..end_offset)+ .await+ {+ Ok(bytes) => {+ metrics::temp_bucket_read(started.elapsed().as_secs_f64());+ Ok(bytes.to_vec())+ }+ Err(object_store::Error::NotFound { .. }) => {+ // The object was deleted out-of-band (e.g. bucket TTL) after its size+ // was cached. Drop the stale entry so the next prepare_key sees the+ // key as unstaged and re-ingests from origin instead of failing every+ // read against a cached size.+ self.sizes.lock().await.remove(key);+ Err(Error::msg(format!(+ "Staged object for key {key} disappeared (deleted out-of-band); \+ it will be re-staged on the next attempt"+ )))+ }+ Err(e) => {+ Err(Error::from(e).context(format!("Failed to read staged object for key: {key}")))+ }+ }+ }++ async fn cleanup_key(&self, key: &str) -> Result<(), Error> {+ match self.store.delete(&self.object_path(key)).await {+ Ok(()) => {}+ Err(object_store::Error::NotFound { .. }) => {}+ Err(e) => {+ return Err(Error::from(e)+ .context(format!("Failed to delete staged object for key: {key}")))+ }+ }+ self.sizes.lock().await.remove(key);+ Ok(())+ }+}++/// Abort an in-flight multipart upload, logging (not failing) if the abort itself errors.+/// Atomicity holds either way — an aborted or failed upload leaves no readable object — but a+/// failed abort can orphan multipart parts until the bucket lifecycle rule reclaims them, so+/// make that visible to operators.+async fn abort_quietly(writer: &mut BufWriter, key: &str) {+ if let Err(abort_err) = writer.abort().await {+ warn!("Failed to abort staged upload for key {key}: {abort_err}");+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::extractor::ExtractorType;+ use crate::staging::backend::LocalDiskBackend;+ use crate::staging::open_plaintext_stream;+ use bytes::Bytes;+ use flate2::{write::GzEncoder, Compression};+ use object_store::memory::InMemory;+ use std::io::Write;+ use tempfile::TempDir;+ use tokio::sync::mpsc;++ fn backend() -> TempBucketBackend {+ TempBucketBackend::new(+ Arc::new(InMemory::new()),+ "batch-import-staging/",+ "job-TEST",+ )+ }++ async fn stage_bytes(be: &TempBucketBackend, key: &str, data: &[u8]) -> u64 {+ let stream = PlaintextStream::from_chunks(vec![Bytes::copy_from_slice(data)]);+ be.stage_part(key, stream).await.unwrap()+ }++ #[tokio::test]+ async fn round_trip_read_slices() {+ let be = backend();+ let body = b"line one\nline two\nline three\n";+ let size = stage_bytes(&be, "2024-01-01:00", body).await;+ assert_eq!(size, body.len() as u64);+ assert_eq!(+ be.size("2024-01-01:00").await.unwrap(),+ Some(body.len() as u64)+ );++ assert_eq!(be.read("2024-01-01:00", 0, 1000).await.unwrap(), body);+ assert_eq!(be.read("2024-01-01:00", 9, 8).await.unwrap(), b"line two");+ assert_eq!(+ be.read("2024-01-01:00", 18, 1000).await.unwrap(),+ b"line three\n"+ );+ assert!(be+ .read("2024-01-01:00", body.len() as u64, 10)+ .await+ .unwrap()+ .is_empty());+ }++ #[tokio::test]+ async fn empty_part_reports_zero_and_reads_empty() {+ let be = backend();+ assert_eq!(stage_bytes(&be, "empty", b"").await, 0);+ assert_eq!(be.size("empty").await.unwrap(), Some(0));+ assert!(be.read("empty", 0, 100).await.unwrap().is_empty());+ }++ #[tokio::test]+ async fn size_none_and_read_errors_for_unstaged_key() {+ let be = backend();+ assert_eq!(be.size("missing").await.unwrap(), None);+ assert!(be.read("missing", 0, 10).await.is_err());+ }++ #[tokio::test]+ async fn misaligned_reads_reconstruct_body() {+ let be = backend();+ crate::staging::backend::assert_reads_reconstruct(+ &be,+ "2024-01-01:00",+ crate::staging::backend::TEST_RECORD_BODY,+ )+ .await;+ }++ #[tokio::test]+ async fn cross_backend_byte_identity_with_local_disk() {+ // The load-bearing guarantee: the same compressed part staged through the pipeline+ // yields identical bytes + size on both backends, so a part's offsets stay valid+ // when the staging backend is flipped.+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("part.raw");+ {+ let file = std::fs::File::create(&raw).unwrap();+ let mut enc = GzEncoder::new(file, Compression::default());+ // No trailing newline: exercises the appended-newline path on both backends.+ enc.write_all(b"{\"a\":1}\n{\"b\":2}\n{\"c\":3}").unwrap();+ enc.finish().unwrap();+ }++ let local = LocalDiskBackend::new(dir.path().join("job-X"));+ let temp = backend();++ let local_size = local+ .stage_part(+ "k",+ open_plaintext_stream(raw.clone(), ExtractorType::PlainGzip, 0),+ )+ .await+ .unwrap();+ let temp_size = temp+ .stage_part("k", open_plaintext_stream(raw, ExtractorType::PlainGzip, 0))+ .await+ .unwrap();++ assert_eq!(local_size, temp_size);+ let local_bytes = local.read("k", 0, local_size + 10).await.unwrap();+ let temp_bytes = temp.read("k", 0, temp_size + 10).await.unwrap();+ assert_eq!(local_bytes, temp_bytes);+ assert_eq!(local_bytes, b"{\"a\":1}\n{\"b\":2}\n{\"c\":3}\n");+ }++ #[tokio::test]+ async fn head_recovers_size_on_cold_process() {+ // Simulate a restart: a completed object exists, but a fresh backend has an empty+ // in-memory size map. It must recover size/read via head without re-staging.+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let body = b"resumed body\n";+ {+ let warm = TempBucketBackend::new(Arc::clone(&store), "p/", "job-R");+ stage_bytes(&warm, "k", body).await;+ }+ let cold = TempBucketBackend::new(store, "p/", "job-R");+ assert_eq!(cold.size("k").await.unwrap(), Some(body.len() as u64));+ assert_eq!(cold.read("k", 0, 1000).await.unwrap(), body);+ }++ #[tokio::test]+ async fn failed_stage_leaves_no_readable_object() {+ // A pipeline error mid-stream must abort the upload so head sees nothing — the+ // property that makes head-based resume safe (no torn parts).+ let be = backend();+ let (tx, rx) = mpsc::channel(4);+ tx.send(Ok(Bytes::from_static(b"partial data")))+ .await+ .unwrap();+ tx.send(Err(anyhow::anyhow!("decode blew up")))+ .await+ .unwrap();+ drop(tx);++ let result = be.stage_part("k", PlaintextStream::new(rx)).await;+ assert!(result.is_err());+ assert_eq!(be.size("k").await.unwrap(), None);+ assert!(be.read("k", 0, 10).await.is_err());+ }++ #[tokio::test]+ async fn cleanup_key_is_idempotent() {+ let be = backend();+ stage_bytes(&be, "k", b"data").await;+ be.cleanup_key("k").await.unwrap();+ assert_eq!(be.size("k").await.unwrap(), None);+ // Second delete of an absent object is a no-op.+ be.cleanup_key("k").await.unwrap();+ }++ #[tokio::test]+ async fn cleanup_job_sweeps_all_objects_under_prefix() {+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let be = TempBucketBackend::new(Arc::clone(&store), "batch-import-staging/", "job-S");+ stage_bytes(&be, "a", b"aaa").await;+ stage_bytes(&be, "b", b"bbb").await;++ // A sibling job's object must be left untouched by this job's sweep.+ let other =+ TempBucketBackend::new(Arc::clone(&store), "batch-import-staging/", "job-OTHER");+ stage_bytes(&other, "c", b"ccc").await;++ be.cleanup_job().await.unwrap();+ assert_eq!(be.size("a").await.unwrap(), None);+ assert_eq!(be.size("b").await.unwrap(), None);+ assert_eq!(other.size("c").await.unwrap(), Some(3));+ // Idempotent.+ be.cleanup_job().await.unwrap();+ }++ #[tokio::test]+ async fn multi_part_upload_is_byte_identical_to_oracle() {+ // Force a genuine multi-part upload (part size far below the body) and prove+ // the assembled object is byte-identical to the LocalDiskBackend oracle —+ // the guarantee that raising TEMP_BUCKET_UPLOAD_PART_SIZE_BYTES only moves+ // the size wall, never the bytes.+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("part.raw");+ let body: String = (0..2_000).map(|i| format!("{{\"n\":{i}}}\n")).collect();+ {+ let file = std::fs::File::create(&raw).unwrap();+ let mut enc = GzEncoder::new(file, Compression::default());+ enc.write_all(body.as_bytes()).unwrap();+ enc.finish().unwrap();+ }++ let local = LocalDiskBackend::new(dir.path().join("job-X"));+ // 1 KiB parts x concurrency 2: the ~22 KB body spans many parts.+ let temp = TempBucketBackend::new(Arc::new(InMemory::new()), "p/", "job-MP")+ .with_upload_tuning(1024, 2);++ let local_size = local+ .stage_part(+ "k",+ open_plaintext_stream(raw.clone(), ExtractorType::PlainGzip, 0),+ )+ .await+ .unwrap();+ let temp_size = temp+ .stage_part("k", open_plaintext_stream(raw, ExtractorType::PlainGzip, 0))+ .await+ .unwrap();++ assert_eq!(local_size, temp_size);+ assert!(+ temp_size > 10 * 1024,+ "body must span many 1 KiB parts (got {temp_size} bytes)"+ );+ let local_bytes = local.read("k", 0, local_size).await.unwrap();+ let temp_bytes = temp.read("k", 0, temp_size).await.unwrap();+ assert_eq!(local_bytes, temp_bytes);+ // Misaligned ranged reads over the multi-part object reconstruct exactly.+ crate::staging::backend::assert_reads_reconstruct(+ &temp,+ "k2",+ crate::staging::backend::TEST_RECORD_BODY,+ )+ .await;+ }++ #[tokio::test]+ async fn head_size_is_cached_and_invalidated_by_notfound_read() {+ // Cold size() recovers via head and caches; an out-of-band deletion (bucket+ // TTL, manual sweep) surfaces as a NotFound read that must invalidate the+ // cache so the next prepare_key re-ingests instead of failing forever.+ let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());+ let body = b"cached body\n";+ {+ let warm = TempBucketBackend::new(Arc::clone(&store), "p/", "job-C");+ stage_bytes(&warm, "k", body).await;+ }++ let cold = TempBucketBackend::new(Arc::clone(&store), "p/", "job-C");+ assert_eq!(cold.size("k").await.unwrap(), Some(body.len() as u64));++ // Delete the object out-of-band. The cached size still answers (proves the+ // head result was cached — no re-head per call)...+ store+ .delete(&ObjectPath::from("p/job-C/k.data"))+ .await+ .unwrap();+ assert_eq!(cold.size("k").await.unwrap(), Some(body.len() as u64));++ // ...but a read observes NotFound, invalidates the entry, and the next+ // size() sees the key as unstaged (the re-ingest trigger).+ let err = cold.read("k", 0, 10).await.unwrap_err();+ assert!(+ err.to_string().contains("disappeared"),+ "unexpected error: {err:#}"+ );+ assert_eq!(cold.size("k").await.unwrap(), None);+ }+}diff --git a/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs b/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rsindex 6e6119e1c98a..958c4d1cea0a 100644--- a/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs+++ b/rust/batch-import-worker/tests/s3_gzip_minio_integration_test.rs@@ -108,7 +108,7 @@ async fn test_s3_gzip_minio_integration() {let _staging = tempfile::TempDir::new().expect("create staging dir");let source = s3_config- .create_gzip_source(&secrets, _staging.path().to_path_buf(), 0)+ .create_gzip_source(&secrets, _staging.path().to_path_buf(), 0, None, 0).await.expect("create gzip source");source.prepare_for_job().await.expect("prepare for job");diff --git a/rust/batch-import-worker/tests/temp_bucket_seaweedfs_integration_test.rs b/rust/batch-import-worker/tests/temp_bucket_seaweedfs_integration_test.rsnew file mode 100644index 000000000000..415d8cb3673c--- /dev/null+++ b/rust/batch-import-worker/tests/temp_bucket_seaweedfs_integration_test.rs@@ -0,0 +1,222 @@+//! SeaweedFS integration test for the temp-bucket staging backend: stage a compressed+//! part through the real decompress pipeline into a live S3-compatible store, then read it+//! back by byte range and clean it up.+//!+//! Requires SeaweedFS running at localhost:8333 with a `posthog` bucket (docker-compose.dev.yml).+//! Skips if unreachable. No MinIO dependency.++use std::collections::HashMap;+use std::sync::Arc;++use batch_import_worker::extractor::ExtractorType;+use batch_import_worker::source::date_range_export::{AuthConfig, DateRangeExportSource};+use batch_import_worker::source::{DataSource, RemoteStaging};+use batch_import_worker::staging::{open_plaintext_stream, StagingBackend, TempBucketBackend};+use chrono::{TimeZone, Utc};+use flate2::write::GzEncoder;+use flate2::Compression;+use httpmock::MockServer;+use object_store::aws::AmazonS3Builder;+use object_store::{ObjectStore, ObjectStoreExt};+use std::io::Write;+use uuid::Uuid;++const SEAWEEDFS_ENDPOINT: &str = "http://localhost:8333";+const TEST_BUCKET: &str = "posthog";++fn seaweedfs_store() -> Arc<dyn ObjectStore> {+ let store = AmazonS3Builder::new()+ .with_bucket_name(TEST_BUCKET)+ .with_endpoint(SEAWEEDFS_ENDPOINT)+ .with_region("us-east-1")+ .with_allow_http(true)+ .with_virtual_hosted_style_request(false)+ // SeaweedFS dev runs in open-access mode; any credentials are accepted.+ .with_access_key_id("any")+ .with_secret_access_key("any")+ .build()+ .expect("failed to build SeaweedFS object_store");+ Arc::new(store)+}++fn gzip(data: &[u8]) -> Vec<u8> {+ let mut encoder = GzEncoder::new(Vec::new(), Compression::default());+ encoder.write_all(data).unwrap();+ encoder.finish().unwrap()+}++/// Probe SeaweedFS: a head on a missing key returns NotFound when reachable, and a+/// transport error when the dev stack isn't running. Unreachable is a silent skip+/// locally (developer convenience) but a hard failure in CI, where the dev compose+/// stack (including SeaweedFS) is always booted — a down store must produce a red+/// build, never a silently-skipped green one.+async fn seaweedfs_reachable(store: &Arc<dyn ObjectStore>) -> bool {+ let probe = object_store::path::Path::from("__reachability_probe__");+ let result = tokio::time::timeout(std::time::Duration::from_secs(3), store.head(&probe)).await;+ let reachable = matches!(+ result,+ Ok(Ok(_)) | Ok(Err(object_store::Error::NotFound { .. }))+ );+ if !reachable && std::env::var("CI").is_ok() {+ panic!("SeaweedFS unreachable at {SEAWEEDFS_ENDPOINT} in CI — the dev stack must be up");+ }+ reachable+}++#[tokio::test]+async fn test_temp_bucket_seaweedfs_round_trip() {+ let store = seaweedfs_store();++ if !seaweedfs_reachable(&store).await {+ eprintln!("SeaweedFS unreachable at {SEAWEEDFS_ENDPOINT}, skipping test");+ return;+ }++ // Unique job id so repeated runs don't collide, and so we can prove prefix cleanup.+ let job_id = format!("job-{}", Uuid::now_v7());+ let backend = TempBucketBackend::new(Arc::clone(&store), "batch-import-staging/", job_id);++ // Body without a trailing newline: exercises the pipeline's appended-newline path.+ let raw_dir = tempfile::TempDir::new().unwrap();+ let raw_path = raw_dir.path().join("part.raw");+ std::fs::write(&raw_path, gzip(b"{\"a\":1}\n{\"b\":2}\n{\"c\":3}")).unwrap();++ let size = backend+ .stage_part(+ "2024-01-01:00",+ open_plaintext_stream(raw_path, ExtractorType::PlainGzip, 0),+ )+ .await+ .unwrap();+ let expected = b"{\"a\":1}\n{\"b\":2}\n{\"c\":3}\n";+ assert_eq!(size, expected.len() as u64);++ // Full read, mid-slice, and overrun-EOF all behave against a real store.+ assert_eq!(backend.size("2024-01-01:00").await.unwrap(), Some(size));+ assert_eq!(+ backend.read("2024-01-01:00", 0, size + 10).await.unwrap(),+ expected+ );+ assert_eq!(+ backend.read("2024-01-01:00", 8, 7).await.unwrap(),+ b"{\"b\":2}"+ );+ assert!(backend+ .read("2024-01-01:00", size, 10)+ .await+ .unwrap()+ .is_empty());++ // cleanup_key removes it; a second delete is a no-op.+ backend.cleanup_key("2024-01-01:00").await.unwrap();+ assert_eq!(backend.size("2024-01-01:00").await.unwrap(), None);+ backend.cleanup_key("2024-01-01:00").await.unwrap();++ // cleanup_job leaves nothing under the job prefix.+ stage_and_assert_swept(&backend).await;+}++async fn stage_and_assert_swept(backend: &TempBucketBackend) {+ let stream = open_plaintext_stream_from_bytes(b"x\ny\nz\n");+ backend.stage_part("k", stream).await.unwrap();+ assert_eq!(backend.size("k").await.unwrap(), Some(6));+ backend.cleanup_job().await.unwrap();+ assert_eq!(backend.size("k").await.unwrap(), None);+}++fn open_plaintext_stream_from_bytes(data: &[u8]) -> batch_import_worker::staging::PlaintextStream {+ batch_import_worker::staging::PlaintextStream::from_chunks(vec![bytes::Bytes::copy_from_slice(+ data,+ )])+}++/// End-to-end remote staging through a real source: a DateRangeExportSource in+/// temp-bucket mode downloads from an httpmock origin, ingests via the pipeline into+/// live SeaweedFS, serves ranged reads back, resumes without re-download, and sweeps+/// its job prefix on cleanup.+#[tokio::test]+async fn test_remote_staged_source_round_trip_on_seaweedfs() {+ let store = seaweedfs_store();+ if !seaweedfs_reachable(&store).await {+ eprintln!("SeaweedFS unreachable at {SEAWEEDFS_ENDPOINT}, skipping test");+ return;+ }++ let body = b"{\"event\":\"a\"}\n{\"event\":\"b\"}\n{\"event\":\"c\"}";+ let server = MockServer::start();+ let mock = server.mock(|when, then| {+ when.method(httpmock::Method::GET).path("/export");+ then.status(200).body(gzip(body));+ });++ // Unique job id so repeated runs don't collide.+ let job_id = format!("job-{}", Uuid::now_v7());+ let build = |staging: &std::path::Path| {+ DateRangeExportSource::builder(+ server.url("/export"),+ Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap(),+ Utc.with_ymd_and_hms(2023, 1, 1, 1, 0, 0).unwrap(),+ 3600,+ ExtractorType::PlainGzip.create_extractor(),+ staging.to_path_buf(),+ )+ .with_auth(AuthConfig::None)+ .with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string())+ .with_headers(HashMap::new())+ .with_remote_staging(Some(RemoteStaging {+ backend: Arc::new(TempBucketBackend::new(+ Arc::clone(&store),+ "batch-import-staging/",+ job_id.clone(),+ )),+ extractor_type: ExtractorType::PlainGzip,+ max_plaintext_bytes: 0,+ }))+ .build()+ .unwrap()+ };++ // The pipeline appends the missing trailing newline.+ let expected = b"{\"event\":\"a\"}\n{\"event\":\"b\"}\n{\"event\":\"c\"}\n";++ let staging = tempfile::TempDir::new().unwrap();+ let source = build(staging.path());+ source.prepare_for_job().await.unwrap();+ let key = source.keys().await.unwrap().remove(0);++ source.prepare_key(&key).await.unwrap();+ assert_eq!(mock.hits(), 1);+ assert_eq!(+ source.size(&key).await.unwrap(),+ Some(expected.len() as u64)+ );++ // Ranged reads reconstruct the body across record-misaligned boundaries.+ let mut out = Vec::new();+ let mut offset = 0u64;+ loop {+ let chunk = source.get_chunk(&key, offset, 7).await.unwrap();+ if chunk.is_empty() {+ break;+ }+ offset += chunk.len() as u64;+ out.extend_from_slice(&chunk);+ }+ assert_eq!(out, expected);++ // A fresh source (cold process) attaches via head without re-downloading.+ let staging_b = tempfile::TempDir::new().unwrap();+ let resumed = build(staging_b.path());+ resumed.prepare_for_job().await.unwrap();+ resumed.prepare_key(&key).await.unwrap();+ assert_eq!(mock.hits(), 1, "resume must not re-hit the origin");+ assert_eq!(+ resumed.get_chunk(&key, 14, 14).await.unwrap(),+ &expected[14..28]+ );++ // Job cleanup sweeps the staged object.+ resumed.cleanup_after_job().await.unwrap();+ let fresh = build(tempfile::TempDir::new().unwrap().path());+ assert_eq!(fresh.size(&key).await.unwrap(), None);+}