:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(batch-import): prevent temp file leaks causing disk pressure (#65895)
Eli Reisman0964ceeb5ebd
diff --git a/rust/batch-import-worker/src/config.rs b/rust/batch-import-worker/src/config.rsindex 42adae30f3f6..bc4a5ae02d9c 100644--- a/rust/batch-import-worker/src/config.rs+++ b/rust/batch-import-worker/src/config.rs@@ -1,3 +1,5 @@+use std::path::PathBuf;+use crate::job::backoff::BackoffPolicy;use common_continuous_profiling::ContinuousProfilingConfig;use envconfig::Envconfig;@@ -88,6 +90,11 @@ pub struct Config {// Internal capture service URL for the CaptureEmitter#[envconfig(from = "CAPTURE_URL", default = "http://localhost:3307")]pub capture_url: String,++ // Dedicated root for temp files created during job processing. Swept on+ // every startup to reclaim space leaked by non-graceful pod terminations.+ #[envconfig(from = "STAGING_DIR", default = "/tmp/batch-import-worker")]+ pub staging_dir: String,}impl Config {@@ -102,6 +109,10 @@ impl Config {}}+ pub fn staging_dir(&self) -> PathBuf {+ PathBuf::from(&self.staging_dir)+ }+pub fn backoff_policy(&self) -> BackoffPolicy {BackoffPolicy::new(std::time::Duration::from_secs(self.backoff_initial_seconds),diff --git a/rust/batch-import-worker/src/job/config.rs b/rust/batch-import-worker/src/job/config.rsindex 21061a311d14..40dacb7828d5 100644--- a/rust/batch-import-worker/src/job/config.rs+++ b/rust/batch-import-worker/src/job/config.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, net::IpAddr, sync::Arc, time::Duration};+use std::{collections::HashMap, net::IpAddr, path::PathBuf, sync::Arc, time::Duration};use anyhow::Error;use aws_config::{retry::RetryConfig, timeout::TimeoutConfig, BehaviorVersion, Region};@@ -191,9 +191,10 @@ impl SourceConfig {pub async fn construct(&self,secrets: &JobSecrets,- _context: Arc<AppContext>,+ context: Arc<AppContext>,is_restarting: bool,) -> Result<Box<dyn DataSource>, Error> {+ let staging_dir = context.config.staging_dir();match self {SourceConfig::Folder(config) => Ok(Box::new(config.create_source().await?)),SourceConfig::UrlList(config) => Ok(Box::new(@@ -202,9 +203,11 @@ impl SourceConfig {config.create_source(secrets, !is_restarting).await?,)),SourceConfig::S3(config) => Ok(Box::new(config.create_source(secrets).await?)),- SourceConfig::S3Gzip(config) => Ok(Box::new(config.create_gzip_source(secrets).await?)),+ SourceConfig::S3Gzip(config) => Ok(Box::new(+ config.create_gzip_source(secrets, staging_dir).await?,+ )),SourceConfig::DateRangeExport(config) => {- Ok(Box::new(config.create_source(secrets).await?))+ Ok(Box::new(config.create_source(secrets, staging_dir).await?))}}}@@ -411,7 +414,11 @@ impl S3SourceConfig {))}- pub async fn create_gzip_source(&self, secrets: &JobSecrets) -> Result<GzipS3Source, Error> {+ pub async fn create_gzip_source(+ &self,+ secrets: &JobSecrets,+ staging_dir: PathBuf,+ ) -> Result<GzipS3Source, Error> {let builder = self.build_s3_config(secrets)?;let client = aws_sdk_s3::Client::from_conf(builder.build());@@ -420,6 +427,7 @@ impl S3SourceConfig {self.bucket.clone(),self.prefix.clone(),ExtractorType::PlainGzip.create_extractor(),+ staging_dir,))}}@@ -427,6 +435,7 @@ impl DateRangeExportSourceConfig {pub async fn create_source(&self,secrets: &JobSecrets,+ staging_dir: PathBuf,) -> Result<DateRangeExportSource, Error> {let auth_config = match &self.auth {AuthSourceConfig::None => AuthConfig::None,@@ -518,6 +527,7 @@ impl DateRangeExportSourceConfig {self.end,self.interval_duration,extractor,+ staging_dir,).with_query_params(self.start_qp.clone(), self.end_qp.clone()).with_timeout(Duration::from_secs(self.timeout_seconds))diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rsindex f5b4a6aa819e..5245e45d047b 100644--- a/rust/batch-import-worker/src/job/mod.rs+++ b/rust/batch-import-worker/src/job/mod.rs@@ -245,6 +245,9 @@ impl Job {// 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 stateerror!("Failed to commit chunk: {:?}", e);+ if let Err(cleanup_err) = self.source.cleanup_after_job().await {+ warn!("Failed to cleanup after commit failure: {:?}", cleanup_err);+ }return Err(e);}diff --git a/rust/batch-import-worker/src/lib.rs b/rust/batch-import-worker/src/lib.rsindex 7efc89a6595b..dafe769752c9 100644--- a/rust/batch-import-worker/src/lib.rs+++ b/rust/batch-import-worker/src/lib.rs@@ -9,3 +9,4 @@ pub mod metrics;pub mod parse;pub mod person_processing_filter;pub mod source;+pub mod staging;diff --git a/rust/batch-import-worker/src/main.rs b/rust/batch-import-worker/src/main.rsindex 2f4d957048ca..258cf2423de5 100644--- a/rust/batch-import-worker/src/main.rs+++ b/rust/batch-import-worker/src/main.rs@@ -7,13 +7,14 @@ use batch_import_worker::{context::AppContext,error::get_user_message,job::{model::JobModel, Job},+ metrics, staging,};use common_metrics::setup_metrics_routes;use envconfig::Envconfig;use lifecycle::{ComponentOptions, Manager};use tracing::level_filters::LevelFilter;-use tracing::{error, info};+use tracing::{error, info, warn};use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};common_alloc::used!();@@ -51,6 +52,39 @@ pub async fn main() -> Result<(), Error> {}};+ let staging_dir = config.staging_dir();+ match staging::sweep_staging_dir(&staging_dir).await {+ Ok(removed) => {+ if removed > 0 {+ metrics::staging_sweep_removed(removed);+ }+ }+ Err(e) => {+ warn!("Failed to sweep staging dir on startup: {e:#}");+ }+ }+ if let Err(e) = staging::ensure_staging_dir(&staging_dir).await {+ error!(+ "Failed to create staging dir {}: {e:#}",+ staging_dir.display()+ );+ return Err(e);+ }++ // Periodically report staging directory disk usage+ {+ let staging_dir = staging_dir.clone();+ tokio::spawn(async move {+ let start = tokio::time::Instant::now() + Duration::from_secs(60);+ let mut interval = tokio::time::interval_at(start, Duration::from_secs(60));+ loop {+ interval.tick().await;+ let bytes = staging::staging_dir_bytes(&staging_dir).await;+ metrics::staging_dir_bytes(bytes as f64);+ }+ });+ }+let context = Arc::new(AppContext::new(&config).await.unwrap());let mut manager = Manager::builder("batch-import-worker").build();@@ -166,8 +200,10 @@ pub async fn main() -> Result<(), Error> {while let Some(job) = next_step {if job_handle.is_shutting_down() {- info!("Shutting down, dropping job");- // The job remains leased for a few minutes, then another worker picks it up+ 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:?}");+ }break;}next_step = match job.process().await {diff --git a/rust/batch-import-worker/src/metrics.rs b/rust/batch-import-worker/src/metrics.rsindex 42ce54953659..62acbf83111a 100644--- a/rust/batch-import-worker/src/metrics.rs+++ b/rust/batch-import-worker/src/metrics.rs@@ -1,8 +1,10 @@pub const BACKOFF_EVENTS_TOTAL: &str = "batch_import_backoff_events_total";pub const BACKOFF_DELAY_SECONDS: &str = "batch_import_backoff_delay_seconds";pub const UNPAUSE_TOTAL: &str = "batch_import_unpause_total";+pub const STAGING_SWEEP_REMOVED: &str = "batch_import_staging_sweep_removed_total";+pub const STAGING_DIR_BYTES: &str = "batch_import_staging_dir_bytes";-use metrics::{counter, histogram};+use metrics::{counter, gauge, histogram};pub fn backoff_event(delay_secs: f64) {counter!(BACKOFF_EVENTS_TOTAL).increment(1);@@ -12,3 +14,11 @@ pub fn backoff_event(delay_secs: f64) {pub fn unpause_event() {counter!(UNPAUSE_TOTAL).increment(1);}++pub fn staging_sweep_removed(count: u64) {+ counter!(STAGING_SWEEP_REMOVED).increment(count);+}++pub fn staging_dir_bytes(bytes: f64) {+ gauge!(STAGING_DIR_BYTES).set(bytes);+}diff --git a/rust/batch-import-worker/src/source/date_range_export.rs b/rust/batch-import-worker/src/source/date_range_export.rsindex 7ac61fc783d4..90de2501c4ef 100644--- a/rust/batch-import-worker/src/source/date_range_export.rs+++ b/rust/batch-import-worker/src/source/date_range_export.rs@@ -1,12 +1,10 @@-use super::DataSource;-use crate::error::{RateLimitedError, ToUserError};-use crate::extractor::{ExtractedPartData, PartExtractor};+use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration};+use anyhow::{Context, Error};use async_trait::async_trait;use chrono::{DateTime, Duration as ChronoDuration, Utc};use reqwest::header::HeaderMap;use reqwest::{Client, Error as ReqwestError};-use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration};use tempfile::TempDir;use tokio::{fs::File,@@ -15,6 +13,10 @@ use tokio::{};use tracing::{debug, info, warn};+use super::DataSource;+use crate::error::{RateLimitedError, ToUserError};+use crate::extractor::{ExtractedPartData, PartExtractor};+// Extract a user friendly error message// from status code of request to the export source endpointfn extract_status_error(error: &ReqwestError) -> String {@@ -77,6 +79,7 @@ pub struct DateRangeExportSourceBuilder {end: DateTime<Utc>,interval_duration: i64,extractor: Arc<dyn PartExtractor>,+ staging_dir: PathBuf,// Optional with defaultsstart_qp: String,@@ -96,6 +99,7 @@ impl DateRangeExportSourceBuilder {end: DateTime<Utc>,interval_duration: i64,extractor: Arc<dyn PartExtractor>,+ staging_dir: PathBuf,) -> Self {Self {base_url,@@ -103,6 +107,7 @@ impl DateRangeExportSourceBuilder {end,interval_duration,extractor,+ staging_dir,start_qp: "start".to_string(),end_qp: "end".to_string(),timeout: Duration::from_secs(30),@@ -180,6 +185,7 @@ impl DateRangeExportSourceBuilder {retries: self.retries,retry_delay: self.retry_delay,extractor: self.extractor,+ staging_dir: self.staging_dir,temp_dir: Arc::new(Mutex::new(None)),prepared_keys: Arc::new(Mutex::new(HashMap::new())),})@@ -198,6 +204,7 @@ pub struct DateRangeExportSource {pub extractor: Arc<dyn PartExtractor>,pub start_qp: String,pub end_qp: String,+ staging_dir: PathBuf,temp_dir: Arc<Mutex<Option<TempDir>>>,prepared_keys: Arc<Mutex<HashMap<String, ExtractedPartData>>>,auth_config: AuthConfig,@@ -225,8 +232,16 @@ impl DateRangeExportSource {end: DateTime<Utc>,interval_duration: i64,extractor: Arc<dyn PartExtractor>,+ staging_dir: PathBuf,) -> DateRangeExportSourceBuilder {- DateRangeExportSourceBuilder::new(base_url, start, end, interval_duration, extractor)+ DateRangeExportSourceBuilder::new(+ base_url,+ start,+ end,+ interval_duration,+ extractor,+ staging_dir,+ )}fn interval_key((start, end): (DateTime<Utc>, DateTime<Utc>)) -> String {@@ -556,14 +571,17 @@ impl DataSource for DateRangeExportSource {}}- // The lifecycle of this temp dir matches the lifecycle of the job- // It should be cleaned up when the job completes, fails, panics, etc.- // This ensures that files are cleaned up on a per job basis, but does not clean up- // .raw and .data files that are created for each key that we process per job- // We need to make sure to properly manage the clean up of those files as wellasync fn prepare_for_job(&self) -> Result<(), Error> {- let temp_dir =- tempfile::tempdir().with_context(|| "Failed to create temp directory for job")?;+ // Temp dir lifetime is tied to the job via self.temp_dir+ let temp_dir = tempfile::Builder::new()+ .prefix("job-")+ .tempdir_in(&self.staging_dir)+ .with_context(|| {+ format!(+ "Failed to create temp directory in staging dir: {}",+ self.staging_dir.display()+ )+ })?;debug!("Created temp directory for job: {:?}", temp_dir.path());{@@ -575,8 +593,7 @@ impl DataSource for DateRangeExportSource {}async fn cleanup_after_job(&self) -> Result<(), Error> {- // Best-effort:clear in-memory references and drop the job-scoped temp dir.- // TempDir drop removes the directory recursively; per-file deletes are redundant and noisy.+ // Clear refs then explicitly close() the temp dir to surface removal errors{let mut prepared_keys = self.prepared_keys.lock().await;prepared_keys.clear();@@ -584,8 +601,12 @@ impl DataSource for DateRangeExportSource {{let mut temp_dir_guard = self.temp_dir.lock().await;if let Some(temp_dir) = temp_dir_guard.take() {- drop(temp_dir);- debug!("Cleaned up temp directory");+ 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());+ }}}debug!("Job cleanup complete");@@ -642,6 +663,7 @@ mod tests {use chrono::{TimeZone, Utc};use httpmock::MockServer;use std::path::Path;+ use tempfile::TempDir;use tokio::fs;struct MockExtractor;@@ -671,7 +693,11 @@ mod tests {{"event": "test2", "timestamp": "2023-01-01T01:00:00Z"}{"event": "test3", "timestamp": "2023-01-01T02:00:00Z"}"#;- fn create_test_source(base_url: String, interval_duration: i64) -> DateRangeExportSource {+ fn create_test_source(+ base_url: String,+ interval_duration: i64,+ staging_dir: PathBuf,+ ) -> 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, 6, 0, 0).unwrap();@@ -681,6 +707,7 @@ mod tests {end,interval_duration,Arc::new(MockExtractor),+ staging_dir,).with_auth(AuthConfig::None).with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string())@@ -692,7 +719,8 @@ mod tests {#[tokio::test]async fn test_interval_generation() {let server = MockServer::start();- let source = create_test_source(server.url("/export"), 3600); // 1 hour intervals+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf()); // 1 hour intervalslet keys = source.keys().await.unwrap();assert_eq!(keys.len(), 6); // 6 hours with 1-hour intervals@@ -731,7 +759,8 @@ mod tests {#[tokio::test]async fn test_interval_key_parsing() {let server = MockServer::start();- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());let key = "2023-01-01T00:00:00+00:00_2023-01-01T01:00:00+00:00";let interval = source.interval_from_key(key).unwrap();@@ -761,7 +790,8 @@ mod tests {.body(TEST_DATA);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -784,7 +814,8 @@ mod tests {then.status(404);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -811,6 +842,7 @@ mod tests {let start = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();let end = Utc.with_ymd_and_hms(2023, 1, 1, 1, 0, 0).unwrap();+ let _staging = TempDir::new().unwrap();let source = DateRangeExportSource::builder(server.url("/export"),@@ -818,6 +850,7 @@ mod tests {end,3600,Arc::new(MockExtractor),+ _staging.path().to_path_buf(),).with_auth(AuthConfig::ApiKey {header_name: "X-API-Key".to_string(),@@ -847,6 +880,7 @@ mod tests {let start = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();let end = Utc.with_ymd_and_hms(2023, 1, 1, 1, 0, 0).unwrap();+ let _staging = TempDir::new().unwrap();let source = DateRangeExportSource::builder(server.url("/export"),@@ -854,6 +888,7 @@ mod tests {end,3600,Arc::new(MockExtractor),+ _staging.path().to_path_buf(),).with_auth(AuthConfig::BearerToken {token: "test-token".to_string(),@@ -877,7 +912,8 @@ mod tests {then.status(200).body(TEST_DATA);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -904,7 +940,8 @@ mod tests {then.status(200).body(TEST_DATA);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -933,7 +970,8 @@ mod tests {then.status(401);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -958,7 +996,8 @@ mod tests {then.status(500);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -985,6 +1024,7 @@ mod tests {let start = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();let end = Utc.with_ymd_and_hms(2023, 1, 1, 1, 0, 0).unwrap();+ let _staging = TempDir::new().unwrap();let mut headers = HashMap::new();headers.insert("X-Custom-Header".to_string(), "custom-value".to_string());@@ -995,6 +1035,7 @@ mod tests {end,3600,Arc::new(MockExtractor),+ _staging.path().to_path_buf(),).with_auth(AuthConfig::None).with_date_format("%Y-%m-%dT%H:%M:%SZ".to_string())@@ -1016,7 +1057,8 @@ mod tests {then.status(200).body(TEST_DATA);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -1041,7 +1083,8 @@ mod tests {then.status(200).body(TEST_DATA);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -1063,7 +1106,8 @@ mod tests {then.status(200).body(TEST_DATA);});- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());source.prepare_for_job().await.unwrap();let keys = source.keys().await.unwrap();@@ -1083,7 +1127,8 @@ mod tests {#[tokio::test]async fn test_format_date_range_from_key() {let server = MockServer::start();- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());let key = "2023-01-01T00:00:00+00:00_2023-01-01T01:00:00+00:00";let formatted = source.format_date_range_from_key(key).unwrap();@@ -1094,7 +1139,8 @@ mod tests {#[tokio::test]async fn test_format_date_range_from_key_different_dates() {let server = MockServer::start();- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());let key = "2023-12-31T23:30:00+00:00_2024-01-01T00:30:00+00:00";let formatted = source.format_date_range_from_key(key).unwrap();@@ -1105,7 +1151,8 @@ mod tests {#[tokio::test]async fn test_format_date_range_from_invalid_key() {let server = MockServer::start();- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());let key = "invalid-key-format";let formatted = source.format_date_range_from_key(key);@@ -1116,7 +1163,8 @@ mod tests {#[tokio::test]async fn test_get_date_range_for_key_trait_method() {let server = MockServer::start();- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());let key = "2023-06-15T12:00:00+00:00_2023-06-15T13:00:00+00:00";let date_range = source.get_date_range_for_key(key).unwrap();@@ -1127,7 +1175,8 @@ mod tests {#[tokio::test]async fn test_format_date_range_edge_cases() {let server = MockServer::start();- let source = create_test_source(server.url("/export"), 3600);+ let _staging = TempDir::new().unwrap();+ let source = create_test_source(server.url("/export"), 3600, _staging.path().to_path_buf());let key_with_ms = "2023-01-01T00:00:00.123+00:00_2023-01-01T01:30:45.456+00:00";let formatted = source.format_date_range_from_key(key_with_ms).unwrap();@@ -1154,12 +1203,14 @@ mod tests {then.status(429); // Always return 429});+ let _staging = TempDir::new().unwrap();let source = 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,Arc::new(MockExtractor),+ _staging.path().to_path_buf(),).build().unwrap();@@ -1251,6 +1302,7 @@ mod tests {// the end date query parameter for inclusive APIs.let start = Utc.with_ymd_and_hms(2025, 6, 5, 0, 0, 0).unwrap();let end = Utc.with_ymd_and_hms(2025, 6, 7, 0, 0, 0).unwrap();+ let _staging = TempDir::new().unwrap();let source = DateRangeExportSource::builder(server.url("/export"),@@ -1258,6 +1310,7 @@ mod tests {end,86400, // 1 day intervals - also used to adjust end date for inclusive APIsArc::new(MockExtractor),+ _staging.path().to_path_buf(),).with_query_params("from_date".to_string(), "to_date".to_string()).with_date_format("%Y-%m-%d".to_string())diff --git a/rust/batch-import-worker/src/source/s3_gzip.rs b/rust/batch-import-worker/src/source/s3_gzip.rsindex 5f1ced538cea..6cc196dec809 100644--- a/rust/batch-import-worker/src/source/s3_gzip.rs+++ b/rust/batch-import-worker/src/source/s3_gzip.rs@@ -1,16 +1,18 @@-use crate::error::ToUserError;-use crate::extractor::{ExtractedPartData, PartExtractor};-use anyhow::{Context, Error};-use async_trait::async_trait;-use aws_sdk_s3::Client as S3Client;use std::collections::HashMap;use std::path::PathBuf;use std::sync::Arc;++use anyhow::{Context, Error};+use async_trait::async_trait;+use aws_sdk_s3::Client as S3Client;use tempfile::TempDir;use tokio::sync::Mutex;use tokio::{fs::File, io::AsyncReadExt, io::AsyncSeekExt, io::AsyncWriteExt};use tracing::{debug, info, warn};+use crate::error::ToUserError;+use crate::extractor::{ExtractedPartData, PartExtractor};+use super::s3::extract_user_friendly_error;use super::DataSource;@@ -27,6 +29,7 @@ pub struct GzipS3Source {bucket: String,prefix: String,extractor: Arc<dyn PartExtractor>,+ staging_dir: PathBuf,temp_dir: Arc<Mutex<Option<TempDir>>>,prepared_keys: Arc<Mutex<HashMap<String, ExtractedPartData>>>,}@@ -37,12 +40,14 @@ impl GzipS3Source {bucket: String,prefix: String,extractor: Arc<dyn PartExtractor>,+ staging_dir: PathBuf,) -> Self {Self {client,bucket,prefix,extractor,+ staging_dir,temp_dir: Arc::new(Mutex::new(None)),prepared_keys: Arc::new(Mutex::new(HashMap::new())),}@@ -163,8 +168,15 @@ impl DataSource for GzipS3Source {}async fn prepare_for_job(&self) -> Result<(), Error> {- let temp_dir =- tempfile::tempdir().with_context(|| "Failed to create temp directory for job")?;+ let temp_dir = tempfile::Builder::new()+ .prefix("job-")+ .tempdir_in(&self.staging_dir)+ .with_context(|| {+ format!(+ "Failed to create temp directory in staging dir: {}",+ self.staging_dir.display()+ )+ })?;debug!("Created temp directory for job: {:?}", temp_dir.path());{@@ -183,8 +195,12 @@ impl DataSource for GzipS3Source {{let mut temp_dir_guard = self.temp_dir.lock().await;if let Some(temp_dir) = temp_dir_guard.take() {- drop(temp_dir);- debug!("Cleaned up temp directory");+ 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());+ }}}debug!("Job cleanup complete");@@ -213,18 +229,42 @@ impl DataSource for GzipS3Source {Err(sdk_error).user_error(friendly_msg)})?;- let data = get.body.collect().await.with_context(|| {+ let temp_dir = self.get_temp_dir_path().await?;+ let safe_key = sanitize_key_for_path(key);++ 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;+ }- let bytes = data.to_vec();- let temp_dir = self.get_temp_dir_path().await?;- let safe_key = sanitize_key_for_path(key);+ 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()+ );+ }- if bytes.is_empty() {let empty_data_file_path = temp_dir.join(format!("{}.data", safe_key));let empty_file = File::create(&empty_data_file_path).await@@ -241,19 +281,10 @@ impl DataSource for GzipS3Source {return 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()))?;- raw_file- .write_all(&bytes)- .await- .with_context(|| format!("Failed to write raw file: {}", raw_file_path.display()))?;- raw_file- .sync_all()- .await- .with_context(|| format!("Failed to sync raw file: {}", raw_file_path.display()))?;- drop(raw_file);+ debug!(+ "Streamed {total_bytes} bytes to {} for key: {key}",+ raw_file_path.display()+ );let extracted_part = self.extractordiff --git a/rust/batch-import-worker/src/staging.rs b/rust/batch-import-worker/src/staging.rsnew file mode 100644index 000000000000..1304564f2336--- /dev/null+++ b/rust/batch-import-worker/src/staging.rs@@ -0,0 +1,195 @@+use std::path::Path;++use anyhow::{Context, Error};+use tracing::{debug, info, warn};++/// Ensure the staging directory exists, creating it if necessary.+pub async fn ensure_staging_dir(path: &Path) -> Result<(), Error> {+ tokio::fs::create_dir_all(path)+ .await+ .with_context(|| format!("Failed to create staging directory: {}", path.display()))+}++/// Remove all contents of the staging directory without removing the directory+/// itself. Called on startup to reclaim temp trees leaked by previous+/// non-graceful pod terminations (SIGKILL, OOM, disk-pressure eviction).+pub async fn sweep_staging_dir(path: &Path) -> Result<u64, Error> {+ let mut entries = match tokio::fs::read_dir(path).await {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),+ Err(e) => {+ return Err(+ Error::from(e).context(format!("Failed to read staging dir: {}", path.display()))+ );+ }+ };++ let mut removed: u64 = 0;+ loop {+ let entry = match entries.next_entry().await {+ Ok(Some(e)) => e,+ Ok(None) => break,+ Err(e) => {+ warn!("Error iterating staging dir {}: {e}", path.display());+ continue;+ }+ };++ let entry_path = entry.path();+ let name = entry.file_name();+ if !name.to_string_lossy().starts_with("job-") {+ continue;+ }++ let is_dir = match entry.file_type().await {+ Ok(ft) => ft.is_dir(),+ Err(e) => {+ warn!("Cannot stat {}, skipping: {e}", entry_path.display());+ continue;+ }+ };++ let result = if is_dir {+ tokio::fs::remove_dir_all(&entry_path).await+ } else {+ tokio::fs::remove_file(&entry_path).await+ };++ match result {+ Ok(()) => removed += 1,+ Err(e) => {+ warn!(+ "Failed to remove stale staging entry {}: {e}",+ entry_path.display()+ );+ }+ }+ }++ if removed > 0 {+ info!(+ "Startup sweep: removed {removed} stale entries from {}",+ path.display()+ );+ }++ Ok(removed)+}++/// Compute total disk usage of the staging directory (recursive).+/// Returns 0 if the directory doesn't exist.+pub async fn staging_dir_bytes(path: &Path) -> u64 {+ match compute_dir_size(path).await {+ Ok(bytes) => bytes,+ Err(e) => {+ debug!("Failed to compute staging dir size: {e}");+ 0+ }+ }+}++async fn compute_dir_size(path: &Path) -> Result<u64, std::io::Error> {+ let mut total: u64 = 0;+ let mut entries = tokio::fs::read_dir(path).await?;+ loop {+ let entry = match entries.next_entry().await {+ Ok(Some(e)) => e,+ Ok(None) => break,+ Err(_) => continue,+ };+ let is_dir = match entry.file_type().await {+ Ok(ft) => ft.is_dir(),+ Err(_) => continue,+ };+ if is_dir {+ total += Box::pin(compute_dir_size(&entry.path())).await.unwrap_or(0);+ } else {+ total += entry.metadata().await.map(|m| m.len()).unwrap_or(0);+ }+ }+ Ok(total)+}++#[cfg(test)]+mod tests {+ use super::*;+ use tempfile::TempDir;++ #[tokio::test]+ async fn test_sweep_removes_stale_entries() {+ let root = TempDir::new().unwrap();+ let staging = root.path().join("staging");+ ensure_staging_dir(&staging).await.unwrap();++ // Simulate leaked temp dirs from crashed pods (job- prefix)+ let leaked_dir = staging.join("job-ABCDEF");+ tokio::fs::create_dir(&leaked_dir).await.unwrap();+ tokio::fs::write(leaked_dir.join("key.raw"), b"raw data")+ .await+ .unwrap();+ tokio::fs::write(leaked_dir.join("key.data"), b"decompressed data")+ .await+ .unwrap();++ let leaked_dir2 = staging.join("job-GHIJKL");+ tokio::fs::create_dir(&leaked_dir2).await.unwrap();++ // Non-job entry should be left alone+ let other = staging.join("something-else");+ tokio::fs::create_dir(&other).await.unwrap();++ let removed = sweep_staging_dir(&staging).await.unwrap();+ assert_eq!(removed, 2);++ // Staging dir should still contain the non-job entry+ assert!(staging.exists());+ assert!(other.exists());+ let mut entries = tokio::fs::read_dir(&staging).await.unwrap();+ let remaining = entries.next_entry().await.unwrap().unwrap();+ assert_eq!(remaining.file_name(), "something-else");+ assert!(entries.next_entry().await.unwrap().is_none());+ }++ #[tokio::test]+ async fn test_sweep_nonexistent_dir_is_noop() {+ let root = TempDir::new().unwrap();+ let staging = root.path().join("does-not-exist");+ let removed = sweep_staging_dir(&staging).await.unwrap();+ assert_eq!(removed, 0);+ }++ #[tokio::test]+ async fn test_ensure_creates_nested_dirs() {+ let root = TempDir::new().unwrap();+ let staging = root.path().join("a").join("b").join("staging");+ ensure_staging_dir(&staging).await.unwrap();+ assert!(staging.exists());+ }++ #[tokio::test]+ async fn test_staging_dir_bytes_counts_files() {+ let root = TempDir::new().unwrap();+ let staging = root.path().join("staging");+ ensure_staging_dir(&staging).await.unwrap();++ let subdir = staging.join("job-tmpXYZ");+ tokio::fs::create_dir(&subdir).await.unwrap();+ tokio::fs::write(subdir.join("key.raw"), vec![0u8; 1024])+ .await+ .unwrap();+ tokio::fs::write(subdir.join("key.data"), vec![0u8; 2048])+ .await+ .unwrap();++ let bytes = staging_dir_bytes(&staging).await;+ assert_eq!(bytes, 3072);+ }++ #[tokio::test]+ async fn test_staging_dir_bytes_nonexistent() {+ let root = TempDir::new().unwrap();+ let staging = root.path().join("does-not-exist");+ let bytes = staging_dir_bytes(&staging).await;+ assert_eq!(bytes, 0);+ }+}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 155c39ffe018..fe9fca8482f0 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@@ -115,8 +115,9 @@ async fn test_s3_gzip_minio_integration() {.collect(),};+ let _staging = tempfile::TempDir::new().expect("create staging dir");let source = s3_config- .create_gzip_source(&secrets)+ .create_gzip_source(&secrets, _staging.path().to_path_buf()).await.expect("create gzip source");source.prepare_for_job().await.expect("prepare for job");