diff --git a/changelog.d/447.fixed.md b/changelog.d/447.fixed.md new file mode 100644 index 00000000..f26ba58b --- /dev/null +++ b/changelog.d/447.fixed.md @@ -0,0 +1,5 @@ +- The team background loops (every 2 seconds on every API replica) no longer scan all team + run and queue history: migration `0065_team_loop_indexes` adds partial indexes that hold + only running rows. The worker cancel poll (every second per running execution) is one + query instead of four for executions bound to the polling token at claim + ([#447](https://github.com/opsifyhq/orbit/issues/447)). diff --git a/crates/orbit-api/src/handlers/worker_api.rs b/crates/orbit-api/src/handlers/worker_api.rs index 2e22d88f..86d2212a 100644 --- a/crates/orbit-api/src/handlers/worker_api.rs +++ b/crates/orbit-api/src/handlers/worker_api.rs @@ -1024,6 +1024,16 @@ pub async fn cancel_requested( auth: WorkerAuth, Path(execution_id): Path, ) -> Result, ApiError> { + // Workers poll this every second per running execution, so the usual case (an + // execution bound to this token at claim) is one query. Only rows from before token + // binding take the full `ensure_execution` path. + if let Some(cancel_requested) = state + .store + .cancel_requested_for_worker_token(auth.org_id, execution_id, auth.token_id) + .await? + { + return Ok(Json(CancelResponse { cancel_requested })); + } ensure_execution(&state, &auth, execution_id).await?; Ok(Json(CancelResponse { cancel_requested: state.store.is_cancel_requested(execution_id).await?, diff --git a/crates/orbit-api/tests/api_integration.rs b/crates/orbit-api/tests/api_integration.rs index e465ec4a..0b507948 100644 --- a/crates/orbit-api/tests/api_integration.rs +++ b/crates/orbit-api/tests/api_integration.rs @@ -6499,7 +6499,15 @@ async fn worker_cannot_act_on_execution_claimed_by_another_worker() { assert_eq!(untouched.status, "dispatched"); assert!(untouched.output.is_none()); - // The claiming worker still drives its execution end to end. + // The claiming worker still drives its execution end to end, starting with the + // one-query cancel poll (#447). + let (status, body) = send( + &app.router, + worker_request("GET", &format!("{base}/cancel"), &token_a, None), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["cancelRequested"], json!(false)); let (status, _) = send( &app.router, worker_request( diff --git a/crates/orbit-store/migrations/0065_team_loop_indexes.sql b/crates/orbit-store/migrations/0065_team_loop_indexes.sql new file mode 100644 index 00000000..2d90f6a7 --- /dev/null +++ b/crates/orbit-store/migrations/0065_team_loop_indexes.sql @@ -0,0 +1,18 @@ +-- #447: partial indexes for the team background loops, which run every 2 seconds on +-- every API replica and used to scan all of team_runs / team_queue_items (history is +-- never pruned). Each index only holds the few rows that are currently running. + +-- list_running_team_runs: status = 'running' AND id > $1 ORDER BY id. +CREATE INDEX IF NOT EXISTS team_runs_running_idx + ON team_runs (id) + WHERE status = 'running'; + +-- list_team_runs_pending_outcome: running queue items joined to their run. +CREATE INDEX IF NOT EXISTS team_queue_items_running_run_idx + ON team_queue_items (team_run_id) + WHERE status = 'running'; + +-- release_stale_team_queue_claims: running items not yet linked to a run, by age. +CREATE INDEX IF NOT EXISTS team_queue_items_running_unlinked_idx + ON team_queue_items (updated_at) + WHERE status = 'running' AND team_run_id IS NULL; diff --git a/crates/orbit-store/src/executions.rs b/crates/orbit-store/src/executions.rs index 7c9e8018..09183ef9 100644 --- a/crates/orbit-store/src/executions.rs +++ b/crates/orbit-store/src/executions.rs @@ -431,6 +431,26 @@ impl Store { Ok(flag.unwrap_or(false)) } + /// The worker cancel poll in one query: the cancel flag of an execution in `org_id` + /// that is bound to `token_id`. `Ok(None)` when no such row exists (another org, + /// another token, or a legacy row claimed before token binding, which callers check + /// the slow way). + pub async fn cancel_requested_for_worker_token( + &self, + org_id: Uuid, + execution_id: Uuid, + token_id: Uuid, + ) -> StoreResult> { + Ok(sqlx::query_scalar( + "SELECT cancel_requested FROM executions WHERE id = $1 AND org_id = $2 AND worker_token_id = $3", + ) + .bind(execution_id) + .bind(org_id) + .bind(token_id) + .fetch_optional(&self.pool) + .await?) + } + pub async fn append_execution_event( &self, org_id: Uuid, diff --git a/crates/orbit-store/tests/store_integration.rs b/crates/orbit-store/tests/store_integration.rs index afbba8cf..661d4911 100644 --- a/crates/orbit-store/tests/store_integration.rs +++ b/crates/orbit-store/tests/store_integration.rs @@ -3615,6 +3615,84 @@ async fn launch_claim_binds_the_worker_token_atomically() { .is_none()); } +#[tokio::test] +async fn worker_cancel_poll_reads_only_the_bound_token_row() { + let Some(store) = test_store().await else { + return; + }; + let (org, user) = seed_org(&store).await; + let (other_org, _) = seed_org(&store).await; + let (agent, version) = store + .create_agent(org, Some(user), &definition("Cancel Poll Agent")) + .await + .unwrap(); + let execution = queued_execution(&store, org, user, &agent, &version).await; + let profile = launch_profile_fixture(&store, org, "CancelPoll").await; + let mut tokens = Vec::new(); + for name in ["a", "b"] { + tokens.push( + store + .create_worker_token( + org, + Some(profile.id), + name, + "pfx", + &format!("hash-cancel-{name}-{}", uuid::Uuid::now_v7()), + &["mock".into()], + ) + .await + .unwrap(), + ); + } + let (bound, other) = (&tokens[0], &tokens[1]); + // Unclaimed: no token is bound yet, so the fast path finds nothing. + assert_eq!( + store + .cancel_requested_for_worker_token(org, execution.id, bound.id) + .await + .unwrap(), + None + ); + store + .claim_execution_for_launch(execution.id, "worker-x", bound.id) + .await + .unwrap() + .expect("claimable"); + assert_eq!( + store + .cancel_requested_for_worker_token(org, execution.id, bound.id) + .await + .unwrap(), + Some(false) + ); + store + .request_execution_cancel(org, execution.id) + .await + .unwrap(); + assert_eq!( + store + .cancel_requested_for_worker_token(org, execution.id, bound.id) + .await + .unwrap(), + Some(true) + ); + // Another token or another org never reads the row. + assert_eq!( + store + .cancel_requested_for_worker_token(org, execution.id, other.id) + .await + .unwrap(), + None + ); + assert_eq!( + store + .cancel_requested_for_worker_token(other_org, execution.id, bound.id) + .await + .unwrap(), + None + ); +} + #[tokio::test] async fn deleting_an_access_team_is_blocked_while_it_owns_team_visible_resources() { let Some(store) = test_store().await else {