Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(batch-imports): quarantine staged parts on data-error pause (#69835)

Nick Best450d3860dc05
diff --git a/rust/batch-import-worker/src/config.rs b/rust/batch-import-worker/src/config.rs
index a0098b3616a8..4c686249ec2e 100644
--- a/rust/batch-import-worker/src/config.rs
+++ b/rust/batch-import-worker/src/config.rs
@@ -184,6 +184,13 @@ pub struct Config {
// 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,
+
+ // Per-object ceiling on staged plaintext retained as quarantine evidence when a
+ // job pauses on a data error. Objects above it are deleted without an evidence
+ // copy, bounding how much temp-bucket capacity repeated pause-and-recreate loops
+ // can pin until the bucket TTL. 0 disables the cap. Default 10 GiB.
+ #[envconfig(from = "TEMP_BUCKET_QUARANTINE_MAX_BYTES", default = "10737418240")]
+ pub temp_bucket_quarantine_max_bytes: u64,
}
/// S3 multipart uploads are capped at 10,000 parts (AWS hard limit).
diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rs
index a1532032e949..284d8b884d61 100644
--- a/rust/batch-import-worker/src/job/mod.rs
+++ b/rust/batch-import-worker/src/job/mod.rs
@@ -638,10 +638,13 @@ impl Job {
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);
+ // source data in place, so the resume must re-download a
+ // clean copy, never attach to a stale staged one. Staged
+ // sources quarantine (rather than delete) the staged bytes,
+ // since they are the exact stream the failing offset points
+ // into — the evidence for debugging the parse failure.
+ if let Err(cleanup_err) = self.source.cleanup_after_data_error().await {
+ warn!("Failed to cleanup after data error: {:?}", cleanup_err);
}
let mut model = self.model.lock().await;
error!(
diff --git a/rust/batch-import-worker/src/source/date_range_export.rs b/rust/batch-import-worker/src/source/date_range_export.rs
index 0031be9dbfeb..d3dcd36c6baf 100644
--- a/rust/batch-import-worker/src/source/date_range_export.rs
+++ b/rust/batch-import-worker/src/source/date_range_export.rs
@@ -610,6 +610,20 @@ impl DataSource for DateRangeExportSource {
Ok(())
}
+ async fn cleanup_after_data_error(&self) -> Result<(), Error> {
+ // Data-error pause: quarantine staged plaintext for post-mortem (it is
+ // the exact byte stream the failing offset points into), so the resume
+ // re-downloads a clean copy while support can still inspect the bytes
+ // that failed to parse.
+ let quarantine_result = match &self.remote_staging {
+ Some(remote) => remote.quarantine_job().await,
+ None => Ok(()),
+ };
+ self.cleanup_local_resources().await;
+ debug!("Job data-error cleanup complete (staged parts quarantined)");
+ quarantine_result
+ }
+
// 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 prepared
async fn prepare_key(&self, key: &str) -> Result<(), Error> {
diff --git a/rust/batch-import-worker/src/source/mod.rs b/rust/batch-import-worker/src/source/mod.rs
index ad34df9340ec..bd7e395d620d 100644
--- a/rust/batch-import-worker/src/source/mod.rs
+++ b/rust/batch-import-worker/src/source/mod.rs
@@ -4,7 +4,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
-use anyhow::Error;
+use anyhow::{Context, Error};
use async_trait::async_trait;
use tokio::sync::Mutex;
use tracing::{debug, info, warn};
@@ -120,6 +120,18 @@ impl RemoteStaging {
}
}
+ /// `DataSource::cleanup_after_data_error` delegation: move staged objects to
+ /// quarantine for post-mortem instead of deleting them. The evidence copy is
+ /// best-effort, but a canonical object that could not be deleted is an error:
+ /// it stays attachable, so a resume could read stale staged bytes instead of
+ /// re-downloading the fixed source data.
+ pub(crate) async fn quarantine_job(&self) -> Result<(), Error> {
+ self.backend
+ .quarantine_job()
+ .await
+ .context("Failed to quarantine remote staging after data error")
+ }
+
/// 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.
@@ -289,13 +301,22 @@ pub trait DataSource: Sync + Send {
}
/// 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.
+ /// Called when the job completes.
async fn cleanup_after_job(&self) -> Result<(), Error> {
Ok(())
}
+ /// Data-error-pause cleanup: a human may fix the source data in place before
+ /// resuming, so the resume must re-download a clean copy rather than attach
+ /// to a stale staged one — but the staged bytes are the exact stream the
+ /// failing offset was committed against, so staged sources move them to
+ /// quarantine for post-mortem instead of deleting them. Defaults to
+ /// [`cleanup_after_job`](Self::cleanup_after_job) for sources with nothing
+ /// staged remotely.
+ async fn cleanup_after_data_error(&self) -> Result<(), Error> {
+ self.cleanup_after_job().await
+ }
+
/// 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
diff --git a/rust/batch-import-worker/src/source/s3_gzip.rs b/rust/batch-import-worker/src/source/s3_gzip.rs
index 7f1b12ecb4f8..f58d9a411983 100644
--- a/rust/batch-import-worker/src/source/s3_gzip.rs
+++ b/rust/batch-import-worker/src/source/s3_gzip.rs
@@ -272,6 +272,20 @@ impl DataSource for GzipS3Source {
Ok(())
}
+ async fn cleanup_after_data_error(&self) -> Result<(), Error> {
+ // Data-error pause: quarantine staged plaintext for post-mortem (it is
+ // the exact byte stream the failing offset points into), so the resume
+ // re-downloads a clean copy while support can still inspect the bytes
+ // that failed to parse.
+ let quarantine_result = match &self.remote_staging {
+ Some(remote) => remote.quarantine_job().await,
+ None => Ok(()),
+ };
+ self.cleanup_local_resources().await;
+ debug!("Job data-error cleanup complete (staged parts quarantined)");
+ quarantine_result
+ }
+
async fn prepare_key(&self, key: &str) -> Result<(), Error> {
if let Some(remote) = &self.remote_staging {
return remote
diff --git a/rust/batch-import-worker/src/staging/backend.rs b/rust/batch-import-worker/src/staging/backend.rs
index 4fb56d39ec89..c953dfe253e8 100644
--- a/rust/batch-import-worker/src/staging/backend.rs
+++ b/rust/batch-import-worker/src/staging/backend.rs
@@ -98,6 +98,16 @@ pub trait StagingBackend: Send + Sync {
Ok(())
}
+ /// Move the job's staged objects aside for post-mortem instead of deleting
+ /// them, called when a job pauses on a data error. The moved objects must
+ /// never be attachable by a resume (`size`/`read` must not see them) but
+ /// must still be reclaimed by [`cleanup_job`](Self::cleanup_job) and by
+ /// whatever retention backstop the backend has. Backends without a place
+ /// to keep evidence fall back to deletion.
+ async fn quarantine_job(&self) -> Result<(), Error> {
+ self.cleanup_job().await
+ }
+
/// 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>;
diff --git a/rust/batch-import-worker/src/staging/temp_bucket.rs b/rust/batch-import-worker/src/staging/temp_bucket.rs
index 7c67b3dd328b..d79bfec1cb62 100644
--- a/rust/batch-import-worker/src/staging/temp_bucket.rs
+++ b/rust/batch-import-worker/src/staging/temp_bucket.rs
@@ -27,6 +27,13 @@ const DEFAULT_UPLOAD_PART_SIZE_BYTES: usize = 64 * 1024 * 1024;
/// (origin download + gzip decode), so a small window keeps uploads fully
/// overlapped without multiplying memory. Config-overridable.
const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;
+/// Ceiling on the size of a staged object retained as quarantine evidence on a
+/// data-error pause. Objects above it are deleted without an evidence copy:
+/// pause-and-recreate loops with highly compressible parts would otherwise let
+/// one team pin ceiling-sized objects (potentially >100 GiB each) in the temp
+/// bucket until the TTL. 10 GiB retains evidence for realistic parts while
+/// bounding the amplification. Config-overridable; 0 disables the cap.
+const DEFAULT_QUARANTINE_MAX_BYTES: u64 = 10 * 1024 * 1024 * 1024;
/// 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`.
@@ -42,6 +49,7 @@ pub struct TempBucketBackend {
job_id: String,
upload_part_size: usize,
upload_concurrency: usize,
+ quarantine_max_bytes: u64,
// Sizes recorded at stage time; on a cold process they are recovered via `head`.
sizes: Mutex<HashMap<String, u64>>,
}
@@ -63,6 +71,7 @@ impl TempBucketBackend {
job_id: job_id.into(),
upload_part_size: DEFAULT_UPLOAD_PART_SIZE_BYTES,
upload_concurrency: DEFAULT_UPLOAD_CONCURRENCY,
+ quarantine_max_bytes: DEFAULT_QUARANTINE_MAX_BYTES,
sizes: Mutex::new(HashMap::new()),
}
}
@@ -76,15 +85,21 @@ impl TempBucketBackend {
self
}
+ /// Cap the per-object quarantine evidence size (0 disables the cap).
+ pub fn with_quarantine_cap(mut self, max_bytes: u64) -> Self {
+ self.quarantine_max_bytes = max_bytes;
+ 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(
+ 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,
- ),
- )
+ )
+ .with_quarantine_cap(config.temp_bucket_quarantine_max_bytes))
}
fn object_path(&self, key: &str) -> ObjectPath {
@@ -99,6 +114,10 @@ impl TempBucketBackend {
fn job_prefix(&self) -> ObjectPath {
ObjectPath::from(format!("{}{}/", self.prefix, self.job_id))
}
+
+ fn quarantine_prefix(&self) -> String {
+ format!("{}{}/quarantine/", self.prefix, self.job_id)
+ }
}
#[async_trait]
@@ -120,6 +139,87 @@ impl StagingBackend for TempBucketBackend {
Ok(())
}
+ /// Server-side move of every staged object into `quarantine/` under the job
+ /// prefix. The quarantine location is never produced by `object_path`, so
+ /// `size`/`read` (and therefore a resume) cannot attach to it, while
+ /// `cleanup_job` and the bucket TTL still reclaim it.
+ ///
+ /// Deleting the canonical object is NOT conditional on the evidence copy
+ /// succeeding: a canonical object left behind would let a resume attach to
+ /// stale staged bytes instead of re-downloading the customer's fixed source
+ /// data. Correctness (delete) always wins over evidence (copy); a delete
+ /// that fails even after a retry is reported as an error so callers surface
+ /// it loudly rather than pausing as if the staging were clean.
+ async fn quarantine_job(&self) -> Result<(), Error> {
+ let prefix = self.job_prefix();
+ let quarantine_prefix = self.quarantine_prefix();
+ let mut stream = self.store.list(Some(&prefix));
+ // `None` destination = delete without an evidence copy (over the cap).
+ let mut moves: Vec<(ObjectPath, Option<ObjectPath>)> = Vec::new();
+ while let Some(item) = stream.next().await {
+ match item {
+ Ok(meta) => {
+ if meta.location.as_ref().starts_with(&quarantine_prefix) {
+ continue;
+ }
+ if self.quarantine_max_bytes > 0 && meta.size > self.quarantine_max_bytes {
+ warn!(
+ "Staged object {} ({} bytes) exceeds the quarantine evidence cap ({} bytes); deleting without evidence",
+ meta.location, meta.size, self.quarantine_max_bytes
+ );
+ moves.push((meta.location, None));
+ continue;
+ }
+ let name = meta
+ .location
+ .filename()
+ .unwrap_or("unnamed.data")
+ .to_string();
+ let to = ObjectPath::from(format!("{quarantine_prefix}{name}"));
+ moves.push((meta.location, Some(to)));
+ }
+ Err(e) => warn!("Failed to list staged objects under {prefix}: {e}"),
+ }
+ }
+ let mut undeleted: Vec<ObjectPath> = Vec::new();
+ for (from, to) in moves {
+ if let Some(to) = to {
+ if let Err(e) = self.store.copy(&from, &to).await {
+ warn!(
+ "Failed to quarantine staged object {from}, deleting without evidence: {e}"
+ );
+ }
+ }
+ let deleted = match self.store.delete(&from).await {
+ Ok(()) => true,
+ Err(object_store::Error::NotFound { .. }) => true,
+ Err(first_err) => {
+ warn!("Failed to delete staged object {from}, retrying: {first_err}");
+ match self.store.delete(&from).await {
+ Ok(()) => true,
+ Err(object_store::Error::NotFound { .. }) => true,
+ Err(retry_err) => {
+ warn!("Retried delete of staged object {from} failed: {retry_err}");
+ false
+ }
+ }
+ }
+ };
+ if !deleted {
+ undeleted.push(from);
+ }
+ }
+ self.sizes.lock().await.clear();
+ if !undeleted.is_empty() {
+ return Err(Error::msg(format!(
+ "{} staged object(s) could not be deleted during quarantine and remain \
+ attachable by a resume: {undeleted:?}",
+ undeleted.len()
+ )));
+ }
+ Ok(())
+ }
+
async fn stage_part(&self, key: &str, mut plaintext: PlaintextStream) -> Result<u64, Error> {
let path = self.object_path(key);
let mut writer =
@@ -266,6 +366,264 @@ mod tests {
be.stage_part(key, stream).await.unwrap()
}
+ fn backend_with_store() -> (Arc<InMemory>, TempBucketBackend) {
+ let store = Arc::new(InMemory::new());
+ let be = TempBucketBackend::new(store.clone(), "batch-import-staging/", "job-TEST");
+ (store, be)
+ }
+
+ async fn quarantined_bytes(store: &Arc<InMemory>, key: &str) -> Option<Vec<u8>> {
+ let path = ObjectPath::from(format!(
+ "batch-import-staging/job-TEST/quarantine/{}.data",
+ sanitize_key(key)
+ ));
+ let result = store.get(&path).await.ok()?;
+ Some(result.bytes().await.ok()?.to_vec())
+ }
+
+ /// Delegating store that injects failures into copies and/or deletes, for
+ /// proving quarantine keeps its correctness guarantee (canonical object
+ /// deleted) when the storage misbehaves mid-move.
+ #[derive(Debug)]
+ struct FailingStore {
+ inner: Arc<InMemory>,
+ fail_copies: bool,
+ fail_deletes: Arc<std::sync::atomic::AtomicUsize>,
+ }
+
+ impl std::fmt::Display for FailingStore {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "FailingStore({})", self.inner)
+ }
+ }
+
+ fn injected(op: &'static str) -> object_store::Error {
+ object_store::Error::Generic {
+ store: "FailingStore",
+ source: format!("injected {op} failure").into(),
+ }
+ }
+
+ #[async_trait]
+ impl ObjectStore for FailingStore {
+ async fn put_opts(
+ &self,
+ location: &ObjectPath,
+ payload: object_store::PutPayload,
+ opts: object_store::PutOptions,
+ ) -> object_store::Result<object_store::PutResult> {
+ self.inner.put_opts(location, payload, opts).await
+ }
+
+ async fn put_multipart_opts(
+ &self,
+ location: &ObjectPath,
+ opts: object_store::PutMultipartOptions,
+ ) -> object_store::Result<Box<dyn object_store::MultipartUpload>> {
+ self.inner.put_multipart_opts(location, opts).await
+ }
+
+ async fn get_opts(
+ &self,
+ location: &ObjectPath,
+ options: object_store::GetOptions,
+ ) -> object_store::Result<object_store::GetResult> {
+ self.inner.get_opts(location, options).await
+ }
+
+ fn delete_stream(
+ &self,
+ locations: futures_util::stream::BoxStream<'static, object_store::Result<ObjectPath>>,
+ ) -> futures_util::stream::BoxStream<'static, object_store::Result<ObjectPath>> {
+ use std::sync::atomic::Ordering;
+ let counter = Arc::clone(&self.fail_deletes);
+ let inner = Arc::clone(&self.inner);
+ locations
+ .then(move |res| {
+ let counter = Arc::clone(&counter);
+ let inner = Arc::clone(&inner);
+ async move {
+ let location = res?;
+ if counter
+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
+ .is_ok()
+ {
+ return Err(injected("delete"));
+ }
+ inner.delete(&location).await?;
+ Ok(location)
+ }
+ })
+ .boxed()
+ }
+
+ fn list(
+ &self,
+ prefix: Option<&ObjectPath>,
+ ) -> futures_util::stream::BoxStream<'static, object_store::Result<object_store::ObjectMeta>>
+ {
+ self.inner.list(prefix)
+ }
+
+ async fn list_with_delimiter(
+ &self,
+ prefix: Option<&ObjectPath>,
+ ) -> object_store::Result<object_store::ListResult> {
+ self.inner.list_with_delimiter(prefix).await
+ }
+
+ async fn copy_opts(
+ &self,
+ from: &ObjectPath,
+ to: &ObjectPath,
+ options: object_store::CopyOptions,
+ ) -> object_store::Result<()> {
+ if self.fail_copies {
+ return Err(injected("copy"));
+ }
+ self.inner.copy_opts(from, to, options).await
+ }
+ }
+
+ /// The evidence copy failing must not leave the canonical object behind:
+ /// a resume attaching to stale staged bytes (instead of re-downloading the
+ /// fixed source data) is strictly worse than lost evidence.
+ #[tokio::test]
+ async fn quarantine_copy_failure_still_deletes_canonical() {
+ let inner = Arc::new(InMemory::new());
+ let store = Arc::new(FailingStore {
+ inner: inner.clone(),
+ fail_copies: true,
+ fail_deletes: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
+ });
+ let be = TempBucketBackend::new(store, "batch-import-staging/", "job-TEST");
+ stage_bytes(&be, "k", b"stale bytes").await;
+
+ be.quarantine_job().await.unwrap();
+
+ assert_eq!(
+ be.size("k").await.unwrap(),
+ None,
+ "canonical object must be deleted even when the evidence copy fails"
+ );
+ assert!(quarantined_bytes(&inner, "k").await.is_none());
+ }
+
+ /// A transient delete failure is retried; a persistent one surfaces as an
+ /// error (the canonical object remains attachable) instead of reporting a
+ /// clean quarantine.
+ #[tokio::test]
+ async fn quarantine_delete_failure_retries_then_errors() {
+ // One injected failure: the retry succeeds and the move completes.
+ let inner = Arc::new(InMemory::new());
+ let store = Arc::new(FailingStore {
+ inner: inner.clone(),
+ fail_copies: false,
+ fail_deletes: Arc::new(std::sync::atomic::AtomicUsize::new(1)),
+ });
+ let be = TempBucketBackend::new(store, "batch-import-staging/", "job-TEST");
+ stage_bytes(&be, "k", b"bytes").await;
+ be.quarantine_job().await.unwrap();
+ assert_eq!(be.size("k").await.unwrap(), None);
+ assert_eq!(
+ quarantined_bytes(&inner, "k").await.as_deref(),
+ Some(b"bytes".as_slice())
+ );
+
+ // Persistent failures: quarantine_job must report the attachable leftover.
+ let inner = Arc::new(InMemory::new());
+ let store = Arc::new(FailingStore {
+ inner: inner.clone(),
+ fail_copies: false,
+ fail_deletes: Arc::new(std::sync::atomic::AtomicUsize::new(usize::MAX)),
+ });
+ let be = TempBucketBackend::new(store, "batch-import-staging/", "job-TEST");
+ stage_bytes(&be, "k", b"bytes").await;
+ let err = be
+ .quarantine_job()
+ .await
+ .expect_err("an undeletable canonical object must surface as an error");
+ assert!(err.to_string().contains("remain"), "got: {err}");
+ }
+
+ /// The evidence cap: an over-cap staged object must be deleted without a
+ /// quarantine copy, so pause-and-recreate loops with highly compressible
+ /// parts cannot pin ceiling-sized objects in the temp bucket until the TTL.
+ #[tokio::test]
+ async fn quarantine_cap_deletes_oversized_objects_without_evidence() {
+ let (store, be) = backend_with_store();
+ let be = be.with_quarantine_cap(16);
+ stage_bytes(&be, "big", b"more than sixteen bytes of data").await;
+ stage_bytes(&be, "small", b"tiny").await;
+
+ be.quarantine_job().await.unwrap();
+
+ // Both canonical objects are gone regardless of size.
+ assert_eq!(be.size("big").await.unwrap(), None);
+ assert_eq!(be.size("small").await.unwrap(), None);
+ // Only the under-cap object is retained as evidence.
+ assert!(quarantined_bytes(&store, "big").await.is_none());
+ assert_eq!(
+ quarantined_bytes(&store, "small").await.as_deref(),
+ Some(b"tiny".as_slice())
+ );
+ }
+
+ #[tokio::test]
+ async fn quarantine_preserves_bytes_and_detaches_resume() {
+ let (store, be) = backend_with_store();
+ let body = b"{\"a\":1}\nnot json at all\n";
+ stage_bytes(&be, "2024-01-01:00", body).await;
+
+ be.quarantine_job().await.unwrap();
+
+ // The canonical object is gone: a resume's size/read (and therefore
+ // prepare_key's head-based attach) must not see the stale bytes.
+ assert_eq!(be.size("2024-01-01:00").await.unwrap(), None);
+ assert!(be.read("2024-01-01:00", 0, 100).await.is_err());
+
+ // The exact failing bytes are preserved for post-mortem.
+ assert_eq!(
+ quarantined_bytes(&store, "2024-01-01:00").await.as_deref(),
+ Some(body.as_slice())
+ );
+ }
+
+ #[tokio::test]
+ async fn quarantine_is_idempotent_and_swept_by_cleanup_job() {
+ let (store, be) = backend_with_store();
+ stage_bytes(&be, "k1", b"data-one").await;
+ stage_bytes(&be, "k2", b"data-two").await;
+
+ be.quarantine_job().await.unwrap();
+ // A second pause on the same job must not double-move or error.
+ be.quarantine_job().await.unwrap();
+ assert_eq!(
+ quarantined_bytes(&store, "k1").await.as_deref(),
+ Some(b"data-one".as_slice())
+ );
+ assert_eq!(
+ quarantined_bytes(&store, "k2").await.as_deref(),
+ Some(b"data-two".as_slice())
+ );
+
+ // Re-staging after quarantine works (the resume path), and the fresh
+ // canonical object coexists with the quarantined evidence.
+ stage_bytes(&be, "k1", b"data-one-fixed").await;
+ assert_eq!(be.size("k1").await.unwrap(), Some(14));
+ assert_eq!(
+ quarantined_bytes(&store, "k1").await.as_deref(),
+ Some(b"data-one".as_slice())
+ );
+
+ // Terminal cleanup reclaims quarantine along with everything else, so
+ // quarantined evidence cannot outlive the job inside the bucket.
+ be.cleanup_job().await.unwrap();
+ assert!(quarantined_bytes(&store, "k1").await.is_none());
+ assert!(quarantined_bytes(&store, "k2").await.is_none());
+ assert_eq!(be.size("k1").await.unwrap(), None);
+ }
+
#[tokio::test]
async fn round_trip_read_slices() {
let be = backend();
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.rs
index 415d8cb3673c..d9f338a8d1b9 100644
--- a/rust/batch-import-worker/tests/temp_bucket_seaweedfs_integration_test.rs
+++ b/rust/batch-import-worker/tests/temp_bucket_seaweedfs_integration_test.rs
@@ -134,6 +134,96 @@ fn open_plaintext_stream_from_bytes(data: &[u8]) -> batch_import_worker::staging
/// 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.
+/// A data-error pause must quarantine the staged plaintext (the exact bytes the
+/// failing offset points into) rather than delete it: the resume re-downloads a
+/// clean copy from the origin, while support can still read the failing bytes
+/// from the quarantine location. Terminal cleanup sweeps quarantine with the
+/// rest of the job prefix.
+#[tokio::test]
+async fn test_data_error_pause_quarantines_staged_part_and_resume_redownloads() {
+ let store = seaweedfs_store();
+ if !seaweedfs_reachable(&store).await {
+ eprintln!("SeaweedFS unreachable at {SEAWEEDFS_ENDPOINT}, skipping test");
+ return;
+ }
+
+ let body = b"{\"event\":\"a\"}\nnot valid json\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));
+ });
+
+ 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()
+ };
+
+ // Stage the part and read a chunk, like a job that then hits the bad line.
+ 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!(!source.get_chunk(&key, 0, 14).await.unwrap().is_empty());
+ assert_eq!(mock.hits(), 1);
+
+ // The data-error pause path.
+ source.cleanup_after_data_error().await.unwrap();
+
+ // Support can read the exact staged bytes that failed to parse (the
+ // pipeline appends the trailing newline, matching what the offsets index).
+ let quarantine_path = object_store::path::Path::from(format!(
+ "batch-import-staging/{job_id}/quarantine/{}.data",
+ key.replace([':', '/'], "_")
+ ));
+ let quarantined = store
+ .get(&quarantine_path)
+ .await
+ .expect("staged part must be quarantined, not deleted")
+ .bytes()
+ .await
+ .unwrap();
+ let mut expected = body.to_vec();
+ expected.push(b'\n');
+ assert_eq!(quarantined.as_ref(), expected.as_slice());
+
+ // The resume cannot attach to the stale copy: a fresh source re-downloads.
+ 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(), 2, "resume after a data error must re-download");
+
+ // Terminal cleanup sweeps the quarantined evidence with the job prefix.
+ resumed.cleanup_after_job().await.unwrap();
+ assert!(
+ store.get(&quarantine_path).await.is_err(),
+ "cleanup_after_job must sweep quarantine"
+ );
+}
+
#[tokio::test]
async fn test_remote_staged_source_round_trip_on_seaweedfs() {
let store = seaweedfs_store();