: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(managed-migrations): add trial run support to batch-import-worker (#71873)
José Sequeira3170e2e10350
diff --git a/rust/batch-import-worker/src/config.rs b/rust/batch-import-worker/src/config.rsindex 4c686249ec2e..9796cc57c773 100644--- a/rust/batch-import-worker/src/config.rs+++ b/rust/batch-import-worker/src/config.rs@@ -191,6 +191,48 @@ pub struct Config {// 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,++ // Bucket for trial-run output (browsable pages + summary, served to users via+ // the Django API). Empty string disables trial jobs on this worker: claimed+ // trial jobs pause with a configuration error.+ #[envconfig(from = "TRIAL_BUCKET_NAME", default = "")]+ pub trial_bucket_name: String,+ // Custom S3 endpoint for local dev / CI (SeaweedFS, same shape as+ // TEMP_BUCKET_ENDPOINT).+ #[envconfig(from = "TRIAL_BUCKET_ENDPOINT", default = "")]+ pub trial_bucket_endpoint: String,+ #[envconfig(from = "TRIAL_BUCKET_REGION", default = "")]+ pub trial_bucket_region: String,+ // Key prefix inside the bucket; the per-job layout below it is+ // `team_<team_id>/job_<job_id>/`. An S3 lifecycle rule on this prefix+ // enforces trial-result retention.+ #[envconfig(from = "TRIAL_BUCKET_PREFIX", default = "trial_runs/")]+ pub trial_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 = "TRIAL_BUCKET_ACCESS_KEY_ID", default = "")]+ pub trial_bucket_access_key_id: String,+ #[envconfig(from = "TRIAL_BUCKET_SECRET_ACCESS_KEY", default = "")]+ pub trial_bucket_secret_access_key: String,+ // Path-style object URLs (required by S3-compatible dev stores like SeaweedFS).+ #[envconfig(from = "TRIAL_BUCKET_FORCE_PATH_STYLE", default = "false")]+ pub trial_bucket_force_path_style: bool,++ // Records per JSONL page of trial output. Pages are proxied whole through the+ // Django API, so this bounds the response size of a page fetch.+ #[envconfig(from = "TRIAL_RECORDS_PER_PAGE", default = "500")]+ pub trial_records_per_page: usize,++ // Bytes fetched from the source per iteration for trial jobs. Smaller than+ // CHUNK_SIZE so a bounded trial produces first results quickly instead of+ // downloading ~100 MB before the first page.+ #[envconfig(from = "TRIAL_CHUNK_SIZE", default = "8388608")]+ pub trial_chunk_size: usize,++ // Worker-side clamp on a trial job's record_limit (defense in depth on top of+ // API validation).+ #[envconfig(from = "TRIAL_MAX_RECORD_LIMIT", default = "50000")]+ pub trial_max_record_limit: u64,}/// S3 multipart uploads are capped at 10,000 parts (AWS hard limit).@@ -305,6 +347,27 @@ impl Config {(!key.is_empty() && !secret.is_empty()).then_some((key, secret))}+ /// Optional custom S3 endpoint for the trial output bucket. `None` when unset.+ pub fn trial_bucket_endpoint(&self) -> Option<&str> {+ let e = self.trial_bucket_endpoint.trim();+ (!e.is_empty()).then_some(e)+ }++ /// Optional S3 region override for the trial output bucket. `None` when unset.+ pub fn trial_bucket_region(&self) -> Option<&str> {+ let r = self.trial_bucket_region.trim();+ (!r.is_empty()).then_some(r)+ }++ /// Explicit S3 credentials for the trial output bucket (local dev / CI).+ /// `None` unless both parts are set; production relies on the standard AWS+ /// chain (IRSA) instead.+ pub fn trial_bucket_credentials(&self) -> Option<(&str, &str)> {+ let key = self.trial_bucket_access_key_id.trim();+ let secret = self.trial_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),diff --git a/rust/batch-import-worker/src/job/config.rs b/rust/batch-import-worker/src/job/config.rsindex 349aff7cd4ed..349c9c87c09c 100644--- a/rust/batch-import-worker/src/job/config.rs+++ b/rust/batch-import-worker/src/job/config.rs@@ -166,6 +166,16 @@ pub enum SinkConfig {Kafka(KafkaEmitterConfig),Capture(CaptureEmitterConfig),NoOp,+ // Trial run: parse and transform only, writing browsable results to the+ // worker-configured trial output bucket instead of emitting events. Jobs+ // with this sink take the trial path in the main loop; the bucket and+ // prefix come from worker env, never from job config.+ #[serde(rename = "trial_s3")]+ TrialS3 {+ // Stop after this many source records; clamped to the worker's+ // TRIAL_MAX_RECORD_LIMIT.+ record_limit: u64,+ },}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -330,6 +340,14 @@ impl SinkConfig {KafkaEmitter::new(resolved_config, &model.id.to_string(), context).await?,))}+ SinkConfig::TrialS3 { .. } => {+ // Trial jobs never construct an Emitter: the main loop dispatches+ // them to TrialJob before Job::new runs. Reaching this arm means+ // the dispatch check is broken.+ anyhow::bail!(+ "trial_s3 is not an emitter sink; trial jobs must take the trial path"+ )+ }SinkConfig::Capture(capture_config) => {let token = context.get_token_for_team_id(model.team_id).await?;let options = posthog_rs::ClientOptionsBuilder::default()diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rsindex 8176dc95536f..72ff92b04464 100644--- a/rust/batch-import-worker/src/job/mod.rs+++ b/rust/batch-import-worker/src/job/mod.rs@@ -20,7 +20,10 @@ use crate::{},extractor::detect_compression_magic,job::{backoff::format_backoff_messages, config::SinkConfig},- parse::{format::ParserFn, Parsed},+ parse::{+ format::{ParserFn, ParserFnFor},+ Parsed,+ },source::DataSource,};@@ -120,6 +123,127 @@ fn should_pause_due_to_max_attempts(next_attempt: u32, max_attempts: u32) -> boomax_attempts > 0 && next_attempt >= max_attempts}+/// Classify a fetch/parse error and transition the job accordingly: transient+/// errors schedule a backoff (or pause once max attempts is exhausted), anything+/// else pauses the job with a user-facing message. Shared by the import path+/// ([`Job::process`]) and the trial path.+///+/// Cleanup is deferred until after classification: transient interruptions keep+/// remote staging for the resume to attach to, while source-side pauses sweep it+/// for a clean re-download.+pub(crate) async fn handle_fetch_error(+ e: &Error,+ context: &Arc<AppContext>,+ model: &Mutex<JobModel>,+ state: &Mutex<JobState>,+ source: &dyn DataSource,+) -> Result<(), Error> {+ let user_facing_error_message = get_user_message(e);+ let current_date_range = {+ let state = state.lock().await;+ state+ .parts+ .iter()+ .find(|p| !p.is_done())+ .and_then(|p| source.get_date_range_for_key(&p.key))+ };++ let policy = context.config.backoff_policy();+ let current_attempt = {+ let model = model.lock().await;+ model.backoff_attempt.max(0) as u32+ };+ let next_attempt = current_attempt.saturating_add(1);+ match decide_on_error(+ e,+ current_date_range.as_deref(),+ policy,+ current_attempt,+ &user_facing_error_message,+ ) {+ ErrorHandlingDecision::Backoff {+ delay,+ 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) = source.release_job_resources().await {+ warn!("Failed to release job resources: {:?}", cleanup_err);+ }+ if should_pause_due_to_max_attempts(next_attempt, context.config.backoff_max_attempts) {+ let mut model = model.lock().await;+ let msg = match current_date_range.as_deref() {+ Some(dr) => format!(+ "Max backoff attempts reached for date range {dr} (attempt {next_attempt}). Pausing."+ ),+ None => {+ format!("Max backoff attempts reached (attempt {next_attempt}). Pausing.")+ }+ };+ model+ .pause(+ context.clone(),+ msg,+ Some(+ "Transient error persisted. Job paused after maximum retries."+ .to_string(),+ ),+ )+ .await?;+ return Ok(());+ }++ error!(+ job_id = %model.lock().await.id,+ attempt = next_attempt,+ delay_secs = delay.as_secs(),+ "transient error, scheduling retry: {:#}",+ e+ );+ metric_emit::backoff_event(delay.as_secs_f64());++ let mut model = model.lock().await;+ model+ .schedule_backoff(+ &context.db,+ delay,+ status_msg,+ Some(display_msg),+ next_attempt as i32,+ )+ .await?;+ Ok(())+ }+ ErrorHandlingDecision::Pause {+ error_msg,+ display_msg,+ } => {+ // Source-side pause: a human intervenes and may fix the+ // 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) = source.cleanup_after_data_error().await {+ warn!("Failed to cleanup after data error: {:?}", cleanup_err);+ }+ let mut model = model.lock().await;+ error!(+ job_id = %model.id,+ user_msg = %error_msg,+ "Pausing job due to error: {:#}",+ e+ );+ model+ .pause(context.clone(), error_msg, Some(display_msg))+ .await?;+ Ok(())+ }+ }+}+async fn reset_backoff_after_success(context: Arc<AppContext>,model: &mut JobModel,@@ -150,14 +274,14 @@ async fn mirror_part_total(model: &Mutex<JobModel>, key: &str, total: u64) {/// only on the empty-key short-circuit (so the caller skips the success backoff/// reset, matching the original control flow) and `true` otherwise. `None` means/// every part is done.-pub async fn select_and_fetch_next_chunk(+pub async fn select_and_fetch_next_chunk<T: Send + 'static>(state: &Mutex<JobState>,model: &Mutex<JobModel>,source: &dyn DataSource,- transform: &Arc<ParserFn>,+ transform: &Arc<ParserFnFor<T>>,chunk_size: usize,job_id: Uuid,-) -> Result<Option<(String, Parsed<Vec<InternallyCapturedEvent>>, bool)>, Error> {+) -> Result<Option<(String, Parsed<Vec<T>>, bool)>, Error> {let mut state = state.lock().await;let Some(next_part) = state.parts.iter_mut().find(|p| !p.is_done()) else {@@ -365,6 +489,45 @@ pub async fn select_and_fetch_next_chunk(Ok(Some((key, parsed, true)))}+/// Load the job's state from the model, initializing the parts list from the+/// source on first pickup. A freshly initialized state is mirrored back into+/// the model so the next flush persists it. Shared by the import path+/// ([`Job::new`]) and the trial path.+pub(crate) async fn load_or_init_state(+ source: &dyn DataSource,+ model: &mut JobModel,+) -> Result<JobState, Error> {+ let mut state = model.state.clone().unwrap_or_default();++ if state.parts.is_empty() {+ info!(job_id = %model.id, "Found job with no parts, initializing parts list");+ // If we have no parts, we assume this is the first time picking up the job,+ // and populate the parts list+ let mut parts = Vec::new();+ let keys = source+ .keys()+ .await+ .with_context(|| "Failed to get source keys".to_string())?;+ for key in keys {+ let size = source+ .size(&key)+ .await+ .with_context(|| format!("Failed to get size for part {key}"))?;+ debug!("Got size for part {key}: {size:?}");+ parts.push(PartState {+ key,+ current_offset: 0,+ total_size: size,+ });+ }+ state.parts = parts;+ model.state = Some(state.clone());+ info!(job_id = %model.id, "Initialized parts list: {:?}", state.parts);+ }++ Ok(state)+}+/// 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@@ -467,37 +630,7 @@ impl Job {.await.with_context(|| format!("Failed to construct sink for job {}", model.id))?;- let mut state = model- .state- .as_ref()- .cloned()- .unwrap_or_else(|| JobState { parts: vec![] });-- if state.parts.is_empty() {- info!(job_id = %model.id, "Found job with no parts, initializing parts list");- // If we have no parts, we assume this is the first time picking up the job,- // and populate the parts list- let mut parts = Vec::new();- let keys = source- .keys()- .await- .with_context(|| "Failed to get source keys".to_string())?;- for key in keys {- let size = source- .size(&key)- .await- .with_context(|| format!("Failed to get size for part {key}"))?;- debug!("Got size for part {key}: {size:?}");- parts.push(PartState {- key,- current_offset: 0,- total_size: size,- });- }- state.parts = parts;- model.state = Some(state.clone());- info!(job_id = %model.id, "Initialized parts list: {:?}", state.parts);- }+ let state = load_or_init_state(source.as_ref(), &mut model).await?;let job_id = model.id;let chunk_size = match &model.import_config.sink {@@ -549,116 +682,15 @@ impl Job {return Ok(None);}Err(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;- state- .parts- .iter()- .find(|p| !p.is_done())- .and_then(|p| self.source.get_date_range_for_key(&p.key))- };-- let policy = self.context.config.backoff_policy();- let current_attempt = {- let model = self.model.lock().await;- model.backoff_attempt.max(0) as u32- };- let next_attempt = current_attempt.saturating_add(1);- match decide_on_error(+ handle_fetch_error(&e,- current_date_range.as_deref(),- policy,- current_attempt,- &user_facing_error_message,- ) {- ErrorHandlingDecision::Backoff {- delay,- 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,- ) {- let mut model = self.model.lock().await;- let msg = match current_date_range.as_deref() {- Some(dr) => format!(- "Max backoff attempts reached for date range {dr} (attempt {next_attempt}). Pausing."- ),- None => format!(- "Max backoff attempts reached (attempt {next_attempt}). Pausing."- ),- };- model- .pause(- self.context.clone(),- msg,- Some(- "Transient error persisted. Job paused after maximum retries."- .to_string(),- ),- )- .await?;- return Ok(None);- }-- error!(- job_id = %self.model.lock().await.id,- attempt = next_attempt,- delay_secs = delay.as_secs(),- "transient error, scheduling retry: {:#}",- e- );- metric_emit::backoff_event(delay.as_secs_f64());-- let mut model = self.model.lock().await;- model- .schedule_backoff(- &self.context.db,- delay,- status_msg,- Some(display_msg),- next_attempt as i32,- )- .await?;- return Ok(None);- }- ErrorHandlingDecision::Pause {- error_msg,- display_msg,- } => {- // Source-side pause: a human intervenes and may fix the- // 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!(- job_id = %model.id,- user_msg = %error_msg,- "Pausing job due to error: {:#}",- e- );- model- .pause(self.context.clone(), error_msg, Some(display_msg))- .await?;- return Ok(None);- }- }+ &self.context,+ &self.model,+ &self.state,+ self.source.as_ref(),+ )+ .await?;+ return Ok(None);}};@@ -1155,7 +1187,10 @@ mod tests {status: super::model::JobStatus::Running,status_message: None,display_status_message: None,- state: Some(JobState { parts: vec![] }),+ state: Some(JobState {+ parts: vec![],+ trial: None,+ }),import_config: super::config::JobConfig {// Construct a trivially valid config that won't be used by this testsource: super::config::SourceConfig::Folder(super::config::FolderSourceConfig {@@ -1631,6 +1666,7 @@ mod tests {total_size: None,}).collect(),+ trial: None,}}@@ -1841,6 +1877,7 @@ mod tests {total_size: None,},],+ trial: None,};let state = Mutex::new(poisoned.clone());let model = Mutex::new(dummy_model(poisoned));@@ -2619,6 +2656,7 @@ mod tests {current_offset: resume_offset,total_size: None,}],+ trial: None,};let state = Mutex::new(resumed.clone());let model = Mutex::new(dummy_model(resumed));@@ -2698,6 +2736,7 @@ mod tests {current_offset: offset,total_size: part_total,}],+ trial: None,};let state = Mutex::new(part_state.clone());let model = Mutex::new(dummy_model(part_state));@@ -2898,6 +2937,7 @@ mod tests {total_size: None,},],+ trial: None,};let state = Mutex::new(poisoned.clone());let model = Mutex::new(dummy_model(poisoned));diff --git a/rust/batch-import-worker/src/job/model.rs b/rust/batch-import-worker/src/job/model.rsindex 69428d972bcf..feea3478dae0 100644--- a/rust/batch-import-worker/src/job/model.rs+++ b/rust/batch-import-worker/src/job/model.rs@@ -49,12 +49,17 @@ pub enum JobStatus {Completed,}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, Default)]#[serde(rename_all = "lowercase")]pub struct JobState {// Parts are sorted, and we iterate through them in order, to let us import// from oldest to newestpub parts: Vec<PartState>,+ // Trial-run progress; None for normal imports. Persisted alongside parts so+ // a trial resumed after backoff or lease loss continues its page numbering+ // and running summary instead of starting over.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub trial: Option<crate::trial::TrialProgress>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -413,7 +418,10 @@ impl TryFrom<(JobRow, &[String], String)> for JobModel {let (row, keys, lease_id) = input;let state = match row.state {Some(s) => serde_json::from_value(s).context("Parsing state")?,- None => JobState { parts: vec![] },+ None => JobState {+ parts: vec![],+ trial: None,+ },};let import_config = serde_json::from_value(row.import_config).context("Parsing config")?;@@ -513,6 +521,7 @@ mod tests {total_size: None,}).collect(),+ trial: None,}}diff --git a/rust/batch-import-worker/src/lib.rs b/rust/batch-import-worker/src/lib.rsindex dafe769752c9..304e4cdae62b 100644--- a/rust/batch-import-worker/src/lib.rs+++ b/rust/batch-import-worker/src/lib.rs@@ -10,3 +10,4 @@ pub mod parse;pub mod person_processing_filter;pub mod source;pub mod staging;+pub mod trial;diff --git a/rust/batch-import-worker/src/main.rs b/rust/batch-import-worker/src/main.rsindex fd1315dfc02a..835259e61956 100644--- a/rust/batch-import-worker/src/main.rs+++ b/rust/batch-import-worker/src/main.rs@@ -6,8 +6,9 @@ use batch_import_worker::{config::Config,context::AppContext,error::get_user_message,- job::{model::JobModel, Job},+ job::{config::SinkConfig, model::JobModel, Job},metrics, staging,+ trial::TrialJob,};use common_metrics::setup_metrics_routes;use envconfig::Envconfig;@@ -36,6 +37,23 @@ pub async fn index() -> &'static str {"batch import worker"}+/// Pause a job whose initialization failed, so it isn't endlessly re-claimed;+/// the developer message keeps the full error, the user sees the extracted one.+async fn pause_job_on_init_error(model: &mut JobModel, context: Arc<AppContext>, e: &Error) {+ let error_msg = format!("Job initialization failed for job {}: {:?}", model.id, e);+ error!("{}", error_msg);+ let user_facing_error_message = get_user_message(e);+ if let Err(pause_err) = model+ .pause(context, error_msg, Some(user_facing_error_message))+ .await+ {+ error!(+ "Failed to pause job after initialization error: {:?}",+ pause_err+ );+ }+}+#[tokio::main]pub async fn main() -> Result<(), Error> {setup_tracing();@@ -191,27 +209,30 @@ pub async fn main() -> Result<(), Error> {info!("Claimed job: {:?}", model.id);+ // Trial jobs (trial_s3 sink) take their own bounded, sequential path+ // instead of the import pipeline.+ if matches!(model.import_config.sink, SinkConfig::TrialS3 { .. }) {+ match TrialJob::new(model.clone(), context.clone(), job_handle.clone()).await {+ Ok(trial_job) => {+ if let Err(e) = trial_job.run().await {+ // Like the import path, the job transitions itself+ // (pause/backoff) where it can; anything escaping here+ // is left for the lease to expire and a re-claim.+ error!("Error processing trial job: {:?}, dropping", e);+ }+ }+ Err(e) => {+ pause_job_on_init_error(&mut model, context.clone(), &e).await;+ }+ }+ continue;+ }+let mut next_step =match Job::new(model.clone(), context.clone(), job_handle.clone()).await {Ok(job) => Some(job),Err(e) => {- let error_msg =- format!("Job initialization failed for job {}: {:?}", model.id, e);- error!("{}", error_msg);- let user_facing_error_message = get_user_message(&e);- if let Err(pause_err) = model- .pause(- context.clone(),- error_msg,- Some(user_facing_error_message.to_string()),- )- .await- {- error!(- "Failed to pause job after initialization error: {:?}",- pause_err- );- }+ pause_job_on_init_error(&mut model, context.clone(), &e).await;continue;}};diff --git a/rust/batch-import-worker/src/parse/format.rs b/rust/batch-import-worker/src/parse/format.rsindex f2bd8cf81265..8d4bc8ce06da 100644--- a/rust/batch-import-worker/src/parse/format.rs+++ b/rust/batch-import-worker/src/parse/format.rs@@ -27,8 +27,9 @@ pub enum FormatConfig {},}-pub type ParserFn =- Box<dyn Fn(Vec<u8>) -> Result<Parsed<Vec<InternallyCapturedEvent>>, Error> + Send + Sync>;+pub type ParserFnFor<T> = Box<dyn Fn(Vec<u8>) -> Result<Parsed<Vec<T>>, Error> + Send + Sync>;++pub type ParserFn = ParserFnFor<InternallyCapturedEvent>;impl FormatConfig {pub async fn get_parser(@@ -138,6 +139,19 @@ const NEWLINE_DELIM: u8 = b'\n';pub fn newline_delim<T: Send>(skip_blank_lines: bool,inner: impl Fn(&str) -> Result<T, Error> + Sync,+) -> impl Fn(Vec<u8>) -> Result<Parsed<Vec<T>>, Error> {+ newline_delim_lines(skip_blank_lines, move |line, _is_complete| inner(line))+}++/// Like [`newline_delim`], but the inner closure also receives whether the line+/// was newline-terminated (`true`) or is the chunk's trailing remainder+/// (`false`). The remainder is usually a line split at the chunk boundary, so an+/// error-tolerant parser (the trial path) must still return `Err` for it — that+/// leaves it unconsumed for the next chunk to re-read — while recording parse+/// errors on complete lines inline instead of failing the whole chunk.+pub fn newline_delim_lines<T: Send>(+ skip_blank_lines: bool,+ inner: impl Fn(&str, bool) -> Result<T, Error> + Sync,) -> impl Fn(Vec<u8>) -> Result<Parsed<Vec<T>>, Error> {move |data: Vec<u8>| {// A zero-length chunk (e.g. a read at or past the end of a part) has nothing@@ -186,12 +200,12 @@ pub fn newline_delim<T: Send>(// as consumed so the caller's offset can reach the end of the part - at the end// of a stream-decompressed part there is no next chunk to re-read it from.let remainder_is_blank = remainder_str.is_some_and(|r| r.trim().is_empty());- let remainder = remainder_str.map(&inner);+ let remainder = remainder_str.map(|r| inner(r, false));let mut output = Vec::with_capacity(lines.len());let intermediate: Vec<_> = lines.into_par_iter()- .map(|(end_byte_idx, line)| (end_byte_idx, inner(line)))+ .map(|(end_byte_idx, line)| (end_byte_idx, inner(line, true))).collect();drop(data);diff --git a/rust/batch-import-worker/src/staging/s3_client.rs b/rust/batch-import-worker/src/staging/s3_client.rsindex a81458c25ee8..00bdcf879804 100644--- a/rust/batch-import-worker/src/staging/s3_client.rs+++ b/rust/batch-import-worker/src/staging/s3_client.rs@@ -83,3 +83,61 @@ pub async fn create_temp_bucket_store(config: &Config) -> Result<Arc<dyn ObjectSconfig.temp_bucket_max_concurrent_requests,)))}++/// Build the `object_store` client for the trial output bucket. Same credential+/// priority and non-eager-validation rationale as [`create_temp_bucket_store`];+/// timeout/retry/concurrency knobs are shared with the temp bucket since both+/// are internal buckets with the same infrastructure profile, and trial pages+/// are far smaller than staged parts.+pub async fn create_trial_output_store(config: &Config) -> Result<Arc<dyn ObjectStore>> {+ anyhow::ensure!(+ !config.trial_bucket_name.trim().is_empty(),+ "TRIAL_BUCKET_NAME is not set; trial jobs are disabled on this worker"+ );++ let mut builder = AmazonS3Builder::from_env()+ .with_bucket_name(&config.trial_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.trial_bucket_region() {+ builder = builder.with_region(region);+ }++ if let Some(endpoint) = config.trial_bucket_endpoint() {+ builder = builder.with_endpoint(endpoint);+ if endpoint.starts_with("http://") {+ builder = builder.with_allow_http(true);+ }+ }++ if let Some((access_key, secret_key)) = config.trial_bucket_credentials() {+ info!("Trial bucket: using explicit S3 credentials from config");+ builder = builder+ .with_access_key_id(access_key)+ .with_secret_access_key(secret_key);+ }++ if config.trial_bucket_force_path_style {+ builder = builder.with_virtual_hosted_style_request(false);+ }++ let store = builder.build().with_context(|| {+ format!(+ "Failed to build trial-output S3 client for bucket '{}'",+ config.trial_bucket_name+ )+ })?;++ Ok(Arc::new(LimitStore::new(+ store,+ config.temp_bucket_max_concurrent_requests,+ )))+}diff --git a/rust/batch-import-worker/src/trial/job.rs b/rust/batch-import-worker/src/trial/job.rsnew file mode 100644index 000000000000..2eecf8ee5498--- /dev/null+++ b/rust/batch-import-worker/src/trial/job.rs@@ -0,0 +1,242 @@+use std::sync::Arc;++use anyhow::{Context, Error};+use lifecycle::Handle;+use tokio::sync::Mutex;+use tracing::{info, warn};+use uuid::Uuid;++use crate::{+ context::AppContext,+ error::ensure_user_message,+ job::{+ cleanup_committed_part_if_done,+ config::SinkConfig,+ handle_fetch_error, load_or_init_state,+ model::{JobModel, JobState},+ select_and_fetch_next_chunk,+ },+ parse::{format::ParserFnFor, Parsed},+ source::DataSource,+ staging::s3_client::create_trial_output_store,+ trial::{parser::build_trial_parser, sink::TrialSink, TrialRecord},+};++/// User-facing message for infrastructure failures on the trial output path+/// (bucket config, page/summary writes, progress flushes) — never something+/// that suggests a problem with the user's data.+const TRIAL_UNAVAILABLE_MSG: &str =+ "Trial runs are temporarily unavailable. Please try again later.";++/// A bounded trial run of an import: same source, format, and transforms as the+/// real thing, but each source record is paired with its would-be output (or the+/// reason it failed) and written to the trial output bucket instead of being+/// captured.+///+/// Unlike [`crate::job::Job`], processing is sequential — no pipelined+/// fetch/commit, no two-stage offset commit. Durability comes from ordering:+/// pages are written to object storage before the progress that counts them is+/// flushed, so a worker death re-fetches at most one chunk and overwrites the+/// same page indices. Re-transformed records can differ in generated values+/// (fresh UUIDs for events without one, identify-cache dedup state), which is+/// acceptable for a preview.+pub struct TrialJob {+ context: Arc<AppContext>,+ handle: Handle,+ job_id: Uuid,+ chunk_size: usize,+ state: Mutex<JobState>,+ model: Mutex<JobModel>,+ source: Box<dyn DataSource>,+ transform: Arc<ParserFnFor<TrialRecord>>,+ sink: TrialSink,+ record_limit: u64,+}++impl TrialJob {+ pub async fn new(+ mut model: JobModel,+ context: Arc<AppContext>,+ handle: Handle,+ ) -> Result<Self, Error> {+ let SinkConfig::TrialS3 { record_limit } = &model.import_config.sink else {+ anyhow::bail!(+ "TrialJob constructed for job {} without a trial_s3 sink",+ model.id+ );+ };+ let record_limit = (*record_limit).clamp(1, context.config.trial_max_record_limit);++ // Fail fast (pausing the job with a user-facing message) when this+ // worker has no trial bucket configured, before any source work starts.+ let store = create_trial_output_store(&context.config)+ .await+ .map_err(|e| ensure_user_message(e, TRIAL_UNAVAILABLE_MSG))?;+ let prefix = format!(+ "{}/team_{}/job_{}",+ context.config.trial_bucket_prefix.trim_matches('/'),+ model.team_id,+ model.id+ );+ let sink = TrialSink::new(store, prefix, context.config.trial_records_per_page);++ let is_restarting = model.state.is_some();+ let source = model+ .import_config+ .source+ .construct(&model.secrets, context.clone(), is_restarting, model.id)+ .await+ .with_context(|| "Failed to construct data source for trial job".to_string())?;+ source.prepare_for_job().await?;++ let transform = Arc::new(build_trial_parser(&model, context.clone()).await?);+ let state = load_or_init_state(source.as_ref(), &mut model).await?;++ let job_id = model.id;+ let chunk_size = context.config.trial_chunk_size;++ Ok(Self {+ context,+ handle,+ job_id,+ chunk_size,+ state: Mutex::new(state),+ model: Mutex::new(model),+ source,+ transform,+ sink,+ record_limit,+ })+ }++ pub async fn run(self) -> Result<(), Error> {+ loop {+ if self.handle.is_shutting_down() {+ // Keep remote staging on shutdown so the pod that re-claims the+ // trial attaches to staged parts instead of re-downloading.+ info!("Shutting down, releasing in-flight trial job resources");+ if let Err(e) = self.source.release_job_resources().await {+ warn!("Failed to release trial job source resources: {:?}", e);+ }+ return Ok(());+ }++ let records_emitted = {+ let state = self.state.lock().await;+ state.trial.as_ref().map_or(0, |t| t.records_emitted)+ };+ if records_emitted >= self.record_limit {+ break;+ }++ let fetched = select_and_fetch_next_chunk(+ &self.state,+ &self.model,+ self.source.as_ref(),+ &self.transform,+ self.chunk_size,+ self.job_id,+ )+ .await;++ let outcome = match fetched {+ Ok(Some((key, parsed, reset_backoff))) => self+ .commit_chunk(&key, parsed, reset_backoff)+ .await+ // Commit failures (page writes, progress flushes) are on+ // our side, never the user's data: transient ones still+ // back off below, but a pause must surface the infra+ // message rather than implying a data problem.+ .map_err(|e| ensure_user_message(e, TRIAL_UNAVAILABLE_MSG)),+ Ok(None) => break, // Source exhausted before the record limit+ Err(e) => Err(e),+ };++ if let Err(e) = outcome {+ // Same classification as the import path: transient errors+ // (source rate limits, object-store weather) back off and the+ // trial resumes from its persisted progress; anything else+ // pauses with a user-facing message.+ handle_fetch_error(+ &e,+ &self.context,+ &self.model,+ &self.state,+ self.source.as_ref(),+ )+ .await?;+ return Ok(());+ }+ }++ self.complete().await+ }++ /// Persist one fetched chunk: write its records as pages, fold them into the+ /// running summary, then flush the advanced offsets and trial progress.+ /// Ordering matters — pages first, progress second — so a crash in between+ /// re-fetches the chunk and overwrites the same pages.+ async fn commit_chunk(+ &self,+ key: &str,+ parsed: Parsed<Vec<TrialRecord>>,+ reset_backoff: bool,+ ) -> Result<(), Error> {+ let mut progress = {+ let state = self.state.lock().await;+ state.trial.clone().unwrap_or_default()+ };++ let mut records = parsed.data;+ progress.truncate_to_budget(&mut records, self.record_limit);++ if !records.is_empty() {+ let pages = self+ .sink+ .write_pages(progress.pages_written, progress.records_emitted, &records)+ .await?;+ progress.absorb(&records, pages);+ }++ let state_snapshot = {+ let mut state = self.state.lock().await;+ state.trial = Some(progress);+ state.clone()+ };++ {+ let mut model = self.model.lock().await;+ if reset_backoff && model.backoff_attempt > 0 {+ model.reset_backoff_in_db(&self.context.db).await?;+ }+ model.state = Some(state_snapshot);+ model.flush(&self.context.db, true).await?;+ }++ cleanup_committed_part_if_done(self.source.as_ref(), &self.model, key).await;+ Ok(())+ }++ /// Write the summary and mark the job completed. Idempotent: a resume after+ /// a failure here re-enters via the record-limit (or exhausted-source) check+ /// and rewrites the same summary from the persisted progress.+ async fn complete(self) -> Result<(), Error> {+ if let Err(e) = self.source.cleanup_after_job().await {+ warn!("Failed to cleanup after trial job: {:?}", e);+ }++ let progress = {+ let state = self.state.lock().await;+ state.trial.clone().unwrap_or_default()+ };+ self.sink.write_summary(&progress).await?;++ let mut model = self.model.lock().await;+ info!(+ job_id = %self.job_id,+ records = progress.records_emitted,+ "Trial job completed"+ );+ model.complete(&self.context.db).await+ }+}diff --git a/rust/batch-import-worker/src/trial/mod.rs b/rust/batch-import-worker/src/trial/mod.rsnew file mode 100644index 000000000000..94b621edb25d--- /dev/null+++ b/rust/batch-import-worker/src/trial/mod.rs@@ -0,0 +1,299 @@+use std::collections::HashMap;++use common_types::InternallyCapturedEvent;+use serde::{Deserialize, Serialize};+use serde_json::Value;+use uuid::Uuid;++pub mod job;+pub mod parser;+pub mod sink;++pub use job::TrialJob;++/// Cap on distinct event names tracked in the summary; everything past it is+/// folded into `other_event_names` so a pathological source can't bloat the+/// state JSON persisted to Postgres on every chunk.+const EVENT_NAME_COUNT_CAP: usize = 500;+/// Same guard for distinct error messages.+const ERROR_COUNT_CAP: usize = 100;+/// Byte cap on each summary key (event name or error message). Keys come from+/// user data and a single one can be nearly a whole source line, so without+/// this the count caps alone still let the persisted state grow unbounded.+const SUMMARY_KEY_MAX_BYTES: usize = 200;+/// Timestamps longer than this cannot be the RFC 3339 strings the transforms+/// produce; ignore them instead of cloning arbitrary payload data into state.+const TIMESTAMP_MAX_BYTES: usize = 64;++/// One source line paired with the event(s) it would produce on a real import.+/// Empty `outputs` with an `error` means the line would be dropped; empty+/// `outputs` without one means it was intentionally skipped (e.g. a Mixpanel+/// event with no distinct id, or an Amplitude session marker).+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TrialRecord {+ pub source: Value,+ pub outputs: Vec<TrialOutputEvent>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++/// A browsable projection of an [`InternallyCapturedEvent`]: the double-encoded+/// `data` payload is parsed back into JSON so the UI can render the target event+/// without unwrapping capture internals, and capture-transport fields (token,+/// now, sent_at) are dropped.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TrialOutputEvent {+ pub uuid: Uuid,+ pub distinct_id: String,+ pub event: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub timestamp: Option<String>,+ pub payload: Value,+}++impl From<InternallyCapturedEvent> for TrialOutputEvent {+ fn from(e: InternallyCapturedEvent) -> Self {+ let payload: Value = serde_json::from_str(&e.inner.data).unwrap_or(Value::Null);+ let event = payload+ .get("event")+ .and_then(Value::as_str)+ .unwrap_or_default()+ .to_string();+ let timestamp = payload+ .get("timestamp")+ .and_then(Value::as_str)+ .map(String::from);+ Self {+ uuid: e.inner.uuid,+ distinct_id: e.inner.distinct_id,+ event,+ timestamp,+ payload,+ }+ }+}++/// Trial progress persisted inside the job's `state` JSON. Written only after+/// the corresponding pages are durably in object storage, so a resumed trial+/// re-fetches at most one chunk and overwrites the same page indices.+#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct TrialProgress {+ pub records_emitted: u64,+ pub pages_written: u32,+ pub summary: TrialSummary,+}++impl TrialProgress {+ /// Truncate one chunk's records to the remaining budget under `record_limit`.+ pub fn truncate_to_budget(&self, records: &mut Vec<TrialRecord>, record_limit: u64) {+ let remaining = record_limit.saturating_sub(self.records_emitted);+ records.truncate(remaining as usize);+ }++ /// Fold one chunk's durably written records (and the pages holding them)+ /// into the running progress.+ pub fn absorb(&mut self, records: &[TrialRecord], pages: u32) {+ for record in records {+ self.summary.record(record);+ }+ self.records_emitted += records.len() as u64;+ self.pages_written += pages;+ }+}++/// Running aggregates over the emitted records; becomes `summary.json` when the+/// trial completes.+#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct TrialSummary {+ pub source_records: u64,+ pub output_events: u64,+ /// Records that failed to parse or transform (have an `error`).+ pub dropped_records: u64,+ /// Records intentionally producing no output (no `error`).+ pub skipped_records: u64,+ pub event_name_counts: HashMap<String, u64>,+ #[serde(default, skip_serializing_if = "is_zero")]+ pub other_event_names: u64,+ pub error_counts: HashMap<String, u64>,+ #[serde(default, skip_serializing_if = "is_zero")]+ pub other_errors: u64,+ /// Lexicographic min/max of output event timestamps; correct for the+ /// RFC 3339 strings the transforms produce.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub first_timestamp: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub last_timestamp: Option<String>,+}++fn is_zero(v: &u64) -> bool {+ *v == 0+}++impl TrialSummary {+ pub fn record(&mut self, record: &TrialRecord) {+ self.source_records += 1;+ self.output_events += record.outputs.len() as u64;++ match (&record.error, record.outputs.is_empty()) {+ (Some(error), _) => {+ self.dropped_records += 1;+ if !bounded_count(&mut self.error_counts, error, ERROR_COUNT_CAP) {+ self.other_errors += 1;+ }+ }+ (None, true) => self.skipped_records += 1,+ (None, false) => {}+ }++ for output in &record.outputs {+ if !bounded_count(+ &mut self.event_name_counts,+ &output.event,+ EVENT_NAME_COUNT_CAP,+ ) {+ self.other_event_names += 1;+ }+ if let Some(ts) = &output.timestamp {+ if ts.len() > TIMESTAMP_MAX_BYTES {+ continue;+ }+ if self.first_timestamp.as_ref().is_none_or(|f| ts < f) {+ self.first_timestamp = Some(ts.clone());+ }+ if self.last_timestamp.as_ref().is_none_or(|l| ts > l) {+ self.last_timestamp = Some(ts.clone());+ }+ }+ }+ }+}++/// Increment `key` in `counts`, refusing to add new keys past `cap`. Keys are+/// truncated to [`SUMMARY_KEY_MAX_BYTES`] first, so oversized names share one+/// truncated entry instead of each growing the state. Returns whether the+/// count was recorded.+fn bounded_count(counts: &mut HashMap<String, u64>, key: &str, cap: usize) -> bool {+ let key = truncate_at_char_boundary(key, SUMMARY_KEY_MAX_BYTES);+ if let Some(count) = counts.get_mut(key) {+ *count += 1;+ return true;+ }+ if counts.len() >= cap {+ return false;+ }+ counts.insert(key.to_string(), 1);+ true+}++fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> &str {+ if s.len() <= max_bytes {+ return s;+ }+ let mut end = max_bytes;+ while !s.is_char_boundary(end) {+ end -= 1;+ }+ &s[..end]+}++#[cfg(test)]+mod tests {+ use super::*;++ fn output(event: &str, timestamp: Option<&str>) -> TrialOutputEvent {+ TrialOutputEvent {+ uuid: Uuid::now_v7(),+ distinct_id: "u".to_string(),+ event: event.to_string(),+ timestamp: timestamp.map(String::from),+ payload: Value::Null,+ }+ }++ fn record(outputs: Vec<TrialOutputEvent>, error: Option<&str>) -> TrialRecord {+ TrialRecord {+ source: Value::Null,+ outputs,+ error: error.map(String::from),+ }+ }++ #[test]+ fn summary_classifies_records_and_tracks_timestamp_range() {+ let mut summary = TrialSummary::default();+ summary.record(&record(+ vec![+ output("a", Some("2024-01-02T00:00:00Z")),+ output("b", Some("2024-01-01T00:00:00Z")),+ ],+ None,+ ));+ summary.record(&record(vec![], Some("bad line")));+ summary.record(&record(vec![], Some("bad line")));+ summary.record(&record(vec![], None)); // intentionally skipped++ assert_eq!(summary.source_records, 4);+ assert_eq!(summary.output_events, 2);+ assert_eq!(summary.dropped_records, 2);+ assert_eq!(summary.skipped_records, 1);+ assert_eq!(summary.event_name_counts["a"], 1);+ assert_eq!(summary.event_name_counts["b"], 1);+ assert_eq!(summary.error_counts["bad line"], 2);+ assert_eq!(+ summary.first_timestamp.as_deref(),+ Some("2024-01-01T00:00:00Z")+ );+ assert_eq!(+ summary.last_timestamp.as_deref(),+ Some("2024-01-02T00:00:00Z")+ );+ }++ #[test]+ fn summary_bounds_key_bytes_and_ignores_oversized_timestamps() {+ let mut summary = TrialSummary::default();+ let long_a = format!("{}_a", "x".repeat(SUMMARY_KEY_MAX_BYTES));+ let long_b = format!("{}_b", "x".repeat(SUMMARY_KEY_MAX_BYTES));+ let huge_ts = "9".repeat(TIMESTAMP_MAX_BYTES + 1);+ summary.record(&record(+ vec![+ output(&long_a, Some(&huge_ts)),+ output(&long_b, Some("2024-01-01T00:00:00Z")),+ ],+ None,+ ));+ summary.record(&record(vec![], Some(&long_a)));++ // Distinct oversized names merge into one truncated key+ assert_eq!(summary.event_name_counts.len(), 1);+ let (key, count) = summary.event_name_counts.iter().next().unwrap();+ assert_eq!(key.len(), SUMMARY_KEY_MAX_BYTES);+ assert_eq!(*count, 2);++ let error_key = summary.error_counts.keys().next().unwrap();+ assert_eq!(error_key.len(), SUMMARY_KEY_MAX_BYTES);++ // The oversized timestamp is ignored; the valid one still tracks+ assert_eq!(+ summary.first_timestamp.as_deref(),+ Some("2024-01-01T00:00:00Z")+ );+ assert_eq!(+ summary.last_timestamp.as_deref(),+ Some("2024-01-01T00:00:00Z")+ );+ }++ #[test]+ fn summary_caps_distinct_event_names() {+ let mut summary = TrialSummary::default();+ let outputs: Vec<_> = (0..EVENT_NAME_COUNT_CAP + 2)+ .map(|i| output(&format!("event_{i}"), None))+ .collect();+ summary.record(&record(outputs, None));++ assert_eq!(summary.event_name_counts.len(), EVENT_NAME_COUNT_CAP);+ assert_eq!(summary.other_event_names, 2);+ assert_eq!(summary.output_events, (EVENT_NAME_COUNT_CAP + 2) as u64);+ }+}diff --git a/rust/batch-import-worker/src/trial/parser.rs b/rust/batch-import-worker/src/trial/parser.rsnew file mode 100644index 000000000000..0332ecebb5aa--- /dev/null+++ b/rust/batch-import-worker/src/trial/parser.rs@@ -0,0 +1,281 @@+use std::sync::Arc;++use anyhow::Error;+use chrono::Duration;+use common_types::InternallyCapturedEvent;+use serde::de::DeserializeOwned;+use serde_json::Value;++use crate::{+ cache::{GroupCache, IdentifyCache, MemoryGroupCache, MemoryIdentifyCache},+ context::AppContext,+ error::UserError,+ job::model::JobModel,+ parse::{+ content::{+ amplitude::AmplitudeEvent, captured::captured_parse_fn, mixpanel::MixpanelEvent,+ ContentType, TransformContext,+ },+ format::{+ newline_delim_lines, skip_geoip, FormatConfig, ParserFnFor, UserFacingParseError,+ },+ },+};++use super::TrialRecord;++/// Build the trial-mode parser for a claimed job: resolves the team token and+/// delegates to [`trial_parser`].+pub async fn build_trial_parser(+ model: &JobModel,+ context: Arc<AppContext>,+) -> Result<ParserFnFor<TrialRecord>, Error> {+ // Fresh caches, never the process-wide ones: a trial marking user/device+ // pairs or groups as seen would make a later real import over the same+ // data skip its $identify / group identify events.+ let identify_cache: Arc<dyn IdentifyCache> = Arc::new(MemoryIdentifyCache::new(+ context.config.identify_memory_cache_capacity,+ std::time::Duration::from_secs(context.config.identify_memory_cache_ttl_seconds),+ ));+ let group_cache: Arc<dyn GroupCache> = Arc::new(MemoryGroupCache::new(+ context.config.group_memory_cache_capacity,+ std::time::Duration::from_secs(context.config.group_memory_cache_ttl_seconds),+ ));+ let transform_context = TransformContext {+ team_id: model.team_id,+ token: context.get_token_for_team_id(model.team_id).await?,+ job_id: model.id,+ identify_cache,+ group_cache,+ import_events: model.import_config.import_events,+ generate_identify_events: model.import_config.generate_identify_events,+ generate_group_identify_events: model.import_config.generate_group_identify_events,+ };+ Ok(trial_parser(+ &model.import_config.data_format,+ transform_context,+ ))+}++/// The trial-mode parser: same source format and transforms as the real import+/// ([`FormatConfig::get_parser`]), but each source line becomes a+/// [`TrialRecord`] pairing the line with its outputs, and parse/transform+/// failures are recorded on the line instead of failing the chunk.+pub fn trial_parser(+ format: &FormatConfig,+ transform_context: TransformContext,+) -> ParserFnFor<TrialRecord> {+ let FormatConfig::JsonLines {+ skip_blanks,+ content,+ } = format;++ match content {+ ContentType::Mixpanel(config) => {+ let transform = MixpanelEvent::parse_fn(+ transform_context,+ config.skip_no_distinct_id,+ config+ .timestamp_offset_seconds+ .map(Duration::seconds)+ .unwrap_or_default(),+ skip_geoip(),+ );+ Box::new(newline_delim_lines(+ *skip_blanks,+ trial_line_fn::<MixpanelEvent, _>(move |e| {+ transform(e).map(|o| o.into_iter().collect())+ }),+ ))+ }+ ContentType::Amplitude => {+ let transform = AmplitudeEvent::parse_fn(transform_context, skip_geoip());+ Box::new(newline_delim_lines(+ *skip_blanks,+ trial_line_fn::<AmplitudeEvent, _>(transform),+ ))+ }+ ContentType::Captured => {+ let transform = captured_parse_fn(transform_context, skip_geoip());+ Box::new(newline_delim_lines(+ *skip_blanks,+ trial_line_fn::<common_types::RawEvent, _>(move |e| {+ transform(e).map(|o| o.into_iter().collect())+ }),+ ))+ }+ }+}++/// Per-line trial parser: deserialize the line as `T`, run the import transform,+/// and fold any failure into the record's `error` instead of propagating it.+///+/// The one deliberate `Err` path is a parse failure on the chunk's trailing+/// remainder (`is_complete_line == false`): that is almost always a line split+/// at the chunk boundary, and returning `Err` leaves it unconsumed so the next+/// chunk re-reads it whole. The trade-off (matching the real import) is that a+/// genuinely corrupt final line without a trailing newline pauses the trial+/// instead of becoming an error record.+fn trial_line_fn<T, F>(transform: F) -> impl Fn(&str, bool) -> Result<TrialRecord, Error> + Sync+where+ T: DeserializeOwned + UserFacingParseError,+ F: Fn(T) -> Result<Vec<InternallyCapturedEvent>, Error> + Sync,+{+ move |line, is_complete_line| {+ let typed: T = match serde_json::from_str(line) {+ Ok(typed) => typed,+ Err(e) if !is_complete_line => {+ let user_msg = T::user_facing_parse_error(&e);+ return Err(Error::from(e).context(UserError::new(user_msg)));+ }+ Err(e) => {+ return Ok(TrialRecord {+ source: source_value(line),+ outputs: vec![],+ error: Some(T::user_facing_parse_error(&e)),+ });+ }+ };++ let source = source_value(line);+ match transform(typed) {+ Ok(outputs) => Ok(TrialRecord {+ source,+ outputs: outputs.into_iter().map(Into::into).collect(),+ error: None,+ }),+ Err(e) => Ok(TrialRecord {+ source,+ outputs: vec![],+ error: Some(user_facing_transform_error(&e)),+ }),+ }+ }+}++/// The user-facing message for a transform failure. Transform errors describe+/// the user's own data, so when the chain carries no explicit [`UserError`] the+/// outermost message (e.g. "No distinct_id found") is the most specific safe+/// description we have — better than the generic unknown-error fallback.+fn user_facing_transform_error(e: &Error) -> String {+ match e.downcast_ref::<UserError>() {+ Some(user_error) => user_error.msg.clone(),+ None => e.to_string(),+ }+}++/// The source line as JSON when it is valid JSON (so the UI renders an object),+/// or the raw text otherwise.+fn source_value(line: &str) -> Value {+ serde_json::from_str(line).unwrap_or_else(|_| Value::String(line.to_string()))+}++#[cfg(test)]+mod tests {+ use std::sync::Arc;++ use uuid::Uuid;++ use super::*;+ use crate::cache::{MockGroupCache, MockIdentifyCache};+ use crate::parse::content::ContentType;++ fn captured_trial_parser() -> ParserFnFor<TrialRecord> {+ let context = TransformContext {+ team_id: 1,+ token: "token".to_string(),+ job_id: Uuid::now_v7(),+ identify_cache: Arc::new(MockIdentifyCache::new()),+ group_cache: Arc::new(MockGroupCache::new()),+ import_events: true,+ generate_identify_events: false,+ generate_group_identify_events: false,+ };+ trial_parser(+ &FormatConfig::JsonLines {+ skip_blanks: true,+ content: ContentType::Captured,+ },+ context,+ )+ }++ fn valid_line(event: &str, distinct_id: &str) -> String {+ format!(+ r#"{{"event":"{event}","distinct_id":"{distinct_id}","timestamp":"2024-01-01T00:00:00Z","properties":{{}}}}"#+ )+ }++ #[test]+ fn records_pair_sources_with_outputs_and_tolerate_bad_lines() {+ let parser = captured_trial_parser();+ let chunk = [+ valid_line("first", "u1"),+ "{not json".to_string(),+ r#"{"distinct_id":"u2"}"#.to_string(), // missing `event`+ r#"{"event":"orphan","properties":{}}"#.to_string(), // no distinct_id -> transform error+ valid_line("last", "u3"),+ ]+ .join("\n")+ + "\n";++ let parsed = parser(chunk.clone().into_bytes()).unwrap();++ assert_eq!(parsed.consumed, chunk.len());+ assert_eq!(parsed.data.len(), 5);++ let ok = &parsed.data[0];+ assert_eq!(ok.error, None);+ assert_eq!(ok.outputs.len(), 1);+ assert_eq!(ok.outputs[0].event, "first");+ assert_eq!(ok.outputs[0].distinct_id, "u1");+ assert_eq!(ok.source["event"], "first");++ let syntax = &parsed.data[1];+ assert!(syntax.outputs.is_empty());+ assert!(syntax.error.is_some());+ // An unparseable line is preserved as raw text+ assert_eq!(syntax.source, Value::String("{not json".to_string()));++ let schema = &parsed.data[2];+ assert!(schema+ .error+ .as_deref()+ .unwrap()+ .contains("Missing required field 'event'"));+ assert_eq!(schema.source["distinct_id"], "u2");++ let transform = &parsed.data[3];+ assert_eq!(transform.error.as_deref(), Some("No distinct_id found"));+ assert!(transform.outputs.is_empty());++ assert_eq!(parsed.data[4].outputs[0].event, "last");+ }++ #[test]+ fn partial_trailing_line_is_deferred_not_recorded_as_error() {+ let parser = captured_trial_parser();+ let complete = valid_line("first", "u1") + "\n";+ let chunk = format!("{complete}{{\"event\":\"spl");++ let parsed = parser(chunk.into_bytes()).unwrap();++ assert_eq!(+ parsed.data.len(),+ 1,+ "the partial line must not produce a record"+ );+ assert_eq!(parsed.consumed, complete.len());+ }++ #[test]+ fn valid_unterminated_final_line_is_consumed() {+ let parser = captured_trial_parser();+ let chunk = valid_line("first", "u1") + "\n" + &valid_line("last", "u2");++ let parsed = parser(chunk.clone().into_bytes()).unwrap();++ assert_eq!(parsed.data.len(), 2);+ assert_eq!(parsed.consumed, chunk.len());+ }+}diff --git a/rust/batch-import-worker/src/trial/sink.rs b/rust/batch-import-worker/src/trial/sink.rsnew file mode 100644index 000000000000..0ae4efd3ae99--- /dev/null+++ b/rust/batch-import-worker/src/trial/sink.rs@@ -0,0 +1,188 @@+use std::sync::Arc;++use anyhow::{Context, Error};+use object_store::{path::Path, ObjectStore, ObjectStoreExt, PutPayload};+use serde::Serialize;+use tracing::info;++use super::{TrialProgress, TrialRecord};++/// Writes trial output to object storage as size-bounded JSONL pages plus a+/// final `summary.json`, under `{prefix}/`. Page indices are deterministic:+/// a resumed trial that re-fetches a chunk rewrites the same objects, so page+/// writes are idempotent as long as they happen before the progress flush.+pub struct TrialSink {+ store: Arc<dyn ObjectStore>,+ prefix: String,+ records_per_page: usize,+}++/// One JSONL line in a page: the record plus its stable global sequence number.+#[derive(Serialize)]+struct PageRecord<'a> {+ seq: u64,+ #[serde(flatten)]+ record: &'a TrialRecord,+}++/// The completed trial's `summary.json`: pagination metadata plus the+/// accumulated aggregates.+#[derive(Serialize)]+struct FinalSummary<'a> {+ records: u64,+ pages: u32,+ records_per_page: usize,+ #[serde(flatten)]+ summary: &'a super::TrialSummary,+}++impl TrialSink {+ pub fn new(store: Arc<dyn ObjectStore>, prefix: String, records_per_page: usize) -> Self {+ Self {+ store,+ prefix,+ records_per_page: records_per_page.max(1),+ }+ }++ fn page_path(&self, index: u32) -> Path {+ Path::from(format!("{}/pages/{:05}.jsonl", self.prefix, index))+ }++ /// Write one chunk's records as pages starting at index `first_page`, with+ /// global sequence numbers starting at `first_seq`. Returns the number of+ /// pages written. The last page of a chunk may be short — page boundaries+ /// never span chunks, so a chunk's pages depend only on its own records.+ pub async fn write_pages(+ &self,+ first_page: u32,+ first_seq: u64,+ records: &[TrialRecord],+ ) -> Result<u32, Error> {+ let mut pages_written = 0u32;+ for (page_offset, page) in records.chunks(self.records_per_page).enumerate() {+ let mut body = Vec::new();+ for (i, record) in page.iter().enumerate() {+ let line = serde_json::to_vec(&PageRecord {+ seq: first_seq + (page_offset * self.records_per_page + i) as u64,+ record,+ })?;+ body.extend_from_slice(&line);+ body.push(b'\n');+ }+ let path = self.page_path(first_page + page_offset as u32);+ self.store+ .put(&path, PutPayload::from(body))+ .await+ .with_context(|| format!("Writing trial page {path}"))?;+ pages_written += 1;+ }+ Ok(pages_written)+ }++ pub async fn write_summary(&self, progress: &TrialProgress) -> Result<(), Error> {+ let path = Path::from(format!("{}/summary.json", self.prefix));+ let body = serde_json::to_vec(&FinalSummary {+ records: progress.records_emitted,+ pages: progress.pages_written,+ records_per_page: self.records_per_page,+ summary: &progress.summary,+ })?;+ self.store+ .put(&path, PutPayload::from(body))+ .await+ .with_context(|| format!("Writing trial summary {path}"))?;+ info!(+ "Wrote trial summary to {path} ({} records, {} pages)",+ progress.records_emitted, progress.pages_written+ );+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use object_store::memory::InMemory;+ use object_store::ObjectStoreExt;+ use serde_json::Value;++ use super::*;++ fn record(n: usize) -> TrialRecord {+ TrialRecord {+ source: serde_json::json!({"n": n}),+ outputs: vec![],+ error: None,+ }+ }++ async fn read_lines(store: &Arc<InMemory>, path: &str) -> Vec<Value> {+ let bytes = store+ .get(&Path::from(path))+ .await+ .unwrap()+ .bytes()+ .await+ .unwrap();+ String::from_utf8(bytes.to_vec())+ .unwrap()+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect()+ }++ #[tokio::test]+ async fn pages_are_size_bounded_with_continuous_seq_across_chunks() {+ let store = Arc::new(InMemory::new());+ let sink = TrialSink::new(store.clone(), "trial_runs/team_1/job_x".to_string(), 2);++ // First chunk: 5 records -> pages 0,1 full and page 2 short+ let chunk_one: Vec<_> = (0..5).map(record).collect();+ let pages = sink.write_pages(0, 0, &chunk_one).await.unwrap();+ assert_eq!(pages, 3);++ // Second chunk continues numbering after the first+ let chunk_two: Vec<_> = (5..8).map(record).collect();+ let pages = sink.write_pages(3, 5, &chunk_two).await.unwrap();+ assert_eq!(pages, 2);++ let mut seqs = vec![];+ for (page, expected_len) in [(0, 2), (1, 2), (2, 1), (3, 2), (4, 1)] {+ let lines = read_lines(+ &store,+ &format!("trial_runs/team_1/job_x/pages/{page:05}.jsonl"),+ )+ .await;+ assert_eq!(lines.len(), expected_len, "page {page}");+ for line in &lines {+ seqs.push(line["seq"].as_u64().unwrap());+ assert_eq!(line["source"]["n"].as_u64(), line["seq"].as_u64());+ }+ }+ assert_eq!(seqs, (0..8).collect::<Vec<u64>>());+ }++ #[tokio::test]+ async fn summary_carries_pagination_metadata_and_aggregates() {+ let store = Arc::new(InMemory::new());+ let sink = TrialSink::new(store.clone(), "p".to_string(), 500);++ let mut progress = super::super::TrialProgress::default();+ progress.absorb(&[record(0), record(1)], 1);+ sink.write_summary(&progress).await.unwrap();++ let bytes = store+ .get(&Path::from("p/summary.json"))+ .await+ .unwrap()+ .bytes()+ .await+ .unwrap();+ let summary: Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(summary["records"], 2);+ assert_eq!(summary["pages"], 1);+ assert_eq!(summary["records_per_page"], 500);+ assert_eq!(summary["source_records"], 2);+ assert_eq!(summary["skipped_records"], 2);+ }+}diff --git a/rust/batch-import-worker/tests/common/harness.rs b/rust/batch-import-worker/tests/common/harness.rsindex 1ccda424b8df..ef598bed1cbb 100644--- a/rust/batch-import-worker/tests/common/harness.rs+++ b/rust/batch-import-worker/tests/common/harness.rs@@ -90,7 +90,7 @@ impl Harness {total_size: None,}).collect();- let job_state = JobState { parts };+ let job_state = JobState { parts, trial: None };let model = JobModel {id: job_id,diff --git a/rust/batch-import-worker/tests/trial_e2e_test.rs b/rust/batch-import-worker/tests/trial_e2e_test.rsnew file mode 100644index 000000000000..90c57a986d22--- /dev/null+++ b/rust/batch-import-worker/tests/trial_e2e_test.rs@@ -0,0 +1,329 @@+//! End-to-end trial run test: the real `TrialJob` against local Postgres and+//! SeaweedFS (docker-compose.dev.yml). A `FolderSource` chunked small enough to+//! split lines at chunk boundaries feeds the production trial parser, pages land+//! in SeaweedFS via the real trial store client, and progress/status flushes go+//! through the lease-guarded Postgres path.+//!+//! Skips when the dev stack isn't running (SeaweedFS unreachable is a hard+//! failure in CI, matching the temp-bucket integration test).++use std::sync::Arc;++use batch_import_worker::config::Config;+use batch_import_worker::context::AppContext;+use batch_import_worker::job::config::{+ FolderSourceConfig, JobConfig, JobSecrets, SinkConfig, SourceConfig,+};+use batch_import_worker::job::model::{JobModel, JobStatus};+use batch_import_worker::parse::content::ContentType;+use batch_import_worker::parse::format::FormatConfig;+use batch_import_worker::trial::TrialJob;+use chrono::Utc;+use envconfig::Envconfig;+use lifecycle::{ComponentOptions, Manager};+use object_store::aws::AmazonS3Builder;+use object_store::path::Path;+use object_store::{ObjectStore, ObjectStoreExt};+use serde_json::Value;+use tempfile::TempDir;+use uuid::Uuid;++const SEAWEEDFS_ENDPOINT: &str = "http://localhost:8333";+const TEST_BUCKET: &str = "posthog";+const TEAM_ID: i32 = 1;+// Small enough to split the ~100-byte test lines across chunk boundaries.+const CHUNK_SIZE: usize = 96;+const RECORDS_PER_PAGE: usize = 3;++fn valid_line(n: usize) -> String {+ format!(+ r#"{{"event":"event_{n}","distinct_id":"user_{n}","timestamp":"2024-01-01T00:00:00Z","properties":{{}}}}"#+ )+}++/// 12 lines: 10 valid, one malformed (index 3), one missing distinct_id (index 7).+fn source_lines() -> Vec<String> {+ (0..12)+ .map(|n| match n {+ 3 => "{broken json".to_string(),+ 7 => r#"{"event":"orphan","properties":{}}"#.to_string(),+ _ => valid_line(n),+ })+ .collect()+}++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)+}++/// Probe SeaweedFS: unreachable is a silent skip locally but a hard failure in+/// CI, where the dev stack is always booted.+async fn seaweedfs_reachable(store: &Arc<dyn ObjectStore>) -> bool {+ let probe = 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+}++struct TrialRun {+ // Owns the source directory for the duration of the run.+ _dir: TempDir,+ context: Arc<AppContext>,+ store: Arc<dyn ObjectStore>,+ prefix: String,+ job_id: Uuid,+ model: JobModel,+}++impl TrialRun {+ /// Set up config, context, source dir, and a leased `posthog_batchimport`+ /// row, exactly as a claimed trial job would look. Returns `None` (skip)+ /// when the dev stack or the seed team isn't available.+ async fn create(record_limit: u64) -> Option<Self> {+ let store = seaweedfs_store();+ if !seaweedfs_reachable(&store).await {+ eprintln!("SeaweedFS unreachable at {SEAWEEDFS_ENDPOINT}, skipping test");+ return None;+ }++ let mut config = Config::init_from_env().unwrap();+ config.trial_bucket_name = TEST_BUCKET.to_string();+ config.trial_bucket_endpoint = SEAWEEDFS_ENDPOINT.to_string();+ config.trial_bucket_region = "us-east-1".to_string();+ config.trial_bucket_access_key_id = "any".to_string();+ config.trial_bucket_secret_access_key = "any".to_string();+ config.trial_bucket_force_path_style = true;+ config.trial_bucket_prefix = "trial-e2e-test/".to_string();+ config.trial_records_per_page = RECORDS_PER_PAGE;+ config.trial_chunk_size = CHUNK_SIZE;++ let Ok(context) = AppContext::new(&config).await else {+ eprintln!(+ "Postgres unreachable at {}, skipping test",+ config.database_url+ );+ return None;+ };+ let context = Arc::new(context);++ // The trial parser resolves the team's token; the dev/CI database seeds+ // team 1. Skip (rather than fabricate a team) when it's absent.+ if context.get_token_for_team_id(TEAM_ID).await.is_err() {+ eprintln!("team {TEAM_ID} not found in database, skipping test");+ return None;+ }++ let dir = TempDir::new().unwrap();+ std::fs::write(+ dir.path().join("events.jsonl"),+ source_lines().join("\n") + "\n",+ )+ .unwrap();++ let job_id = Uuid::now_v7();+ let lease_id = format!("trial-e2e-{job_id}");+ let import_config = JobConfig {+ source: SourceConfig::Folder(FolderSourceConfig {+ path: dir.path().to_string_lossy().to_string(),+ }),+ data_format: FormatConfig::JsonLines {+ skip_blanks: true,+ content: ContentType::Captured,+ },+ sink: SinkConfig::TrialS3 { record_limit },+ import_events: true,+ generate_identify_events: false,+ generate_group_identify_events: false,+ };++ sqlx::query(+ r#"+ INSERT INTO posthog_batchimport+ (id, team_id, created_at, updated_at, status, import_config, secrets, lease_id, leased_until, backoff_attempt)+ VALUES ($1, $2, now(), now(), 'running', $3, '', $4, now() + interval '30 minutes', 0)+ "#,+ )+ .bind(job_id)+ .bind(TEAM_ID)+ .bind(serde_json::to_value(&import_config).unwrap())+ .bind(&lease_id)+ .execute(&context.db)+ .await+ .unwrap();++ let model = JobModel {+ id: job_id,+ team_id: TEAM_ID,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ lease_id: Some(lease_id.clone()),+ leased_until: None,+ status: JobStatus::Running,+ status_message: None,+ display_status_message: None,+ state: None,+ import_config,+ secrets: JobSecrets::empty(),+ backoff_attempt: 0,+ backoff_until: None,+ was_leased: false,+ };++ let prefix = format!("trial-e2e-test/team_{TEAM_ID}/job_{job_id}");+ Some(Self {+ _dir: dir,+ context,+ store,+ prefix,+ job_id,+ model,+ })+ }++ async fn run_job(&self) {+ let mut manager = Manager::builder("trial-e2e-test")+ .with_trap_signals(false)+ .with_prestop_check(false)+ .build();+ let handle = manager.register("job", ComponentOptions::new());++ let job = TrialJob::new(self.model.clone(), self.context.clone(), handle)+ .await+ .unwrap();+ job.run().await.unwrap();+ }++ async fn db_status_and_state(&self) -> (String, Value) {+ let row: (String, Value) =+ sqlx::query_as("SELECT status, state FROM posthog_batchimport WHERE id = $1")+ .bind(self.job_id)+ .fetch_one(&self.context.db)+ .await+ .unwrap();+ row+ }++ async fn read_object(&self, rel: &str) -> Vec<u8> {+ self.store+ .get(&Path::from(format!("{}/{rel}", self.prefix)))+ .await+ .unwrap()+ .bytes()+ .await+ .unwrap()+ .to_vec()+ }++ async fn read_all_page_lines(&self, pages: u64) -> Vec<Value> {+ let mut lines = vec![];+ for page in 0..pages {+ let bytes = self.read_object(&format!("pages/{page:05}.jsonl")).await;+ for line in String::from_utf8(bytes).unwrap().lines() {+ lines.push(serde_json::from_str(line).unwrap());+ }+ }+ lines+ }++ /// Best-effort teardown: the row is deleted; objects are left under the+ /// uniquely-named job prefix.+ async fn cleanup(&self) {+ sqlx::query("DELETE FROM posthog_batchimport WHERE id = $1")+ .bind(self.job_id)+ .execute(&self.context.db)+ .await+ .ok();+ }+}++#[tokio::test]+async fn trial_job_pairs_every_source_line_and_completes() {+ let Some(run) = TrialRun::create(100).await else {+ return;+ };+ run.run_job().await;++ let (status, state) = run.db_status_and_state().await;+ assert_eq!(status, "completed");++ // Progress persisted through the lease-guarded flush path+ let trial = &state["trial"];+ assert_eq!(trial["records_emitted"], 12);+ assert_eq!(trial["summary"]["dropped_records"], 2);+ assert_eq!(trial["summary"]["output_events"], 10);+ let pages = trial["pages_written"].as_u64().unwrap();++ // Every source line becomes exactly one record despite lines being split+ // across ~96-byte chunks, and bad lines don't abort the run.+ let lines = run.read_all_page_lines(pages).await;+ assert_eq!(lines.len(), 12);+ for (i, line) in lines.iter().enumerate() {+ assert_eq!(+ line["seq"].as_u64(),+ Some(i as u64),+ "seq must be continuous"+ );+ }++ // The two planted failures carry their reasons and original source+ assert!(lines[3]["error"].as_str().is_some());+ assert_eq!(+ lines[3]["source"],+ Value::String("{broken json".to_string())+ );+ assert_eq!(lines[7]["error"], "No distinct_id found");+ assert_eq!(lines[7]["source"]["event"], "orphan");++ // A valid record pairs its source with the transformed output+ assert_eq!(lines[0]["source"]["event"], "event_0");+ assert_eq!(lines[0]["outputs"][0]["event"], "event_0");+ assert_eq!(lines[0]["outputs"][0]["distinct_id"], "user_0");+ assert_eq!(+ lines[0]["outputs"][0]["payload"]["properties"]["$import_job_id"],+ run.job_id.to_string()+ );++ // Summary is readable and consistent with the pages+ let summary: Value = serde_json::from_slice(&run.read_object("summary.json").await).unwrap();+ assert_eq!(summary["records"], 12);+ assert_eq!(summary["pages"], pages);+ assert_eq!(summary["error_counts"]["No distinct_id found"], 1);++ run.cleanup().await;+}++#[tokio::test]+async fn trial_job_stops_at_the_record_limit() {+ let Some(run) = TrialRun::create(4).await else {+ return;+ };+ run.run_job().await;++ let (status, state) = run.db_status_and_state().await;+ assert_eq!(status, "completed");+ assert_eq!(state["trial"]["records_emitted"], 4);++ let pages = state["trial"]["pages_written"].as_u64().unwrap();+ let lines = run.read_all_page_lines(pages).await;+ assert_eq!(lines.len(), 4);+ assert_eq!(lines.last().unwrap()["seq"], 3);++ run.cleanup().await;+}