Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/436.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
- A short database outage no longer turns into permanent failures (#436). A storage error
while a worker claims an execution puts the execution back in the queue instead of
failing it as `invalid_config`; a 24/7 runtime is only stopped when its agent is really
gone, and other lookup errors are retried on the next tick; `GET /api/v1/worker/env`
answers with an error instead of a shorter list, so a run whose environment mapping
points at a removed connection or secret fails with the variable name instead of
starting without it. See [Worker profiles](docs/guide/worker-profiles.md).
141 changes: 99 additions & 42 deletions crates/orbit-api/src/background.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1067,35 +1067,64 @@ pub async fn runtime_tick(state: &AppState) -> anyhow::Result<()> {
Ok(())
}

/// A runtime bookkeeping write whose failure must not stop the tick, but must not vanish
/// either (#436).
fn logged<T>(runtime_id: uuid::Uuid, what: &str, result: Result<T, orbit_store::StoreError>) {
if let Err(error) = result {
tracing::warn!(%runtime_id, %error, "agent runtime {what} write failed");
}
}

async fn advance_runtime(
state: &AppState,
runtime: orbit_store::agent_runtimes::AgentRuntime,
) -> Result<(), RuntimeTickError> {
let _ = state.store.heartbeat_agent_runtime(runtime.id).await;
logged(
runtime.id,
"heartbeat",
state.store.heartbeat_agent_runtime(runtime.id).await,
);
// Only a missing agent stops the runtime; any other lookup error is a storage
// failure, retried with backoff on the next tick (#436).
let agent = match state
.store
.get_agent(runtime.org_id, runtime.agent_id)
.await
{
Ok(agent) => agent,
Err(_) => {
let _ = state
.store
.halt_agent_runtime(runtime.id, "agent no longer exists")
.await;
Err(orbit_store::StoreError::NotFound(_)) => {
logged(
runtime.id,
"halt",
state
.store
.halt_agent_runtime(runtime.id, "agent no longer exists")
.await,
);
return Ok(());
}
Err(error) => return Err(error.into()),
};
if agent.status != "active" {
let _ = state
.store
.halt_agent_runtime(runtime.id, "agent is not active")
.await;
logged(
runtime.id,
"halt",
state
.store
.halt_agent_runtime(runtime.id, "agent is not active")
.await,
);
return Ok(());
}

// A last execution that cannot be read is not "finished": starting another run on a
// read error could run two at once. Only a row that is really gone counts as done.
let last = match runtime.last_execution_id {
Some(id) => state.store.get_execution(runtime.org_id, id).await.ok(),
Some(id) => match state.store.get_execution(runtime.org_id, id).await {
Ok(execution) => Some(execution),
Err(orbit_store::StoreError::NotFound(_)) => None,
Err(error) => return Err(error.into()),
},
None => None,
};
let last_terminal = last.as_ref().is_none_or(|execution| {
Expand All @@ -1106,14 +1135,22 @@ async fn advance_runtime(
});
if runtime.status == "stopping" {
if last_terminal {
let _ = state.store.finish_agent_runtime_stop(runtime.id).await;
logged(
runtime.id,
"finish stop",
state.store.finish_agent_runtime_stop(runtime.id).await,
);
} else if let Some(id) = runtime.last_execution_id {
// An execution launched by a tick that raced the Stop is not covered by the
// handler's cancel; cancel it here so Stop does not wait for a full run.
let _ = state
.store
.request_execution_cancel(runtime.org_id, id)
.await;
logged(
runtime.id,
"cancel execution",
state
.store
.request_execution_cancel(runtime.org_id, id)
.await,
);
}
return Ok(());
}
Expand Down Expand Up @@ -1222,6 +1259,10 @@ async fn advance_runtime(
.err(),
Ok(None) => None,
};
// A storage failure while checking access is not a refusal: retry it (#436).
if let Some(error) = denied.as_ref().filter(|error| error.is_transient()) {
return Err(RuntimeTickError::Transient(error.clone().into()));
}
if let Some(error) = denied {
crate::preflight::audit_denied_run(
state,
Expand All @@ -1233,10 +1274,14 @@ async fn advance_runtime(
runtime.created_by.or(agent.owner_user_id),
)
.await;
let _ = state
.store
.halt_agent_runtime(runtime.id, &format!("run refused: {}", error.message))
.await;
logged(
runtime.id,
"halt",
state
.store
.halt_agent_runtime(runtime.id, &format!("run refused: {}", error.message))
.await,
);
return Ok(());
}
let delayed = match crate::preflight::require_harness_available(
Expand All @@ -1252,15 +1297,19 @@ async fn advance_runtime(
Err(error) => Err(error),
};
if let Err(error) = delayed {
let _ = state
.store
.advance_agent_runtime(
runtime.id,
Some(&format!("run delayed: {}", error.message)),
chrono::Utc::now()
+ chrono::Duration::seconds(runtime.interval_seconds.max(30) as i64),
)
.await;
logged(
runtime.id,
"delay",
state
.store
.advance_agent_runtime(
runtime.id,
Some(&format!("run delayed: {}", error.message)),
chrono::Utc::now()
+ chrono::Duration::seconds(runtime.interval_seconds.max(30) as i64),
)
.await,
);
return Ok(());
}
let input = serde_json::json!({
Expand Down Expand Up @@ -1315,15 +1364,19 @@ async fn advance_runtime(
.await;
// Skip this tick without counting it as a failure: the runtime stays
// enabled and tries again at its normal interval.
let _ = state
.store
.advance_agent_runtime(
runtime.id,
Some("run skipped: license limit reached"),
chrono::Utc::now()
+ chrono::Duration::seconds(runtime.interval_seconds.max(30) as i64),
)
.await;
logged(
runtime.id,
"skip",
state
.store
.advance_agent_runtime(
runtime.id,
Some("run skipped: license limit reached"),
chrono::Utc::now()
+ chrono::Duration::seconds(runtime.interval_seconds.max(30) as i64),
)
.await,
);
return Ok(());
}
Err(error) => return Err(RuntimeTickError::Transient(error.into())),
Expand All @@ -1340,10 +1393,14 @@ async fn advance_runtime(
)
.await?;
if recorded.is_none() {
let _ = state
.store
.request_execution_cancel(runtime.org_id, execution.id)
.await;
logged(
runtime.id,
"cancel execution",
state
.store
.request_execution_cancel(runtime.org_id, execution.id)
.await,
);
}

Ok(())
Expand Down
48 changes: 46 additions & 2 deletions crates/orbit-api/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ pub struct ApiError {
pub code: &'static str,
pub message: String,
pub details: Vec<ValidationIssue>,
/// Caused by a storage failure a retry can clear (#436). Not serialized; lets callers
/// keep work queued instead of failing it for good.
transient: bool,
}

impl ApiError {
Expand All @@ -40,6 +43,7 @@ impl ApiError {
code,
message: message.into(),
details: Vec::new(),
transient: false,
}
}

Expand All @@ -57,6 +61,7 @@ impl ApiError {
code: "validation_error",
message,
details: issues,
transient: false,
}
}

Expand Down Expand Up @@ -91,6 +96,12 @@ impl ApiError {
pub fn status(&self) -> StatusCode {
self.status
}

/// Whether a retry may succeed: the error came from a storage failure such as a pool
/// timeout or a dropped connection, not from the request or the stored data.
pub fn is_transient(&self) -> bool {
self.transient
}
}

impl std::fmt::Display for ApiError {
Expand Down Expand Up @@ -135,8 +146,12 @@ impl From<StoreError> for ApiError {
));
}
}
tracing::error!(error = %err, "store error");
ApiError::internal("a storage error occurred")
let error = StoreError::Database(err);
tracing::error!(error = %error, "store error");
ApiError {
transient: error.is_transient(),
..ApiError::internal("a storage error occurred")
}
}
other => {
tracing::error!(error = %other, "store error");
Expand Down Expand Up @@ -288,3 +303,32 @@ pub async fn envelope_rejections(
pub async fn not_found_fallback() -> ApiError {
ApiError::not_found("no such route")
}

#[cfg(test)]
mod transient_tests {
use super::*;

#[test]
fn storage_outages_are_transient_and_keep_the_generic_message() {
let error = ApiError::from(StoreError::Database(sqlx::Error::PoolTimedOut));
assert!(error.is_transient());
assert_eq!(error.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(error.code, "internal");
assert_eq!(error.message, "a storage error occurred");
assert!(error.clone().is_transient());
}

#[test]
fn missing_rows_and_request_errors_are_not_transient() {
for error in [
ApiError::from(StoreError::NotFound("agent".into())),
ApiError::from(StoreError::Conflict("x".into())),
ApiError::from(StoreError::Internal("cipher".into())),
ApiError::from(StoreError::Database(sqlx::Error::RowNotFound)),
ApiError::internal("stored agent spec is invalid"),
ApiError::conflict("harness 'mock' is disabled"),
] {
assert!(!error.is_transient(), "{error}");
}
}
}
Loading