diff --git a/changelog.d/436.fixed.md b/changelog.d/436.fixed.md new file mode 100644 index 00000000..e17a9ac0 --- /dev/null +++ b/changelog.d/436.fixed.md @@ -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). diff --git a/crates/orbit-api/src/background.rs b/crates/orbit-api/src/background.rs index f54c8462..f4eed675 100644 --- a/crates/orbit-api/src/background.rs +++ b/crates/orbit-api/src/background.rs @@ -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(runtime_id: uuid::Uuid, what: &str, result: Result) { + 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| { @@ -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(()); } @@ -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, @@ -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( @@ -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!({ @@ -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())), @@ -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(()) diff --git a/crates/orbit-api/src/error.rs b/crates/orbit-api/src/error.rs index 4cf7018f..bac72875 100644 --- a/crates/orbit-api/src/error.rs +++ b/crates/orbit-api/src/error.rs @@ -31,6 +31,9 @@ pub struct ApiError { pub code: &'static str, pub message: String, pub details: Vec, + /// 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 { @@ -40,6 +43,7 @@ impl ApiError { code, message: message.into(), details: Vec::new(), + transient: false, } } @@ -57,6 +61,7 @@ impl ApiError { code: "validation_error", message, details: issues, + transient: false, } } @@ -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 { @@ -135,8 +146,12 @@ impl From 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"); @@ -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}"); + } + } +} diff --git a/crates/orbit-api/src/handlers/worker_api.rs b/crates/orbit-api/src/handlers/worker_api.rs index 2e22d88f..dfe6dcbd 100644 --- a/crates/orbit-api/src/handlers/worker_api.rs +++ b/crates/orbit-api/src/handlers/worker_api.rs @@ -22,7 +22,7 @@ use orbit_domain::{ ModelManagement, ToolPolicyRule, TriggerSpec, }; use orbit_store::{ - Approval, Connection, ConnectorRecord, ExecutionRecord, Skill, Store, WorkerProfile, + Approval, Connection, ConnectorRecord, ExecutionRecord, Skill, Store, StoreError, WorkerProfile, }; use crate::access::AccessScope; @@ -461,6 +461,25 @@ pub async fn claim( execution: Some(context), })) } + Err(error) if error.is_transient() => { + // A storage blip is not a configuration error: hand the execution back to the + // queue so a later claim runs it (#436). If even that write fails, the row + // stays `dispatched` and the dispatch timeout ends it. + state.metrics.worker_claim("error"); + match state + .store + .release_claimed_execution(execution.id, &body.worker_id) + .await + { + Ok(_) => { + tracing::warn!(execution_id = %execution.id, error = %error, "claimed execution returned to the queue after a transient error") + } + Err(release) => { + tracing::warn!(execution_id = %execution.id, error = %release, "could not return a claimed execution to the queue") + } + } + Err(error) + } Err(error) => { state.metrics.worker_claim("error"); let message = error.message.clone(); @@ -541,12 +560,22 @@ async fn build_context( .store .get_agent(org_id, agent_id) .await - .map_err(|_| ApiError::conflict(format!("subagent '{name}' no longer exists")))?; + .map_err(|error| match error { + StoreError::NotFound(_) => { + ApiError::conflict(format!("subagent '{name}' no longer exists")) + } + other => other.into(), + })?; let version = state .store .get_current_version(org_id, &agent) .await - .map_err(|_| ApiError::conflict(format!("subagent '{name}' has no current version")))?; + .map_err(|error| match error { + StoreError::NotFound(_) => { + ApiError::conflict(format!("subagent '{name}' has no current version")) + } + other => other.into(), + })?; let mut sub_spec: AgentSpec = serde_json::from_value(version.spec).map_err(|error| { ApiError::internal(format!("subagent '{name}' spec is invalid: {error}")) })?; @@ -827,8 +856,14 @@ async fn resolve_team_env( } } for mapping_id in team_ids(execution, "envMappingIds") { - let Ok(mapping) = store.get_env_mapping(org_id, mapping_id).await else { - continue; + let mapping = match store.get_env_mapping(org_id, mapping_id).await { + Ok(mapping) => mapping, + Err(StoreError::NotFound(_)) => { + return Err(ApiError::conflict(format!( + "environment mapping {mapping_id} no longer exists" + ))) + } + Err(error) => return Err(error.into()), }; // Checked when the team was saved, and again here: access removed since then // must not keep handing the mapping's secrets to runs (#322). @@ -844,39 +879,12 @@ async fn resolve_team_env( mapping.name ))); } - let Ok(items) = serde_json::from_value::>(mapping.mappings) else { - continue; - }; - for item in items { - let value = if let Some(connection_id) = item.connection_id { - match store.get_connection(org_id, connection_id).await { - Ok(connection) => match connection.credential_ref { - Some(reference) => store - .get_secret_value_for_org(org_id, &reference) - .await - .ok() - .flatten() - .map(|value| value.expose().to_string()), - None => None, - }, - Err(_) => None, - } - } else if let Some(reference) = item.secret_ref.as_ref().or(item.secret_key.as_ref()) { - store - .get_secret_value_for_org(org_id, reference) - .await - .ok() - .flatten() - .map(|value| value.expose().to_string()) - } else { - None - }; - if let Some(value) = value { - resolved.push(ResolvedEnv { - env_var: item.env_var, - value, - }); - } + for item in parse_env_mappings(&mapping.name, mapping.mappings)? { + let value = resolve_mapped_value(store, org_id, &item).await?; + resolved.push(ResolvedEnv { + env_var: item.env_var, + value, + }); } } Ok(resolved) @@ -1665,70 +1673,93 @@ pub async fn resolve_env( State(state): State, auth: WorkerAuth, ) -> Result>, ApiError> { - // Get the worker's profile to find env_mappings + // A failed lookup is an error, never a shorter list (#436): the worker retries a + // storage error and fails the run on a mapping that cannot be resolved, instead of + // starting it without the variable. let profile = match auth.profile_id { - Some(id) => state.store.get_worker_profile(auth.org_id, id).await.ok(), + Some(id) => match state.store.get_worker_profile(auth.org_id, id).await { + Ok(profile) => Some(profile), + Err(StoreError::NotFound(_)) => None, + Err(error) => return Err(error.into()), + }, None => None, }; let mut mappings: Vec = Vec::new(); if let Some(profile) = &profile { // Reusable mappings first, then inline mappings (inline wins on duplicates). - if let Ok(attached) = state + for mapping in state .store .list_worker_profile_env_mappings(profile.id) - .await + .await? { - for mapping in attached { - if let Ok(items) = serde_json::from_value::>(mapping.mappings) { - mappings.extend(items); - } - } - } - if let Ok(items) = serde_json::from_value::>(profile.env_mappings.clone()) { - mappings.extend(items); + mappings.extend(parse_env_mappings(&mapping.name, mapping.mappings)?); } + mappings.extend(parse_env_mappings( + &profile.name, + profile.env_mappings.clone(), + )?); } let mut resolved = Vec::new(); for mapping in mappings { - let value = if let Some(conn_id) = mapping.connection_id { - // Fetch connection and extract the secret value - match state.store.get_connection(auth.org_id, conn_id).await { - Ok(conn) => { - if let Some(ref secret_ref) = conn.credential_ref { - state - .store - .get_secret_value_for_org(auth.org_id, secret_ref) - .await - .ok() - .flatten() - .map(|s| s.expose().to_string()) - } else { - None - } - } - Err(_) => None, + let value = resolve_mapped_value(&state.store, auth.org_id, &mapping).await?; + resolved.push(ResolvedEnv { + env_var: mapping.env_var, + value, + }); + } + Ok(Json(resolved)) +} + +fn parse_env_mappings(owner: &str, value: serde_json::Value) -> Result, ApiError> { + if value.is_null() { + return Ok(Vec::new()); + } + serde_json::from_value(value).map_err(|error| { + ApiError::conflict(format!( + "environment mappings of '{owner}' are invalid: {error}" + )) + }) +} + +/// The value one environment mapping points at. A connection, credential or secret that +/// no longer exists is a conflict naming the variable, so the run fails with a clear +/// message; storage errors pass through so the worker retries them. +async fn resolve_mapped_value( + store: &Store, + org_id: Uuid, + mapping: &EnvMapping, +) -> Result { + let env_var = &mapping.env_var; + let reference = if let Some(connection_id) = mapping.connection_id { + let connection = match store.get_connection(org_id, connection_id).await { + Ok(connection) => connection, + Err(StoreError::NotFound(_)) => { + return Err(ApiError::conflict(format!( + "environment variable {env_var}: connection {connection_id} no longer exists" + ))) } - } else if let Some(secret_ref) = mapping.secret_ref.as_ref().or(mapping.secret_key.as_ref()) - { - state - .store - .get_secret_value_for_org(auth.org_id, secret_ref) - .await - .ok() - .flatten() - .map(|s| s.expose().to_string()) - } else { - None + Err(error) => return Err(error.into()), }; - if let Some(value) = value { - resolved.push(ResolvedEnv { - env_var: mapping.env_var, - value, - }); - } + connection.credential_ref.ok_or_else(|| { + ApiError::conflict(format!( + "environment variable {env_var}: connection '{}' has no credential", + connection.name + )) + })? + } else if let Some(reference) = mapping.secret_ref.as_ref().or(mapping.secret_key.as_ref()) { + reference.clone() + } else { + return Err(ApiError::conflict(format!( + "environment variable {env_var}: the mapping names no connection or secret" + ))); + }; + match store.get_secret_value_for_org(org_id, &reference).await? { + Some(value) => Ok(value.expose().to_string()), + None => Err(ApiError::conflict(format!( + "environment variable {env_var}: its secret no longer exists" + ))), } - Ok(Json(resolved)) } /// Workers never read triggers, and workers older than the schedule `task` field refuse diff --git a/crates/orbit-api/tests/api_integration.rs b/crates/orbit-api/tests/api_integration.rs index e465ec4a..61164245 100644 --- a/crates/orbit-api/tests/api_integration.rs +++ b/crates/orbit-api/tests/api_integration.rs @@ -11213,6 +11213,80 @@ async fn worker_facing_paths_still_receive_env_values_and_resolved_secrets() { assert_eq!(sent[0]["authSecretName"], "orbit-pi-auth"); } +#[tokio::test] +async fn worker_env_refuses_a_mapping_it_cannot_resolve() { + let Some(app) = test_app(true).await else { + return; + }; + let secret_ref = format!("test/env-gone-{}", Uuid::now_v7()); + app.store + .put_secret( + Some(app.org_id), + &secret_ref, + &orbit_security::SecretValue::new("soon-deleted-value"), + "t", + ) + .await + .unwrap(); + let (status, created) = send( + &app.router, + post( + "/api/v1/worker-profiles", + json!({ + "name": format!("env-gone-{}", Uuid::now_v7()), + "harnessKind": "mock", + "envMappings": [{ "envVar": "GONE_TOKEN", "secretKey": secret_ref }], + }), + ), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{created}"); + let id = created["id"].as_str().unwrap(); + let (status, body) = send( + &app.router, + post(&format!("/api/v1/worker-profiles/{id}/enable"), json!({})), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + let (status, token) = send( + &app.router, + post(&format!("/api/v1/worker-profiles/{id}/token"), json!({})), + ) + .await; + assert_eq!(status, StatusCode::OK, "{token}"); + let token = token["token"].as_str().unwrap().to_string(); + let (status, resolved) = send( + &app.router, + worker_request("GET", "/api/v1/worker/env", &token, None), + ) + .await; + assert_eq!(status, StatusCode::OK, "{resolved}"); + assert_eq!(resolved[0]["envVar"], "GONE_TOKEN"); + + // The secret disappears: the worker gets an error naming the variable (#436), not + // a 200 with a shorter list that would start the run without it. + sqlx::query("DELETE FROM secrets WHERE org_id = $1 AND reference = $2") + .bind(app.org_id) + .bind(&secret_ref) + .execute(&raw_pool().await) + .await + .unwrap(); + let (status, body) = send( + &app.router, + worker_request("GET", "/api/v1/worker/env", &token, None), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + assert!( + body["error"]["message"] + .as_str() + .unwrap() + .contains("GONE_TOKEN"), + "{body}" + ); + assert!(!body.to_string().contains("soon-deleted-value")); +} + #[tokio::test] async fn env_mappings_hold_references_only() { let Some(app) = test_app(true).await else { @@ -12817,13 +12891,24 @@ async fn team_env_mappings_are_checked_for_the_run_principal() { return; }; let owner = owner_user(&app).await; + // The secret must exist: an unresolvable mapping fails the run on its own (#436). + let secret_ref = format!("test/team-env-{}", Uuid::now_v7()); + app.store + .put_secret( + Some(app.org_id), + &secret_ref, + &orbit_security::SecretValue::new("team-env-value"), + "t", + ) + .await + .unwrap(); let mapping = app .store .create_env_mapping( app.org_id, &format!("private-{}", Uuid::now_v7().simple()), "", - &json!([{ "envVar": "TOKEN", "secretKey": "x" }]), + &json!([{ "envVar": "TOKEN", "secretKey": secret_ref }]), ) .await .unwrap(); diff --git a/crates/orbit-store/src/executions.rs b/crates/orbit-store/src/executions.rs index 7c9e8018..5480196c 100644 --- a/crates/orbit-store/src/executions.rs +++ b/crates/orbit-store/src/executions.rs @@ -711,6 +711,32 @@ impl Store { } Ok(query.fetch_optional(&self.pool).await?) } + + /// Undo a claim the API could not hand to the worker because of a transient error + /// (#436): the execution goes back to `queued` with no worker, so the next claim picks + /// it up. Only a still-`dispatched` row owned by `worker_id` moves; returns whether it + /// did. + pub async fn release_claimed_execution( + &self, + execution_id: Uuid, + worker_id: &str, + ) -> StoreResult { + let result = sqlx::query( + r#" + UPDATE executions + SET status = 'queued', worker_id = NULL, worker_token_id = NULL, + started_at = NULL, execution_lease_until = NULL, + last_execution_heartbeat_at = NULL, worker_boot_id = NULL, + worker_boot_started_at = NULL, updated_at = now() + WHERE id = $1 AND status = 'dispatched' AND worker_id = $2 + "#, + ) + .bind(execution_id) + .bind(worker_id) + .execute(&self.pool) + .await?; + Ok(result.rows_affected() == 1) + } } impl Store { diff --git a/crates/orbit-store/src/lib.rs b/crates/orbit-store/src/lib.rs index 77bb92ea..b0ab2b39 100644 --- a/crates/orbit-store/src/lib.rs +++ b/crates/orbit-store/src/lib.rs @@ -101,6 +101,36 @@ impl StoreError { _ => false, } } + + /// The database was unreachable or refused the statement for a reason that a retry + /// can clear: a pool timeout, a dropped connection, a serialization failure, a + /// deadlock, an exhausted server or an administrator shutdown (#436). Callers keep + /// work queued or retry instead of recording a permanent failure. + pub fn is_transient(&self) -> bool { + let Self::Database(err) = self else { + return false; + }; + match err { + sqlx::Error::PoolTimedOut + | sqlx::Error::PoolClosed + | sqlx::Error::WorkerCrashed + | sqlx::Error::BeginFailed + | sqlx::Error::Io(_) + | sqlx::Error::Tls(_) + | sqlx::Error::Protocol(_) => true, + sqlx::Error::Database(db) => db.code().is_some_and(|code| is_transient_sqlstate(&code)), + _ => false, + } + } +} + +/// SQLSTATE classes a retry can clear: 08 connection exception, 40 transaction rollback +/// (serialization failure, deadlock), 53 insufficient resources, 57P operator +/// intervention (shutdown, cannot connect now). +fn is_transient_sqlstate(code: &str) -> bool { + ["08", "40", "53", "57P"] + .iter() + .any(|prefix| code.starts_with(prefix)) } pub type StoreResult = Result; @@ -300,3 +330,42 @@ pub(crate) fn page_of( }; (items, next) } + +#[cfg(test)] +mod transient_tests { + use super::*; + + #[test] + fn connection_and_pool_failures_are_transient() { + assert!(StoreError::Database(sqlx::Error::PoolTimedOut).is_transient()); + assert!(StoreError::Database(sqlx::Error::PoolClosed).is_transient()); + assert!( + StoreError::Database(sqlx::Error::Io(std::io::Error::other("reset"))).is_transient() + ); + assert!( + StoreError::Database(sqlx::Error::Protocol("unexpected eof".into())).is_transient() + ); + } + + #[test] + fn missing_rows_and_bad_data_are_not_transient() { + assert!(!StoreError::NotFound("agent".into()).is_transient()); + assert!(!StoreError::Conflict("x".into()).is_transient()); + assert!(!StoreError::Invalid("x".into()).is_transient()); + assert!(!StoreError::Internal("cipher".into()).is_transient()); + assert!(!StoreError::Database(sqlx::Error::RowNotFound).is_transient()); + assert!(!StoreError::Database(sqlx::Error::ColumnNotFound("x".into())).is_transient()); + } + + #[test] + fn sqlstate_classes() { + for code in [ + "08006", "08001", "40001", "40P01", "53300", "57P01", "57P03", + ] { + assert!(is_transient_sqlstate(code), "{code}"); + } + for code in ["23505", "23503", "42P01", "22P02", "57014"] { + assert!(!is_transient_sqlstate(code), "{code}"); + } + } +} diff --git a/crates/orbit-store/tests/store_integration.rs b/crates/orbit-store/tests/store_integration.rs index afbba8cf..3f535ae6 100644 --- a/crates/orbit-store/tests/store_integration.rs +++ b/crates/orbit-store/tests/store_integration.rs @@ -4833,3 +4833,81 @@ async fn foreign_worker_token_cannot_renew_an_execution_lease() { .unwrap(); assert_eq!(renewed, vec![execution.id]); } + +#[tokio::test] +async fn a_released_claim_is_queued_and_claimable_again() { + let Some(store) = test_store().await else { + return; + }; + let (org, user) = seed_org(&store).await; + let (agent, version) = store + .create_agent(org, Some(user), &definition("Released Claim Agent")) + .await + .unwrap(); + let execution = store + .create_execution(NewExecution { + org_id: org, + agent_id: agent.id, + agent_version_id: version.id, + agent_name: &agent.name, + harness_kind: HarnessKind::Mock, + trigger_source: TriggerSource::Manual, + placement: "auto", + trigger_id: None, + input: serde_json::json!({ + "task": "x", "payload": {}, + "provenance": { "source": "test", "trusted": true, "receivedAt": chrono::Utc::now() } + }), + session_ref: None, + skills: &[], + timeout_seconds: 30, + requested_by: Some(user), + idempotency_key: Some("release-claim"), + team_run_id: None, + team_step_index: None, + }) + .await + .unwrap(); + let claim = |worker: &'static str| { + let store = store.clone(); + async move { + store + .claim_next_queued( + org, + worker, + &["mock".into()], + "local", + &[agent.id], + None, + None, + ) + .await + .unwrap() + } + }; + let claimed = claim("worker-a").await.expect("claimable"); + assert_eq!(claimed.id, execution.id); + assert_eq!(claimed.status, "dispatched"); + + // Only the claiming worker's dispatched row is released. + assert!(!store + .release_claimed_execution(execution.id, "worker-b") + .await + .unwrap()); + assert!(store + .release_claimed_execution(execution.id, "worker-a") + .await + .unwrap()); + let released = store.get_execution_by_id(execution.id).await.unwrap(); + assert_eq!(released.status, "queued"); + assert!(released.worker_id.is_none()); + assert!(released.started_at.is_none()); + // A second release is a no-op, and the next claim picks the execution up again. + assert!(!store + .release_claimed_execution(execution.id, "worker-a") + .await + .unwrap()); + let again = claim("worker-b").await.expect("claimable again"); + assert_eq!(again.id, execution.id); + assert_eq!(again.worker_id.as_deref(), Some("worker-b")); +} diff --git a/docs/guide/worker-profiles.md b/docs/guide/worker-profiles.md index b9ba803e..1cbc1890 100644 --- a/docs/guide/worker-profiles.md +++ b/docs/guide/worker-profiles.md @@ -65,8 +65,10 @@ plain text. Manage them under **Environments** in the Infrastructure group of th The list works like the other registries: search by name, variable or connection, a filter **All / In use / Unused / Needs attention** with counts, which worker profiles use each one, -and row checkboxes for **Change access**. **Needs attention** means a variable would be -empty because its connection was removed or has no credential. +and row checkboxes for **Change access**. **Needs attention** means a variable cannot be +resolved because its connection was removed or has no credential. A run whose worker uses +such an environment fails before the harness starts, with the variable name in the error; +it never starts without the variable. **New environment** opens Environment Studio, one section at a time: **Details** (name and optional description), **Variables** and **Access control**. For each variable choose **Add