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.

fix(batch-import-worker): honor operator status and live send rate (#122343)

Eli Reismand2915758c0c1
diff --git a/rust/batch-import-worker/.sqlx/query-2d6a6bf5da8ebaf50b33458aedba3ad6a16c6701ade51325abbc2724dc21038f.json b/rust/batch-import-worker/.sqlx/query-2d6a6bf5da8ebaf50b33458aedba3ad6a16c6701ade51325abbc2724dc21038f.json
deleted file mode 100644
index b586b3a2af2e..000000000000
--- a/rust/batch-import-worker/.sqlx/query-2d6a6bf5da8ebaf50b33458aedba3ad6a16c6701ade51325abbc2724dc21038f.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE posthog_batchimport\n SET\n status = $2,\n status_message = $3,\n display_status_message = $4,\n state = $5,\n updated_at = now(),\n lease_id = $6,\n leased_until = $7\n WHERE id = $1 AND lease_id = $8\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Text",
- "Jsonb",
- "Text",
- "Timestamptz",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "2d6a6bf5da8ebaf50b33458aedba3ad6a16c6701ade51325abbc2724dc21038f"
-}
diff --git a/rust/batch-import-worker/.sqlx/query-3011a61a485c88955cc08dd8ad6f81749e4264667a44e60f4e849bf0eef71694.json b/rust/batch-import-worker/.sqlx/query-3011a61a485c88955cc08dd8ad6f81749e4264667a44e60f4e849bf0eef71694.json
new file mode 100644
index 000000000000..a618d8ada41c
--- /dev/null
+++ b/rust/batch-import-worker/.sqlx/query-3011a61a485c88955cc08dd8ad6f81749e4264667a44e60f4e849bf0eef71694.json
@@ -0,0 +1,39 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE posthog_batchimport\n SET\n status = CASE WHEN $2::text IS NOT NULL AND status = 'running' THEN $2 ELSE status END,\n status_message = CASE WHEN $2::text IS NOT NULL AND status = 'running' THEN $3 ELSE status_message END,\n display_status_message = CASE WHEN $2::text IS NOT NULL AND status = 'running' THEN $4 ELSE display_status_message END,\n state = $5,\n pending_commit = $6,\n backoff_attempt = $7,\n backoff_until = $8,\n updated_at = now(),\n lease_id = $9,\n leased_until = $10\n WHERE id = $1 AND lease_id = $11 AND (NOT $12 OR status = 'running')\n RETURNING status, import_config->'sink'->>'send_rate' AS send_rate\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "send_rate",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Jsonb",
+ "Int4",
+ "Timestamptz",
+ "Text",
+ "Timestamptz",
+ "Text",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "3011a61a485c88955cc08dd8ad6f81749e4264667a44e60f4e849bf0eef71694"
+}
diff --git a/rust/batch-import-worker/.sqlx/query-47f70914316487c242188c276ccc5175e2fd63eedfdaebfb4933ec70700fc33d.json b/rust/batch-import-worker/.sqlx/query-7af4b421dcae198ade3eef31a56f6490b75ef0a7552788ac2c61ea2d769256a2.json
similarity index 72%
rename from rust/batch-import-worker/.sqlx/query-47f70914316487c242188c276ccc5175e2fd63eedfdaebfb4933ec70700fc33d.json
rename to rust/batch-import-worker/.sqlx/query-7af4b421dcae198ade3eef31a56f6490b75ef0a7552788ac2c61ea2d769256a2.json
index 4a8f7419a0d1..8b70552da8c4 100644
--- a/rust/batch-import-worker/.sqlx/query-47f70914316487c242188c276ccc5175e2fd63eedfdaebfb4933ec70700fc33d.json
+++ b/rust/batch-import-worker/.sqlx/query-7af4b421dcae198ade3eef31a56f6490b75ef0a7552788ac2c61ea2d769256a2.json
@@ -1,16 +1,17 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE posthog_batchimport\n SET\n lease_id = null,\n leased_until = null,\n status = 'paused',\n status_message = $2,\n display_status_message = $3\n WHERE id = $1\n ",
+ "query": "\n UPDATE posthog_batchimport\n SET\n lease_id = null,\n leased_until = null,\n status = 'paused',\n status_message = $2,\n display_status_message = $3\n WHERE id = $1 AND lease_id = $4 AND status = 'running'\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Text",
+ "Text",
"Text"
]
},
"nullable": []
},
- "hash": "47f70914316487c242188c276ccc5175e2fd63eedfdaebfb4933ec70700fc33d"
+ "hash": "7af4b421dcae198ade3eef31a56f6490b75ef0a7552788ac2c61ea2d769256a2"
}
diff --git a/rust/batch-import-worker/.sqlx/query-7c4dccace778cc931a460e982d16a8aa058d6728135e358c8ba1722954e56b57.json b/rust/batch-import-worker/.sqlx/query-89f4bfbdd97031b3da1cdf2b255bca4fcd3f0677b54cb0ec07df3c99762842d8.json
similarity index 89%
rename from rust/batch-import-worker/.sqlx/query-7c4dccace778cc931a460e982d16a8aa058d6728135e358c8ba1722954e56b57.json
rename to rust/batch-import-worker/.sqlx/query-89f4bfbdd97031b3da1cdf2b255bca4fcd3f0677b54cb0ec07df3c99762842d8.json
index a8c480d365db..a5447dae4631 100644
--- a/rust/batch-import-worker/.sqlx/query-7c4dccace778cc931a460e982d16a8aa058d6728135e358c8ba1722954e56b57.json
+++ b/rust/batch-import-worker/.sqlx/query-89f4bfbdd97031b3da1cdf2b255bca4fcd3f0677b54cb0ec07df3c99762842d8.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH next_job AS (\n SELECT *, lease_id as previous_lease_id\n FROM posthog_batchimport\n WHERE status = 'running' AND (leased_until IS NULL OR leased_until <= now())\n ORDER BY created_at\n LIMIT 1\n FOR UPDATE SKIP LOCKED\n )\n UPDATE posthog_batchimport\n SET\n status = 'running',\n leased_until = now() + interval '30 minutes', -- We lease for a long time because job init can be quite slow\n lease_id = $1\n FROM next_job\n WHERE posthog_batchimport.id = next_job.id\n RETURNING\n posthog_batchimport.id,\n posthog_batchimport.team_id,\n posthog_batchimport.created_at,\n posthog_batchimport.updated_at,\n posthog_batchimport.status_message,\n posthog_batchimport.display_status_message,\n posthog_batchimport.state,\n posthog_batchimport.import_config,\n posthog_batchimport.secrets as \"secrets?\",\n posthog_batchimport.backoff_attempt,\n posthog_batchimport.backoff_until,\n next_job.previous_lease_id\n ",
+ "query": "\n WITH next_job AS (\n SELECT *, lease_id as previous_lease_id\n FROM posthog_batchimport\n WHERE status = 'running' AND (leased_until IS NULL OR leased_until <= now())\n ORDER BY created_at\n LIMIT 1\n FOR UPDATE SKIP LOCKED\n )\n UPDATE posthog_batchimport\n SET\n status = 'running',\n leased_until = now() + interval '30 minutes', -- We lease for a long time because job init can be quite slow\n lease_id = $1\n FROM next_job\n WHERE posthog_batchimport.id = next_job.id\n RETURNING\n posthog_batchimport.id,\n posthog_batchimport.team_id,\n posthog_batchimport.created_at,\n posthog_batchimport.updated_at,\n posthog_batchimport.status_message,\n posthog_batchimport.display_status_message,\n posthog_batchimport.state,\n posthog_batchimport.import_config,\n posthog_batchimport.secrets as \"secrets?\",\n posthog_batchimport.backoff_attempt,\n posthog_batchimport.backoff_until,\n posthog_batchimport.pending_commit,\n next_job.previous_lease_id\n ",
"describe": {
"columns": [
{
@@ -60,6 +60,11 @@
},
{
"ordinal": 11,
+ "name": "pending_commit",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 12,
"name": "previous_lease_id",
"type_info": "Text"
}
@@ -78,11 +83,12 @@
true,
true,
false,
+ true,
false,
- false,
+ true,
true,
true
]
},
- "hash": "7c4dccace778cc931a460e982d16a8aa058d6728135e358c8ba1722954e56b57"
+ "hash": "89f4bfbdd97031b3da1cdf2b255bca4fcd3f0677b54cb0ec07df3c99762842d8"
}
diff --git a/rust/batch-import-worker/.sqlx/query-bdd2508c7a5b598f1556bf01b684f9c962a6386df33569b5fa7295f9e844a953.json b/rust/batch-import-worker/.sqlx/query-bdd2508c7a5b598f1556bf01b684f9c962a6386df33569b5fa7295f9e844a953.json
new file mode 100644
index 000000000000..a205d413c767
--- /dev/null
+++ b/rust/batch-import-worker/.sqlx/query-bdd2508c7a5b598f1556bf01b684f9c962a6386df33569b5fa7295f9e844a953.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE posthog_batchimport\n SET lease_id = NULL, leased_until = NULL\n WHERE id = $1 AND lease_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "bdd2508c7a5b598f1556bf01b684f9c962a6386df33569b5fa7295f9e844a953"
+}
diff --git a/rust/batch-import-worker/.sqlx/query-c23436649ea4a7f8c9c40d5df88c5080487d250641f7478d462f183d8cbffa60.json b/rust/batch-import-worker/.sqlx/query-c23436649ea4a7f8c9c40d5df88c5080487d250641f7478d462f183d8cbffa60.json
new file mode 100644
index 000000000000..3dc1f7dc6ca0
--- /dev/null
+++ b/rust/batch-import-worker/.sqlx/query-c23436649ea4a7f8c9c40d5df88c5080487d250641f7478d462f183d8cbffa60.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT status, lease_id FROM posthog_batchimport WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "lease_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "c23436649ea4a7f8c9c40d5df88c5080487d250641f7478d462f183d8cbffa60"
+}
diff --git a/rust/batch-import-worker/src/emit/capture.rs b/rust/batch-import-worker/src/emit/capture.rs
index 0ecbe0cf1731..fb4ab5d76eb4 100644
--- a/rust/batch-import-worker/src/emit/capture.rs
+++ b/rust/batch-import-worker/src/emit/capture.rs
@@ -39,6 +39,13 @@ impl CaptureEmitter {
#[async_trait]
impl Emitter for CaptureEmitter {
+ fn set_send_rate(&mut self, send_rate: u64) {
+ if send_rate != self.send_rate {
+ info!(old = self.send_rate, new = send_rate, "send rate changed");
+ self.send_rate = send_rate;
+ }
+ }
+
async fn begin_write<'a>(&'a mut self) -> Result<Box<dyn Transaction<'a> + 'a>, Error> {
Ok(Box::new(CaptureTransaction {
client: &self.client,
diff --git a/rust/batch-import-worker/src/emit/kafka.rs b/rust/batch-import-worker/src/emit/kafka.rs
index 065b2c38f555..bbf0e5bb4c25 100644
--- a/rust/batch-import-worker/src/emit/kafka.rs
+++ b/rust/batch-import-worker/src/emit/kafka.rs
@@ -62,6 +62,13 @@ impl KafkaEmitter {
#[async_trait]
impl Emitter for KafkaEmitter {
+ fn set_send_rate(&mut self, send_rate: u64) {
+ if send_rate != self.send_rate {
+ info!(old = self.send_rate, new = send_rate, "send rate changed");
+ self.send_rate = send_rate;
+ }
+ }
+
async fn begin_write<'a>(&'a mut self) -> Result<Box<dyn Transaction<'a> + 'a>, Error> {
let txn = self.producer.begin()?;
Ok(Box::new(KafkaEmitterTransaction {
@@ -130,6 +137,13 @@ impl<'a> Transaction<'a> for KafkaEmitterTransaction<'a> {
info!("committed transaction");
Ok(to_sleep)
}
+
+ // Records already produced stay in an open transaction until it ends. Leaving it open holds
+ // back read_committed consumers of the topic until the broker times it out.
+ async fn abort(self: Box<Self>) -> Result<(), Error> {
+ self.inner.abort()?;
+ Ok(())
+ }
}
impl<'a> KafkaEmitterTransaction<'a> {
diff --git a/rust/batch-import-worker/src/emit/mod.rs b/rust/batch-import-worker/src/emit/mod.rs
index 71850e3314b7..7c4e25da6a2f 100644
--- a/rust/batch-import-worker/src/emit/mod.rs
+++ b/rust/batch-import-worker/src/emit/mod.rs
@@ -12,6 +12,9 @@ pub mod kafka;
#[async_trait]
pub trait Emitter: Send + Sync {
async fn begin_write<'a>(&'a mut self) -> Result<Box<dyn Transaction<'a> + 'a>, Error>;
+
+ /// Apply a send rate changed on the job row, from the next transaction on.
+ fn set_send_rate(&mut self, _send_rate: u64) {}
}
#[async_trait]
@@ -22,6 +25,11 @@ pub trait Transaction<'a>: Send + Sync {
async fn commit_write(self: Box<Self>) -> Result<Duration, Error> {
Ok(Duration::from_secs(0))
}
+
+ /// Discard everything emitted in this transaction. Sinks that send only on commit need nothing.
+ async fn abort(self: Box<Self>) -> Result<(), Error> {
+ Ok(())
+ }
}
pub struct StdoutEmitter {
diff --git a/rust/batch-import-worker/src/job/mod.rs b/rust/batch-import-worker/src/job/mod.rs
index 5502c9ca305a..2bf17c318d36 100644
--- a/rust/batch-import-worker/src/job/mod.rs
+++ b/rust/batch-import-worker/src/job/mod.rs
@@ -30,6 +30,8 @@ use crate::{
pub mod backoff;
pub mod config;
pub mod model;
+#[cfg(test)]
+pub(crate) mod test_db;
#[derive(Debug, PartialEq)]
enum ErrorHandlingDecision {
@@ -607,6 +609,14 @@ struct Checkpoint {
data: Parsed<Vec<InternallyCapturedEvent>>,
}
+/// Whether the job keeps going after a commit.
+#[derive(Debug, PartialEq, Eq)]
+enum CommitOutcome {
+ Continue,
+ /// The row is no longer running because an operator or a customer changed its status.
+ Stopped,
+}
+
impl Job {
pub async fn new(
mut model: JobModel,
@@ -674,6 +684,19 @@ impl Job {
let (next_chunk, next_commit) = tokio::join!(next_chunk_fut, next_commit_fut);
+ if let Ok(CommitOutcome::Stopped) = next_commit {
+ // Keep staged data for the resume, like a shutdown does. The chunk fetched in
+ // parallel is dropped: its offsets live only in memory.
+ info!(job_id = %self.job_id, "Job is no longer running, stopping");
+ if let Err(cleanup_err) = self.source.release_job_resources().await {
+ warn!(
+ "Failed to release job resources after stop: {:?}",
+ cleanup_err
+ );
+ }
+ return Ok(None);
+ }
+
if let Err(e) = next_commit {
// If we fail to commit, we just log and bail out - the job will be paused if it needs to be,
// but this pod should restart, in case it's sink is in some bad state.
@@ -749,13 +772,13 @@ impl Job {
Ok(Some((key, parsed)))
}
- async fn do_commit(&self) -> Result<(), Error> {
+ async fn do_commit(&self) -> Result<CommitOutcome, Error> {
self.shutdown_guard()?;
let mut checkpoint_lock = self.checkpoint.lock().await;
let Some(checkpoint) = checkpoint_lock.take() else {
info!(job_id = %self.job_id, "No checkpointed data to commit, returning");
- return Ok(());
+ return Ok(CommitOutcome::Continue);
};
let (key, parsed) = (checkpoint.key, checkpoint.data);
@@ -769,14 +792,21 @@ impl Job {
info!(job_id = %self.job_id, "Writing {} events", parsed.data.len());
self.shutdown_guard()?;
txn.emit(&parsed.data).await?;
- // Two-stage commit: advance the offset and pause the job in PG *before* committing to
- // the sink. If we crash between the two, the job is left paused at the advanced offset
- // and requires manual intervention rather than silently skipping a chunk — the operator
- // confirms whether the sink commit landed via the last event written or the logs.
+ // Save the advanced offset and a pending-commit marker before the sink commit. After a crash
+ // between the two, the next claim finds the marker and pauses the job for review.
self.shutdown_guard()?;
info!(job_id = %self.job_id, "Beginning PG part commit");
- self.begin_part_commit(&key, parsed.consumed, parsed.data.len())
- .await?;
+ if self
+ .begin_part_commit(&key, parsed.consumed, parsed.data.len())
+ .await?
+ == CommitOutcome::Stopped
+ {
+ if let Err(e) = txn.abort().await {
+ warn!(job_id = %self.job_id, "Failed to abort the sink transaction: {e:#}");
+ }
+ metric_emit::operator_stop("before_send");
+ return Ok(CommitOutcome::Stopped);
+ }
info!(job_id = %self.job_id, "Beginning emitter part commit");
// A *returned* error (as opposed to a crash) means the sink definitively rejected the
@@ -791,8 +821,11 @@ impl Job {
}
};
info!(job_id = %self.job_id, "Finishing PG part commit");
- self.complete_commit().await?;
+ let committed = self.complete_commit().await?;
info!(job_id = %self.job_id, "Committed part {} consumed {} bytes", key, parsed.consumed);
+ if let Some(send_rate) = committed.send_rate {
+ sink.set_send_rate(send_rate);
+ }
// The committed part may now be fully consumed: free its staging eagerly and only
// after its offsets are durable. Safe against concurrent reads: the in-memory state
@@ -807,13 +840,23 @@ impl Job {
// preserving the staged data for the byte-identical re-read on resume.
cleanup_committed_part_if_done(self.source.as_ref(), &self.model, &key).await;
+ if committed.status != model::JobStatus::Running {
+ metric_emit::operator_stop("after_send");
+ self.model
+ .lock()
+ .await
+ .release_lease(&self.context.db)
+ .await?;
+ return Ok(CommitOutcome::Stopped);
+ }
+
info!(job_id = %self.job_id, "Sleeping for {:?}", to_sleep);
tokio::select! {
_ = tokio::time::sleep(to_sleep) => {},
_ = self.handle.shutdown_recv() => {},
}
- Ok(())
+ Ok(CommitOutcome::Continue)
}
async fn successfully_complete(self) -> Result<(), Error> {
@@ -836,30 +879,32 @@ impl Job {
.await;
}
- let result = model.complete(&self.context.db).await;
- if result.is_ok() {
- let parts = stored.parts.len();
- let events = stored.events_emitted;
- metric_emit::completed_job_size(parts, events);
- if events == 0 {
- metric_emit::job_completion("completed_empty");
- warn!(job_id = %self.job_id, parts, "Batch import job complete, but it emitted no events");
- } else {
- metric_emit::job_completion("completed");
- info!(job_id = %self.job_id, parts, events, "Batch import job complete");
- }
+ let status = model.complete(&self.context.db).await?;
+ if status != model::JobStatus::Completed {
+ info!(job_id = %self.job_id, %status, "Job reached its end, but an operator status was kept");
+ return Ok(());
+ }
+ let parts = stored.parts.len();
+ let events = stored.events_emitted;
+ metric_emit::completed_job_size(parts, events);
+ if events == 0 {
+ metric_emit::job_completion("completed_empty");
+ warn!(job_id = %self.job_id, parts, "Batch import job complete, but it emitted no events");
+ } else {
+ metric_emit::job_completion("completed");
+ info!(job_id = %self.job_id, parts, events, "Batch import job complete");
}
- result
+ Ok(())
}
- // Writes the new partstate to the DB, and sets the job status to paused, such that if there's an issue with the sink commit, the job
- // will be paused, and manual intervention will be required to resume it
+ // Saves the advanced offset and a pending-commit marker. Writes nothing and returns `Stopped`
+ // when the row is no longer running.
async fn begin_part_commit(
&self,
key: &str,
consumed: usize,
events: usize,
- ) -> Result<(), Error> {
+ ) -> Result<CommitOutcome, Error> {
let mut model = self.model.lock().await;
let Some(model_state) = &mut model.state else {
return Err(Error::msg("No model state found"));
@@ -870,17 +915,25 @@ impl Job {
};
model_state.events_emitted = model_state.events_emitted.saturating_add(events as u64);
- let status_message = format!(
- "Starting commit of part {key} to offset {new_offset}, consumed {consumed} additional bytes"
- );
+ model.pending_commit = Some(model::PendingCommit {
+ key: key.to_string(),
+ from_offset: new_offset.saturating_sub(consumed as u64),
+ to_offset: new_offset,
+ });
- model
- .pause(
- self.context.clone(),
- status_message,
- Some("Job paused while committing events".to_string()),
- )
- .await
+ let written = model.save_progress(&self.context.db, true, true).await?;
+ if written.applied {
+ return Ok(CommitOutcome::Continue);
+ }
+
+ // Keep the in-memory model equal to the row, which the refused write left unchanged.
+ model.pending_commit = None;
+ if let Some(model_state) = &mut model.state {
+ model_state.revert_part_offset(key, consumed as u64);
+ model_state.events_emitted = model_state.events_emitted.saturating_sub(events as u64);
+ }
+ model.release_lease(&self.context.db).await?;
+ Ok(CommitOutcome::Stopped)
}
// Reverts the speculative offset advance from begin_part_commit after a definitive sink
@@ -902,6 +955,7 @@ impl Job {
return Err(Error::msg(format!("No part found with key {key}")));
};
model_state.events_emitted = model_state.events_emitted.saturating_sub(events as u64);
+ model.pending_commit = None;
let status_message =
format!("Commit of part {key} failed, rolled back to offset {new_offset}: {err:#}");
@@ -912,13 +966,15 @@ impl Job {
status_message,
Some("Job paused after a failed commit. Resolve the error and resume.".to_string()),
)
- .await
+ .await?;
+ model.release_lease(&self.context.db).await
}
- // Unpauses the job
- async fn complete_commit(&self) -> Result<(), Error> {
+ // Clears the pending-commit marker, and reports the row's current status and send rate
+ async fn complete_commit(&self) -> Result<model::RowWrite, Error> {
let mut model = self.model.lock().await;
- model.unpause(self.context.clone()).await
+ model.pending_commit = None;
+ model.save_committed(&self.context.db).await
}
fn shutdown_guard(&self) -> Result<(), Error> {
@@ -1265,6 +1321,7 @@ mod tests {
was_leased: false,
backoff_attempt: 5,
backoff_until: None,
+ pending_commit: None,
};
// Only verifies local field change; DB write path covered elsewhere
@@ -1500,6 +1557,360 @@ mod tests {
}
}
+ mod operator_control_tests {
+ use std::future::Future;
+ use std::pin::Pin;
+
+ use std::time::Duration;
+
+ use super::*;
+ use crate::emit::Transaction;
+ use crate::job::model::{JobStatus, PartState};
+ use crate::job::test_db;
+ use sqlx::PgPool;
+ use tokio_util::sync::CancellationToken;
+
+ const PART_BYTES: usize = 64;
+ const SEND_RATE: u64 = 1000;
+
+ type SendHook =
+ Arc<dyn Fn(usize) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
+
+ /// Parts held in memory, one chunk each.
+ struct MemorySource {
+ parts: Vec<String>,
+ }
+
+ #[async_trait]
+ impl DataSource for MemorySource {
+ async fn keys(&self) -> Result<Vec<String>, Error> {
+ Ok(self.parts.clone())
+ }
+
+ async fn size(&self, _key: &str) -> Result<Option<u64>, Error> {
+ Ok(Some(PART_BYTES as u64))
+ }
+
+ async fn get_chunk(
+ &self,
+ _key: &str,
+ offset: u64,
+ size: u64,
+ ) -> Result<Vec<u8>, Error> {
+ let end = (offset + size).min(PART_BYTES as u64);
+ Ok(vec![b'x'; (end - offset) as usize])
+ }
+ }
+
+ /// Delivers in `commit_write` like the capture sink, recording each send rate and abort.
+ /// `on_send` runs during a delivery, which is where an operator change races the worker.
+ struct RecordingEmitter {
+ send_rate: u64,
+ sends: Arc<std::sync::Mutex<Vec<u64>>>,
+ aborts: Arc<std::sync::atomic::AtomicUsize>,
+ on_send: Option<SendHook>,
+ fail_sends: bool,
+ }
+
+ struct RecordingTransaction<'a> {
+ emitter: &'a RecordingEmitter,
+ }
+
+ #[async_trait]
+ impl Emitter for RecordingEmitter {
+ async fn begin_write<'a>(&'a mut self) -> Result<Box<dyn Transaction<'a> + 'a>, Error> {
+ Ok(Box::new(RecordingTransaction { emitter: self }))
+ }
+
+ fn set_send_rate(&mut self, send_rate: u64) {
+ self.send_rate = send_rate;
+ }
+ }
+
+ #[async_trait]
+ impl<'a> Transaction<'a> for RecordingTransaction<'a> {
+ async fn emit(&self, _data: &[InternallyCapturedEvent]) -> Result<(), Error> {
+ Ok(())
+ }
+
+ async fn commit_write(self: Box<Self>) -> Result<Duration, Error> {
+ let index = {
+ let mut sends = self.emitter.sends.lock().unwrap();
+ sends.push(self.emitter.send_rate);
+ sends.len() - 1
+ };
+ if let Some(hook) = &self.emitter.on_send {
+ hook(index).await;
+ }
+ if self.emitter.fail_sends {
+ return Err(Error::msg("sink rejected the chunk"));
+ }
+ Ok(Duration::ZERO)
+ }
+
+ async fn abort(self: Box<Self>) -> Result<(), Error> {
+ self.emitter
+ .aborts
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(())
+ }
+ }
+
+ fn consume_all() -> Arc<ParserFn> {
+ Arc::new(Box::new(|bytes: Vec<u8>| {
+ Ok(Parsed {
+ consumed: bytes.len(),
+ data: Vec::new(),
+ })
+ }))
+ }
+
+ fn make_handle() -> lifecycle::Handle {
+ let mut manager = lifecycle::Manager::builder("test")
+ .with_trap_signals(false)
+ .with_prestop_check(false)
+ .with_shutdown_token(CancellationToken::new())
+ .build();
+ manager.register("test-component", lifecycle::ComponentOptions::new())
+ }
+
+ struct Run {
+ id: Uuid,
+ context: Arc<AppContext>,
+ sends: Arc<std::sync::Mutex<Vec<u64>>>,
+ aborts: Arc<std::sync::atomic::AtomicUsize>,
+ result: Result<(), Error>,
+ }
+
+ /// Run a three-part job on a fresh row, calling `before_process` between commits and the
+ /// `on_send` hook during deliveries.
+ async fn run_job<H, B, BF>(on_send: H, before_process: B, fail_sends: bool) -> Run
+ where
+ H: FnOnce(Uuid, PgPool) -> Option<SendHook>,
+ B: Fn(usize, Uuid, Arc<AppContext>) -> BF,
+ BF: Future<Output = ()>,
+ {
+ let context = test_db::context().await;
+ let parts: Vec<String> = (1..=3).map(|n| format!("part-{n}")).collect();
+ let state = JobState {
+ parts: parts
+ .iter()
+ .map(|key| PartState {
+ key: key.clone(),
+ current_offset: 0,
+ total_size: Some(PART_BYTES as u64),
+ })
+ .collect(),
+ trial: None,
+ events_emitted: 0,
+ };
+ let row = test_db::JobRowFixture {
+ status: JobStatus::Running,
+ lease_id: "lease-from-claim",
+ state: state.clone(),
+ sink: serde_json::json!({"type": "capture", "send_rate": SEND_RATE}),
+ pending_commit: None,
+ };
+ let id = test_db::insert_job(&context.db, &row).await;
+ let sends = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let aborts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let mut next = Some(Job {
+ context: context.clone(),
+ handle: make_handle(),
+ job_id: id,
+ chunk_size: PART_BYTES,
+ state: Mutex::new(state),
+ model: Mutex::new(test_db::claimed_model(id, &row)),
+ source: Box::new(MemorySource { parts }),
+ transform: consume_all(),
+ sink: Mutex::new(Box::new(RecordingEmitter {
+ send_rate: SEND_RATE,
+ sends: sends.clone(),
+ aborts: aborts.clone(),
+ on_send: on_send(id, context.db.clone()),
+ fail_sends,
+ })),
+ checkpoint: Mutex::new(None),
+ });
+
+ let mut step = 0;
+ let result = loop {
+ let Some(job) = next else { break Ok(()) };
+ before_process(step, id, context.clone()).await;
+ step += 1;
+ match job.process().await {
+ Ok(job) => next = job,
+ Err(e) => break Err(e),
+ }
+ };
+ Run {
+ id,
+ context,
+ sends,
+ aborts,
+ result,
+ }
+ }
+
+ /// A delivery hook that runs `action` on the job row during the first send.
+ fn during_first_send<F, Fut>(action: F) -> impl FnOnce(Uuid, PgPool) -> Option<SendHook>
+ where
+ F: Fn(PgPool, Uuid) -> Fut + Send + Sync + 'static,
+ Fut: Future<Output = ()> + Send + 'static,
+ {
+ move |id, pool| {
+ let action = Arc::new(action);
+ let hook: SendHook = Arc::new(move |index| {
+ let (action, pool) = (action.clone(), pool.clone());
+ Box::pin(async move {
+ if index == 0 {
+ action(pool, id).await;
+ }
+ })
+ });
+ Some(hook)
+ }
+ }
+
+ fn no_hook(_id: Uuid, _pool: PgPool) -> Option<SendHook> {
+ None
+ }
+
+ fn offsets(stored: &test_db::StoredJob) -> Vec<u64> {
+ stored
+ .state
+ .parts
+ .iter()
+ .map(|p| p.current_offset)
+ .collect()
+ }
+
+ async fn no_op(_step: usize, _id: Uuid, _context: Arc<AppContext>) {}
+
+ #[tokio::test]
+ async fn test_send_rate_change_applies_from_the_next_chunk() {
+ let run = run_job(
+ during_first_send(|pool, id| async move {
+ test_db::set_send_rate(&pool, id, 250).await;
+ }),
+ no_op,
+ false,
+ )
+ .await;
+
+ run.result.unwrap();
+ assert_eq!(*run.sends.lock().unwrap(), vec![SEND_RATE, 250, 250]);
+ let stored = test_db::read_job(&run.context.db, run.id).await;
+ assert_eq!(stored.status, "completed");
+ assert_eq!(offsets(&stored), vec![PART_BYTES as u64; 3]);
+ assert_eq!(stored.pending_commit, None);
+ test_db::delete_job(&run.context.db, run.id).await;
+ }
+
+ #[tokio::test]
+ async fn test_operator_change_between_chunks_sends_nothing_more() {
+ for operator_status in [JobStatus::Paused, JobStatus::Completed, JobStatus::Failed] {
+ // Step 0 fetches part 1 and step 1 commits it, so this lands before any send.
+ let run = run_job(
+ no_hook,
+ |step, id, context| async move {
+ if step == 1 {
+ test_db::operator_sets(&context.db, id, operator_status).await;
+ }
+ },
+ false,
+ )
+ .await;
+
+ run.result.unwrap();
+ assert!(run.sends.lock().unwrap().is_empty(), "{operator_status}");
+ assert_eq!(
+ run.aborts.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the emitted chunk's transaction is aborted, not left open"
+ );
+ let stored = test_db::read_job(&run.context.db, run.id).await;
+ assert_eq!(stored.status, operator_status.to_string());
+ assert_eq!(offsets(&stored), vec![0, 0, 0], "{operator_status}");
+ assert_eq!(stored.pending_commit, None);
+ assert_eq!(stored.lease_id, None, "{operator_status}");
+ test_db::delete_job(&run.context.db, run.id).await;
+ }
+ }
+
+ #[tokio::test]
+ async fn test_operator_change_during_send_records_the_chunk_and_stops() {
+ for operator_status in [JobStatus::Paused, JobStatus::Completed, JobStatus::Failed] {
+ let run = run_job(
+ during_first_send(move |pool, id| async move {
+ test_db::operator_sets(&pool, id, operator_status).await;
+ }),
+ no_op,
+ false,
+ )
+ .await;
+
+ run.result.unwrap();
+ assert_eq!(run.sends.lock().unwrap().len(), 1, "{operator_status}");
+ let stored = test_db::read_job(&run.context.db, run.id).await;
+ assert_eq!(stored.status, operator_status.to_string());
+ assert_eq!(
+ offsets(&stored),
+ vec![PART_BYTES as u64, 0, 0],
+ "the sent chunk is recorded, so a resume does not send it again"
+ );
+ assert_eq!(stored.pending_commit, None);
+ assert_eq!(stored.lease_id, None, "{operator_status}");
+ test_db::delete_job(&run.context.db, run.id).await;
+ }
+ }
+
+ #[tokio::test]
+ async fn test_lost_lease_drops_the_job_without_sending() {
+ let run = run_job(
+ no_hook,
+ |step, id, context| async move {
+ if step == 1 {
+ test_db::resume_elsewhere(&context.db, id).await;
+ }
+ },
+ false,
+ )
+ .await;
+
+ assert!(run.result.is_err());
+ assert!(run.sends.lock().unwrap().is_empty());
+ let stored = test_db::read_job(&run.context.db, run.id).await;
+ assert_eq!(stored.status, "running");
+ assert_eq!(offsets(&stored), vec![0, 0, 0]);
+ test_db::delete_job(&run.context.db, run.id).await;
+ }
+
+ #[tokio::test]
+ async fn test_failed_send_on_an_operator_paused_row_rolls_back_and_releases_the_lease() {
+ let run = run_job(
+ during_first_send(|pool, id| async move {
+ test_db::operator_sets(&pool, id, JobStatus::Paused).await;
+ }),
+ no_op,
+ true,
+ )
+ .await;
+
+ assert!(run.result.is_err());
+ let stored = test_db::read_job(&run.context.db, run.id).await;
+ assert_eq!(stored.status, "paused");
+ assert_eq!(
+ offsets(&stored),
+ vec![0, 0, 0],
+ "a resume re-sends the chunk"
+ );
+ assert_eq!(stored.pending_commit, None);
+ assert_eq!(stored.lease_id, None);
+ test_db::delete_job(&run.context.db, run.id).await;
+ }
+ }
+
mod shutdown_guard_tests {
use tokio_util::sync::CancellationToken;
@@ -1706,6 +2117,7 @@ mod tests {
},
backoff_attempt: 0,
backoff_until: None,
+ pending_commit: None,
was_leased: false,
}
}
diff --git a/rust/batch-import-worker/src/job/model.rs b/rust/batch-import-worker/src/job/model.rs
index cfda97751818..5e16b41c8d4d 100644
--- a/rust/batch-import-worker/src/job/model.rs
+++ b/rust/batch-import-worker/src/job/model.rs
@@ -1,10 +1,10 @@
-use std::{fmt::Display, sync::Arc, time::Duration as StdDuration};
+use std::{fmt::Display, str::FromStr, sync::Arc, time::Duration as StdDuration};
use crate::metrics;
use anyhow::{Context, Error};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
-use sqlx::{postgres::PgQueryResult, PgPool, Row};
+use sqlx::{PgPool, Row};
use tracing::{info, warn};
use uuid::Uuid;
@@ -35,12 +35,14 @@ pub struct JobModel {
pub backoff_attempt: i32,
pub backoff_until: Option<DateTime<Utc>>,
+ pub pending_commit: Option<PendingCommit>,
+
// Not actually in the model, but we calculate it on fetch to let us reason about whether
// we're resuming an interrupted job
pub was_leased: bool,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum JobStatus {
Running,
@@ -49,6 +51,32 @@ pub enum JobStatus {
Completed,
}
+/// The chunk a worker is sending; a value left on the row means a worker stopped mid-commit.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PendingCommit {
+ pub key: String,
+ pub from_offset: u64,
+ pub to_offset: u64,
+}
+
+/// The result of a worker write to its job row.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct RowWrite {
+ /// False when the write required a running row and the row was no longer running.
+ pub applied: bool,
+ /// The row status after the write; anything but running means the worker must stop.
+ pub status: JobStatus,
+ /// The sink send rate stored on the row, if the sink has one.
+ pub send_rate: Option<u64>,
+}
+
+/// A worker-made status change, applied only while the row is running.
+struct StatusChange {
+ status: JobStatus,
+ status_message: Option<String>,
+ display_status_message: Option<String>,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub struct JobState {
@@ -159,6 +187,7 @@ impl JobModel {
posthog_batchimport.secrets as "secrets?",
posthog_batchimport.backoff_attempt,
posthog_batchimport.backoff_until,
+ posthog_batchimport.pending_commit,
next_job.previous_lease_id
"#,
new_lease_id
@@ -172,10 +201,13 @@ impl JobModel {
let id = row.id;
- let parsed: anyhow::Result<JobModel> =
- (row, context.encryption_keys.as_slice(), new_lease_id)
- .try_into()
- .context("Failed to parse job row");
+ let parsed: anyhow::Result<JobModel> = (
+ row,
+ context.encryption_keys.as_slice(),
+ new_lease_id.clone(),
+ )
+ .try_into()
+ .context("Failed to parse job row");
match parsed {
Ok(model) => Ok(Some(model)),
@@ -190,11 +222,12 @@ impl JobModel {
status = 'paused',
status_message = $2,
display_status_message = $3
- WHERE id = $1
+ WHERE id = $1 AND lease_id = $4 AND status = 'running'
"#,
id,
format!("{:?}", e), // We like context
- "Failed to parse source event data into Posthog event data"
+ "Failed to parse source event data into Posthog event data",
+ new_lease_id
)
.execute(&context.db)
.await?;
@@ -241,14 +274,13 @@ impl JobModel {
r#"
UPDATE posthog_batchimport
SET
- status = 'running',
status_message = $3,
display_status_message = $4,
updated_at = now(),
leased_until = now() + make_interval(secs => $2),
backoff_attempt = $5,
backoff_until = leased_until
- WHERE id = $1 AND lease_id = $6
+ WHERE id = $1 AND lease_id = $6 AND status = 'running'
RETURNING leased_until, backoff_until, updated_at
"#,
)
@@ -258,9 +290,17 @@ impl JobModel {
.bind(&display_message)
.bind(next_attempt)
.bind(current_lease)
- .fetch_one(pool)
+ .fetch_optional(pool)
.await?;
+ let Some(rec) = rec else {
+ let current_lease = current_lease.clone();
+ let status = self.explain_missed_write(pool, &current_lease).await?;
+ info!(job_id = %self.id, %status, "job is no longer running, skipping backoff");
+ self.status = status;
+ return Ok(());
+ };
+
let until: DateTime<Utc> = rec.try_get("leased_until")?;
let returned_backoff_until: DateTime<Utc> = rec.try_get("backoff_until")?;
let returned_updated_at: DateTime<Utc> = rec.try_get("updated_at")?;
@@ -285,51 +325,29 @@ impl JobModel {
Ok(())
}
- pub async fn flush(&mut self, pool: &PgPool, extend_lease: bool) -> Result<(), Error> {
- let Some(old_lease) = self.lease_id.take() else {
- anyhow::bail!("Cannot flush a job with no lease")
- };
-
- if extend_lease {
- self.lease_id = Some(Uuid::now_v7().to_string());
- }
+ /// Save worker-owned progress without touching the status. With `only_if_running`, a stopped
+ /// row refuses the write, so use it before a send.
+ pub async fn save_progress(
+ &mut self,
+ pool: &PgPool,
+ extend_lease: bool,
+ only_if_running: bool,
+ ) -> Result<RowWrite, Error> {
+ self.write(pool, None, extend_lease, only_if_running).await
+ }
- if extend_lease {
- // We only allow the lease to be set to 5 minutes from now, except in the initial claim
- // case, where we allow it to be set to 30 minutes from now, because job init can be slow
- self.leased_until = Some(Utc::now() + chrono::Duration::minutes(5));
- } else {
- self.leased_until = None;
+ /// Save progress after a sink commit, clearing backoff and stale messages while the row runs.
+ pub async fn save_committed(&mut self, pool: &PgPool) -> Result<RowWrite, Error> {
+ self.backoff_attempt = 0;
+ self.backoff_until = None;
+ let change = StatusChange {
+ status: JobStatus::Running,
+ status_message: None,
+ display_status_message: None,
};
-
- let res = sqlx::query!(
- r#"
- UPDATE posthog_batchimport
- SET
- status = $2,
- status_message = $3,
- display_status_message = $4,
- state = $5,
- updated_at = now(),
- lease_id = $6,
- leased_until = $7
- WHERE id = $1 AND lease_id = $8
- "#,
- self.id,
- self.status.to_string(),
- self.status_message,
- self.display_status_message,
- serde_json::to_value(&self.state)?,
- self.lease_id,
- self.leased_until,
- old_lease
- )
- .execute(pool)
- .await?;
-
- throw_if_no_rows(res)?;
-
- Ok(())
+ let written = self.write(pool, Some(change), true, false).await?;
+ metrics::unpause_event();
+ Ok(written)
}
pub async fn pause(
@@ -338,37 +356,62 @@ impl JobModel {
reason: String,
display_reason: Option<String>,
) -> Result<(), Error> {
- self.status = JobStatus::Paused;
- self.status_message = Some(reason);
- self.display_status_message = display_reason;
- self.flush(&context.db, true).await
+ let change = StatusChange {
+ status: JobStatus::Paused,
+ status_message: Some(reason),
+ display_status_message: display_reason,
+ };
+ self.write(&context.db, Some(change), true, false).await?;
+ Ok(())
}
- pub async fn unpause(&mut self, context: Arc<AppContext>) -> Result<(), Error> {
- self.status = JobStatus::Running;
- self.status_message = None;
- self.display_status_message = None;
- self.backoff_attempt = 0;
- self.backoff_until = None;
+ /// Pause a job left mid-commit for review, because its `pending_commit` chunk may not have
+ /// reached the sink, and release the lease so a resume is not blocked. Returns true when paused.
+ pub async fn pause_if_interrupted_commit(
+ &mut self,
+ context: Arc<AppContext>,
+ ) -> Result<bool, Error> {
+ let Some(pending) = self.pending_commit.clone() else {
+ return Ok(false);
+ };
+ warn!(
+ job_id = %self.id,
+ key = %pending.key,
+ from_offset = pending.from_offset,
+ to_offset = pending.to_offset,
+ "job was interrupted mid-commit, pausing for review"
+ );
+ metrics::interrupted_commit_paused();
+ self.pause(
+ context.clone(),
+ format!(
+ "A worker stopped while committing part {} (offsets {} to {}). The chunk may not have reached the sink.",
+ pending.key, pending.from_offset, pending.to_offset
+ ),
+ Some("Job paused after an interrupted commit. Resume it to continue.".to_string()),
+ )
+ .await?;
+ self.release_lease(&context.db).await?;
+ Ok(true)
+ }
- self.flush(&context.db, true).await?;
- let rec = sqlx::query(
+ /// Give up the lease so the row shows that no worker holds it.
+ pub async fn release_lease(&mut self, pool: &PgPool) -> Result<(), Error> {
+ let Some(lease) = self.lease_id.take() else {
+ return Ok(());
+ };
+ self.leased_until = None;
+ sqlx::query!(
r#"
UPDATE posthog_batchimport
- SET backoff_attempt = 0, backoff_until = NULL
- WHERE id = $1
- RETURNING updated_at
+ SET lease_id = NULL, leased_until = NULL
+ WHERE id = $1 AND lease_id = $2
"#,
+ self.id,
+ lease
)
- .bind(self.id)
- .fetch_one(&context.db)
+ .execute(pool)
.await?;
-
- self.updated_at = rec.try_get("updated_at")?;
-
- info!(job_id = %self.id, "unpaused job and reset backoff state");
- metrics::unpause_event();
-
Ok(())
}
@@ -378,10 +421,11 @@ impl JobModel {
r#"
UPDATE posthog_batchimport
SET backoff_attempt = 0, backoff_until = NULL
- WHERE id = $1
+ WHERE id = $1 AND lease_id = $2
"#,
)
.bind(self.id)
+ .bind(&self.lease_id)
.execute(pool)
.await?;
@@ -396,16 +440,156 @@ impl JobModel {
reason: String,
display_reason: String,
) -> Result<(), Error> {
- self.status = JobStatus::Failed;
- self.status_message = Some(reason);
- self.display_status_message = Some(display_reason);
- self.flush(pool, false).await
+ let change = StatusChange {
+ status: JobStatus::Failed,
+ status_message: Some(reason),
+ display_status_message: Some(display_reason),
+ };
+ self.write(pool, Some(change), false, false).await?;
+ Ok(())
}
- pub async fn complete(&mut self, pool: &PgPool) -> Result<(), Error> {
- self.status = JobStatus::Completed;
- self.display_status_message = None;
- self.flush(pool, false).await
+ /// Mark the job completed, unless an operator changed its status. Returns the row status.
+ pub async fn complete(&mut self, pool: &PgPool) -> Result<JobStatus, Error> {
+ let change = StatusChange {
+ status: JobStatus::Completed,
+ status_message: self.status_message.clone(),
+ display_status_message: None,
+ };
+ Ok(self.write(pool, Some(change), false, false).await?.status)
+ }
+
+ /// Every worker write to the job row goes through here: it needs this worker's lease, and
+ /// `change` applies only while the row is running. A lost lease is an error.
+ async fn write(
+ &mut self,
+ pool: &PgPool,
+ change: Option<StatusChange>,
+ extend_lease: bool,
+ only_if_running: bool,
+ ) -> Result<RowWrite, Error> {
+ let Some(old_lease) = self.lease_id.clone() else {
+ anyhow::bail!("Cannot write a job with no lease")
+ };
+
+ // A claim leases for 30 minutes because job init is slow; later writes extend it by 5.
+ let (new_lease, new_leased_until) = if extend_lease {
+ (
+ Some(Uuid::now_v7().to_string()),
+ Some(Utc::now() + chrono::Duration::minutes(5)),
+ )
+ } else {
+ (None, None)
+ };
+ let (new_status, new_message, new_display_message) = match &change {
+ Some(change) => (
+ Some(change.status.to_string()),
+ change.status_message.clone(),
+ change.display_status_message.clone(),
+ ),
+ None => (None, None, None),
+ };
+
+ let row = sqlx::query!(
+ r#"
+ UPDATE posthog_batchimport
+ SET
+ status = CASE WHEN $2::text IS NOT NULL AND status = 'running' THEN $2 ELSE status END,
+ status_message = CASE WHEN $2::text IS NOT NULL AND status = 'running' THEN $3 ELSE status_message END,
+ display_status_message = CASE WHEN $2::text IS NOT NULL AND status = 'running' THEN $4 ELSE display_status_message END,
+ state = $5,
+ pending_commit = $6,
+ backoff_attempt = $7,
+ backoff_until = $8,
+ updated_at = now(),
+ lease_id = $9,
+ leased_until = $10
+ WHERE id = $1 AND lease_id = $11 AND (NOT $12 OR status = 'running')
+ RETURNING status, import_config->'sink'->>'send_rate' AS send_rate
+ "#,
+ self.id,
+ new_status,
+ new_message,
+ new_display_message,
+ serde_json::to_value(&self.state)?,
+ self.pending_commit
+ .as_ref()
+ .map(serde_json::to_value)
+ .transpose()?,
+ self.backoff_attempt,
+ self.backoff_until,
+ new_lease,
+ new_leased_until,
+ old_lease,
+ only_if_running
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ let Some(row) = row else {
+ let status = self.explain_missed_write(pool, &old_lease).await?;
+ self.status = status;
+ return Ok(RowWrite {
+ applied: false,
+ status,
+ send_rate: None,
+ });
+ };
+
+ let status = JobStatus::from_str(&row.status)?;
+ self.lease_id = new_lease;
+ self.leased_until = new_leased_until;
+ if let Some(change) = change {
+ if status == change.status {
+ self.status_message = change.status_message;
+ self.display_status_message = change.display_status_message;
+ }
+ }
+ self.status = status;
+
+ Ok(RowWrite {
+ applied: true,
+ status,
+ send_rate: row
+ .send_rate
+ .and_then(|rate| rate.parse::<u64>().ok())
+ .filter(|rate| *rate > 0),
+ })
+ }
+
+ /// Explain a write that matched no row: a lost lease is an error, otherwise return the status
+ /// an operator or a customer set.
+ async fn explain_missed_write(&self, pool: &PgPool, lease: &str) -> Result<JobStatus, Error> {
+ let row = sqlx::query!(
+ r#"SELECT status, lease_id FROM posthog_batchimport WHERE id = $1"#,
+ self.id
+ )
+ .fetch_optional(pool)
+ .await?;
+ let Some(row) = row else {
+ anyhow::bail!("Job {} no longer exists", self.id)
+ };
+ if row.lease_id.as_deref() != Some(lease) {
+ anyhow::bail!(
+ "Lost the lease on job {}: another worker or a resume took it",
+ self.id
+ )
+ }
+ JobStatus::from_str(&row.status)
+ }
+}
+
+impl FromStr for JobStatus {
+ type Err = Error;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ "running" => Ok(JobStatus::Running),
+ "paused" => Ok(JobStatus::Paused),
+ "failed" => Ok(JobStatus::Failed),
+ "completed" => Ok(JobStatus::Completed),
+ other => anyhow::bail!("Unknown job status {other:?}"),
+ }
}
}
@@ -432,6 +616,7 @@ struct JobRow {
secrets: Option<String>,
backoff_attempt: Option<i32>,
backoff_until: Option<DateTime<Utc>>,
+ pending_commit: Option<serde_json::Value>,
previous_lease_id: Option<String>,
}
@@ -450,6 +635,11 @@ impl TryFrom<(JobRow, &[String], String)> for JobModel {
};
let import_config = serde_json::from_value(row.import_config).context("Parsing config")?;
+ let pending_commit = row
+ .pending_commit
+ .map(serde_json::from_value)
+ .transpose()
+ .context("Parsing pending commit")?;
// Jobs authenticating via IAM role have no secrets — the column is NULL.
let secrets = match row.secrets.as_deref() {
@@ -474,25 +664,17 @@ impl TryFrom<(JobRow, &[String], String)> for JobModel {
secrets,
backoff_attempt: row.backoff_attempt.unwrap_or(0),
backoff_until: row.backoff_until,
+ pending_commit,
was_leased: row.previous_lease_id.is_some(),
})
}
}
-// Returns an InvalidLock error if the query run did not affect any rows.
-pub fn throw_if_no_rows(res: PgQueryResult) -> Result<(), Error> {
- if res.rows_affected() == 0 {
- anyhow::bail!("No update done")
- } else {
- Ok(())
- }
-}
-
#[cfg(test)]
mod tests {
+ use super::super::test_db;
use super::*;
use chrono::Utc;
- use envconfig::Envconfig;
use sqlx::Row;
async fn get_pool() -> Option<PgPool> {
@@ -532,6 +714,7 @@ mod tests {
},
backoff_attempt: 0,
backoff_until: None,
+ pending_commit: None,
was_leased: false,
}
}
@@ -567,6 +750,7 @@ mod tests {
secrets,
backoff_attempt: None,
backoff_until: None,
+ pending_commit: None,
previous_lease_id: None,
}
}
@@ -744,54 +928,208 @@ mod tests {
Ok(())
}
- #[tokio::test]
- async fn test_unpause_resets_backoff_db() -> Result<(), anyhow::Error> {
- let Some(pool) = get_pool().await else {
- return Ok(());
- };
- let cfg = crate::config::Config::init_from_env().unwrap();
- let context = Arc::new(crate::context::AppContext::new(&cfg).await?);
+ fn fixture(
+ status: JobStatus,
+ pending_commit: Option<serde_json::Value>,
+ ) -> test_db::JobRowFixture {
+ test_db::JobRowFixture {
+ status,
+ lease_id: "lease-from-claim",
+ state: make_job_state(&[("part-1", 0)]),
+ sink: serde_json::json!({"type": "noop"}),
+ pending_commit,
+ }
+ }
- let mut tx = pool.begin().await?;
+ #[derive(Debug, Clone, Copy)]
+ enum WorkerAction {
+ Pause,
+ Fail,
+ Complete,
+ Backoff,
+ Committed,
+ }
- let id = Uuid::now_v7();
- let team_id = 1;
- let lease = "test-lease";
- let inserted = sqlx::query(
- r#"
- INSERT INTO posthog_batchimport (id, team_id, status, import_config, secrets, lease_id, backoff_attempt, backoff_until)
- VALUES ($1, $2, 'running', '{}'::jsonb, '', $3, 5, now())
- "#,
- )
- .bind(id)
- .bind(team_id)
- .bind(lease)
- .execute(&mut *tx)
- .await;
- if inserted.is_err() {
- return Ok(());
+ impl WorkerAction {
+ async fn run(self, model: &mut JobModel, context: Arc<AppContext>) {
+ match self {
+ WorkerAction::Pause => model
+ .pause(context, "worker pause".to_string(), None)
+ .await
+ .unwrap(),
+ WorkerAction::Fail => model
+ .fail(&context.db, "worker fail".to_string(), "failed".to_string())
+ .await
+ .unwrap(),
+ WorkerAction::Complete => {
+ model.complete(&context.db).await.unwrap();
+ }
+ WorkerAction::Backoff => model
+ .schedule_backoff(
+ &context.db,
+ StdDuration::from_secs(60),
+ "rate limited".to_string(),
+ Some("retrying".to_string()),
+ 1,
+ )
+ .await
+ .unwrap(),
+ WorkerAction::Committed => {
+ model.save_committed(&context.db).await.unwrap();
+ }
+ }
}
- let mut model = make_dummy_job_model(id, lease, team_id);
- model.backoff_attempt = 5;
- model.backoff_until = Some(Utc::now());
+ fn status_on_running_row(self) -> &'static str {
+ match self {
+ WorkerAction::Pause => "paused",
+ WorkerAction::Fail => "failed",
+ WorkerAction::Complete => "completed",
+ WorkerAction::Backoff | WorkerAction::Committed => "running",
+ }
+ }
+ }
- model.unpause(context.clone()).await?;
+ #[tokio::test]
+ async fn test_worker_status_changes_never_override_operator_status() {
+ let context = test_db::context().await;
+ let actions = [
+ WorkerAction::Pause,
+ WorkerAction::Fail,
+ WorkerAction::Complete,
+ WorkerAction::Backoff,
+ WorkerAction::Committed,
+ ];
+ let row_statuses = [
+ JobStatus::Running,
+ JobStatus::Paused,
+ JobStatus::Completed,
+ JobStatus::Failed,
+ ];
+ for action in actions {
+ for row_status in row_statuses {
+ let row = fixture(JobStatus::Running, None);
+ let id = test_db::insert_job(&context.db, &row).await;
+ let mut model = test_db::claimed_model(id, &row);
+ test_db::operator_sets(&context.db, id, row_status).await;
+ model.state = Some(make_job_state(&[("part-1", 42)]));
+
+ action.run(&mut model, context.clone()).await;
+
+ let stored = test_db::read_job(&context.db, id).await;
+ let expected = match row_status {
+ JobStatus::Running => action.status_on_running_row().to_string(),
+ operator_status => operator_status.to_string(),
+ };
+ assert_eq!(stored.status, expected, "{action:?} on a {row_status} row");
+ if row_status != JobStatus::Running {
+ assert_eq!(
+ stored.status_message.as_deref(),
+ Some(test_db::OPERATOR_MESSAGE),
+ "{action:?} must keep the operator's message on a {row_status} row"
+ );
+ }
+ if matches!(action, WorkerAction::Backoff) {
+ assert_eq!(
+ stored.backoff_until.is_some(),
+ row_status == JobStatus::Running,
+ "a backoff on a {row_status} row"
+ );
+ } else {
+ assert_eq!(
+ stored.state.parts[0].current_offset, 42,
+ "{action:?} on a {row_status} row must still save progress"
+ );
+ }
+ test_db::delete_job(&context.db, id).await;
+ }
+ }
+ }
- let rec = sqlx::query(
- r#"SELECT backoff_attempt, backoff_until FROM posthog_batchimport WHERE id = $1"#,
- )
- .bind(id)
- .fetch_one(&mut *tx)
- .await?;
+ #[tokio::test]
+ async fn test_claim_with_pending_commit_pauses_for_review() {
+ let context = test_db::context().await;
+ for pending in [
+ None,
+ Some(serde_json::json!({"key": "part-1", "from_offset": 100, "to_offset": 250})),
+ ] {
+ let row = fixture(JobStatus::Running, pending.clone());
+ let id = test_db::insert_job(&context.db, &row).await;
+ let mut model = test_db::claimed_model(id, &row);
+
+ let paused = model
+ .pause_if_interrupted_commit(context.clone())
+ .await
+ .unwrap();
+
+ let stored = test_db::read_job(&context.db, id).await;
+ assert_eq!(paused, pending.is_some());
+ if pending.is_some() {
+ assert_eq!(stored.status, "paused");
+ let message = stored.status_message.unwrap();
+ assert!(message.contains("part-1"), "{message}");
+ assert!(message.contains("100 to 250"), "{message}");
+ assert!(stored.display_status_message.is_some());
+ assert_eq!(stored.pending_commit, pending);
+ assert_eq!(
+ stored.lease_id, None,
+ "a resume must not wait for this lease"
+ );
+ } else {
+ assert_eq!(stored.status, "running");
+ }
+ test_db::delete_job(&context.db, id).await;
+ }
+ }
- let backoff_attempt: Option<i32> = rec.try_get("backoff_attempt")?;
- let backoff_until: Option<DateTime<Utc>> = rec.try_get("backoff_until")?;
- assert_eq!(backoff_attempt.unwrap_or_default(), 0);
- assert!(backoff_until.is_none());
+ #[tokio::test]
+ async fn test_send_rate_from_the_row_is_a_positive_integer_or_nothing() {
+ let context = test_db::context().await;
+ let cases: [(&str, serde_json::Value, Option<u64>); 5] = [
+ ("integer", serde_json::json!(250), Some(250)),
+ ("zero", serde_json::json!(0), None),
+ ("decimal", serde_json::json!(1000.5), None),
+ ("beyond bigint", serde_json::json!(1e20), None),
+ ("string", serde_json::json!("fast"), None),
+ ];
+ for (name, send_rate, expected) in cases {
+ let row = test_db::JobRowFixture {
+ sink: serde_json::json!({"type": "noop", "send_rate": send_rate}),
+ ..fixture(JobStatus::Running, None)
+ };
+ let id = test_db::insert_job(&context.db, &row).await;
+ let mut model = test_db::claimed_model(id, &row);
+
+ let written = model
+ .save_progress(&context.db, true, false)
+ .await
+ .unwrap_or_else(|e| {
+ panic!("case '{name}': a bad send rate must not fail the write: {e:#}")
+ });
+
+ assert!(written.applied, "case '{name}'");
+ assert_eq!(written.send_rate, expected, "case '{name}'");
+ test_db::delete_job(&context.db, id).await;
+ }
+ }
- tx.rollback().await?;
- Ok(())
+ #[test]
+ fn test_claimed_row_carries_pending_commit() {
+ let keys = vec!["0".repeat(32)];
+ let mut row = make_job_row(None);
+ row.pending_commit =
+ Some(serde_json::json!({"key": "k", "from_offset": 1, "to_offset": 2}));
+
+ let model = JobModel::try_from((row, keys.as_slice(), "l".to_string())).unwrap();
+
+ assert_eq!(
+ model.pending_commit,
+ Some(PendingCommit {
+ key: "k".to_string(),
+ from_offset: 1,
+ to_offset: 2
+ })
+ );
}
#[tokio::test]
diff --git a/rust/batch-import-worker/src/job/test_db.rs b/rust/batch-import-worker/src/job/test_db.rs
new file mode 100644
index 000000000000..da3ae543583b
--- /dev/null
+++ b/rust/batch-import-worker/src/job/test_db.rs
@@ -0,0 +1,183 @@
+//! Real-Postgres fixtures for tests of how the worker shares the job row with operators. They fail
+//! instead of skipping without a database, because CI builds `test_posthog` before the Rust tests.
+
+use std::sync::Arc;
+
+use chrono::{DateTime, Duration, Utc};
+use envconfig::Envconfig;
+use serde_json::Value;
+use sqlx::{PgPool, Row};
+use uuid::Uuid;
+
+use crate::{config::Config, context::AppContext};
+
+use super::model::{JobModel, JobState, JobStatus};
+
+const DEFAULT_TEST_DATABASE_URL: &str = "postgres://posthog:posthog@localhost:5432/test_posthog";
+
+pub async fn context() -> Arc<AppContext> {
+ let mut config = Config::init_from_env().expect("worker config from env");
+ config.database_url =
+ std::env::var("DATABASE_URL").unwrap_or_else(|_| DEFAULT_TEST_DATABASE_URL.to_string());
+ let context = AppContext::new(&config).await.unwrap_or_else(|e| {
+ panic!(
+ "these tests need the Django test database at {}: {e:?}",
+ config.database_url
+ )
+ });
+ Arc::new(context)
+}
+
+/// A job row as a worker sees it right after its claim.
+pub struct JobRowFixture {
+ pub status: JobStatus,
+ pub lease_id: &'static str,
+ pub state: JobState,
+ pub sink: Value,
+ pub pending_commit: Option<Value>,
+}
+
+pub async fn insert_job(pool: &PgPool, row: &JobRowFixture) -> Uuid {
+ let id = Uuid::now_v7();
+ let mut conn = pool.acquire().await.expect("connection");
+ // Replica mode skips the foreign key check for this session, because the test database has no
+ // team for the row and worker writes never change team_id.
+ sqlx::query("SET session_replication_role = replica")
+ .execute(&mut *conn)
+ .await
+ .expect("replica role needs a superuser, like the dev and CI postgres user");
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_batchimport
+ (id, team_id, created_at, updated_at, status, import_config, secrets, state,
+ lease_id, leased_until, backoff_attempt, pending_commit)
+ VALUES ($1, 1, now(), now(), $2, $3, '', $4, $5, now() + interval '30 minutes', 0, $6)
+ "#,
+ )
+ .bind(id)
+ .bind(row.status.to_string())
+ .bind(serde_json::json!({
+ "source": {"type": "folder", "path": "/tmp"},
+ "data_format": {"type": "json_lines", "skip_blanks": true, "content": {"type": "captured"}},
+ "sink": row.sink,
+ }))
+ .bind(serde_json::to_value(&row.state).unwrap())
+ .bind(row.lease_id)
+ .bind(&row.pending_commit)
+ .execute(&mut *conn)
+ .await
+ .expect("insert job row");
+ sqlx::query("SET session_replication_role = DEFAULT")
+ .execute(&mut *conn)
+ .await
+ .expect("reset replica role");
+ id
+}
+
+/// What the tests assert about a job row.
+#[derive(Debug)]
+pub struct StoredJob {
+ pub status: String,
+ pub status_message: Option<String>,
+ pub display_status_message: Option<String>,
+ pub lease_id: Option<String>,
+ pub state: JobState,
+ pub pending_commit: Option<Value>,
+ pub backoff_until: Option<DateTime<Utc>>,
+}
+
+pub async fn read_job(pool: &PgPool, id: Uuid) -> StoredJob {
+ let row = sqlx::query(
+ r#"
+ SELECT status, status_message, display_status_message, lease_id, state, pending_commit,
+ backoff_until
+ FROM posthog_batchimport WHERE id = $1
+ "#,
+ )
+ .bind(id)
+ .fetch_one(pool)
+ .await
+ .expect("read job row");
+ StoredJob {
+ status: row.get("status"),
+ status_message: row.get("status_message"),
+ display_status_message: row.get("display_status_message"),
+ lease_id: row.get("lease_id"),
+ state: serde_json::from_value(row.get("state")).expect("state json"),
+ pending_commit: row.get("pending_commit"),
+ backoff_until: row.get("backoff_until"),
+ }
+}
+
+pub const OPERATOR_MESSAGE: &str = "set by an operator";
+
+/// Change the row the way an operator does in Django admin or a customer does through the API.
+pub async fn operator_sets(pool: &PgPool, id: Uuid, status: JobStatus) {
+ sqlx::query("UPDATE posthog_batchimport SET status = $2, status_message = $3 WHERE id = $1")
+ .bind(id)
+ .bind(status.to_string())
+ .bind(OPERATOR_MESSAGE)
+ .execute(pool)
+ .await
+ .expect("operator status change");
+}
+
+/// Resume the job elsewhere: Django clears the lease, so this worker no longer owns the row.
+pub async fn resume_elsewhere(pool: &PgPool, id: Uuid) {
+ sqlx::query(
+ "UPDATE posthog_batchimport SET lease_id = NULL, leased_until = NULL WHERE id = $1",
+ )
+ .bind(id)
+ .execute(pool)
+ .await
+ .expect("clear lease");
+}
+
+pub async fn set_send_rate(pool: &PgPool, id: Uuid, send_rate: u64) {
+ sqlx::query(
+ "UPDATE posthog_batchimport SET import_config = jsonb_set(import_config, '{sink,send_rate}', to_jsonb($2::bigint)) WHERE id = $1",
+ )
+ .bind(id)
+ .bind(send_rate as i64)
+ .execute(pool)
+ .await
+ .expect("set send rate");
+}
+
+pub async fn delete_job(pool: &PgPool, id: Uuid) {
+ sqlx::query("DELETE FROM posthog_batchimport WHERE id = $1")
+ .bind(id)
+ .execute(pool)
+ .await
+ .expect("delete job row");
+}
+
+/// The in-memory model a worker holds for `row` after claiming it.
+pub fn claimed_model(id: Uuid, row: &JobRowFixture) -> JobModel {
+ JobModel {
+ id,
+ team_id: 1,
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ lease_id: Some(row.lease_id.to_string()),
+ leased_until: Some(Utc::now() + Duration::minutes(30)),
+ status: JobStatus::Running,
+ status_message: None,
+ display_status_message: None,
+ state: Some(row.state.clone()),
+ import_config: serde_json::from_value(serde_json::json!({
+ "source": {"type": "folder", "path": "/tmp"},
+ "data_format": {"type": "json_lines", "skip_blanks": true, "content": {"type": "captured"}},
+ "sink": row.sink,
+ }))
+ .expect("import config"),
+ secrets: super::config::JobSecrets::empty(),
+ backoff_attempt: 0,
+ backoff_until: None,
+ pending_commit: row
+ .pending_commit
+ .clone()
+ .map(|v| serde_json::from_value(v).expect("pending commit")),
+ was_leased: false,
+ }
+}
diff --git a/rust/batch-import-worker/src/main.rs b/rust/batch-import-worker/src/main.rs
index 835259e61956..17a346a57462 100644
--- a/rust/batch-import-worker/src/main.rs
+++ b/rust/batch-import-worker/src/main.rs
@@ -209,6 +209,15 @@ pub async fn main() -> Result<(), Error> {
info!("Claimed job: {:?}", model.id);
+ match model.pause_if_interrupted_commit(context.clone()).await {
+ Ok(true) => continue,
+ Ok(false) => {}
+ Err(e) => {
+ error!("Failed to pause interrupted job {}: {:?}", model.id, e);
+ continue;
+ }
+ }
+
// Trial jobs (trial_s3 sink) take their own bounded, sequential path
// instead of the import pipeline.
if matches!(model.import_config.sink, SinkConfig::TrialS3 { .. }) {
diff --git a/rust/batch-import-worker/src/metrics.rs b/rust/batch-import-worker/src/metrics.rs
index 68e896e1180b..b8e61dcb4ed4 100644
--- a/rust/batch-import-worker/src/metrics.rs
+++ b/rust/batch-import-worker/src/metrics.rs
@@ -16,6 +16,8 @@ pub const PART_CLEANUP_TOTAL: &str = "batch_import_part_cleanup_total";
pub const JOB_COMPLETION_TOTAL: &str = "batch_import_job_completion_total";
pub const COMPLETED_JOB_EVENTS: &str = "batch_import_completed_job_events";
pub const COMPLETED_JOB_PARTS: &str = "batch_import_completed_job_parts";
+pub const OPERATOR_STOP_TOTAL: &str = "batch_import_operator_stop_total";
+pub const INTERRUPTED_COMMIT_PAUSED_TOTAL: &str = "batch_import_interrupted_commit_paused_total";
use metrics::{counter, gauge, histogram};
@@ -28,6 +30,17 @@ pub fn unpause_event() {
counter!(UNPAUSE_TOTAL).increment(1);
}
+/// Count jobs a worker stopped because the row left the running status, by commit stage
+/// ("before_send" / "after_send").
+pub fn operator_stop(stage: &'static str) {
+ counter!(OPERATOR_STOP_TOTAL, "stage" => stage).increment(1);
+}
+
+/// Count jobs paused at claim because an earlier worker stopped mid-commit.
+pub fn interrupted_commit_paused() {
+ counter!(INTERRUPTED_COMMIT_PAUSED_TOTAL).increment(1);
+}
+
pub fn staging_sweep_removed(count: u64) {
counter!(STAGING_SWEEP_REMOVED).increment(count);
}
diff --git a/rust/batch-import-worker/src/trial/job.rs b/rust/batch-import-worker/src/trial/job.rs
index f923192afb69..82ac814a5e9b 100644
--- a/rust/batch-import-worker/src/trial/job.rs
+++ b/rust/batch-import-worker/src/trial/job.rs
@@ -13,7 +13,7 @@ use crate::{
cleanup_committed_part_if_done,
config::SinkConfig,
handle_fetch_error, load_or_init_state,
- model::{JobModel, JobState},
+ model::{JobModel, JobState, JobStatus},
select_and_fetch_next_chunk,
},
parse::{format::ParserFnFor, Parsed},
@@ -158,36 +158,55 @@ impl TrialJob {
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(());
+ match outcome {
+ Ok(true) => {}
+ Ok(false) => return self.stop().await,
+ Err(e) => {
+ // 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
}
+ /// Stop a trial whose row is no longer running because an operator or a customer
+ /// changed its status. Progress is already saved, so a resume continues from it.
+ async fn stop(self) -> Result<(), Error> {
+ info!(job_id = %self.job_id, "Trial job is no longer running, stopping");
+ if let Err(e) = self.source.release_job_resources().await {
+ warn!("Failed to release trial job source resources: {:?}", e);
+ }
+ self.model
+ .lock()
+ .await
+ .release_lease(&self.context.db)
+ .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.
+ /// re-fetches the chunk and overwrites the same pages. Returns false when the
+ /// job is no longer running.
async fn commit_chunk(
&self,
key: &str,
parsed: Parsed<Vec<TrialRecord>>,
reset_backoff: bool,
- ) -> Result<(), Error> {
+ ) -> Result<bool, Error> {
let mut progress = {
let state = self.state.lock().await;
state.trial.clone().unwrap_or_default()
@@ -210,17 +229,17 @@ impl TrialJob {
state.clone()
};
- {
+ let written = {
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?;
- }
+ model.save_progress(&self.context.db, true, false).await?
+ };
cleanup_committed_part_if_done(self.source.as_ref(), &self.model, key).await;
- Ok(())
+ Ok(written.status == JobStatus::Running)
}
/// Write the summary and mark the job completed. Idempotent: a resume after
@@ -238,11 +257,16 @@ impl TrialJob {
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
+ let status = model.complete(&self.context.db).await?;
+ if status == JobStatus::Completed {
+ info!(
+ job_id = %self.job_id,
+ records = progress.records_emitted,
+ "Trial job completed"
+ );
+ } else {
+ info!(job_id = %self.job_id, %status, "Trial job reached its end, but an operator status was kept");
+ }
+ Ok(())
}
}
diff --git a/rust/batch-import-worker/tests/common/harness.rs b/rust/batch-import-worker/tests/common/harness.rs
index 4f7ba6eddae2..2cbbcdf84f18 100644
--- a/rust/batch-import-worker/tests/common/harness.rs
+++ b/rust/batch-import-worker/tests/common/harness.rs
@@ -111,6 +111,7 @@ impl Harness {
secrets: JobSecrets::empty(),
backoff_attempt: 0,
backoff_until: None,
+ pending_commit: None,
was_leased: false,
};
diff --git a/rust/batch-import-worker/tests/trial_e2e_test.rs b/rust/batch-import-worker/tests/trial_e2e_test.rs
index 90c57a986d22..95bfb2e02488 100644
--- a/rust/batch-import-worker/tests/trial_e2e_test.rs
+++ b/rust/batch-import-worker/tests/trial_e2e_test.rs
@@ -183,6 +183,7 @@ impl TrialRun {
secrets: JobSecrets::empty(),
backoff_attempt: 0,
backoff_until: None,
+ pending_commit: None,
was_leased: false,
};