diff --git a/changelog.d/396.fixed.md b/changelog.d/396.fixed.md new file mode 100644 index 00000000..0ae8fd5d --- /dev/null +++ b/changelog.d/396.fixed.md @@ -0,0 +1,8 @@ +- Worker launches no longer hold the installation-wide licence lock across the launcher + call, and take no lock when the licence sets no worker limit, so one slow launcher no + longer serialises every launch or makes other replicas answer `409 license limit is busy` + (#396). The in-process wait for the lock now counts toward the same 10-second deadline. + Under a limit, re-activating an agent reads its status under the lock, a duplicate + request with the same idempotency key at the exact execution limit gets the first + request's execution instead of `402`, and a first OIDC login that links a pre-provisioned + user no longer needs a free seat. See [Licensing](docs/guide/licensing.md). diff --git a/crates/orbit-api/src/auth.rs b/crates/orbit-api/src/auth.rs index 2d00a57d..46e7f9c2 100644 --- a/crates/orbit-api/src/auth.rs +++ b/crates/orbit-api/src/auth.rs @@ -194,7 +194,14 @@ async fn resolve_oidc(state: &AppState, token: Option<&str>) -> Result) -> Result, +) -> Result { + let email = email + .filter(|value| !value.trim().is_empty()) + .unwrap_or(subject) + .to_lowercase(); + Ok(state + .store + .get_user_by_email(state.default_org_id, &email) + .await? + .is_some()) +} + fn team_role_rank(role: &str) -> u8 { match role { "lead" => 3, diff --git a/crates/orbit-api/src/handlers/agents.rs b/crates/orbit-api/src/handlers/agents.rs index 97abd107..987fcf01 100644 --- a/crates/orbit-api/src/handlers/agents.rs +++ b/crates/orbit-api/src/handlers/agents.rs @@ -359,17 +359,20 @@ pub async fn activate_agent( let agent = require_agent_manage(&state, &auth, agent_id).await?; // Draft and paused agents already count as non-archived. Restoring an archived one // adds a seat to the installation-wide agent count, so it needs the same guard as - // creating a new agent. - let _agent_limit = if agent.status == AgentStatus::Archived.as_str() { - state.agent_limit_guard().await? - } else { - None - }; + // creating a new agent. The status is read under the lock: an agent archived + // concurrently after `require_agent_manage` must still be counted (#396). + let agent_limit = state.license_limit_lock("agents").await?; + if agent_limit.is_some() { + let current = state.store.get_agent(auth.org_id, agent.id).await?; + if current.status == AgentStatus::Archived.as_str() { + state.enforce_agent_limit().await?; + } + } state .store .set_agent_status(auth.org_id, agent_id, AgentStatus::Active) .await?; - drop(_agent_limit); + drop(agent_limit); audit::record( &state, &auth, diff --git a/crates/orbit-api/src/handlers/worker_launches.rs b/crates/orbit-api/src/handlers/worker_launches.rs index 247e8b9c..6be08207 100644 --- a/crates/orbit-api/src/handlers/worker_launches.rs +++ b/crates/orbit-api/src/handlers/worker_launches.rs @@ -455,8 +455,9 @@ pub(crate) async fn launch_profile_internal( } } // Count running workers installation-wide. Held through the launch insert so two - // concurrent launches (manual, team run or dispatcher) cannot exceed the seat count. - let _worker_limit = state.worker_limit_guard().await?; + // concurrent launches (manual, team run or dispatcher) cannot exceed the worker limit, + // and released before the launcher call: the pending row already counts (#396). + let worker_limit = state.worker_limit_guard().await?; let issued = crate::handlers::worker_profiles::issue_profile_token(state, auth.org_id, &profile, false) .await?; @@ -499,6 +500,7 @@ pub(crate) async fn launch_profile_internal( return Err(error.into()); } }; + drop(worker_limit); let worker_id = launch_worker_id(launch.id); let mut timeout_seconds = None; if let Some(execution_id) = single_execution_id { diff --git a/crates/orbit-api/src/state.rs b/crates/orbit-api/src/state.rs index ac93f927..93e97ada 100644 --- a/crates/orbit-api/src/state.rs +++ b/crates/orbit-api/src/state.rs @@ -96,12 +96,24 @@ impl AppState { self.license.status() } - /// Guard + installation-wide seat count. Keep the returned guard alive until the user - /// row is written so concurrent provisions cannot race past the seat limit. - pub async fn seat_limit_guard(&self) -> Result, crate::error::ApiError> { - let guard = self.store.license_limit_guard("seats").await?; - self.enforce_limit("seats", self.store.count_active_users_installation().await?)?; - Ok(guard) + /// Take the installation-wide lock for one license limit, or `None` without touching + /// the database when the license sets no such limit. Callers that decide under the + /// lock whether a slot is needed (re-reading state first) count with the matching + /// `enforce_*` helper; the `*_limit_guard` methods do both. + pub async fn license_limit_lock( + &self, + limit: &str, + ) -> Result>, crate::error::ApiError> { + if self.license_status().limit(limit).is_none() { + return Ok(None); + } + Ok(Some(self.store.license_limit_guard(limit).await?)) + } + + /// Count active users installation-wide and refuse when the seat limit is reached. + /// Call while holding `license_limit_lock("seats")`. + pub async fn enforce_seat_limit(&self) -> Result<(), crate::error::ApiError> { + self.enforce_limit("seats", self.store.count_active_users_installation().await?) } /// Guard + installation-wide agent count. Hold until the agent row is written. Returns @@ -109,12 +121,17 @@ impl AppState { pub async fn agent_limit_guard( &self, ) -> Result>, crate::error::ApiError> { - if self.license_status().limit("agents").is_none() { - return Ok(None); + let guard = self.license_limit_lock("agents").await?; + if guard.is_some() { + self.enforce_agent_limit().await?; } - let guard = self.store.license_limit_guard("agents").await?; - self.enforce_limit("agents", self.store.count_agents_installation().await?)?; - Ok(Some(guard)) + Ok(guard) + } + + /// Count agents installation-wide and refuse when the agent limit is reached. Call + /// while holding `license_limit_lock("agents")`. + pub async fn enforce_agent_limit(&self) -> Result<(), crate::error::ApiError> { + self.enforce_limit("agents", self.store.count_agents_installation().await?) } /// Guard + installation-wide rolling 24h execution count. Hold until the execution @@ -126,47 +143,70 @@ impl AppState { return Ok(ExecutionLimit::Unrestricted); } let guard = self.store.license_limit_guard("executions_per_day").await?; + self.enforce_execution_limit().await?; + Ok(ExecutionLimit::Enforced(guard)) + } + + async fn enforce_execution_limit(&self) -> Result<(), crate::error::ApiError> { let since = Utc::now() - chrono::Duration::hours(24); let count = self .store .count_all_executions_since_installation(since) .await?; - self.enforce_limit("executions_per_day", count)?; - Ok(ExecutionLimit::Enforced(guard)) + self.enforce_limit("executions_per_day", count) } /// The single insertion point for licensed executions. Every manual run, rerun, team /// step, scheduled trigger and runtime tick goes through here so none can skip the /// `executions_per_day` guard. An idempotent replay returns the existing execution - /// without consuming a slot or taking the lock. + /// without consuming a slot. The key is looked up again under the lock, so a concurrent + /// duplicate at the exact limit gets the execution the first request created instead + /// of a license error. pub async fn create_execution_with_limit( &self, new: NewExecution<'_>, ) -> Result { - if let Some(key) = new.idempotency_key { - if let Some(existing) = self - .store - .get_execution_by_idempotency_key(new.org_id, key) - .await? - { + if let Some(existing) = self.execution_for_key(&new).await? { + return Ok(existing); + } + let _limit = self.license_limit_lock("executions_per_day").await?; + if _limit.is_some() { + if let Some(existing) = self.execution_for_key(&new).await? { return Ok(existing); } + self.enforce_execution_limit().await?; } - let _limit = self.execution_limit_guard().await?; Ok(self.store.create_execution(new).await?) } - /// Guard + installation-wide running-worker count. Hold until the launch is inserted. + async fn execution_for_key( + &self, + new: &NewExecution<'_>, + ) -> Result, crate::error::ApiError> { + let Some(key) = new.idempotency_key else { + return Ok(None); + }; + Ok(self + .store + .get_execution_by_idempotency_key(new.org_id, key) + .await?) + } + + /// Guard + installation-wide running-worker count. Hold until the launch row is + /// inserted (a pending launch already counts) and drop it before calling the launcher. + /// Returns `None` without touching the database when the license has no worker limit. pub async fn worker_limit_guard( &self, - ) -> Result, crate::error::ApiError> { - let guard = self.store.license_limit_guard("workers").await?; - self.enforce_limit( - "workers", - self.store - .count_active_worker_launches_installation() - .await?, - )?; + ) -> Result>, crate::error::ApiError> { + let guard = self.license_limit_lock("workers").await?; + if guard.is_some() { + self.enforce_limit( + "workers", + self.store + .count_active_worker_launches_installation() + .await?, + )?; + } Ok(guard) } diff --git a/crates/orbit-api/tests/api_integration.rs b/crates/orbit-api/tests/api_integration.rs index e465ec4a..bd81e27c 100644 --- a/crates/orbit-api/tests/api_integration.rs +++ b/crates/orbit-api/tests/api_integration.rs @@ -1895,6 +1895,11 @@ async fn same_agent_queues_on_different_harnesses() { /// (or interleave with a tick) run one at a time. static RUNTIME_TICK_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +/// License tests derive a limit from an installation-wide count; tests that lower that +/// count (archiving agents, ending worker launches) must not run in between. +static AGENT_COUNT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +static WORKER_LAUNCH_COUNT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + /// Approval policy is a platform-wide setting; tests that change it must not overlap. static APPROVAL_SETTINGS_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); @@ -6360,6 +6365,7 @@ async fn worker_event_and_memory_kinds_are_validated() { /// POST (a GET must not change state), and a live launch cannot be deleted. #[tokio::test] async fn bootstrap_keeps_existing_worker_tokens_and_live_launches_are_kept() { + let _serial = WORKER_LAUNCH_COUNT_LOCK.lock().await; let Some(app) = test_app(true).await else { return; }; @@ -6935,6 +6941,7 @@ async fn startup_reconciliation_reaps_expired_leases_but_not_live_ones() { #[tokio::test] async fn worker_launches_follow_profile_visibility() { + let _serial = WORKER_LAUNCH_COUNT_LOCK.lock().await; let Some(app) = test_app(true).await else { return; }; @@ -9628,6 +9635,7 @@ fn bulk_failed_ids(body: &Value) -> Vec { #[tokio::test] async fn bulk_agents_archive_delete_manage_access_and_partial_failures() { + let _serial = AGENT_COUNT_LOCK.lock().await; let Some(app) = test_app(true).await else { return; }; @@ -10387,6 +10395,7 @@ async fn worker_memory_honours_the_agents_retention_days() { #[tokio::test] async fn archiving_a_live_worker_launch_is_a_conflict() { + let _serial = WORKER_LAUNCH_COUNT_LOCK.lock().await; let Some(app) = test_app(true).await else { return; }; @@ -11116,6 +11125,7 @@ async fn worker_profile_env_update_validates_keep_and_value_types() { #[tokio::test] async fn worker_facing_paths_still_receive_env_values_and_resolved_secrets() { + let _serial = WORKER_LAUNCH_COUNT_LOCK.lock().await; let Some(app) = test_app(true).await else { return; }; @@ -11716,6 +11726,7 @@ async fn licensed_test_app() -> Option { #[tokio::test] async fn settings_write_holder_cannot_touch_other_teams_worker_objects() { + let _serial = WORKER_LAUNCH_COUNT_LOCK.lock().await; let Some(app) = test_app(true).await else { return; }; @@ -14035,6 +14046,7 @@ async fn execution_limit_skips_runtime_tick_without_stopping_it() { #[tokio::test] async fn opencode_import_respects_agent_limit() { + let _serial = AGENT_COUNT_LOCK.lock().await; let Some(mut app) = test_app(true).await else { return; }; @@ -14071,6 +14083,7 @@ async fn opencode_import_respects_agent_limit() { #[tokio::test] async fn reactivating_archived_agent_respects_agent_limit() { + let _serial = AGENT_COUNT_LOCK.lock().await; let Some(mut app) = test_app(true).await else { return; }; @@ -14107,6 +14120,7 @@ async fn reactivating_archived_agent_respects_agent_limit() { #[tokio::test] async fn concurrent_agent_creates_cannot_race_past_the_limit() { + let _serial = AGENT_COUNT_LOCK.lock().await; let Some(url) = orbit_store::test_database_url() else { return; }; @@ -14152,6 +14166,274 @@ async fn concurrent_agent_creates_cannot_race_past_the_limit() { ); } +/// A launcher stub that reports each request on `seen` and answers after `delay`. +async fn slow_launcher( + delay: std::time::Duration, +) -> (String, tokio::sync::mpsc::UnboundedReceiver<()>) { + let (seen, received) = tokio::sync::mpsc::unbounded_channel(); + let mock = axum::Router::new().route( + "/launches", + axum::routing::post(move || { + let seen = seen.clone(); + async move { + let _ = seen.send(()); + tokio::time::sleep(delay).await; + axum::Json(json!({ "status": "running", "runtimeId": "pod-1", "workerId": "w-1" })) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, mock).await.unwrap() }); + (format!("http://{addr}"), received) +} + +/// Create and enable a worker profile through the API; returns its id. +async fn enabled_worker_profile(router: &axum::Router, prefix: &str) -> String { + let (status, created) = send( + router, + post( + "/api/v1/worker-profiles", + json!({ + "name": format!("{prefix}-{}", Uuid::now_v7()), + "harnessKind": "mock", + "target": "kubernetes", + "authSecretName": "orbit-pi-auth", + }), + ), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{created}"); + let id = created["id"].as_str().unwrap().to_string(); + let (status, body) = send( + router, + post(&format!("/api/v1/worker-profiles/{id}/enable"), json!({})), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + id +} + +#[tokio::test] +async fn worker_limit_guard_is_inactive_without_a_limit() { + let Some(app) = test_app(true).await else { + return; + }; + // An unlimited license takes no advisory lock and counts nothing for launches (#396). + assert!(app.state.worker_limit_guard().await.unwrap().is_none()); + assert!(app + .state + .license_limit_lock("workers") + .await + .unwrap() + .is_none()); +} + +#[tokio::test] +async fn worker_launch_releases_the_license_lock_before_calling_the_launcher() { + let _serial = WORKER_LAUNCH_COUNT_LOCK.lock().await; + let Some(mut app) = test_app(true).await else { + return; + }; + let current = app + .store + .count_active_worker_launches_installation() + .await + .unwrap(); + app.state.license = + LicenseHandle::from_status(licensed(&[], json!({ "workers": current + 1000 }))); + let (url, mut received) = slow_launcher(std::time::Duration::from_secs(5)).await; + app.state.launcher_url = Some(url); + app.state.launcher_token = Some("launcher-token".into()); + let router = build_router(app.state.clone()); + let profile = enabled_worker_profile(&router, "slow-launch").await; + + let first = { + let router = router.clone(); + tokio::spawn(async move { + send( + &router, + post( + &format!("/api/v1/worker-profiles/{profile}/launch"), + json!({}), + ), + ) + .await + }) + }; + // The first launch is now inside the launcher call... + tokio::time::timeout(std::time::Duration::from_secs(10), received.recv()) + .await + .expect("the launcher must be called") + .unwrap(); + // ...and a second launch's limit check does not wait for it. + let guard = tokio::time::timeout( + std::time::Duration::from_secs(2), + app.state.worker_limit_guard(), + ) + .await + .expect("the worker limit lock must not be held across the launcher call") + .unwrap(); + assert!(guard.is_some()); + drop(guard); + + let (status, body) = first.await.unwrap(); + assert_eq!(status, StatusCode::CREATED, "{body}"); +} + +#[tokio::test] +async fn concurrent_worker_launches_cannot_race_past_the_limit() { + let _serial = WORKER_LAUNCH_COUNT_LOCK.lock().await; + let Some(mut app) = test_app(true).await else { + return; + }; + let (url, _received) = slow_launcher(std::time::Duration::from_millis(200)).await; + app.state.launcher_url = Some(url); + app.state.launcher_token = Some("launcher-token".into()); + let unlimited = build_router(app.state.clone()); + let first = enabled_worker_profile(&unlimited, "race-a").await; + let second = enabled_worker_profile(&unlimited, "race-b").await; + + // One slot is available installation-wide. + let current = app + .store + .count_active_worker_launches_installation() + .await + .unwrap(); + app.state.license = + LicenseHandle::from_status(licensed(&[], json!({ "workers": current + 1 }))); + let router = build_router(app.state.clone()); + + let mut tasks = Vec::new(); + for profile in [first, second] { + let router = router.clone(); + tasks.push(tokio::spawn(async move { + send( + &router, + post( + &format!("/api/v1/worker-profiles/{profile}/launch"), + json!({}), + ), + ) + .await + })); + } + let mut created = 0; + let mut limited = 0; + for task in tasks { + let (status, body) = task.await.unwrap(); + if status == StatusCode::CREATED { + created += 1; + } else { + assert_eq!(status, StatusCode::PAYMENT_REQUIRED, "{body}"); + assert_eq!(body["error"]["code"], "license_limit"); + limited += 1; + } + } + // Other tests share this database and may add launches concurrently, so the second + // launch is always refused but the first may be too. + assert!( + created <= 1, + "at most one launch may pass the lock: {created}" + ); + assert!(limited >= 1, "the other launch must be refused: {limited}"); +} + +#[tokio::test] +async fn concurrent_idempotent_execution_at_the_limit_returns_the_first_execution() { + let Some(mut app) = test_app(true).await else { + return; + }; + let path = format!("/api/v1/agents/{}/executions", app.agent_id); + let key = format!("limit-race-{}", Uuid::now_v7()); + let request = |key: &str| { + Request::builder() + .method("POST") + .uri(&path) + .header("content-type", "application/json") + .header("idempotency-key", key) + .body(Body::from( + json!({ "task": "idempotent at the limit" }).to_string(), + )) + .unwrap() + }; + // The "first" request inserts through an unlimited router; the duplicate runs at a + // zero limit, so only the lookup under the lock can save it from a 402 (#396). + let unlimited = build_router(app.state.clone()); + app.state.license = LicenseHandle::from_status(licensed(&[], json!({ "executionsPerDay": 0 }))); + let limited = build_router(app.state.clone()); + + let held = app + .state + .license_limit_lock("executions_per_day") + .await + .unwrap() + .expect("a configured limit takes the lock"); + let duplicate = { + let router = limited.clone(); + let request = request(&key); + tokio::spawn(async move { send(&router, request).await }) + }; + // Let the duplicate miss the fast-path lookup and queue on the lock. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let (status, first) = send(&unlimited, request(&key)).await; + assert_eq!(status, StatusCode::ACCEPTED, "{first}"); + drop(held); + + let (status, body) = duplicate.await.unwrap(); + assert_eq!(status, StatusCode::ACCEPTED, "{body}"); + assert_eq!(body["id"], first["id"]); +} + +#[tokio::test] +async fn activating_an_agent_archived_concurrently_respects_agent_limit() { + let _serial = AGENT_COUNT_LOCK.lock().await; + let Some(mut app) = test_app(true).await else { + return; + }; + // At a zero limit, restoring any archived agent is refused. + app.state.license = LicenseHandle::from_status(licensed(&[], json!({ "agents": 0 }))); + let router = build_router(app.state.clone()); + let agent_id = app.agent_id; + + let held = app + .state + .license_limit_lock("agents") + .await + .unwrap() + .expect("a configured limit takes the lock"); + // The request reads the agent while it is still active... + let activate = { + let router = router.clone(); + tokio::spawn(async move { + send( + &router, + post(&format!("/api/v1/agents/{agent_id}/activate"), json!({})), + ) + .await + }) + }; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + // ...and it is archived before the request gets the lock. + app.store + .set_agent_status(app.org_id, agent_id, orbit_domain::AgentStatus::Archived) + .await + .unwrap(); + drop(held); + + let (status, body) = activate.await.unwrap(); + assert_eq!(status, StatusCode::PAYMENT_REQUIRED, "{body}"); + assert_eq!(body["error"]["code"], "license_limit"); + assert_eq!( + app.store + .get_agent(app.org_id, agent_id) + .await + .unwrap() + .status, + "archived" + ); +} + #[tokio::test] async fn reserved_license_flags_are_not_advertised() { let flags = [ diff --git a/crates/orbit-store/src/lib.rs b/crates/orbit-store/src/lib.rs index 77bb92ea..4a385d66 100644 --- a/crates/orbit-store/src/lib.rs +++ b/crates/orbit-store/src/lib.rs @@ -236,8 +236,12 @@ impl Store { .or_insert_with(|| Arc::new(Mutex::new(()))) .clone() }; - let _local = lock.lock_owned().await; + // The local queue counts toward the same deadline as the advisory lock, so a slow + // holder in this process cannot make callers wait without bound (#396). let deadline = Instant::now() + LICENSE_LOCK_WAIT; + let _local = tokio::time::timeout_at(deadline.into(), lock.lock_owned()) + .await + .map_err(|_| StoreError::Conflict("license limit is busy; retry".into()))?; let mut retry_delay = LICENSE_LOCK_RETRY_BASE; loop { diff --git a/docs/development/licensing.md b/docs/development/licensing.md index 9851c9b2..85d5547d 100644 --- a/docs/development/licensing.md +++ b/docs/development/licensing.md @@ -148,12 +148,14 @@ tier stay available without a licence. Numeric `limits` in a licence are enforced too. Counts are installation-wide (all organizations), and the check and insert for each counted resource share a Postgres advisory -lock so concurrent API replicas cannot race past a limit. When a limit is reached the API +lock so concurrent API replicas cannot race past a limit. The lock is only taken when the +licence sets that limit and is held for the count and the insert only (a worker launch drops +it before the launcher call). When a limit is reached the API answers `402` with code `license_limit`: | Limit | Counted as | Checked when | |---|---|---| -| `seats` | Active users in all orgs | A new user is auto-provisioned at OIDC login | +| `seats` | Active users in all orgs | A new user is auto-provisioned at OIDC login (linking a pre-provisioned user by email uses no seat) | | `agents` | Non-archived agents in all orgs | An agent is created | | `workers` | Running worker launches in all orgs | A worker is launched (manual, team or dispatcher) | | `executions_per_day` | Executions in the last 24h in all orgs | An execution or team step is started | diff --git a/docs/guide/licensing.md b/docs/guide/licensing.md index ac119a4f..d2ec7d1c 100644 --- a/docs/guide/licensing.md +++ b/docs/guide/licensing.md @@ -95,14 +95,15 @@ A license problem never prevents ORBIT from starting. | Limit | Counted as | Checked when | |---|---|---| -| `seats` | active users in all orgs | a new user is provisioned (e.g. first OIDC login) | +| `seats` | active users in all orgs | a new user is provisioned (e.g. first OIDC login); a first login that links a user an administrator already created uses no new seat | | `agents` | non-archived agents in all orgs | creating an agent (including import) or re-activating an archived agent | | `workers` | running worker launches in all orgs | launching a worker (manual, team or dispatcher) | | `executions_per_day` | executions in the last 24h in all orgs | creating any execution: manual run, rerun, team step (including dispatcher auto-run), scheduled trigger or continuous runtime tick | Checks and inserts share a database advisory lock, so concurrent API replicas cannot pass the limit together. The lock and count are only taken when the license actually defines -the limit. Warnings appear at 80% in **Settings → Platform → License** and +the limit, and only for the count and the insert: a worker launch releases the lock once +its pending launch row exists (the row already counts), before it calls the launcher. Warnings appear at 80% in **Settings → Platform → License** and `GET /api/v1/license`. At 100% the create is rejected with `402 license_limit`. Using a feature the license does not include (for example creating an access team without `teams`) is rejected with `402 license_required`.