From 5b6ceb0086190abaaf3dfe90b90d27221e474c0f Mon Sep 17 00:00:00 2001 From: ABCxFF <79597906+abcxff@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:53:24 -0500 Subject: [PATCH 1/4] fix(pegboard-outbound): use HTTP/1.1 for serverless start streams --- engine/packages/pools/src/reqwest.rs | 34 ++++++++++++++++------------ 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/engine/packages/pools/src/reqwest.rs b/engine/packages/pools/src/reqwest.rs index 24179f2bca..d52ca18650 100644 --- a/engine/packages/pools/src/reqwest.rs +++ b/engine/packages/pools/src/reqwest.rs @@ -35,7 +35,11 @@ pub async fn client() -> Result { pub async fn guarded_client(config: &rivet_config::Config) -> Result { GUARDED_CLIENT .get_or_try_init(|| async { - build_guarded_client(config, Some(std::time::Duration::from_secs(30))).await + guarded_client_builder(config) + .await? + .timeout(std::time::Duration::from_secs(30)) + .build() + .context("failed building guarded client") }) .await .cloned() @@ -43,29 +47,31 @@ pub async fn guarded_client(config: &rivet_config::Config) -> Result { /// Same as [`guarded_client`] but without a request timeout, for long-lived streaming requests /// such as the serverless SSE connection. +/// +/// Uses HTTP/1.1 so each stream holds its own connection. Over HTTP/2 every stream to a host +/// shares one connection, and once the server's `SETTINGS_MAX_CONCURRENT_STREAMS` is reached +/// (100 on Cloud Run) new requests wait in the client with no timeout until a long-lived stream +/// ends. pub async fn guarded_client_no_timeout(config: &rivet_config::Config) -> Result { GUARDED_CLIENT_NO_TIMEOUT - .get_or_try_init(|| async { build_guarded_client(config, None).await }) + .get_or_try_init(|| async { + guarded_client_builder(config) + .await? + .http1_only() + .build() + .context("failed building guarded client") + }) .await .cloned() } -async fn build_guarded_client( - config: &rivet_config::Config, - timeout: Option, -) -> Result { +async fn guarded_client_builder(config: &rivet_config::Config) -> Result { let policy = outbound_policy(config).await?; - let mut builder = Client::builder() + Ok(Client::builder() .user_agent(CLIENT_USER_AGENT) .dns_resolver(Arc::new(GuardedResolver::new(policy.clone()))) - .redirect(rivet_outbound_guard::redirect_policy(policy)); - - if let Some(timeout) = timeout { - builder = builder.timeout(timeout); - } - - builder.build().context("failed building guarded client") + .redirect(rivet_outbound_guard::redirect_policy(policy))) } /// The destination policy applied to every request to a user-configured URL. From f0f3120d5c64763dd9172a523d6aecf97cb12ca4 Mon Sep 17 00:00:00 2001 From: ABCxFF <79597906+abcxff@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:53:25 -0500 Subject: [PATCH 2/4] fix(guard): stream api-public response bodies instead of buffering them in memory --- Cargo.lock | 1 + engine/packages/guard-core/Cargo.toml | 1 + engine/packages/guard-core/src/response_body.rs | 17 +++++++++++++++++ engine/packages/guard/src/routing/api_public.rs | 14 ++------------ 4 files changed, 21 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 11298ffd38..f30ec1864c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5823,6 +5823,7 @@ version = "2.3.31" dependencies = [ "anyhow", "async-trait", + "axum 0.8.4", "bytes", "futures", "futures-util", diff --git a/engine/packages/guard-core/Cargo.toml b/engine/packages/guard-core/Cargo.toml index 1761694b91..f77dd2185e 100644 --- a/engine/packages/guard-core/Cargo.toml +++ b/engine/packages/guard-core/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true [dependencies] anyhow.workspace = true async-trait.workspace = true +axum.workspace = true bytes.workspace = true futures-util.workspace = true futures.workspace = true diff --git a/engine/packages/guard-core/src/response_body.rs b/engine/packages/guard-core/src/response_body.rs index f128cb0202..b26d9fb7c6 100644 --- a/engine/packages/guard-core/src/response_body.rs +++ b/engine/packages/guard-core/src/response_body.rs @@ -69,6 +69,8 @@ pub enum ResponseBody { Full(Full), /// Streaming response body Incoming(BodyIncoming), + /// Response body produced by an axum router + Axum(axum::body::Body), /// Channel-backed streaming response body Channel(mpsc::Receiver>), /// Bounded channel with an out-of-band terminal error slot. @@ -192,6 +194,19 @@ impl http_body::Body for ResponseBody { std::task::Poll::Pending => std::task::Poll::Pending, } } + ResponseBody::Axum(body) => { + let pin = std::pin::Pin::new(body); + match pin.poll_frame(cx) { + std::task::Poll::Ready(Some(Ok(frame))) => { + std::task::Poll::Ready(Some(Ok(frame))) + } + std::task::Poll::Ready(Some(Err(e))) => { + std::task::Poll::Ready(Some(Err(Box::new(e)))) + } + std::task::Poll::Ready(None) => std::task::Poll::Ready(None), + std::task::Poll::Pending => std::task::Poll::Pending, + } + } ResponseBody::Channel(rx) => match rx.poll_recv(cx) { std::task::Poll::Ready(Some(Ok(bytes))) => { std::task::Poll::Ready(Some(Ok(http_body::Frame::data(bytes)))) @@ -247,6 +262,7 @@ impl http_body::Body for ResponseBody { } ResponseBody::Full(body) => body.is_end_stream(), ResponseBody::Incoming(body) => body.is_end_stream(), + ResponseBody::Axum(body) => body.is_end_stream(), ResponseBody::Channel(rx) => rx.is_closed() && rx.is_empty(), ResponseBody::ChannelWithTerminal { body, terminal } => { body.is_closed() @@ -267,6 +283,7 @@ impl http_body::Body for ResponseBody { ResponseBody::AuthorizationDeadline { .. } => http_body::SizeHint::default(), ResponseBody::Full(body) => body.size_hint(), ResponseBody::Incoming(body) => body.size_hint(), + ResponseBody::Axum(body) => body.size_hint(), ResponseBody::Channel(_) => http_body::SizeHint::default(), ResponseBody::ChannelWithTerminal { .. } => http_body::SizeHint::default(), ResponseBody::WithCompletion { body, .. } => body.size_hint(), diff --git a/engine/packages/guard/src/routing/api_public.rs b/engine/packages/guard/src/routing/api_public.rs index 4cf2b0784b..fdaabc8909 100644 --- a/engine/packages/guard/src/routing/api_public.rs +++ b/engine/packages/guard/src/routing/api_public.rs @@ -4,7 +4,7 @@ use anyhow::{Context, Result}; use async_trait::async_trait; use bytes::Bytes; use gas::prelude::*; -use http_body_util::{BodyExt, Full}; +use http_body_util::Full; use hyper::{Request, Response}; use rivet_guard_core::request_context::RequestContext; use rivet_guard_core::{CustomServeTrait, ResponseBody, RoutingOutput}; @@ -34,17 +34,7 @@ impl CustomServeTrait for ApiPublicService { .await .context("failed to call api-public service")?; - // Collect the body and convert to ResponseBody - let (parts, body) = response.into_parts(); - let collected = body - .collect() - .await - .context("failed to collect response body")?; - let bytes = collected.to_bytes(); - let response_body = ResponseBody::Full(Full::new(bytes)); - let response = Response::from_parts(parts, response_body); - - Ok(response) + Ok(response.map(ResponseBody::Axum)) } } From 24d67305e44539d3204c712e67bee1868a39cad8 Mon Sep 17 00:00:00 2001 From: ABCxFF <79597906+abcxff@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:53:25 -0500 Subject: [PATCH 3/4] feat(udb): add runtime.udb_transaction_tags_enabled knob and drop dynamic ids from transaction tags --- engine/artifacts/config-schema.json | 8 +++++ engine/packages/config/src/config/runtime.rs | 8 +++++ engine/packages/config/tests/runtime.rs | 11 +++++++ engine/packages/gasoline/src/db/kv/debug.rs | 2 +- engine/packages/gasoline/src/db/kv/mod.rs | 30 +++++++++--------- .../pegboard/src/ops/actor/get_for_gateway.rs | 2 +- engine/packages/pools/src/db/udb.rs | 4 ++- engine/packages/universaldb/src/database.rs | 18 +++++++++-- .../packages/universaldb/src/transaction.rs | 31 ++++++++++++++++++- 9 files changed, 93 insertions(+), 21 deletions(-) create mode 100644 engine/packages/config/tests/runtime.rs diff --git a/engine/artifacts/config-schema.json b/engine/artifacts/config-schema.json index f478f387b7..b59e004d8d 100644 --- a/engine/artifacts/config-schema.json +++ b/engine/artifacts/config-schema.json @@ -154,6 +154,7 @@ "gasoline_prune_interval_duration": null, "guard_shutdown_duration": null, "udb_throttle_bytes_per_second": null, + "udb_transaction_tags_enabled": null, "worker_cpu_max": null, "worker_load_shedding_beta": null, "worker_load_shedding_curve": null, @@ -1848,6 +1849,13 @@ "$ref": "#/definitions/UdbThrottle" } }, + "udb_transaction_tags_enabled": { + "description": "Whether UniversalDB transactions pass throttle tags to the storage backend. Defaults to false, which makes every `Transaction::tag` call a no-op so FoundationDB's GRV proxy tag throttler never sees the tags. Requires restart.", + "type": [ + "boolean", + "null" + ] + }, "worker_cpu_max": { "description": "Adjusts worker curve around this value (in millecores, i.e. 1000 = 1 core). Is not a hard limit. When unset, uses /sys/fs/cgroup/cpu.max, and if that is unset uses total host cpu.", "type": [ diff --git a/engine/packages/config/src/config/runtime.rs b/engine/packages/config/src/config/runtime.rs index be026de915..4e51d00497 100644 --- a/engine/packages/config/src/config/runtime.rs +++ b/engine/packages/config/src/config/runtime.rs @@ -66,6 +66,10 @@ pub struct Runtime { /// read and write axes independently, for example /// `udb_throttle_bytes_per_second.depot_compaction.read`. An axis with no entry is unthrottled. udb_throttle_bytes_per_second: Option>, + /// Whether UniversalDB transactions pass throttle tags to the storage backend. Defaults to + /// false, which makes every `Transaction::tag` call a no-op so FoundationDB's GRV proxy tag + /// throttler never sees the tags. Requires restart. + udb_transaction_tags_enabled: Option, } /// Byte-rate budgets for one UniversalDB throttle. An axis left unset is unthrottled. @@ -202,6 +206,10 @@ impl Runtime { self.allow_version_rollback.unwrap_or_default() } + pub fn udb_transaction_tags_enabled(&self) -> bool { + self.udb_transaction_tags_enabled.unwrap_or(false) + } + pub fn gasoline_prune_eligibility_duration(&self) -> Option { if let Some(prune_eligibility_duration) = self.gasoline_prune_eligibility_duration { if prune_eligibility_duration == 0 { diff --git a/engine/packages/config/tests/runtime.rs b/engine/packages/config/tests/runtime.rs new file mode 100644 index 0000000000..5c2b4a8abe --- /dev/null +++ b/engine/packages/config/tests/runtime.rs @@ -0,0 +1,11 @@ +use rivet_config::config::Runtime; + +#[test] +fn udb_transaction_tags_default_to_disabled_and_can_be_enabled() { + assert!(!Runtime::default().udb_transaction_tags_enabled()); + let runtime: Runtime = serde_json::from_str("{}").unwrap(); + assert!(!runtime.udb_transaction_tags_enabled()); + let runtime: Runtime = + serde_json::from_str(r#"{"udb_transaction_tags_enabled":true}"#).unwrap(); + assert!(runtime.udb_transaction_tags_enabled()); +} diff --git a/engine/packages/gasoline/src/db/kv/debug.rs b/engine/packages/gasoline/src/db/kv/debug.rs index da0350f4a8..bf94668a99 100644 --- a/engine/packages/gasoline/src/db/kv/debug.rs +++ b/engine/packages/gasoline/src/db/kv/debug.rs @@ -1848,7 +1848,7 @@ impl DatabaseKv { let mut last_key = last_key.clone(); async move { - tx.tag(&format!("find_dead_workflows:{name}"))?; + tx.tag("find_dead_workflows")?; let mut workflows = Vec::new(); diff --git a/engine/packages/gasoline/src/db/kv/mod.rs b/engine/packages/gasoline/src/db/kv/mod.rs index 97979a697f..a37efe9c1e 100644 --- a/engine/packages/gasoline/src/db/kv/mod.rs +++ b/engine/packages/gasoline/src/db/kv/mod.rs @@ -943,7 +943,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_dispatch_workflow", |tx| async move { - tx.tag(&format!("dispatch_workflow:{workflow_name}"))?; + tx.tag("dispatch_workflow")?; self.dispatch_workflow_inner( ray_id, @@ -1088,7 +1088,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_find_workflow", |tx| async move { - tx.tag(&format!("find_workflow:{workflow_name}"))?; + tx.tag("find_workflow")?; self.find_workflow_inner(workflow_name, tags, &tx).await }) .custom_instrument(tracing::info_span!("find_workflow_tx")) @@ -2486,7 +2486,7 @@ impl Database for DatabaseKv { Ok(()) } - #[tracing::instrument(skip_all, fields(?workflow_id, %location))] + #[tracing::instrument(skip_all, fields(?workflow_id, %workflow_name, %location))] async fn pull_next_signals( &self, worker_id: Id, @@ -2516,7 +2516,7 @@ impl Database for DatabaseKv { let owned_filter = owned_filter.clone(); async move { - tx.tag(&format!("pull_next_signals:{workflow_name}"))?; + tx.tag("pull_next_signals")?; self.validate_lease(&tx, workflow_id, worker_id).await?; @@ -2887,7 +2887,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_publish_signal_from_workflow", |tx| async move { - tx.tag(&format!("publish_signal:{from_workflow_id}"))?; + tx.tag("publish_signal")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -2952,7 +2952,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_dispatch_sub_workflow", |tx| async move { - tx.tag(&format!("dispatch_workflow:{sub_workflow_name}"))?; + tx.tag("dispatch_workflow")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -3008,7 +3008,7 @@ impl Database for DatabaseKv { .map_err(WorkflowError::PoolsGeneric)? .txn("gas_update_workflow_state", |tx| { async move { - tx.tag(&format!("workflow_state_update:{workflow_id}"))?; + tx.tag("workflow_state_update")?; self.validate_lease(&tx, workflow_id, worker_id).await?; @@ -3053,7 +3053,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_commit_workflow_activity_event", |tx| async move { - tx.tag(&format!("update_workflow_history:{from_workflow_id}"))?; + tx.tag("update_workflow_history")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -3097,7 +3097,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_commit_workflow_message_send_event", |tx| async move { - tx.tag(&format!("update_workflow_history:{from_workflow_id}"))?; + tx.tag("update_workflow_history")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -3142,7 +3142,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_upsert_workflow_loop_event", |tx| async move { - tx.tag(&format!("update_workflow_history:{from_workflow_id}"))?; + tx.tag("update_workflow_history")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -3291,7 +3291,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_commit_workflow_sleep_event", |tx| async move { - tx.tag(&format!("update_workflow_history:{from_workflow_id}"))?; + tx.tag("update_workflow_history")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -3330,7 +3330,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_update_workflow_sleep_state", |tx| async move { - tx.tag(&format!("update_workflow_history:{from_workflow_id}"))?; + tx.tag("update_workflow_history")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -3367,7 +3367,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_commit_workflow_branch_event", |tx| async move { - tx.tag(&format!("update_workflow_history:{from_workflow_id}"))?; + tx.tag("update_workflow_history")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -3406,7 +3406,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_commit_workflow_removed_event", |tx| async move { - tx.tag(&format!("update_workflow_history:{from_workflow_id}"))?; + tx.tag("update_workflow_history")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; @@ -3447,7 +3447,7 @@ impl Database for DatabaseKv { .udb() .map_err(WorkflowError::PoolsGeneric)? .txn("gas_commit_workflow_version_check_event", |tx| async move { - tx.tag(&format!("update_workflow_history:{from_workflow_id}"))?; + tx.tag("update_workflow_history")?; self.validate_lease(&tx, from_workflow_id, worker_id) .await?; diff --git a/engine/packages/pegboard/src/ops/actor/get_for_gateway.rs b/engine/packages/pegboard/src/ops/actor/get_for_gateway.rs index e3a09b052a..2ad3671e80 100644 --- a/engine/packages/pegboard/src/ops/actor/get_for_gateway.rs +++ b/engine/packages/pegboard/src/ops/actor/get_for_gateway.rs @@ -78,7 +78,7 @@ pub async fn pegboard_actor_get_for_gateway( return Ok(None); }; - tx.tag(&format!("actor_get_for_gateway:{namespace_id}"))?; + tx.tag("actor_get_for_gateway")?; let envoy_protocol_version = if let Some(envoy_key) = &envoy_key { tx.read_opt( diff --git a/engine/packages/pools/src/db/udb.rs b/engine/packages/pools/src/db/udb.rs index 8eaa7c2a79..996d68ad7b 100644 --- a/engine/packages/pools/src/db/udb.rs +++ b/engine/packages/pools/src/db/udb.rs @@ -62,7 +62,9 @@ pub async fn setup(config: &Config) -> Result> { tracing::debug!("udb started"); - let db = universaldb::Database::new(db_driver).with_throttle(throttle_config(config)); + let db = universaldb::Database::new(db_driver) + .with_throttle(throttle_config(config)) + .with_transaction_tags(config.runtime.udb_transaction_tags_enabled()); Ok(Some(UdbPool { db })) } diff --git a/engine/packages/universaldb/src/database.rs b/engine/packages/universaldb/src/database.rs index b584ce3d89..9a104a7b08 100644 --- a/engine/packages/universaldb/src/database.rs +++ b/engine/packages/universaldb/src/database.rs @@ -41,6 +41,8 @@ fn simulated_latency() -> Option { pub struct Database { driver: DatabaseDriverHandle, throttle: Arc, + /// When false, [`Transaction::tag`] is a no-op on every transaction this database creates. + transaction_tags_enabled: bool, } impl Database { @@ -50,9 +52,17 @@ impl Database { Database { driver, throttle: Arc::new(ThrottleState::new(None)), + transaction_tags_enabled: true, } } + /// Controls whether transactions forward throttle tags to the driver. Disabling keeps every + /// `tag` call site in place while sending nothing to the backend. + pub fn with_transaction_tags(mut self, enabled: bool) -> Self { + self.transaction_tags_enabled = enabled; + self + } + /// Enables cluster-wide byte-rate throttling for transactions that opt in with /// [`Transaction::charge_throttle`]. Without this every axis is unthrottled and charging is inert. /// @@ -136,7 +146,10 @@ impl Database { .run(Box::new(|tx| { attempts.fetch_add(1, Ordering::AcqRel); - let tx = tx.with_name(name).with_throttle(throttle.clone()); + let tx = tx + .with_name(name) + .with_throttle(throttle.clone()) + .with_transaction_tags(self.transaction_tags_enabled); let guard = ThrottleAttemptGuard::new(tx.deref().clone()); async move { let _guard = guard; @@ -194,7 +207,8 @@ impl Database { Ok(self .driver .create_txn()? - .with_throttle(Arc::new(ThrottleTxn::new(self.throttle.clone(), false)))) + .with_throttle(Arc::new(ThrottleTxn::new(self.throttle.clone(), false))) + .with_transaction_tags(self.transaction_tags_enabled)) } pub fn txn_retry_limit(&self, limit: i32) -> Result<()> { diff --git a/engine/packages/universaldb/src/transaction.rs b/engine/packages/universaldb/src/transaction.rs index d87cc6a680..e958efdabe 100644 --- a/engine/packages/universaldb/src/transaction.rs +++ b/engine/packages/universaldb/src/transaction.rs @@ -77,6 +77,8 @@ pub struct Transaction { counters: Arc, /// Throttle bookkeeping, attached by the [`crate::Database`] this transaction came from. throttle: Option>, + /// When false, [`Transaction::tag`] is a no-op. + tags_enabled: bool, } impl Transaction { @@ -87,6 +89,7 @@ impl Transaction { name: DEFAULT_TXN_NAME, counters: Arc::new(TxnCounters::default()), throttle: None, + tags_enabled: true, } } @@ -97,6 +100,7 @@ impl Transaction { name, counters: self.counters.clone(), throttle: self.throttle.clone(), + tags_enabled: self.tags_enabled, } } @@ -107,6 +111,18 @@ impl Transaction { name: self.name, counters: self.counters.clone(), throttle: Some(throttle), + tags_enabled: self.tags_enabled, + } + } + + pub(crate) fn with_transaction_tags(&self, enabled: bool) -> Self { + Transaction { + driver: self.driver.clone(), + subspace: self.subspace.clone(), + name: self.name, + counters: self.counters.clone(), + throttle: self.throttle.clone(), + tags_enabled: enabled, } } @@ -118,6 +134,7 @@ impl Transaction { name: self.name, counters: self.counters.clone(), throttle: self.throttle.clone(), + tags_enabled: self.tags_enabled, } } @@ -596,8 +613,13 @@ impl Transaction { self.driver.approximate_size() } - /// Adds a tag intended for throttling to the current transaction. + /// Adds a tag intended for throttling to the current transaction. Does nothing when the owning + /// [`crate::Database`] has transaction tags disabled. pub fn tag(&self, tag: &str) -> Result<()> { + if !self.tags_enabled { + return Ok(()); + } + self.driver.tag(tag) } @@ -735,6 +757,13 @@ impl RetryableTransaction { } } + pub(crate) fn with_transaction_tags(&self, enabled: bool) -> Self { + RetryableTransaction { + inner: self.inner.with_transaction_tags(enabled), + maybe_committed: self.maybe_committed, + } + } + pub fn maybe_committed(&self) -> MaybeCommitted { self.maybe_committed } From c26f7e45c7a89b808a2ec0791b78f615bbef2d4b Mon Sep 17 00:00:00 2001 From: ABCxFF <79597906+abcxff@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:53:39 -0500 Subject: [PATCH 4/4] feat(api-public): add the Rivet 2 to Rivet 3 migration API --- Cargo.lock | 22 + Cargo.toml | 4 + docs/api/error-registry.json | 31 + .../errors/migration.actor_not_found.json | 5 + .../errors/migration.backfill_incomplete.json | 5 + .../errors/migration.cutover_mismatch.json | 5 + .../errors/migration.invalid_request.json | 5 + .../errors/migration.wrong_datacenter.json | 5 + engine/packages/api-public/Cargo.toml | 8 + engine/packages/api-public/src/errors.rs | 37 + engine/packages/api-public/src/lib.rs | 1 + .../api-public/src/migration/candidates.rs | 203 +++ .../api-public/src/migration/export.rs | 588 +++++++++ .../api-public/src/migration/facts.rs | 333 +++++ .../packages/api-public/src/migration/keys.rs | 102 ++ .../packages/api-public/src/migration/mod.rs | 229 ++++ .../packages/api-public/src/migration/park.rs | 428 +++++++ engine/packages/api-public/src/router.rs | 29 +- engine/packages/engine/Cargo.toml | 2 + .../packages/engine/tests/v2_migration_api.rs | 1097 +++++++++++++++++ engine/packages/universaldb/src/utils/keys.rs | 4 + .../rust/v2-migration-protocol/Cargo.toml | 17 + .../sdks/rust/v2-migration-protocol/build.rs | 21 + .../v2-migration-protocol/src/generated.rs | 1 + .../rust/v2-migration-protocol/src/lib.rs | 63 + .../v2-migration-protocol/src/versioned.rs | 45 + .../schemas/v2-migration-protocol/v1.bare | 238 ++++ 27 files changed, 3526 insertions(+), 2 deletions(-) create mode 100644 engine/artifacts/errors/migration.actor_not_found.json create mode 100644 engine/artifacts/errors/migration.backfill_incomplete.json create mode 100644 engine/artifacts/errors/migration.cutover_mismatch.json create mode 100644 engine/artifacts/errors/migration.invalid_request.json create mode 100644 engine/artifacts/errors/migration.wrong_datacenter.json create mode 100644 engine/packages/api-public/src/migration/candidates.rs create mode 100644 engine/packages/api-public/src/migration/export.rs create mode 100644 engine/packages/api-public/src/migration/facts.rs create mode 100644 engine/packages/api-public/src/migration/keys.rs create mode 100644 engine/packages/api-public/src/migration/mod.rs create mode 100644 engine/packages/api-public/src/migration/park.rs create mode 100644 engine/packages/engine/tests/v2_migration_api.rs create mode 100644 engine/sdks/rust/v2-migration-protocol/Cargo.toml create mode 100644 engine/sdks/rust/v2-migration-protocol/build.rs create mode 100644 engine/sdks/rust/v2-migration-protocol/src/generated.rs create mode 100644 engine/sdks/rust/v2-migration-protocol/src/lib.rs create mode 100644 engine/sdks/rust/v2-migration-protocol/src/versioned.rs create mode 100644 engine/sdks/schemas/v2-migration-protocol/v1.bare diff --git a/Cargo.lock b/Cargo.lock index f30ec1864c..5fa9b1fa05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5196,8 +5196,11 @@ name = "rivet-api-public" version = "2.3.31" dependencies = [ "anyhow", + "async-stream", "axum 0.8.4", "axum-test", + "base64 0.22.1", + "depot", "epoxy", "epoxy-protocol", "fs_extra", @@ -5207,6 +5210,7 @@ dependencies = [ "indexmap 2.14.0", "namespace", "pegboard", + "rand 0.8.5", "reqwest 0.12.22", "rivet-api-builder", "rivet-api-peer", @@ -5227,8 +5231,12 @@ dependencies = [ "tokio", "tower-http", "tracing", + "universaldb", "urlencoding", "utoipa", + "v2-migration-protocol", + "vbare", + "xxhash-rust", ] [[package]] @@ -5670,7 +5678,9 @@ dependencies = [ "url", "urlencoding", "uuid", + "v2-migration-protocol", "vbare", + "xxhash-rust", ] [[package]] @@ -8636,6 +8646,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "v2-migration-protocol" +version = "2.3.31" +dependencies = [ + "anyhow", + "serde", + "serde_bare", + "serde_bytes", + "vbare", + "vbare-compiler", +] + [[package]] name = "valuable" version = "0.1.1" diff --git a/Cargo.toml b/Cargo.toml index 144a4c208a..fc9d6f242c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,6 +77,7 @@ members = [ "engine/sdks/rust/test-envoy", "engine/sdks/rust/universaldb-commit", "engine/sdks/rust/ups-protocol", + "engine/sdks/rust/v2-migration-protocol", "rivetkit-rust/packages/actor-persist", "rivetkit-rust/packages/client", "rivetkit-rust/packages/client-protocol", @@ -699,6 +700,9 @@ members = [ [workspace.dependencies.epoxy-protocol] path = "engine/sdks/rust/epoxy-protocol" + [workspace.dependencies.v2-migration-protocol] + path = "engine/sdks/rust/v2-migration-protocol" + [workspace.dependencies.rivet-test-envoy] path = "engine/sdks/rust/test-envoy" diff --git a/docs/api/error-registry.json b/docs/api/error-registry.json index 632e5b5a67..0ccba21b3e 100644 --- a/docs/api/error-registry.json +++ b/docs/api/error-registry.json @@ -1167,6 +1167,37 @@ } ] }, + { + "name": "migration", + "description": null, + "errors": [ + { + "code": "actor_not_found", + "message": "The actor does not exist in this namespace.", + "statuses": [] + }, + { + "code": "backfill_incomplete", + "message": "Migration is unavailable until the actor migration fix backfill finishes.", + "statuses": [] + }, + { + "code": "cutover_mismatch", + "message": "The actor was parked by a different cutover.", + "statuses": [] + }, + { + "code": "invalid_request", + "message": "Invalid migration request.", + "statuses": [] + }, + { + "code": "wrong_datacenter", + "message": "The actor belongs to another datacenter.", + "statuses": [] + } + ] + }, { "name": "namespace", "description": "Namespace lookup and creation.", diff --git a/engine/artifacts/errors/migration.actor_not_found.json b/engine/artifacts/errors/migration.actor_not_found.json new file mode 100644 index 0000000000..c75336006e --- /dev/null +++ b/engine/artifacts/errors/migration.actor_not_found.json @@ -0,0 +1,5 @@ +{ + "code": "actor_not_found", + "group": "migration", + "message": "The actor does not exist in this namespace." +} \ No newline at end of file diff --git a/engine/artifacts/errors/migration.backfill_incomplete.json b/engine/artifacts/errors/migration.backfill_incomplete.json new file mode 100644 index 0000000000..3d15db87e8 --- /dev/null +++ b/engine/artifacts/errors/migration.backfill_incomplete.json @@ -0,0 +1,5 @@ +{ + "code": "backfill_incomplete", + "group": "migration", + "message": "Migration is unavailable until the actor migration fix backfill finishes." +} \ No newline at end of file diff --git a/engine/artifacts/errors/migration.cutover_mismatch.json b/engine/artifacts/errors/migration.cutover_mismatch.json new file mode 100644 index 0000000000..e5eb6440af --- /dev/null +++ b/engine/artifacts/errors/migration.cutover_mismatch.json @@ -0,0 +1,5 @@ +{ + "code": "cutover_mismatch", + "group": "migration", + "message": "The actor was parked by a different cutover." +} \ No newline at end of file diff --git a/engine/artifacts/errors/migration.invalid_request.json b/engine/artifacts/errors/migration.invalid_request.json new file mode 100644 index 0000000000..e7c6b5a464 --- /dev/null +++ b/engine/artifacts/errors/migration.invalid_request.json @@ -0,0 +1,5 @@ +{ + "code": "invalid_request", + "group": "migration", + "message": "Invalid migration request." +} \ No newline at end of file diff --git a/engine/artifacts/errors/migration.wrong_datacenter.json b/engine/artifacts/errors/migration.wrong_datacenter.json new file mode 100644 index 0000000000..c731719a9f --- /dev/null +++ b/engine/artifacts/errors/migration.wrong_datacenter.json @@ -0,0 +1,5 @@ +{ + "code": "wrong_datacenter", + "group": "migration", + "message": "The actor belongs to another datacenter." +} \ No newline at end of file diff --git a/engine/packages/api-public/Cargo.toml b/engine/packages/api-public/Cargo.toml index 48f473b291..b73b0bf260 100644 --- a/engine/packages/api-public/Cargo.toml +++ b/engine/packages/api-public/Cargo.toml @@ -8,7 +8,10 @@ license.workspace = true [dependencies] anyhow.workspace = true +async-stream.workspace = true axum.workspace = true +base64.workspace = true +depot.workspace = true epoxy-protocol.workspace = true epoxy.workspace = true futures-util.workspace = true @@ -17,6 +20,7 @@ include_dir.workspace = true indexmap.workspace = true namespace.workspace = true pegboard.workspace = true +rand.workspace = true reqwest.workspace = true rivet-api-builder.workspace = true rivet-api-peer.workspace = true @@ -37,8 +41,12 @@ subtle.workspace = true tokio.workspace = true tower-http.workspace = true tracing.workspace = true +universaldb.workspace = true urlencoding.workspace = true utoipa.workspace = true +v2-migration-protocol.workspace = true +vbare.workspace = true +xxhash-rust.workspace = true [build-dependencies] anyhow.workspace = true diff --git a/engine/packages/api-public/src/errors.rs b/engine/packages/api-public/src/errors.rs index 3a4bc5f7cc..8ca75dd428 100644 --- a/engine/packages/api-public/src/errors.rs +++ b/engine/packages/api-public/src/errors.rs @@ -21,3 +21,40 @@ pub enum Validation { )] RaceCondition, } + +#[derive(RivetError, Debug, Deserialize, Serialize)] +#[error("migration")] +pub enum Migration { + #[error("actor_not_found", "The actor does not exist in this namespace.")] + ActorNotFound, + #[error( + "wrong_datacenter", + "The actor belongs to another datacenter.", + "The actor belongs to datacenter {actor_datacenter_label}, but this is datacenter {datacenter_label}. Call the owning datacenter's API." + )] + WrongDatacenter { + actor_datacenter_label: u16, + datacenter_label: u16, + }, + #[error( + "invalid_request", + "Invalid migration request.", + "Invalid migration request: {message}" + )] + InvalidRequest { message: String }, + #[error( + "cutover_mismatch", + "The actor was parked by a different cutover.", + "The actor was parked by cutover {parked_cutover_ts}, not {cutover_ts}." + )] + CutoverMismatch { + parked_cutover_ts: i64, + cutover_ts: i64, + }, + #[error( + "backfill_incomplete", + "Migration is unavailable until the actor migration fix backfill finishes.", + "Migration is unavailable until the actor migration fix backfill finishes. It runs on engine start; retry once it completes." + )] + BackfillIncomplete, +} diff --git a/engine/packages/api-public/src/lib.rs b/engine/packages/api-public/src/lib.rs index 7281dfd94e..756744c9cc 100644 --- a/engine/packages/api-public/src/lib.rs +++ b/engine/packages/api-public/src/lib.rs @@ -6,6 +6,7 @@ pub mod envoys; mod errors; pub mod health; pub mod metadata; +pub mod migration; pub mod namespaces; pub mod router; pub mod runner_configs; diff --git a/engine/packages/api-public/src/migration/candidates.rs b/engine/packages/api-public/src/migration/candidates.rs new file mode 100644 index 0000000000..0351f564fb --- /dev/null +++ b/engine/packages/api-public/src/migration/candidates.rs @@ -0,0 +1,203 @@ +//! `GET /migration/v1/namespaces/{namespace}/candidates`: one page of the namespace's active +//! actors with every fact the migrator selects on. +//! +//! V2 applies no eligibility rule. It returns raw facts so policy such as the minimum sleep age +//! or the largest copy stays in the migrator's configuration. + +use anyhow::{Context, Result}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use futures_util::{StreamExt, TryStreamExt}; +use pegboard::keys; +use rivet_util::Id; +use universaldb::{options::StreamingMode, prelude::*, utils::IsolationLevel::Snapshot}; +use v2_migration_protocol as proto; + +use super::{CandidatesQuery, authorize, ensure_local, ensure_namespace, facts}; +use crate::{ctx::ApiCtx, errors}; + +const DEFAULT_LIMIT: usize = 200; +const MAX_LIMIT: usize = 500; +/// Actors whose facts are read concurrently within the page's transaction. +const READ_CONCURRENCY: usize = 32; + +pub async fn candidates(ctx: ApiCtx, namespace: String, query: CandidatesQuery) -> Result> { + let namespace_id = authorize(&ctx, &namespace).await?; + + let limit = query.limit.unwrap_or(DEFAULT_LIMIT); + if limit == 0 || limit > MAX_LIMIT { + return Err(errors::Migration::InvalidRequest { + message: format!("limit must be between 1 and {MAX_LIMIT}"), + } + .build()); + } + + let after = match &query.after { + Some(after) => Some(URL_SAFE_NO_PAD.decode(after).map_err(|_| { + errors::Migration::InvalidRequest { + message: "after is not a valid cursor".to_string(), + } + .build() + })?), + None => None, + }; + + // The scan covers every actor name and includes sleeping actors. + let active_subspace = + keys::subspace().subspace(&(NAMESPACE, namespace_id, ACTOR, BY_NAME, ACTIVE)); + let (range_start, range_end) = active_subspace.range(); + if let Some(after) = &after { + if !after.starts_with(active_subspace.bytes()) { + return Err(errors::Migration::InvalidRequest { + message: "after does not belong to this namespace".to_string(), + } + .build()); + } + } + + let hibernating_since_ts = facts::hibernating_since_ts( + ctx.config() + .pegboard() + .hibernating_request_eligible_threshold(), + ); + let udb = ctx.pools().udb()?; + let response = udb + .txn("migration_candidates", |tx| { + let after = after.clone(); + let range_start = range_start.clone(); + let range_end = range_end.clone(); + async move { + // The cursor is the last returned key, so the page starts just after it. + let begin = match after { + Some(mut after) => { + after.push(0x00); + after + } + None => range_start, + }; + + let index_rows = tx + .get_ranges_keyvalues( + universaldb::RangeOption { + limit: Some(limit), + mode: StreamingMode::WantAll, + ..(begin, range_end).into() + }, + Snapshot, + ) + .map(|entry| { + let entry = entry?; + let key = tx + .with_subspace(keys::subspace()) + .unpack::(entry.key())?; + Ok::<_, anyhow::Error>((entry.key().to_vec(), key.actor_id)) + }) + .try_collect::>() + .await?; + + let next = if index_rows.len() == limit { + index_rows.last().map(|(raw_key, _)| raw_key.clone()) + } else { + None + }; + + let candidates = futures_util::stream::iter(index_rows) + .map(|(raw_key, actor_id)| { + let tx = tx.clone(); + async move { read_candidate(&tx, actor_id, raw_key, hibernating_since_ts).await } + }) + .buffered(READ_CONCURRENCY) + .try_filter_map(|candidate| async move { Ok(candidate) }) + .try_collect::>() + .await?; + + Ok(proto::CandidatesResponse { candidates, next }) + } + }) + .await?; + + let next = response + .next + .as_ref() + .map(|next| URL_SAFE_NO_PAD.encode(next)); + tracing::debug!( + count = response.candidates.len(), + has_next = next.is_some(), + "listed migration candidates" + ); + + proto::encode(&response) +} + +/// `GET /migration/v1/actors/{actor_id}/candidate`: the facts of one actor, as a listing would +/// return them, for a migration an operator requested by id. An actor outside the namespace is +/// `migration.actor_not_found`, as a missing one is. +pub async fn candidate(ctx: ApiCtx, actor_id: Id, namespace: String) -> Result> { + ensure_local(&ctx, actor_id)?; + let namespace_id = authorize(&ctx, &namespace).await?; + + let hibernating_since_ts = facts::hibernating_since_ts( + ctx.config() + .pegboard() + .hibernating_request_eligible_threshold(), + ); + let udb = ctx.pools().udb()?; + let candidate = udb + .txn("migration_candidate", |tx| async move { + let actor = facts::read(&tx, actor_id, hibernating_since_ts, Snapshot).await?; + ensure_namespace(actor.as_ref(), namespace_id)?; + let actor = actor.context("actor checked above")?; + candidate_of(&tx, actor_id, actor, Vec::new()).await + }) + .await?; + + proto::encode(&candidate) +} + +/// The candidate behind one index row. `cursor` is the row's raw key, which a listing resumes +/// right after. +async fn read_candidate( + tx: &universaldb::Transaction, + actor_id: Id, + cursor: Vec, + hibernating_since_ts: i64, +) -> Result> { + let Some(facts) = facts::read(tx, actor_id, hibernating_since_ts, Snapshot).await? else { + return Ok(None); + }; + Ok(Some(candidate_of(tx, actor_id, facts, cursor).await?)) +} + +async fn candidate_of( + tx: &universaldb::Transaction, + actor_id: Id, + facts: facts::ActorFacts, + cursor: Vec, +) -> Result { + let (sqlite_v1, parked, sqlite_head, kv_bytes_estimate) = tokio::try_join!( + facts::sqlite_v1(tx, facts.namespace_id, actor_id, Snapshot), + facts::is_parked(tx, actor_id), + facts::read_sqlite_head(tx, facts.namespace_id, actor_id, Snapshot), + pegboard::actor_kv::estimate_kv_size(tx, actor_id), + )?; + + Ok(proto::Candidate { + actor_id: actor_id.as_bytes(), + workflow_id: facts.workflow_id.as_bytes(), + name: facts.name, + key: facts.key, + pool_name: facts.pool_name, + create_ts: facts.create_ts, + version: u8::try_from(facts.version).unwrap_or(u8::MAX), + generation: facts.generation, + sleep_ts: facts.sleep_ts, + allocated: facts.allocated, + destroy_ts: facts.destroy_ts, + wake_deadline_ts: facts.wake_deadline_ts, + hibernating: facts.hibernating, + sqlite_v1, + parked, + db_size_pages: sqlite_head.map_or(0, |head| head.db_size_pages), + kv_bytes_estimate: u64::try_from(kv_bytes_estimate).unwrap_or(0), + cursor, + }) +} diff --git a/engine/packages/api-public/src/migration/export.rs b/engine/packages/api-public/src/migration/export.rs new file mode 100644 index 0000000000..48c15cde2a --- /dev/null +++ b/engine/packages/api-public/src/migration/export.rs @@ -0,0 +1,588 @@ +//! `GET /migration/v1/actors/{actor_id}/export`: the actor's whole KV and SQLite as one stream of +//! length-prefixed BARE frames, read without waking the actor. +//! +//! The order is a header, KV in key order, SQLite pages `1..=dbSizePages`, then an end frame with +//! a digest. Each internal transaction reads at most `TX_MAX_BYTES` or for at most `TX_MAX_TIME` +//! and re-reads the fence at its own read version: the generation, the sleep timestamp, the +//! allocation keys, `DestroyTsKey` and the SQLite head. KV and SQLite only change while the actor +//! runs, and running needs an allocation that moves the generation, so an unchanged fence means +//! the chunks join into one consistent copy. Any change ends the stream with `FenceMoved`. +//! +//! An `ExportFence` frame follows every transaction. Its cursor resumes a broken stream from that +//! point, within the same fence. + +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result}; +use axum::{ + body::{Body, Bytes}, + http::header::CONTENT_TYPE, + response::{IntoResponse, Response}, +}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use depot::{ + conveyer::{Db, error::SqliteStorageError}, + types::{DepotReadMode, GetPagesOptions, SQLITE_PAGE_SIZE}, +}; +use futures_util::TryStreamExt; +use pegboard::keys; +use rivet_envoy_protocol as ep; +use rivet_util::Id; +use universaldb::{ + options::StreamingMode, + utils::{FormalKey, IsolationLevel::Snapshot}, +}; +use v2_migration_protocol as proto; + +use super::{ExportQuery, authorize, ensure_local, ensure_namespace, facts}; +use crate::{ctx::ApiCtx, errors}; + +/// Bytes one internal transaction reads before it ends, well inside UniversalDB's limits. +const TX_MAX_BYTES: usize = 8 * 1024 * 1024; +/// Time one internal transaction reads before it ends, inside UniversalDB's 5 s limit. +const TX_MAX_TIME: Duration = Duration::from_secs(1); +/// Bytes per `KvBatch` frame. +const BATCH_MAX_BYTES: usize = 1024 * 1024; +/// Pages per `PageBatch` frame (1 MiB of 4 KiB pages). +const BATCH_MAX_PAGES: u32 = 256; +/// Pages read per depot call, one fenced chunk. +const PAGES_PER_READ: u32 = (TX_MAX_BYTES / SQLITE_PAGE_SIZE as usize) as u32; + +/// The fence an export holds for its whole lifetime, including resumes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Fence { + generation: u32, + sleep_ts: i64, + head_txid: Option, +} + +enum FenceCheck { + Held, + Moved, + Destroyed, +} + +pub async fn export(ctx: ApiCtx, actor_id: Id, query: ExportQuery) -> Result { + ensure_local(&ctx, actor_id)?; + let namespace_id = authorize(&ctx, &query.namespace).await?; + + let resume = match &query.resume { + Some(resume) => { + let raw = URL_SAFE_NO_PAD + .decode(resume) + .map_err(|_| invalid("resume is not base64"))?; + Some( + proto::decode::(&raw) + .map_err(|_| invalid("resume is not a cursor"))?, + ) + } + None => None, + }; + + // Read the facts, the SQLite head and the KV size estimate at one read version. + let hibernating_since_ts = facts::hibernating_since_ts( + ctx.config() + .pegboard() + .hibernating_request_eligible_threshold(), + ); + let udb = std::sync::Arc::new((*ctx.pools().udb()?).clone()); + let (actor, head, sqlite_v1, kv_bytes_estimate) = udb + .txn("migration_export_header", |tx| async move { + let actor = facts::read(&tx, actor_id, hibernating_since_ts, Snapshot).await?; + ensure_namespace(actor.as_ref(), namespace_id)?; + let actor = actor.context("actor checked above")?; + + let (head, sqlite_v1, kv_bytes_estimate) = tokio::try_join!( + facts::read_sqlite_head(&tx, namespace_id, actor_id, Snapshot), + facts::sqlite_v1(&tx, namespace_id, actor_id, Snapshot), + pegboard::actor_kv::estimate_kv_size(&tx, actor_id), + )?; + + Ok((actor, head, sqlite_v1, kv_bytes_estimate)) + }) + .await?; + + let abort = if actor.destroy_ts.is_some() { + Some(proto::AbortReason::Destroyed) + } else if actor.version == 1 || sqlite_v1 { + Some(proto::AbortReason::Ineligible) + } else if actor.sleep_ts.is_none() || actor.allocated { + Some(proto::AbortReason::FenceMoved) + } else { + None + }; + if let Some(reason) = abort { + return Ok(stream_response(Body::from(proto::encode_frame( + &proto::Frame::ExportAbort(proto::ExportAbort { reason }), + )?))); + } + + let fence = Fence { + generation: actor.generation, + sleep_ts: actor.sleep_ts.context("checked sleeping above")?, + head_txid: head.as_ref().map(|head| head.head_txid), + }; + + let cursor = match resume { + Some(cursor) => { + let resumed = Fence { + generation: cursor.generation, + sleep_ts: cursor.sleep_ts, + head_txid: cursor.head_txid, + }; + if resumed != fence { + return Ok(stream_response(Body::from(proto::encode_frame( + &proto::Frame::ExportAbort(proto::ExportAbort { + reason: proto::AbortReason::FenceMoved, + }), + )?))); + } + cursor + } + None => proto::ExportCursor { + generation: fence.generation, + sleep_ts: fence.sleep_ts, + head_txid: fence.head_txid, + after_kv_key: None, + kv_done: false, + next_pgno: 1, + digest: vec![0; 16], + kv_entries: 0, + kv_bytes: 0, + pages: 0, + }, + }; + + let header = proto::ExportHeader { + generation: fence.generation, + sleep_ts: fence.sleep_ts, + wake_deadline_ts: actor.wake_deadline_ts, + name: actor.name.clone(), + key: actor.key.clone(), + pool_name: actor.pool_name.clone(), + create_ts: actor.create_ts, + kv_bytes_estimate: u64::try_from(kv_bytes_estimate).unwrap_or_default(), + sqlite: head.as_ref().map(|head| proto::SqliteHead { + head_txid: head.head_txid, + db_size_pages: head.db_size_pages, + page_size: SQLITE_PAGE_SIZE, + }), + }; + + let depot_db = Db::new( + udb.clone(), + namespace_id, + actor_id.to_string(), + rivet_pools::NodeId::new(), + ) + .with_config(ctx.config().clone()); + + let exporter = Exporter { + udb, + depot_db, + actor_id, + namespace_id, + fence, + hibernating_since_ts, + db_size_pages: head.map_or(0, |head| head.db_size_pages), + cursor, + }; + + let stream = async_stream::stream! { + yield proto::encode_frame(&proto::Frame::ExportHeader(header)).map(Bytes::from); + + let mut exporter = exporter; + loop { + match exporter.next_chunk().await { + Ok(Chunk::Frames(frames)) => { + for frame in frames { + yield Ok(Bytes::from(frame)); + } + } + Ok(Chunk::Last(frame)) => { + yield Ok(Bytes::from(frame)); + break; + } + Err(err) => { + tracing::warn!(?err, actor_id = %exporter.actor_id, "migration export failed mid-stream; the migrator resumes from the last fence"); + yield Err(err); + break; + } + } + } + }; + + Ok(stream_response(Body::from_stream( + stream.map_err(|err| std::io::Error::other(format!("{err:#}"))), + ))) +} + +fn stream_response(body: Body) -> Response { + ([(CONTENT_TYPE, proto::EXPORT_CONTENT_TYPE)], body).into_response() +} + +fn invalid(message: &str) -> anyhow::Error { + errors::Migration::InvalidRequest { + message: message.to_string(), + } + .build() +} + +enum Chunk { + /// Data frames followed by an `ExportFence`. + Frames(Vec>), + /// The final `ExportEnd` or `ExportAbort` frame. + Last(Vec), +} + +struct Exporter { + udb: std::sync::Arc, + depot_db: Db, + actor_id: Id, + namespace_id: Id, + fence: Fence, + /// Fixed at the request's start, so every fence check agrees on which requests are live. + hibernating_since_ts: i64, + db_size_pages: u32, + cursor: proto::ExportCursor, +} + +impl Exporter { + /// Reads one fenced chunk and returns its encoded frames. + async fn next_chunk(&mut self) -> Result { + if !self.cursor.kv_done { + return self.next_kv_chunk().await; + } + + if self.cursor.next_pgno <= self.db_size_pages { + return self.next_page_chunk().await; + } + + let end = proto::Frame::ExportEnd(proto::ExportEnd { + kv_entries: self.cursor.kv_entries, + kv_bytes: self.cursor.kv_bytes, + pages: self.cursor.pages, + digest: self.cursor.digest.clone(), + }); + Ok(Chunk::Last(proto::encode_frame(&end)?)) + } + + async fn next_kv_chunk(&mut self) -> Result { + let actor_id = self.actor_id; + let namespace_id = self.namespace_id; + let fence = self.fence; + let hibernating_since_ts = self.hibernating_since_ts; + let after_key = self.cursor.after_kv_key.clone(); + + let (check, entries, done) = self + .udb + .txn("migration_export_kv", |tx| { + let after_key = after_key.clone(); + async move { + let check = + check_fence(&tx, actor_id, namespace_id, fence, hibernating_since_ts) + .await?; + if !matches!(check, FenceCheck::Held) { + return Ok((check, Vec::new(), false)); + } + + let (entries, done) = read_kv_chunk(&tx, actor_id, after_key).await?; + Ok((FenceCheck::Held, entries, done)) + } + }) + .await?; + + if let Some(last) = abort_for(check)? { + return Ok(Chunk::Last(last)); + } + + let mut frames = Vec::new(); + let mut batch = Vec::new(); + let mut batch_bytes = 0; + for entry in entries { + let entry_bytes = entry.key.len() + entry.value.len(); + if !batch.is_empty() && batch_bytes + entry_bytes > BATCH_MAX_BYTES { + frames.push(self.data_frame(proto::Frame::KvBatch(proto::KvBatch { + entries: std::mem::take(&mut batch), + }))?); + batch_bytes = 0; + } + + self.cursor.kv_entries += 1; + self.cursor.kv_bytes += entry_bytes as u64; + self.cursor.after_kv_key = Some(entry.key.clone()); + batch_bytes += entry_bytes; + batch.push(entry); + } + if !batch.is_empty() { + frames.push(self.data_frame(proto::Frame::KvBatch(proto::KvBatch { entries: batch }))?); + } + + self.cursor.kv_done = done; + frames.push(self.fence_frame()?); + Ok(Chunk::Frames(frames)) + } + + async fn next_page_chunk(&mut self) -> Result { + let first = self.cursor.next_pgno; + let last = first + .saturating_add(PAGES_PER_READ - 1) + .min(self.db_size_pages); + let pgnos = (first..=last).collect::>(); + + // The head fence makes depot refuse the read if the database moved. + let read = self + .depot_db + .get_pages_with_options( + pgnos, + GetPagesOptions { + expected_head_txid: self.fence.head_txid, + mode: DepotReadMode::DiagnosticNoSideEffects, + ..Default::default() + }, + ) + .await; + let mut pages = match read { + Ok(result) => result.pages, + Err(err) if is_head_fence_mismatch(&err) => { + return Ok(Chunk::Last(proto::encode_frame( + &proto::Frame::ExportAbort(proto::ExportAbort { + reason: proto::AbortReason::FenceMoved, + }), + )?)); + } + Err(err) => return Err(err.context("read sqlite pages for migration export")), + }; + pages.sort_by_key(|page| page.pgno); + + // Re-check the pegboard fence after the read, so a wake that raced it ends the stream. + let actor_id = self.actor_id; + let namespace_id = self.namespace_id; + let fence = self.fence; + let hibernating_since_ts = self.hibernating_since_ts; + let check = self + .udb + .txn("migration_export_pages_fence", |tx| async move { + check_fence(&tx, actor_id, namespace_id, fence, hibernating_since_ts).await + }) + .await?; + if let Some(last) = abort_for(check)? { + return Ok(Chunk::Last(last)); + } + + let mut by_pgno = pages + .into_iter() + .map(|page| (page.pgno, page.bytes)) + .collect::>(); + + let mut frames = Vec::new(); + let mut batch_first = first; + while batch_first <= last { + let batch_last = batch_first.saturating_add(BATCH_MAX_PAGES - 1).min(last); + let batch_pages = (batch_first..=batch_last) + .map(|pgno| { + by_pgno + .remove(&pgno) + .flatten() + .unwrap_or_else(|| vec![0; SQLITE_PAGE_SIZE as usize]) + }) + .collect::>(); + + self.cursor.pages += batch_last - batch_first + 1; + frames.push(self.data_frame(proto::Frame::PageBatch(proto::PageBatch { + first_pgno: batch_first, + pages: batch_pages, + }))?); + batch_first = batch_last + 1; + } + + self.cursor.next_pgno = last + 1; + frames.push(self.fence_frame()?); + Ok(Chunk::Frames(frames)) + } + + /// Encodes a data frame and chains it into the digest. + fn data_frame(&mut self, frame: proto::Frame) -> Result> { + let encoded = proto::encode_frame(&frame)?; + self.cursor.digest = chain_digest(&self.cursor.digest, &encoded[4..]); + Ok(encoded) + } + + fn fence_frame(&self) -> Result> { + proto::encode_frame(&proto::Frame::ExportFence(proto::ExportFence { + cursor: proto::encode(&self.cursor)?, + })) + } +} + +/// Chains one frame body into the running digest: `xxh3_128(previous || frame)`. +pub fn chain_digest(previous: &[u8], frame_body: &[u8]) -> Vec { + let mut hasher = xxhash_rust::xxh3::Xxh3::new(); + hasher.update(previous); + hasher.update(frame_body); + hasher.digest128().to_be_bytes().to_vec() +} + +fn abort_for(check: FenceCheck) -> Result>> { + let reason = match check { + FenceCheck::Held => return Ok(None), + FenceCheck::Moved => proto::AbortReason::FenceMoved, + FenceCheck::Destroyed => proto::AbortReason::Destroyed, + }; + + Ok(Some(proto::encode_frame(&proto::Frame::ExportAbort( + proto::ExportAbort { reason }, + ))?)) +} + +fn is_head_fence_mismatch(err: &anyhow::Error) -> bool { + err.chain().any(|source| { + matches!( + source.downcast_ref::(), + Some(SqliteStorageError::HeadFenceMismatch { .. }) + ) + }) +} + +async fn check_fence( + tx: &universaldb::Transaction, + actor_id: Id, + namespace_id: Id, + fence: Fence, + hibernating_since_ts: i64, +) -> Result { + let (actor, head) = tokio::try_join!( + facts::read(tx, actor_id, hibernating_since_ts, Snapshot), + facts::read_sqlite_head(tx, namespace_id, actor_id, Snapshot), + )?; + + let Some(actor) = actor else { + return Ok(FenceCheck::Destroyed); + }; + if actor.destroy_ts.is_some() { + return Ok(FenceCheck::Destroyed); + } + + let held = actor.generation == fence.generation + && actor.sleep_ts == Some(fence.sleep_ts) + && !actor.allocated + && head.map(|head| head.head_txid) == fence.head_txid; + + Ok(if held { + FenceCheck::Held + } else { + FenceCheck::Moved + }) +} + +/// Reads whole KV entries after `after_key`, in key order, until the chunk budget is spent. +/// +/// Returns the entries and whether the end of the actor's KV was reached. An entry is never split +/// across chunks. +async fn read_kv_chunk( + tx: &universaldb::Transaction, + actor_id: Id, + after_key: Option>, +) -> Result<(Vec, bool)> { + let subspace = keys::actor_kv::subspace(actor_id); + let (range_start, range_end) = subspace.range(); + + // Every sub-key of an entry starts with its packed key wrapper, so the byte after it is past + // all of them. + let begin = match after_key { + Some(after_key) => { + let mut begin = subspace.pack(&keys::actor_kv::KeyWrapper(after_key)); + begin.push(0xFF); + begin + } + None => range_start, + }; + + let kv_tx = tx.with_subspace(subspace); + let mut stream = kv_tx.get_ranges_keyvalues( + universaldb::RangeOption { + mode: StreamingMode::Iterator, + ..(begin, range_end).into() + }, + Snapshot, + ); + + let started_at = Instant::now(); + let mut entries = Vec::new(); + let mut read_bytes = 0; + let mut current: Option = None; + + loop { + let Some(row) = stream.try_next().await? else { + if let Some(builder) = current.take() { + entries.push(builder.build()?); + } + return Ok((entries, true)); + }; + + let key = kv_tx.unpack::(row.key())?.key; + + // A new entry starts. Stop at this boundary once the chunk's budget is spent. + if current.as_ref().is_none_or(|builder| builder.key != key.0) { + if let Some(builder) = current.take() { + entries.push(builder.build()?); + + if read_bytes >= TX_MAX_BYTES || started_at.elapsed() >= TX_MAX_TIME { + return Ok((entries, false)); + } + } + current = Some(EntryBuilder::new(key.0.clone())); + } + + read_bytes += row.key().len() + row.value().len(); + let builder = current.as_mut().context("entry builder set above")?; + + if let Ok(chunk_key) = kv_tx.unpack::(row.key()) { + builder.append_chunk(chunk_key.chunk, row.value()); + } else if let Ok(metadata_key) = kv_tx.unpack::(row.key()) + { + builder.metadata = Some(metadata_key.deserialize(row.value())?); + } else { + anyhow::bail!("unexpected actor kv sub key"); + } + } +} + +/// Reassembles one KV entry from its value chunks and metadata row, as `actor_kv::get` does. +struct EntryBuilder { + key: Vec, + value: Vec, + next_chunk: usize, + metadata: Option, +} + +impl EntryBuilder { + fn new(key: Vec) -> Self { + EntryBuilder { + key, + value: Vec::new(), + next_chunk: 0, + metadata: None, + } + } + + fn append_chunk(&mut self, chunk: usize, bytes: &[u8]) { + if chunk >= self.next_chunk { + self.value.extend_from_slice(bytes); + self.next_chunk = chunk + 1; + } + } + + fn build(self) -> Result { + let metadata = self + .metadata + .context("actor kv entry has no metadata row")?; + + Ok(proto::KvEntry { + key: self.key, + value: self.value, + version: metadata.version, + update_ts: metadata.update_ts, + }) + } +} diff --git a/engine/packages/api-public/src/migration/facts.rs b/engine/packages/api-public/src/migration/facts.rs new file mode 100644 index 0000000000..ce974d8ce3 --- /dev/null +++ b/engine/packages/api-public/src/migration/facts.rs @@ -0,0 +1,333 @@ +//! Reads the per-actor facts every migration route decides on. + +use anyhow::{Context, Result}; +use depot::{conveyer::branch as depot_branch, keys as depot_keys, types::BucketId}; +use futures_util::TryStreamExt; +use pegboard::keys; +use rivet_util::Id; +use universaldb::{options::StreamingMode, utils::IsolationLevel}; +use vbare::OwnedVersionedData; + +use super::keys as mkeys; + +/// The SQLite v1 (KV-backed) format stores its files under this KV key prefix. +const SQLITE_V1_PREFIX: u8 = 0x08; + +/// Pegboard and gasoline state of one actor, as of one transaction's read version. +#[derive(Debug, Clone)] +pub struct ActorFacts { + pub actor_id: Id, + pub namespace_id: Id, + pub workflow_id: Id, + pub name: String, + pub key: Option, + pub pool_name: String, + pub create_ts: i64, + pub version: u32, + pub generation: u32, + pub sleep_ts: Option, + /// The actor is connectable, or an envoy still holds it while it stops. + pub allocated: bool, + pub destroy_ts: Option, + pub hibernating: bool, + pub wake_deadline_ts: Option, +} + +/// The oldest last ping a hibernating request may have and still hold its actor: V2's own +/// reads ignore requests the gateway stopped pinging for longer than the eligible threshold, +/// such as the ones a killed gateway leaves behind. +pub fn hibernating_since_ts(eligible_threshold_ms: i64) -> i64 { + rivet_util::timestamp::now() - eligible_threshold_ms +} + +/// Reads an actor's facts. Returns `None` if the actor does not exist. A hibernating request +/// last pinged before `hibernating_since_ts` does not count. +pub async fn read( + tx: &universaldb::Transaction, + actor_id: Id, + hibernating_since_ts: i64, + isolation: IsolationLevel, +) -> Result> { + let pb = tx.with_subspace(keys::subspace()); + + let namespace_id_key = keys::actor::NamespaceIdKey::new(actor_id); + let workflow_id_key = keys::actor::WorkflowIdKey::new(actor_id); + let name_key = keys::actor::NameKey::new(actor_id); + let key_key = keys::actor::KeyKey::new(actor_id); + let pool_name_key = keys::actor::PoolNameKey::new(actor_id); + let runner_name_selector_key = keys::actor::RunnerNameSelectorKey::new(actor_id); + let create_ts_key = keys::actor::CreateTsKey::new(actor_id); + let version_key = keys::actor::VersionKey::new(actor_id); + let generation_key = keys::actor::GenerationKey::new(actor_id); + let sleep_ts_key = keys::actor::SleepTsKey::new(actor_id); + let envoy_key_key = keys::actor::EnvoyKeyKey::new(actor_id); + let connectable_key = keys::actor::ConnectableKey::new(actor_id); + let destroy_ts_key = keys::actor::DestroyTsKey::new(actor_id); + + let ( + namespace_id, + workflow_id, + name, + key, + pool_name, + runner_name_selector, + create_ts, + version, + generation, + sleep_ts, + envoy_key, + connectable, + destroy_ts, + hibernating, + ) = tokio::try_join!( + pb.read_opt(&namespace_id_key, isolation), + pb.read_opt(&workflow_id_key, isolation), + pb.read_opt(&name_key, isolation), + pb.read_opt(&key_key, isolation), + pb.read_opt(&pool_name_key, isolation), + pb.read_opt(&runner_name_selector_key, isolation), + pb.read_opt(&create_ts_key, isolation), + pb.read_opt(&version_key, isolation), + pb.read_opt(&generation_key, isolation), + pb.read_opt(&sleep_ts_key, isolation), + pb.exists(&envoy_key_key, isolation), + pb.exists(&connectable_key, isolation), + pb.read_opt(&destroy_ts_key, isolation), + has_hibernating_request(&pb, actor_id, hibernating_since_ts, isolation), + )?; + + let (Some(namespace_id), Some(workflow_id)) = (namespace_id, workflow_id) else { + return Ok(None); + }; + + let wake_deadline_ts = read_wake_deadline(tx, workflow_id, isolation).await?; + + // A stopping actor keeps its envoy key until the envoy reports it stopped, so the key alone + // marks an actor that may still be running. Gasoline commits an activity's writes apart from + // its state change, so a lost state change can leave the key behind on a sleeping actor that + // no envoy holds. The workflow's own state decides then, as it does for V2's lifecycle. + let allocated = + connectable || (envoy_key && workflow_allocated(tx, workflow_id, isolation).await?); + + Ok(Some(ActorFacts { + actor_id, + namespace_id, + workflow_id, + name: name.unwrap_or_default(), + key, + pool_name: pool_name.or(runner_name_selector).unwrap_or_default(), + create_ts: create_ts.unwrap_or_default(), + version: version.unwrap_or(1), + generation: generation.unwrap_or(0), + sleep_ts, + allocated, + destroy_ts, + hibernating, + wake_deadline_ts, + })) +} + +/// The allocation fields of the `pegboard_actor2` workflow state. +#[derive(serde::Deserialize)] +struct WorkflowAllocation { + allocate_ts: Option, + envoy_key: Option, +} + +/// Whether the actor workflow's state holds an allocation. A workflow with no state reads as +/// allocated, so the migration leaves an actor it cannot judge alone. +async fn workflow_allocated( + tx: &universaldb::Transaction, + workflow_id: Id, + isolation: IsolationLevel, +) -> Result { + let subspace = mkeys::workflow_state_subspace(workflow_id); + let chunks = tx + .get_ranges_keyvalues( + universaldb::RangeOption { + mode: StreamingMode::WantAll, + ..(&subspace).into() + }, + isolation, + ) + .try_collect::>() + .await?; + if chunks.is_empty() { + return Ok(true); + } + + let state = chunks + .iter() + .flat_map(|chunk| chunk.value().iter().copied()) + .collect::>(); + let state = serde_json::from_slice::(&state) + .context("actor workflow state has no allocation fields")?; + Ok(state.allocate_ts.is_some() || state.envoy_key.is_some()) +} + +async fn has_hibernating_request( + pb: &universaldb::Transaction, + actor_id: Id, + since_ts: i64, + isolation: IsolationLevel, +) -> Result { + // Rows are ordered by last ping, so the range starts at the oldest live one, as V2's own + // hibernating request list does. + let start = pb.pack(&keys::actor::HibernatingRequestKey::subspace_with_ts( + actor_id, since_ts, + )); + let end = keys::subspace() + .subspace(&keys::actor::HibernatingRequestKey::subspace(actor_id)) + .range() + .1; + let mut stream = pb.get_ranges_keyvalues( + universaldb::RangeOption { + limit: Some(1), + mode: StreamingMode::Small, + ..(start, end).into() + }, + isolation, + ); + + Ok(stream.try_next().await?.is_some()) +} + +/// The workflow's pending deadline, if it has one. +/// +/// Gasoline keeps a workflow's last deadline in its wake-deadline key after the deadline is +/// consumed: a commit without a new deadline deletes the deadline's wake row but not the key. So +/// the key is a pending deadline only while its wake row exists; otherwise a fired alarm would +/// read as one that is about to fire on every pass. +pub async fn read_wake_deadline( + tx: &universaldb::Transaction, + workflow_id: Id, + isolation: IsolationLevel, +) -> Result> { + let Some(raw) = tx + .get(&mkeys::wake_deadline(workflow_id), isolation) + .await? + else { + return Ok(None); + }; + + let bytes: [u8; 8] = raw[..] + .try_into() + .context("gasoline wake deadline is not 8 bytes")?; + let deadline_ts = i64::from_be_bytes(bytes); + + let workflow_name = read_workflow_name(tx, workflow_id, isolation).await?; + let pending = tx + .get( + &mkeys::deadline_wake_row(&workflow_name, workflow_id, deadline_ts), + isolation, + ) + .await? + .is_some(); + if pending { + Ok(Some(deadline_ts)) + } else { + Ok(None) + } +} + +pub async fn read_workflow_name( + tx: &universaldb::Transaction, + workflow_id: Id, + isolation: IsolationLevel, +) -> Result { + let raw = tx + .get(&mkeys::workflow_name(workflow_id), isolation) + .await? + .context("actor workflow has no name")?; + String::from_utf8(raw.to_vec()).context("actor workflow name is not utf-8") +} + +/// Whether the actor's SQLite is still on the KV-backed v1 format. +/// +/// It is when the v1 import marker is set, or when v1 data exists and no v2 head was ever written. +/// v1 data is never deleted after an import, so v1 data plus a v2 head and no marker is a finished +/// import. +pub async fn sqlite_v1( + tx: &universaldb::Transaction, + namespace_id: Id, + actor_id: Id, + isolation: IsolationLevel, +) -> Result { + let pb = tx.with_subspace(keys::subspace()); + let marker = pb + .exists(&keys::actor::SqliteMigrationKey::new(actor_id), isolation) + .await?; + if marker { + return Ok(true); + } + + let kv_subspace = keys::actor_kv::subspace(actor_id); + let mut start = kv_subspace.pack(&keys::actor_kv::ListKeyWrapper(vec![SQLITE_V1_PREFIX])); + if let Some(&0) = start.last() { + start.pop(); + } + let mut end = start.clone(); + end.push(0xFF); + + let mut stream = tx.get_ranges_keyvalues( + universaldb::RangeOption { + limit: Some(1), + mode: StreamingMode::Small, + ..(start, end).into() + }, + isolation, + ); + let has_v1_data = stream.try_next().await?.is_some(); + drop(stream); + if !has_v1_data { + return Ok(false); + } + + Ok(read_sqlite_head(tx, namespace_id, actor_id, isolation) + .await? + .is_none()) +} + +/// The actor's published SQLite head, if it has a v2 database. +pub async fn read_sqlite_head( + tx: &universaldb::Transaction, + namespace_id: Id, + actor_id: Id, + isolation: IsolationLevel, +) -> Result> { + let database_id = actor_id.to_string(); + let bucket_id = BucketId::from_gas_id(namespace_id); + + let key = match depot_branch::resolve_database_branch(tx, bucket_id, &database_id, isolation) + .await? + { + Some(branch_id) => depot_keys::branch_meta_head_key(branch_id), + None => depot_keys::meta_head_key(&database_id), + }; + + tx.informal() + .get(&key, isolation) + .await? + .map(|bytes| depot::types::decode_db_head(bytes.as_ref())) + .transpose() + .context("decode sqlite db head") +} + +pub async fn is_parked(tx: &universaldb::Transaction, actor_id: Id) -> Result { + Ok(tx + .get(&mkeys::parked(actor_id), IsolationLevel::Serializable) + .await? + .is_some()) +} + +/// Decodes a persisted parked record. +pub fn decode_parked(raw: &[u8]) -> Result { + v2_migration_protocol::versioned::ParkedRecord::deserialize_with_embedded_version(raw) + .context("decode parked record") +} + +pub fn encode_parked(record: v2_migration_protocol::ParkedRecord) -> Result> { + v2_migration_protocol::versioned::ParkedRecord::wrap_latest(record) + .serialize_with_embedded_version(1) + .context("encode parked record") +} diff --git a/engine/packages/api-public/src/migration/keys.rs b/engine/packages/api-public/src/migration/keys.rs new file mode 100644 index 0000000000..3df72bf71f --- /dev/null +++ b/engine/packages/api-public/src/migration/keys.rs @@ -0,0 +1,102 @@ +//! Raw key layout the migration API reads and writes outside pegboard's own key types. +//! +//! Gasoline's key types are private to gasoline, so the few gasoline keys the park touches are +//! packed here from the same tuple layout. `tests/migration.rs` runs a real `pegboard_actor2` +//! workflow and fails if any of these stop matching what gasoline writes. + +use rivet_util::Id; +use universaldb::{prelude::*, utils::Subspace}; + +/// Gasoline's KV subspace. +pub fn gasoline_subspace() -> Subspace { + Subspace::new(&(RIVET, GASOLINE, KV)) +} + +/// The workflow's name. Value: UTF-8 string. +pub fn workflow_name(workflow_id: Id) -> Vec { + gasoline_subspace().pack(&(WORKFLOW, DATA, workflow_id, NAME)) +} + +/// The workflow's state, stored as JSON split into chunks keyed by their index under this +/// prefix. +pub fn workflow_state_subspace(workflow_id: Id) -> Subspace { + gasoline_subspace().subspace(&(WORKFLOW, DATA, workflow_id, STATE)) +} + +/// The workflow's armed deadline. Value: big-endian `i64` milliseconds. +pub fn wake_deadline(workflow_id: Id) -> Vec { + gasoline_subspace().pack(&(WORKFLOW, DATA, workflow_id, WAKE_DEADLINE)) +} + +/// Present while a worker holds or is acquiring the workflow's lease. +pub fn lease(workflow_id: Id) -> Vec { + gasoline_subspace().pack(&(WORKFLOW, LEASE, workflow_id)) +} + +/// Set on a silenced workflow. Gasoline drops a silenced workflow whenever a pull leases it and +/// never reclaims its lease, so a parked workflow stays inert even if a wake row survives the +/// park. Value: big-endian `i64` milliseconds. +pub fn silence_ts(workflow_id: Id) -> Vec { + gasoline_subspace().pack(&(WORKFLOW, DATA, workflow_id, SILENCE_TS)) +} + +/// Present while a worker holds the workflow. +pub fn worker_id(workflow_id: Id) -> Vec { + gasoline_subspace().pack(&(WORKFLOW, DATA, workflow_id, WORKER_ID)) +} + +/// Prefix of the signal names the sleeping workflow listens for. Each row is the prefix followed by +/// the packed signal name, with an empty value. +pub fn wake_signal_subspace(workflow_id: Id) -> Subspace { + gasoline_subspace().subspace(&(WORKFLOW, DATA, workflow_id, WAKE_SIGNAL)) +} + +/// Prefix of the workflow's pending (unacknowledged) signals. +pub fn pending_signal_subspace(workflow_id: Id) -> Subspace { + gasoline_subspace().subspace(&(WORKFLOW, SIGNAL, workflow_id, PENDING)) +} + +/// Gasoline wake condition variants, in key order. +const WAKE_IMMEDIATE: usize = 0; +const WAKE_DEADLINE_VARIANT: usize = 1; + +/// The wake index row that fires the workflow at its deadline. Value: big-endian `u16` nonce. +pub fn deadline_wake_row(workflow_name: &str, workflow_id: Id, deadline_ts: i64) -> Vec { + gasoline_subspace().pack(&( + WAKE, + WORKFLOW, + workflow_name, + deadline_ts, + workflow_id, + WAKE_DEADLINE_VARIANT, + )) +} + +/// A wake index row that makes the next pull run the workflow right away. +pub fn immediate_wake_row(workflow_name: &str, workflow_id: Id, ts: i64) -> Vec { + gasoline_subspace().pack(&( + WAKE, + WORKFLOW, + workflow_name, + ts, + workflow_id, + WAKE_IMMEDIATE, + )) +} + +/// A fresh nonce for a written wake row. Gasoline clears the rows it pulled with a compare against +/// the nonce it read, so a rewritten row needs a new one. +pub fn wake_row_nonce() -> Vec { + rand::random::().to_be_bytes().to_vec() +} + +/// The newest cutover that a confirm or restore undid. A cutover request at or before it is a late +/// duplicate and must not cut the actor again. Value: big-endian `i64`. +pub fn uncut(actor_id: Id) -> Vec { + pegboard::keys::subspace().pack(&(MIGRATION, UNCUT, actor_id)) +} + +/// The parked record of a migrated actor, in pegboard's subspace. +pub fn parked(actor_id: Id) -> Vec { + pegboard::keys::subspace().pack(&(MIGRATION, PARKED, actor_id)) +} diff --git a/engine/packages/api-public/src/migration/mod.rs b/engine/packages/api-public/src/migration/mod.rs new file mode 100644 index 0000000000..fe87817404 --- /dev/null +++ b/engine/packages/api-public/src/migration/mod.rs @@ -0,0 +1,229 @@ +//! The `/migration/v1/` API the V3 migrator drives to move one namespace's actors out of V2. +//! +//! Every route is a stateless handler over existing pegboard, gasoline and depot state, so the +//! module does nothing until called. Bodies are raw BARE from `v2-migration-protocol`, pinned by the +//! `/v1` path. +//! +//! The protocol per actor is list (or a read of one candidate by id), export, cutover, confirm, and +//! optionally restore: +//! - **Cutover** sets `DestroyTsKey` to the migrator's `cutoverTs`, so V2's gateway stops waking the +//! actor. It writes no gasoline state. +//! - **Confirm** runs after a delay that outlasts any wake already in flight. It re-checks the +//! generation, the allocation, the workflow's worker and pending signals, and the deadline. If all +//! hold it parks the actor in the same transaction: the workflow's wake rows move into a parked +//! record, so no worker runs it again. If any fails it clears the cutover so V2 keeps serving. +//! - **Restore** writes the wake rows back and clears the cutover. +//! +//! Each route serves only actors in this datacenter. A multi-datacenter namespace is migrated by +//! calling every datacenter's public API. + +use anyhow::Result; +use axum::{ + body::Bytes, + http::header::CONTENT_TYPE, + response::{IntoResponse, Response}, +}; +use rivet_api_builder::{ + ApiError, + extract::{Extension, Path, Query}, +}; +use rivet_auth::{AccessNamespaceScope, OperationKind, ResourceKind, TargetScope}; +use rivet_util::Id; +use serde::Deserialize; +use universaldb::utils::IsolationLevel::Snapshot; + +use crate::{ctx::ApiCtx, errors}; + +mod candidates; +mod export; +mod facts; +pub mod keys; +mod park; + +#[derive(Debug, Deserialize)] +pub struct NamespacePath { + pub namespace: String, +} + +#[derive(Debug, Deserialize)] +pub struct ActorPath { + pub actor_id: Id, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CandidatesQuery { + pub after: Option, + pub limit: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ActorQuery { + pub namespace: String, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExportQuery { + pub namespace: String, + pub resume: Option, +} + +pub async fn candidates( + Extension(ctx): Extension, + Path(path): Path, + Query(query): Query, +) -> Response { + respond(candidates::candidates(ctx, path.namespace, query).await) +} + +pub async fn candidate( + Extension(ctx): Extension, + Path(path): Path, + Query(query): Query, +) -> Response { + respond(candidates::candidate(ctx, path.actor_id, query.namespace).await) +} + +pub async fn export( + Extension(ctx): Extension, + Path(path): Path, + Query(query): Query, +) -> Response { + match export::export(ctx, path.actor_id, query).await { + Ok(response) => response, + Err(err) => ApiError::from(err).into_response(), + } +} + +pub async fn cutover( + Extension(ctx): Extension, + Path(path): Path, + Query(query): Query, + body: Bytes, +) -> Response { + respond(park::cutover(ctx, path.actor_id, query.namespace, body).await) +} + +pub async fn confirm( + Extension(ctx): Extension, + Path(path): Path, + Query(query): Query, + body: Bytes, +) -> Response { + respond(park::confirm(ctx, path.actor_id, query.namespace, body).await) +} + +pub async fn restore( + Extension(ctx): Extension, + Path(path): Path, + Query(query): Query, + body: Bytes, +) -> Response { + respond(park::restore(ctx, path.actor_id, query.namespace, body).await) +} + +fn respond(result: Result>) -> Response { + match result { + Ok(body) => ( + [(CONTENT_TYPE, v2_migration_protocol::BARE_CONTENT_TYPE)], + body, + ) + .into_response(), + Err(err) => ApiError::from(err).into_response(), + } +} + +/// Requires a token that may read and update every actor and every actor KV in the namespace, then +/// resolves the namespace id. +/// +/// The routes read all of a namespace's actor data and park its actors, so a token scoped to some +/// actors is refused. Use the admin token or a token scoped to the whole namespace. +async fn authorize(ctx: &ApiCtx, namespace: &str) -> Result { + for (resource, operation) in [ + (ResourceKind::Actor, OperationKind::List), + (ResourceKind::Actor, OperationKind::Update), + (ResourceKind::ActorKv, OperationKind::Read), + ] { + ctx.auth( + AccessNamespaceScope::Name(namespace.to_string()), + resource, + TargetScope::Any, + operation, + ) + .await?; + } + + ensure_backfill_complete(ctx).await?; + + let namespace = ctx + .op(namespace::ops::resolve_for_name_global::Input { + name: namespace.to_string(), + }) + .await? + .ok_or_else(|| namespace::errors::Namespace::NotFound.build())?; + + Ok(namespace.namespace_id) +} + +/// Refuses every route until `actor_migration_fix_backfill` has finished. +/// +/// That backfill treats any actor with `DestroyTsKey` as destroyed. Run over a cut-over or parked +/// actor, it would delete the actor's active index entry and mark its key destroyed, and a restore +/// undoes neither. Bootstrap starts the backfill on every engine start until it completes and never +/// runs it again afterward, so once it has finished no later run can touch a parked actor. +async fn ensure_backfill_complete(ctx: &ApiCtx) -> Result<()> { + let complete = ctx + .udb()? + .txn("migration_check_backfill_complete", |tx| async move { + let tx = tx.with_subspace(rivet_types::keys::backfill::subspace()); + tx.exists( + &rivet_types::keys::backfill::CompleteKey::new( + pegboard::workflows::actor_migration_fix_backfill::BACKFILL_NAME, + ), + Snapshot, + ) + .await + }) + .await?; + + if !complete { + return Err(errors::Migration::BackfillIncomplete.build()); + } + + Ok(()) +} + +/// Refuses actors that another datacenter owns. The migrator calls the owning datacenter's API, +/// so these routes never read across datacenters. +fn ensure_local(ctx: &ApiCtx, actor_id: Id) -> Result<()> { + let local = ctx.config().dc_label(); + if actor_id.label() != local { + return Err(errors::Migration::WrongDatacenter { + actor_datacenter_label: actor_id.label(), + datacenter_label: local, + } + .build()); + } + + Ok(()) +} + +/// Refuses actors outside the token's namespace with the same error as a missing actor, so a +/// token cannot probe other namespaces' actor ids. +fn ensure_namespace(facts: Option<&facts::ActorFacts>, namespace_id: Id) -> Result<()> { + match facts { + Some(facts) if facts.namespace_id == namespace_id => Ok(()), + _ => Err(errors::Migration::ActorNotFound.build()), + } +} + +fn decode_body(body: &[u8]) -> Result { + v2_migration_protocol::decode(body).map_err(|err| { + errors::Migration::InvalidRequest { + message: format!("{err:#}"), + } + .build() + }) +} diff --git a/engine/packages/api-public/src/migration/park.rs b/engine/packages/api-public/src/migration/park.rs new file mode 100644 index 0000000000..9c2087fa54 --- /dev/null +++ b/engine/packages/api-public/src/migration/park.rs @@ -0,0 +1,428 @@ +//! `cutover`, `confirm` and `restore`: the fence that hands an actor from V2 to V3 and back. +//! +//! **Cutover** writes only `DestroyTsKey = cutoverTs`. V2's gateway reads `DestroyTsKey` +//! serializably and answers `actor.not_found` without waking, so no new wake starts. `cutoverTs` +//! is the idempotency key: a retry sees `DestroyTsKey == cutoverTs` and answers `alreadyCut`. +//! +//! **Confirm** runs once a delay longer than V2's guard timeouts has passed, so any wake that read +//! the actor before the cutover has landed. Such a wake is visible in one of the checked keys: it +//! moved the generation or armed a retry deadline, holds the workflow's worker, or left a pending +//! signal. If every check holds, the same transaction **parks** the actor: it moves the workflow's +//! deadline and its signal listen set out of gasoline's wake index into a parked record, so no +//! worker pulls the workflow again and no direct signal wakes it. If any check fails, it clears +//! the cutover ("un-cut") and V2 keeps serving the actor. +//! +//! **Restore** writes the wake rows back from the parked record, clears `DestroyTsKey` and deletes +//! the record, so the actor is an ordinary sleeping V2 actor again. + +use anyhow::{Context, Result}; +use axum::body::Bytes; +use futures_util::TryStreamExt; +use pegboard::keys; +use rivet_util::Id; +use universaldb::{options::StreamingMode, utils::IsolationLevel::Serializable}; +use v2_migration_protocol as proto; + +use super::{authorize, decode_body, ensure_local, ensure_namespace, facts, keys as mkeys}; +use crate::{ctx::ApiCtx, errors}; + +pub async fn cutover(ctx: ApiCtx, actor_id: Id, namespace: String, body: Bytes) -> Result> { + ensure_local(&ctx, actor_id)?; + let namespace_id = authorize(&ctx, &namespace).await?; + let request = decode_body::(&body)?; + + let hibernating_since_ts = facts::hibernating_since_ts( + ctx.config() + .pegboard() + .hibernating_request_eligible_threshold(), + ); + let udb = ctx.pools().udb()?; + let response = udb + .txn("migration_cutover", |tx| { + let request = request.clone(); + async move { + let actor = facts::read(&tx, actor_id, hibernating_since_ts, Serializable).await?; + ensure_namespace(actor.as_ref(), namespace_id)?; + let actor = actor.context("actor checked above")?; + + if let Some(destroy_ts) = actor.destroy_ts { + return Ok(if destroy_ts == request.cutover_ts { + proto::CutoverResponse::AlreadyCut + } else { + proto::CutoverResponse::Destroyed + }); + } + + if actor.generation != request.generation { + return Ok(proto::CutoverResponse::Woke); + } + + // A cutover that a confirm or restore already undid is a late duplicate of an + // abandoned attempt. Cutting again would hide the actor with nobody to finish it. + if read_i64(&tx, &mkeys::uncut(actor_id)) + .await? + .is_some_and(|uncut| request.cutover_ts <= uncut) + { + return Ok(proto::CutoverResponse::Woke); + } + + let ineligible = if actor.version == 1 { + Some(proto::IneligibleReason::ActorV1) + } else if actor.sleep_ts.is_none() { + Some(proto::IneligibleReason::NotSleeping) + } else if actor.allocated { + Some(proto::IneligibleReason::Allocated) + } else if actor.hibernating { + Some(proto::IneligibleReason::Hibernating) + } else if facts::sqlite_v1(&tx, namespace_id, actor_id, Serializable).await? { + Some(proto::IneligibleReason::SqliteV1) + } else { + None + }; + if let Some(reason) = ineligible { + return Ok(proto::CutoverResponse::Ineligible(proto::Ineligible { + reason, + })); + } + + tx.with_subspace(keys::subspace()).write( + &keys::actor::DestroyTsKey::new(actor_id), + request.cutover_ts, + )?; + + Ok(proto::CutoverResponse::Cut) + } + }) + .await?; + + tracing::info!(%actor_id, cutover_ts = request.cutover_ts, response = ?response, "migration cutover"); + proto::encode(&response) +} + +pub async fn confirm(ctx: ApiCtx, actor_id: Id, namespace: String, body: Bytes) -> Result> { + ensure_local(&ctx, actor_id)?; + let namespace_id = authorize(&ctx, &namespace).await?; + let request = decode_body::(&body)?; + let v3_actor_id = Id::from_slice(&request.v3_actor_id).map_err(|_| { + errors::Migration::InvalidRequest { + message: "v3ActorId is not an actor id".to_string(), + } + .build() + })?; + + let pull_ahead_ms = pull_ahead_ms(&ctx); + let hibernating_since_ts = facts::hibernating_since_ts( + ctx.config() + .pegboard() + .hibernating_request_eligible_threshold(), + ); + let udb = ctx.pools().udb()?; + let response = udb + .txn("migration_confirm", |tx| { + let request = request.clone(); + async move { + let actor = facts::read(&tx, actor_id, hibernating_since_ts, Serializable).await?; + ensure_namespace(actor.as_ref(), namespace_id)?; + let actor = actor.context("actor checked above")?; + + if let Some(raw) = tx.get(&mkeys::parked(actor_id), Serializable).await? { + let parked = facts::decode_parked(&raw)?; + if parked.cutover_ts == request.cutover_ts { + return Ok(proto::ConfirmResponse::AlreadyConfirmed); + } + return Err(errors::Migration::CutoverMismatch { + parked_cutover_ts: parked.cutover_ts, + cutover_ts: request.cutover_ts, + } + .build()); + } + + match actor.destroy_ts { + None => { + return Ok(proto::ConfirmResponse::ConfirmWoke(proto::ConfirmWoke { + reason: proto::WokeReason::NotCut, + })); + } + Some(destroy_ts) if destroy_ts != request.cutover_ts => { + return Ok(proto::ConfirmResponse::Destroyed); + } + Some(_) => {} + } + + if let Some(reason) = woke_reason(pull_ahead_ms, &tx, &actor, &request).await? { + // Un-cut: only our own cutover value is cleared, never a real destroy. + tx.with_subspace(keys::subspace()) + .delete(&keys::actor::DestroyTsKey::new(actor_id)); + write_uncut(&tx, actor_id, request.cutover_ts).await?; + return Ok(proto::ConfirmResponse::ConfirmWoke(proto::ConfirmWoke { + reason, + })); + } + + park(&tx, &actor, &request, v3_actor_id).await?; + Ok(proto::ConfirmResponse::Confirmed) + } + }) + .await?; + + tracing::info!(%actor_id, cutover_ts = request.cutover_ts, response = ?response, "migration confirm"); + proto::encode(&response) +} + +/// Returns why the actor cannot be parked, or `None` if every confirm check holds. +async fn woke_reason( + pull_ahead_ms: i64, + tx: &universaldb::Transaction, + actor: &facts::ActorFacts, + request: &proto::ConfirmRequest, +) -> Result> { + if actor.generation != request.generation { + return Ok(Some(proto::WokeReason::GenerationMoved)); + } + if actor.sleep_ts != Some(request.sleep_ts) { + return Ok(Some(proto::WokeReason::SleepMoved)); + } + if actor.allocated { + return Ok(Some(proto::WokeReason::Allocated)); + } + if actor.hibernating { + return Ok(Some(proto::WokeReason::Hibernating)); + } + + let workflow_id = actor.workflow_id; + let worker_key = mkeys::worker_id(workflow_id); + let lease_key = mkeys::lease(workflow_id); + let silence_key = mkeys::silence_ts(workflow_id); + let pending_signals = mkeys::pending_signal_subspace(workflow_id); + let (worker, lease, silenced, pending_signal) = tokio::try_join!( + tx.get(&worker_key, Serializable), + tx.get(&lease_key, Serializable), + tx.get(&silence_key, Serializable), + first_row(tx, &pending_signals), + )?; + if worker.is_some() || lease.is_some() { + return Ok(Some(proto::WokeReason::WorkerRunning)); + } + // An operator silenced the workflow already; parking would lose that on restore. + if silenced.is_some() { + return Ok(Some(proto::WokeReason::Silenced)); + } + if pending_signal { + return Ok(Some(proto::WokeReason::PendingSignal)); + } + + if actor.wake_deadline_ts != request.wake_deadline_ts { + return Ok(Some(proto::WokeReason::DeadlineMoved)); + } + if let Some(deadline_ts) = actor.wake_deadline_ts { + // A worker pulls deadlines up to its poll interval ahead and holds them in memory, so a + // deadline inside that window may already belong to a worker that read it. + let horizon_ms = request.horizon_ms.max(pull_ahead_ms); + let horizon = rivet_util::timestamp::now().saturating_add(horizon_ms); + if deadline_ts < horizon { + return Ok(Some(proto::WokeReason::DeadlineSoon)); + } + } + + Ok(None) +} + +/// Moves the workflow's wake rows into the parked record, in the confirm transaction. +async fn park( + tx: &universaldb::Transaction, + actor: &facts::ActorFacts, + request: &proto::ConfirmRequest, + v3_actor_id: Id, +) -> Result<()> { + let workflow_id = actor.workflow_id; + let workflow_name = facts::read_workflow_name(tx, workflow_id, Serializable).await?; + let wake_signals = read_wake_signals(tx, workflow_id).await?; + + if let Some(deadline_ts) = actor.wake_deadline_ts { + tx.clear(&mkeys::wake_deadline(workflow_id)); + tx.clear(&mkeys::deadline_wake_row( + &workflow_name, + workflow_id, + deadline_ts, + )); + } + tx.clear_subspace_range(&mkeys::wake_signal_subspace(workflow_id)); + let parked_at = rivet_util::timestamp::now(); + tx.set(&mkeys::silence_ts(workflow_id), &parked_at.to_be_bytes()); + + let record = proto::ParkedRecord { + generation: actor.generation, + cutover_ts: request.cutover_ts, + parked_at, + v3_actor_id: v3_actor_id.as_bytes(), + workflow_id: workflow_id.as_bytes(), + workflow_name, + wake_deadline_ts: actor.wake_deadline_ts, + wake_signals, + }; + tx.set( + &mkeys::parked(actor.actor_id), + &facts::encode_parked(record)?, + ); + + Ok(()) +} + +pub async fn restore(ctx: ApiCtx, actor_id: Id, namespace: String, body: Bytes) -> Result> { + ensure_local(&ctx, actor_id)?; + let namespace_id = authorize(&ctx, &namespace).await?; + let request = decode_body::(&body)?; + + let hibernating_since_ts = facts::hibernating_since_ts( + ctx.config() + .pegboard() + .hibernating_request_eligible_threshold(), + ); + let udb = ctx.pools().udb()?; + let response = udb + .txn("migration_restore", |tx| { + let request = request.clone(); + async move { + let actor = facts::read(&tx, actor_id, hibernating_since_ts, Serializable).await?; + ensure_namespace(actor.as_ref(), namespace_id)?; + + let Some(raw) = tx.get(&mkeys::parked(actor_id), Serializable).await? else { + return Ok(proto::RestoreResponse::NotParked); + }; + let parked = facts::decode_parked(&raw)?; + if request + .cutover_ts + .is_some_and(|cutover_ts| cutover_ts != parked.cutover_ts) + { + return Err(errors::Migration::CutoverMismatch { + parked_cutover_ts: parked.cutover_ts, + cutover_ts: request.cutover_ts.unwrap_or_default(), + } + .build()); + } + + if let Some(v3_actor_id) = &request.v3_actor_id + && v3_actor_id[..] != parked.v3_actor_id[..] + { + return Err(errors::Migration::InvalidRequest { + message: "the parked actor was migrated to a different V3 actor" + .to_string(), + } + .build()); + } + + let workflow_id = + Id::from_slice(&parked.workflow_id).context("parked workflow id")?; + tx.clear(&mkeys::silence_ts(workflow_id)); + for signal_name in &parked.wake_signals { + let row = + mkeys::wake_signal_subspace(workflow_id).pack(&(signal_name.as_str(),)); + tx.set(&row, &[]); + } + if let Some(deadline_ts) = parked.wake_deadline_ts { + tx.set( + &mkeys::wake_deadline(workflow_id), + &deadline_ts.to_be_bytes(), + ); + tx.set( + &mkeys::deadline_wake_row(&parked.workflow_name, workflow_id, deadline_ts), + &mkeys::wake_row_nonce(), + ); + } + + // A signal sent while parked found no listen row, so nothing woke the workflow for + // it. Wake it once now so it handles what is pending. + if first_row(&tx, &mkeys::pending_signal_subspace(workflow_id)).await? { + tx.set( + &mkeys::immediate_wake_row( + &parked.workflow_name, + workflow_id, + rivet_util::timestamp::now(), + ), + &mkeys::wake_row_nonce(), + ); + } + + // Only the cutover's own value is cleared, never a later real destroy. + let pb = tx.with_subspace(keys::subspace()); + let destroy_key = keys::actor::DestroyTsKey::new(actor_id); + if pb.read_opt(&destroy_key, Serializable).await? == Some(parked.cutover_ts) { + pb.delete(&destroy_key); + } + tx.clear(&mkeys::parked(actor_id)); + // A late duplicate of the original cutover must not cut the restored actor. + write_uncut(&tx, actor_id, parked.cutover_ts).await?; + + Ok(proto::RestoreResponse::Restored) + } + }) + .await?; + + tracing::info!(%actor_id, cutover_ts = ?request.cutover_ts, response = ?response, "migration restore"); + proto::encode(&response) +} + +async fn read_wake_signals(tx: &universaldb::Transaction, workflow_id: Id) -> Result> { + let subspace = mkeys::wake_signal_subspace(workflow_id); + tx.get_ranges_keyvalues( + universaldb::RangeOption { + mode: StreamingMode::WantAll, + ..(&subspace).into() + }, + Serializable, + ) + .map_err(anyhow::Error::from) + .and_then(|row| { + let subspace = subspace.clone(); + async move { + let (signal_name,) = subspace + .unpack::<(String,)>(row.key()) + .context("unpack wake signal row")?; + Ok(signal_name) + } + }) + .try_collect() + .await +} + +async fn first_row( + tx: &universaldb::Transaction, + subspace: &universaldb::utils::Subspace, +) -> Result { + let mut stream = tx.get_ranges_keyvalues( + universaldb::RangeOption { + limit: Some(1), + mode: StreamingMode::Small, + ..subspace.into() + }, + Serializable, + ); + + Ok(stream.try_next().await?.is_some()) +} + +/// Gasoline's pull-ahead window plus a margin: the shortest confirm horizon that is safe. +fn pull_ahead_ms(ctx: &ApiCtx) -> i64 { + let poll_ms = ctx.config().runtime.worker_poll_interval().as_millis() as i64; + poll_ms.saturating_add(5_000) +} + +async fn read_i64(tx: &universaldb::Transaction, key: &[u8]) -> Result> { + let Some(raw) = tx.get(key, Serializable).await? else { + return Ok(None); + }; + let bytes: [u8; 8] = raw[..] + .try_into() + .context("migration value is not 8 bytes")?; + Ok(Some(i64::from_be_bytes(bytes))) +} + +/// Raises the actor's un-cut tombstone to `cutover_ts`. +async fn write_uncut(tx: &universaldb::Transaction, actor_id: Id, cutover_ts: i64) -> Result<()> { + let key = mkeys::uncut(actor_id); + let current = read_i64(tx, &key).await?; + if current.is_none_or(|current| current < cutover_ts) { + tx.set(&key, &cutover_ts.to_be_bytes()); + } + Ok(()) +} diff --git a/engine/packages/api-public/src/router.rs b/engine/packages/api-public/src/router.rs index d53f3d0970..069d35eba2 100644 --- a/engine/packages/api-public/src/router.rs +++ b/engine/packages/api-public/src/router.rs @@ -10,8 +10,8 @@ use tower_http::cors::CorsLayer; use utoipa::OpenApi; use crate::{ - actors, auth, ctx, datacenters, envoys, health, metadata, namespaces, runner_configs, runners, - ui, + actors, auth, ctx, datacenters, envoys, health, metadata, migration, namespaces, + runner_configs, runners, ui, }; #[derive(OpenApi)] @@ -139,6 +139,31 @@ pub async fn router( .route("/ui", axum::routing::get(ui::serve_index)) .route("/ui/", axum::routing::get(ui::serve_index)) .route("/ui/{*path}", axum::routing::get(ui::serve_ui)) + // MARK: Migration + .route( + "/migration/v1/namespaces/{namespace}/candidates", + axum::routing::get(migration::candidates), + ) + .route( + "/migration/v1/actors/{actor_id}/candidate", + axum::routing::get(migration::candidate), + ) + .route( + "/migration/v1/actors/{actor_id}/export", + axum::routing::get(migration::export), + ) + .route( + "/migration/v1/actors/{actor_id}/cutover", + axum::routing::post(migration::cutover), + ) + .route( + "/migration/v1/actors/{actor_id}/confirm", + axum::routing::post(migration::confirm), + ) + .route( + "/migration/v1/actors/{actor_id}/restore", + axum::routing::post(migration::restore), + ) // MARK: Middleware (must go after all routes) // Add CORS layer that mirrors the request origin .layer( diff --git a/engine/packages/engine/Cargo.toml b/engine/packages/engine/Cargo.toml index 2cb71ff786..f542c8befc 100644 --- a/engine/packages/engine/Cargo.toml +++ b/engine/packages/engine/Cargo.toml @@ -97,4 +97,6 @@ tokio-tungstenite.workspace = true tracing-subscriber.workspace = true urlencoding.workspace = true universalpubsub.workspace = true +v2-migration-protocol.workspace = true vbare.workspace = true +xxhash-rust.workspace = true diff --git a/engine/packages/engine/tests/v2_migration_api.rs b/engine/packages/engine/tests/v2_migration_api.rs new file mode 100644 index 0000000000..84b3f17b55 --- /dev/null +++ b/engine/packages/engine/tests/v2_migration_api.rs @@ -0,0 +1,1097 @@ +//! The `/migration/v1/` API against a real `pegboard_actor2` workflow. +//! +//! The park moves gasoline wake rows that the API packs itself, because gasoline's key types are +//! private. These tests read the raw gasoline keys a real sleeping actor2 workflow wrote, so a +//! change to gasoline's layout fails here instead of silently leaving parked actors wakeable. + +use std::{ + sync::{Arc, Mutex}, + time::Duration, +}; + +use anyhow::{Context, Result, bail}; +use async_trait::async_trait; +use base64::Engine as _; +use common::test_envoy::*; +use futures_util::TryStreamExt; +use gas::prelude::*; +use rivet_api_public::migration::keys as mkeys; +use rivet_envoy_protocol as protocol; +use tokio::sync::broadcast; +use universaldb::{options::StreamingMode, utils::IsolationLevel::Serializable}; +use v2_migration_protocol as proto; + +#[path = "common/mod.rs"] +mod common; + +const ACTOR_NAME: &str = "migration-actor"; + +/// A value larger than one 10 KB KV chunk, so export has to reassemble chunks. +fn large_value() -> Vec { + (0..25_000u32).map(|i| (i % 251) as u8).collect() +} + +fn seeded_kv() -> Vec<(Vec, Vec)> { + vec![ + (b"a".to_vec(), b"first".to_vec()), + (b"b/large".to_vec(), large_value()), + (vec![0x01, 0x00, 0xFF], vec![]), + (b"z".to_vec(), b"last".to_vec()), + ] +} + +const EMPTY_DB_PAGE_HEADER_PREFIX: [u8; 108] = [ + 83, 81, 76, 105, 116, 101, 32, 102, 111, 114, 109, 97, 116, 32, 51, 0, 16, 0, 1, 1, 0, 64, 32, + 32, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 46, 138, 17, 13, 0, 0, 0, 0, 16, 0, 0, +]; + +/// Page one carries a SQLite header whose database size field says three pages; the other +/// pages are filler that depot stores opaquely. +fn page(pgno: u8) -> Vec { + if pgno == 1 { + let mut page = vec![0; 4096]; + page[..EMPTY_DB_PAGE_HEADER_PREFIX.len()].copy_from_slice(&EMPTY_DB_PAGE_HEADER_PREFIX); + page[28..32].copy_from_slice(&3u32.to_be_bytes()); + return page; + } + + vec![pgno; 4096] +} + +/// Seeds KV on its first start, hands its config to the test, and stays awake until the test +/// asks it to sleep. Later generations stay awake and report their start. +struct SeedActor { + config_tx: Arc>>>, +} + +#[async_trait] +impl Actor for SeedActor { + async fn on_start(&mut self, config: ActorConfig) -> Result { + if config.generation == 1 { + let (keys, values): (Vec<_>, Vec<_>) = seeded_kv().into_iter().unzip(); + config.send_kv_put(keys, values).await?; + if let Some(tx) = self.config_tx.lock().expect("config tx lock").take() { + let _ = tx.send(config.clone()); + } + } + + Ok(ActorStartResult::Running) + } + + async fn on_stop(&mut self) -> Result { + Ok(ActorStopResult::Success) + } + + fn name(&self) -> &str { + "SeedActor" + } +} + +struct Seeded { + namespace: String, + actor_id: Id, + workflow_id: Id, + envoy: common::test_envoy::TestEnvoy, + lifecycle_rx: broadcast::Receiver, + alarm_ts: i64, + pages: Vec>, +} + +fn backfill_complete_key() -> Vec { + rivet_types::keys::backfill::subspace().pack(&rivet_types::keys::backfill::CompleteKey::new( + pegboard::workflows::actor_migration_fix_backfill::BACKFILL_NAME, + )) +} + +/// Creates an actor with KV and three SQLite pages, arms an alarm, and waits for it to sleep. +async fn seed_sleeping_actor(dc: &common::TestDatacenter, alarm_offset_ms: i64) -> Seeded { + // The routes refuse every call until bootstrap finishes the actor migration fix backfill. + wait_for_raw(dc, backfill_complete_key(), true).await; + + let (namespace, _) = common::setup_test_namespace(dc).await; + + let (config_tx, config_rx) = tokio::sync::oneshot::channel(); + let config_tx = Arc::new(Mutex::new(Some(config_tx))); + let envoy = common::setup_envoy(dc, &namespace, |builder| { + builder.with_actor_behavior(ACTOR_NAME, move |_| { + Box::new(SeedActor { + config_tx: config_tx.clone(), + }) + }) + }) + .await; + let lifecycle_rx = envoy.subscribe_lifecycle_events(); + + let res = common::create_actor( + dc.guard_port(), + &namespace, + ACTOR_NAME, + envoy.pool_name(), + rivet_types::actors::CrashPolicy::Sleep, + ) + .await; + let actor_id = res.actor.actor_id; + + let config = tokio::time::timeout(Duration::from_secs(10), config_rx) + .await + .expect("actor should start") + .expect("actor should hand over its config"); + + // Commit three SQLite pages while generation 1 runs. + let pages = vec![page(1), page(2), page(3)]; + let commit = envoy + .sqlite_commit(protocol::SqliteCommitRequest { + actor_id: actor_id.to_string(), + dirty_pages: pages + .iter() + .enumerate() + .map(|(i, bytes)| protocol::SqliteDirtyPage { + pgno: i as u32 + 1, + bytes: bytes.clone(), + }) + .collect(), + db_size_pages: pages.len() as u32, + now_ms: rivet_util::timestamp::now(), + expected_generation: Some(1), + expected_head_txid: None, + }) + .await + .expect("sqlite commit should complete"); + assert!( + matches!(commit, protocol::SqliteCommitResponse::SqliteCommitOk(_)), + "sqlite commit failed: {commit:?}" + ); + + let alarm_ts = rivet_util::timestamp::now() + alarm_offset_ms; + config.send_set_alarm(alarm_ts); + config.send_sleep_intent(); + + common::wait_with_poll(Duration::from_secs(15), Duration::from_millis(50), || { + let namespace = namespace.clone(); + async move { + let actor = common::try_get_actor(dc.guard_port(), &actor_id.to_string(), &namespace) + .await + .ok() + .flatten()?; + actor.sleep_ts.map(|_| ()) + } + }) + .await + .expect("actor should sleep"); + + let workflow_id = dc + .workflow_ctx + .udb() + .unwrap() + .txn("test_read_workflow_id", |tx| async move { + tx.with_subspace(pegboard::keys::subspace()) + .read( + &pegboard::keys::actor::WorkflowIdKey::new(actor_id), + Serializable, + ) + .await + }) + .await + .unwrap(); + + // The workflow commits its sleep after the actor stops; wait for the worker to let go. + wait_for_raw(dc, mkeys::worker_id(workflow_id), false).await; + + Seeded { + namespace, + actor_id, + workflow_id, + envoy, + lifecycle_rx, + alarm_ts, + pages, + } +} + +async fn raw_exists(dc: &common::TestDatacenter, key: Vec) -> bool { + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_raw_exists", |tx| { + let key = key.clone(); + async move { Ok(tx.get(&key, Serializable).await?.is_some()) } + }) + .await + .unwrap() +} + +async fn raw_subspace_len( + dc: &common::TestDatacenter, + subspace: universaldb::utils::Subspace, +) -> usize { + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_raw_subspace_len", |tx| { + let subspace = subspace.clone(); + async move { + let rows = tx + .get_ranges_keyvalues( + universaldb::RangeOption { + mode: StreamingMode::WantAll, + ..(&subspace).into() + }, + Serializable, + ) + .try_collect::>() + .await?; + Ok(rows.len()) + } + }) + .await + .unwrap() +} + +async fn wait_for_raw(dc: &common::TestDatacenter, key: Vec, present: bool) { + common::wait_with_poll(Duration::from_secs(10), Duration::from_millis(50), || { + let key = key.clone(); + async move { + if raw_exists(dc, key).await == present { + Some(()) + } else { + None + } + } + }) + .await + .expect("raw key did not reach the expected state"); +} + +async fn read_wake_deadline(dc: &common::TestDatacenter, workflow_id: Id) -> Option { + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_read_wake_deadline", |tx| async move { + Ok(tx + .get(&mkeys::wake_deadline(workflow_id), Serializable) + .await? + .map(|raw| i64::from_be_bytes(raw[..].try_into().unwrap()))) + }) + .await + .unwrap() +} + +async fn read_workflow_name(dc: &common::TestDatacenter, workflow_id: Id) -> String { + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_read_workflow_name", |tx| async move { + let raw = tx + .get(&mkeys::workflow_name(workflow_id), Serializable) + .await? + .context("workflow name")?; + Ok(String::from_utf8(raw.to_vec())?) + }) + .await + .unwrap() +} + +async fn destroy_ts(dc: &common::TestDatacenter, actor_id: Id) -> Option { + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_read_destroy_ts", |tx| async move { + tx.with_subspace(pegboard::keys::subspace()) + .read_opt( + &pegboard::keys::actor::DestroyTsKey::new(actor_id), + Serializable, + ) + .await + }) + .await + .unwrap() +} + +// MARK: HTTP helpers + +fn url(dc: &common::TestDatacenter, path: &str) -> String { + format!("http://127.0.0.1:{}/migration/v1/{path}", dc.guard_port()) +} + +async fn get_bytes(dc: &common::TestDatacenter, path: &str) -> Result> { + let res = reqwest::Client::new() + .get(url(dc, path)) + .bearer_auth(common::TEST_ADMIN_TOKEN) + .send() + .await?; + let status = res.status(); + let body = res.bytes().await?.to_vec(); + if !status.is_success() { + bail!( + "{path} returned {status}: {}", + String::from_utf8_lossy(&body) + ); + } + Ok(body) +} + +async fn post( + dc: &common::TestDatacenter, + path: &str, + request: &Req, +) -> Result { + let res = reqwest::Client::new() + .post(url(dc, path)) + .bearer_auth(common::TEST_ADMIN_TOKEN) + .body(proto::encode(request)?) + .send() + .await?; + let status = res.status(); + let body = res.bytes().await?.to_vec(); + if !status.is_success() { + bail!( + "{path} returned {status}: {}", + String::from_utf8_lossy(&body) + ); + } + proto::decode(&body) +} + +async fn candidate(dc: &common::TestDatacenter, namespace: &str, actor_id: Id) -> proto::Candidate { + let body = get_bytes(dc, &format!("namespaces/{namespace}/candidates?limit=500")) + .await + .unwrap(); + let page = proto::decode::(&body).unwrap(); + page.candidates + .into_iter() + .find(|c| c.actor_id == actor_id.as_bytes()) + .expect("actor should be listed") +} + +struct Export { + header: proto::ExportHeader, + kv: Vec, + pages: Vec>, + end: Option, + abort: Option, + digest: Vec, +} + +async fn export(dc: &common::TestDatacenter, namespace: &str, actor_id: Id) -> Export { + let body = get_bytes( + dc, + &format!("actors/{actor_id}/export?namespace={namespace}"), + ) + .await + .unwrap(); + + let mut out = Export { + header: proto::ExportHeader { + generation: 0, + sleep_ts: 0, + wake_deadline_ts: None, + name: String::new(), + key: None, + pool_name: String::new(), + create_ts: 0, + kv_bytes_estimate: 0, + sqlite: None, + }, + kv: Vec::new(), + pages: Vec::new(), + end: None, + abort: None, + digest: vec![0; 16], + }; + + let mut rest = &body[..]; + while let Some((frame_body, used)) = proto::split_frame(rest).unwrap() { + match proto::decode_frame(frame_body).unwrap() { + proto::Frame::ExportHeader(header) => out.header = header, + proto::Frame::KvBatch(batch) => { + out.digest = chain(&out.digest, frame_body); + out.kv.extend(batch.entries); + } + proto::Frame::PageBatch(batch) => { + out.digest = chain(&out.digest, frame_body); + assert_eq!(batch.first_pgno as usize, out.pages.len() + 1); + out.pages.extend(batch.pages); + } + proto::Frame::ExportFence(_) => {} + proto::Frame::ExportEnd(end) => out.end = Some(end), + proto::Frame::ExportAbort(abort) => out.abort = Some(abort.reason), + } + rest = &rest[used..]; + } + assert!(rest.is_empty(), "trailing bytes after the last frame"); + + out +} + +fn chain(previous: &[u8], frame_body: &[u8]) -> Vec { + let mut hasher = xxhash_rust::xxh3::Xxh3::new(); + hasher.update(previous); + hasher.update(frame_body); + hasher.digest128().to_be_bytes().to_vec() +} + +async fn wait_for_start( + rx: &mut broadcast::Receiver, + actor_id: Id, + within: Duration, +) -> Option { + let actor_id = actor_id.to_string(); + tokio::time::timeout(within, async { + loop { + match rx.recv().await { + Ok(ActorLifecycleEvent::Started { + actor_id: id, + generation, + }) if id == actor_id && generation > 1 => { + return generation; + } + Ok(_) | Err(broadcast::error::RecvError::Lagged(_)) => {} + Err(broadcast::error::RecvError::Closed) => panic!("lifecycle channel closed"), + } + } + }) + .await + .ok() +} + +// MARK: Tests + +/// The full protocol on one actor: list, export, cutover, confirm (park), restore. +/// +/// The alarm is 45 s out, beyond gasoline's 16 s pull-ahead window plus the confirm's margin, so the workflow commits its +/// sleep instead of waiting in a worker. While parked, the alarm must not fire, which proves the park +/// removed the deadline from gasoline's wake index. After restore the overdue deadline fires and +/// the actor wakes in V2. +#[test] +fn migration_park_and_restore_real_actor2() { + common::run( + common::TestOpts::new(1).with_timeout(150), + |ctx| async move { + let dc = ctx.leader_dc(); + let mut seeded = seed_sleeping_actor(dc, 45_000).await; + let actor_id = seeded.actor_id; + let workflow_id = seeded.workflow_id; + let namespace = seeded.namespace.clone(); + + // Pin gasoline's layout: the sleeping workflow has a deadline, its deadline wake row and a + // signal listen set, under the names and tuple shapes the API packs. + let workflow_name = read_workflow_name(dc, workflow_id).await; + assert_eq!(workflow_name, "pegboard_actor2"); + let deadline = read_wake_deadline(dc, workflow_id) + .await + .expect("sleeping actor with an alarm has a wake deadline"); + assert!( + raw_exists( + dc, + mkeys::deadline_wake_row(&workflow_name, workflow_id, deadline) + ) + .await, + "deadline wake row should exist at the packed key" + ); + let listen_rows = raw_subspace_len(dc, mkeys::wake_signal_subspace(workflow_id)).await; + assert!(listen_rows > 0, "sleeping actor2 listens for signals"); + assert_eq!( + raw_subspace_len(dc, mkeys::pending_signal_subspace(workflow_id)).await, + 0 + ); + + // Candidates carry the raw facts. + let c = candidate(dc, &namespace, actor_id).await; + assert_eq!(c.version, 2); + assert_eq!(c.generation, 1); + assert!(c.sleep_ts.is_some()); + assert!(!c.allocated && !c.hibernating && !c.sqlite_v1 && !c.parked); + assert_eq!(c.destroy_ts, None); + assert_eq!(c.wake_deadline_ts, Some(deadline)); + assert_eq!(c.name, ACTOR_NAME); + assert_eq!(c.workflow_id, workflow_id.as_bytes()); + assert_eq!( + c.db_size_pages, 3, + "candidates report the SQLite head's size" + ); + + // A read by id returns the same facts as the listing, and an unknown id is not found. + let by_id = get_bytes( + dc, + &format!("actors/{actor_id}/candidate?namespace={namespace}"), + ) + .await + .unwrap(); + // A read by id carries no listing cursor; every fact matches the listing. + let by_id = proto::decode::(&by_id).unwrap(); + assert!(by_id.cursor.is_empty()); + assert!( + !c.cursor.is_empty(), + "a listed candidate carries its resume cursor" + ); + assert_eq!( + proto::Candidate { + cursor: c.cursor.clone(), + ..by_id + }, + c + ); + + // Resuming after the candidate's own cursor continues past it. + let after = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&c.cursor); + let resumed = get_bytes( + dc, + &format!("namespaces/{namespace}/candidates?limit=500&after={after}"), + ) + .await + .unwrap(); + let resumed = proto::decode::(&resumed).unwrap(); + assert!( + resumed.candidates.iter().all(|r| r.actor_id != c.actor_id), + "a listing resumed after a candidate's cursor does not repeat it" + ); + let unknown = Id::new_v1(dc.config.dc_label()); + let missing = get_bytes( + dc, + &format!("actors/{unknown}/candidate?namespace={namespace}"), + ) + .await + .unwrap_err(); + assert!( + missing.to_string().contains("actor_not_found"), + "unknown actor: {missing:#}" + ); + + // Export returns KV in key order, reassembled, and the SQLite pages, with a matching digest. + let exported = export(dc, &namespace, actor_id).await; + assert_eq!(exported.abort, None); + let mut expected_kv = seeded_kv(); + expected_kv.sort(); + let got_kv = exported + .kv + .iter() + .map(|e| (e.key.clone(), e.value.clone())) + .collect::>(); + assert_eq!(got_kv, expected_kv); + assert_eq!(exported.pages, seeded.pages); + let sqlite = exported.header.sqlite.clone().expect("actor has sqlite"); + assert_eq!(sqlite.db_size_pages, 3); + assert_eq!(sqlite.page_size, 4096); + let end = exported.end.expect("export should end"); + assert_eq!(end.digest, exported.digest); + assert_eq!(end.kv_entries, expected_kv.len() as u64); + assert_eq!(end.pages, 3); + assert_eq!(exported.header.generation, 1); + + // Cutover is idempotent by cutoverTs, and a stale generation is refused. + let cutover_ts = rivet_util::timestamp::now(); + let stale: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 7, + cutover_ts, + }, + ) + .await + .unwrap(); + assert_eq!(stale, proto::CutoverResponse::Woke); + for expected in [ + proto::CutoverResponse::Cut, + proto::CutoverResponse::AlreadyCut, + ] { + let res: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 1, + cutover_ts, + }, + ) + .await + .unwrap(); + assert_eq!(res, expected); + } + assert_eq!(destroy_ts(dc, actor_id).await, Some(cutover_ts)); + + // The gateway lookup now sees a destroyed actor and will not wake it. + let gateway = dc + .workflow_ctx + .op(pegboard::ops::actor::get_for_gateway::Input { actor_id }) + .await + .unwrap() + .unwrap(); + assert!(gateway.destroyed); + + // Confirm parks: the wake rows move into the parked record. A retry is idempotent. + let confirm = proto::ConfirmRequest { + generation: 1, + sleep_ts: c.sleep_ts.unwrap(), + wake_deadline_ts: c.wake_deadline_ts, + cutover_ts, + horizon_ms: 0, + v3_actor_id: actor_id.as_bytes(), + }; + for expected in [ + proto::ConfirmResponse::Confirmed, + proto::ConfirmResponse::AlreadyConfirmed, + ] { + let res: proto::ConfirmResponse = post( + dc, + &format!("actors/{actor_id}/confirm?namespace={namespace}"), + &confirm, + ) + .await + .unwrap(); + assert_eq!(res, expected); + } + assert!(raw_exists(dc, mkeys::parked(actor_id)).await); + assert!( + raw_exists(dc, mkeys::silence_ts(workflow_id)).await, + "park silences the workflow" + ); + assert_eq!(read_wake_deadline(dc, workflow_id).await, None); + assert!( + !raw_exists( + dc, + mkeys::deadline_wake_row(&workflow_name, workflow_id, deadline) + ) + .await + ); + assert_eq!( + raw_subspace_len(dc, mkeys::wake_signal_subspace(workflow_id)).await, + 0 + ); + assert!(candidate(dc, &namespace, actor_id).await.parked); + + // The alarm passes while parked and the actor must not wake. + let until_alarm = (seeded.alarm_ts - rivet_util::timestamp::now()).max(0) as u64; + assert_eq!( + wait_for_start( + &mut seeded.lifecycle_rx, + actor_id, + Duration::from_millis(until_alarm + 3_000) + ) + .await, + None, + "a parked actor must not wake on its alarm" + ); + + // Restore puts the rows back and clears the cutover. The overdue deadline then fires. + let res: proto::RestoreResponse = post( + dc, + &format!("actors/{actor_id}/restore?namespace={namespace}"), + &proto::RestoreRequest { + cutover_ts: Some(cutover_ts), + v3_actor_id: Some(actor_id.as_bytes()), + }, + ) + .await + .unwrap(); + assert_eq!(res, proto::RestoreResponse::Restored); + assert!(!raw_exists(dc, mkeys::parked(actor_id)).await); + assert!(!raw_exists(dc, mkeys::silence_ts(workflow_id)).await); + assert_eq!(destroy_ts(dc, actor_id).await, None); + + // A late duplicate of the original cutover must not cut the restored actor again. + let late: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 1, + cutover_ts, + }, + ) + .await + .unwrap(); + assert_eq!(late, proto::CutoverResponse::Woke); + assert_eq!(destroy_ts(dc, actor_id).await, None); + + let woke = + wait_for_start(&mut seeded.lifecycle_rx, actor_id, Duration::from_secs(15)).await; + assert_eq!(woke, Some(2), "restored actor wakes on its overdue alarm"); + + // A second restore finds nothing to do. + let res: proto::RestoreResponse = post( + dc, + &format!("actors/{actor_id}/restore?namespace={namespace}"), + &proto::RestoreRequest { + cutover_ts: Some(cutover_ts), + v3_actor_id: Some(actor_id.as_bytes()), + }, + ) + .await + .unwrap(); + assert_eq!(res, proto::RestoreResponse::NotParked); + + // Restore returned the original data. + let after = export_running_kv(dc, actor_id).await; + let mut expected_kv = seeded_kv(); + expected_kv.sort(); + assert_eq!(after, expected_kv); + + drop(seeded.envoy); + }, + ); +} + +/// A wake that read the actor before the cutover and lands after it must make confirm un-cut. +#[test] +fn migration_confirm_uncuts_when_a_wake_raced_the_cutover() { + common::run( + common::TestOpts::new(1).with_timeout(60), + |ctx| async move { + let dc = ctx.leader_dc(); + let mut seeded = seed_sleeping_actor(dc, 3_600_000).await; + let actor_id = seeded.actor_id; + let namespace = seeded.namespace.clone(); + let c = candidate(dc, &namespace, actor_id).await; + + let cutover_ts = rivet_util::timestamp::now(); + let res: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 1, + cutover_ts, + }, + ) + .await + .unwrap(); + assert_eq!(res, proto::CutoverResponse::Cut); + + // The in-flight wake: guard read the actor as sleeping before the cutover, then sends Wake. + dc.workflow_ctx + .signal(pegboard::workflows::actor2::Wake {}) + .to_workflow_id(seeded.workflow_id) + .send() + .await + .unwrap(); + + let res: proto::ConfirmResponse = post( + dc, + &format!("actors/{actor_id}/confirm?namespace={namespace}"), + &proto::ConfirmRequest { + generation: 1, + sleep_ts: c.sleep_ts.unwrap(), + wake_deadline_ts: c.wake_deadline_ts, + cutover_ts, + horizon_ms: 0, + v3_actor_id: actor_id.as_bytes(), + }, + ) + .await + .unwrap(); + assert!( + matches!(res, proto::ConfirmResponse::ConfirmWoke(_)), + "confirm must see the raced wake, got {res:?}" + ); + assert_eq!(destroy_ts(dc, actor_id).await, None, "confirm un-cuts"); + assert!(!raw_exists(dc, mkeys::parked(actor_id)).await); + + // The first cutover request arrives late, after the un-cut. It must not cut again. + let late: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 1, + cutover_ts, + }, + ) + .await + .unwrap(); + assert_eq!(late, proto::CutoverResponse::Woke); + assert_eq!(destroy_ts(dc, actor_id).await, None); + + // V2 keeps serving the actor: it wakes. + let woke = + wait_for_start(&mut seeded.lifecycle_rx, actor_id, Duration::from_secs(15)).await; + assert_eq!(woke, Some(2)); + }, + ); +} + +/// A confirm whose deadline is inside the horizon un-cuts, and an export of a running actor +/// aborts with `FenceMoved`. +#[test] +fn migration_refuses_every_route_until_the_migration_fix_backfill_completes() { + common::run( + common::TestOpts::new(1).with_timeout(60), + |ctx| async move { + let dc = ctx.leader_dc(); + let seeded = seed_sleeping_actor(dc, 3_600_000).await; + let namespace = seeded.namespace.clone(); + let actor_id = seeded.actor_id; + + // Remove the completion marker to stand in for an engine that has not finished the + // backfill yet. + let key = backfill_complete_key(); + let raw = dc + .workflow_ctx + .udb() + .unwrap() + .txn("test_clear_backfill_complete", |tx| { + let key = key.clone(); + async move { + let raw = tx.get(&key, Serializable).await?.context("marker")?; + tx.clear(&key); + Ok(raw.to_vec()) + } + }) + .await + .unwrap(); + + let err = get_bytes(dc, &format!("namespaces/{namespace}/candidates")) + .await + .unwrap_err(); + assert!( + format!("{err:#}").contains("backfill_incomplete"), + "candidates should be refused: {err:#}" + ); + let err = post::<_, proto::CutoverResponse>( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 1, + cutover_ts: rivet_util::timestamp::now(), + }, + ) + .await + .unwrap_err(); + assert!( + format!("{err:#}").contains("backfill_incomplete"), + "cutover should be refused: {err:#}" + ); + assert_eq!(destroy_ts(dc, actor_id).await, None); + + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_restore_backfill_complete", |tx| { + let key = key.clone(); + let raw = raw.clone(); + async move { + tx.set(&key, &raw); + Ok(()) + } + }) + .await + .unwrap(); + + candidate(dc, &namespace, actor_id).await; + }, + ); +} + +#[test] +fn migration_refuses_running_and_soon_waking_actors() { + common::run( + common::TestOpts::new(1).with_timeout(60), + |ctx| async move { + let dc = ctx.leader_dc(); + let mut seeded = seed_sleeping_actor(dc, 3_600_000).await; + let actor_id = seeded.actor_id; + let namespace = seeded.namespace.clone(); + let c = candidate(dc, &namespace, actor_id).await; + + let cutover_ts = rivet_util::timestamp::now(); + let _: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 1, + cutover_ts, + }, + ) + .await + .unwrap(); + let res: proto::ConfirmResponse = post( + dc, + &format!("actors/{actor_id}/confirm?namespace={namespace}"), + &proto::ConfirmRequest { + generation: 1, + sleep_ts: c.sleep_ts.unwrap(), + wake_deadline_ts: c.wake_deadline_ts, + cutover_ts, + horizon_ms: 7_200_000, + v3_actor_id: actor_id.as_bytes(), + }, + ) + .await + .unwrap(); + assert_eq!( + res, + proto::ConfirmResponse::ConfirmWoke(proto::ConfirmWoke { + reason: proto::WokeReason::DeadlineSoon + }) + ); + assert_eq!(destroy_ts(dc, actor_id).await, None); + + // Wake it and export while it runs. + dc.workflow_ctx + .signal(pegboard::workflows::actor2::Wake {}) + .to_workflow_id(seeded.workflow_id) + .send() + .await + .unwrap(); + assert_eq!( + wait_for_start(&mut seeded.lifecycle_rx, actor_id, Duration::from_secs(15)).await, + Some(2) + ); + let exported = export(dc, &namespace, actor_id).await; + assert_eq!(exported.abort, Some(proto::AbortReason::FenceMoved)); + assert!(exported.kv.is_empty()); + + // The cutover refuses a running actor. + let res: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 2, + cutover_ts: cutover_ts + 1, + }, + ) + .await + .unwrap(); + assert!( + matches!(res, proto::CutoverResponse::Ineligible(_)), + "got {res:?}" + ); + }, + ); +} + +/// Writes a hibernating request row for `actor_id` pinged at `last_ping_ts`, as a gateway's +/// keepalive does. +async fn write_hibernating_request( + dc: &common::TestDatacenter, + actor_id: Id, + last_ping_ts: i64, + request_id: [u8; 4], +) { + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_write_hibernating_request", |tx| async move { + let tx = tx.with_subspace(pegboard::keys::subspace()); + tx.write( + &pegboard::keys::actor::HibernatingRequestKey::new( + actor_id, + last_ping_ts, + [1, 2, 3, 4], + request_id, + ), + (), + )?; + Ok(()) + }) + .await + .unwrap(); +} + +/// A hibernating request row the gateway stopped pinging, as one a killed gateway leaves behind, +/// does not hold a sleeping actor in V2; a row pinged within the eligible threshold does. +#[test] +fn migration_counts_only_live_hibernating_requests() { + common::run( + common::TestOpts::new(1).with_timeout(60), + |ctx| async move { + let dc = ctx.leader_dc(); + let seeded = seed_sleeping_actor(dc, 3_600_000).await; + let actor_id = seeded.actor_id; + let namespace = seeded.namespace.clone(); + let threshold = dc + .workflow_ctx + .config() + .pegboard() + .hibernating_request_eligible_threshold(); + + let stale_ts = rivet_util::timestamp::now() - threshold - 60_000; + write_hibernating_request(dc, actor_id, stale_ts, [0, 0, 0, 1]).await; + let c = candidate(dc, &namespace, actor_id).await; + assert!(!c.hibernating, "a stale hibernating request held the actor"); + + write_hibernating_request(dc, actor_id, rivet_util::timestamp::now(), [0, 0, 0, 2]) + .await; + let c = candidate(dc, &namespace, actor_id).await; + assert!( + c.hibernating, + "a live hibernating request did not hold the actor" + ); + }, + ); +} + +/// An envoy key left on a sleeping actor whose workflow state holds no allocation, as a lost +/// allocate state change leaves it, does not hold the actor back from migrating. +#[test] +fn migration_ignores_an_envoy_key_the_workflow_state_does_not_hold() { + common::run( + common::TestOpts::new(1).with_timeout(60), + |ctx| async move { + let dc = ctx.leader_dc(); + let seeded = seed_sleeping_actor(dc, 3_600_000).await; + let actor_id = seeded.actor_id; + let namespace = seeded.namespace.clone(); + + dc.workflow_ctx + .udb() + .unwrap() + .txn("test_leave_envoy_key", |tx| async move { + tx.with_subspace(pegboard::keys::subspace()).write( + &pegboard::keys::actor::EnvoyKeyKey::new(actor_id), + "stale-envoy".to_string(), + )?; + Ok(()) + }) + .await + .unwrap(); + + let c = candidate(dc, &namespace, actor_id).await; + assert!( + !c.allocated, + "a stale envoy key should not read as allocated" + ); + + let res: proto::CutoverResponse = post( + dc, + &format!("actors/{actor_id}/cutover?namespace={namespace}"), + &proto::CutoverRequest { + generation: 1, + cutover_ts: rivet_util::timestamp::now(), + }, + ) + .await + .unwrap(); + assert_eq!(res, proto::CutoverResponse::Cut); + }, + ); +} + +/// Reads the actor's KV directly, as the actor would see it. +async fn export_running_kv(dc: &common::TestDatacenter, actor_id: Id) -> Vec<(Vec, Vec)> { + let udb = dc.workflow_ctx.udb().unwrap(); + let actor = dc + .workflow_ctx + .op(pegboard::ops::actor::get::Input { + actor_ids: vec![actor_id], + fetch_error: false, + }) + .await + .unwrap() + .actors + .into_iter() + .next() + .unwrap(); + let (keys, values, _) = pegboard::actor_kv::list( + &udb, + &pegboard::actor_kv::Recipient { + actor_id, + namespace_id: actor.namespace_id, + name: actor.name, + }, + rivet_envoy_protocol::KvListQuery::KvListAllQuery, + false, + None, + ) + .await + .unwrap(); + keys.into_iter().zip(values).collect() +} diff --git a/engine/packages/universaldb/src/utils/keys.rs b/engine/packages/universaldb/src/utils/keys.rs index 6974332972..fca23c3c5e 100644 --- a/engine/packages/universaldb/src/utils/keys.rs +++ b/engine/packages/universaldb/src/utils/keys.rs @@ -169,4 +169,8 @@ define_keys! { (141, JWT, "jwt"), (142, KEY_RING, "key_ring"), (143, PRIVATE_KEY, "private_key"), + // 144 is reserved. + (145, MIGRATION, "migration"), + (146, PARKED, "parked"), + (147, UNCUT, "uncut"), } diff --git a/engine/sdks/rust/v2-migration-protocol/Cargo.toml b/engine/sdks/rust/v2-migration-protocol/Cargo.toml new file mode 100644 index 0000000000..13ffd097a4 --- /dev/null +++ b/engine/sdks/rust/v2-migration-protocol/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "v2-migration-protocol" +publish = false +version.workspace = true +authors.workspace = true +license.workspace = true +edition.workspace = true + +[dependencies] +anyhow.workspace = true +serde_bare.workspace = true +serde.workspace = true +serde_bytes.workspace = true +vbare.workspace = true + +[build-dependencies] +vbare-compiler.workspace = true diff --git a/engine/sdks/rust/v2-migration-protocol/build.rs b/engine/sdks/rust/v2-migration-protocol/build.rs new file mode 100644 index 0000000000..b978c40987 --- /dev/null +++ b/engine/sdks/rust/v2-migration-protocol/build.rs @@ -0,0 +1,21 @@ +use std::path::Path; + +fn main() -> Result<(), Box> { + let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")?; + let workspace_root = Path::new(&manifest_dir) + .parent() + .and_then(|p| p.parent()) + .and_then(|p| p.parent()) + .ok_or("Failed to find workspace root")?; + + let schema_dir = workspace_root + .join("sdks") + .join("schemas") + .join("v2-migration-protocol"); + println!("cargo:rerun-if-changed={}", schema_dir.display()); + + let cfg = vbare_compiler::Config::default(); + vbare_compiler::process_schemas_with_config(&schema_dir, &cfg)?; + + Ok(()) +} diff --git a/engine/sdks/rust/v2-migration-protocol/src/generated.rs b/engine/sdks/rust/v2-migration-protocol/src/generated.rs new file mode 100644 index 0000000000..84801af8dc --- /dev/null +++ b/engine/sdks/rust/v2-migration-protocol/src/generated.rs @@ -0,0 +1 @@ +include!(concat!(env!("OUT_DIR"), "/combined_imports.rs")); diff --git a/engine/sdks/rust/v2-migration-protocol/src/lib.rs b/engine/sdks/rust/v2-migration-protocol/src/lib.rs new file mode 100644 index 0000000000..98f48277f1 --- /dev/null +++ b/engine/sdks/rust/v2-migration-protocol/src/lib.rs @@ -0,0 +1,63 @@ +//! Wire types for the V2 public API's `/migration/v1/` routes. +//! +//! Request and response bodies are raw BARE: the `/v1` path pins the schema version for both peers. +//! The parked record is persisted, so it alone carries a vbare version header (see [`versioned`]). + +use anyhow::{Context, Result, bail}; + +pub mod generated; +pub mod versioned; + +pub use generated::v1::*; + +/// Content type of the streamed export response. +pub const EXPORT_CONTENT_TYPE: &str = "application/x-rivet-v2-migration"; + +/// Content type of every other BARE request and response body. +pub const BARE_CONTENT_TYPE: &str = "application/x-bare"; + +/// Largest frame a reader accepts. Batches are capped well below this. +pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024; + +/// Encodes one export frame with its little-endian `u32` length prefix. +pub fn encode_frame(frame: &Frame) -> Result> { + let body = serde_bare::to_vec(frame).context("encode export frame")?; + let len = u32::try_from(body.len()).context("export frame too large")?; + + let mut out = Vec::with_capacity(4 + body.len()); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&body); + Ok(out) +} + +/// Splits one length-prefixed frame off the front of `buf`. +/// +/// Returns `None` until the whole frame is buffered. The returned bytes are the frame's BARE body, +/// which is also what the export digest chains over. +pub fn split_frame(buf: &[u8]) -> Result> { + if buf.len() < 4 { + return Ok(None); + } + + let len = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize; + if len > MAX_FRAME_BYTES { + bail!("export frame of {len} bytes exceeds the {MAX_FRAME_BYTES} byte limit"); + } + if buf.len() < 4 + len { + return Ok(None); + } + + Ok(Some((&buf[4..4 + len], 4 + len))) +} + +pub fn decode_frame(body: &[u8]) -> Result { + serde_bare::from_slice(body).context("decode export frame") +} + +pub fn encode(value: &T) -> Result> { + serde_bare::to_vec(value).context("encode migration message") +} + +pub fn decode(body: &[u8]) -> Result { + serde_bare::from_slice(body).context("decode migration message") +} diff --git a/engine/sdks/rust/v2-migration-protocol/src/versioned.rs b/engine/sdks/rust/v2-migration-protocol/src/versioned.rs new file mode 100644 index 0000000000..4cc2cc6bdc --- /dev/null +++ b/engine/sdks/rust/v2-migration-protocol/src/versioned.rs @@ -0,0 +1,45 @@ +//! Versioned wrapper for the one persisted type, the parked record. + +use anyhow::{Result, bail}; +use vbare::OwnedVersionedData; + +use crate::generated::v1; + +pub enum ParkedRecord { + V1(v1::ParkedRecord), +} + +impl OwnedVersionedData for ParkedRecord { + type Latest = v1::ParkedRecord; + + fn wrap_latest(latest: v1::ParkedRecord) -> Self { + ParkedRecord::V1(latest) + } + + fn unwrap_latest(self) -> Result { + match self { + ParkedRecord::V1(data) => Ok(data), + } + } + + fn deserialize_version(payload: &[u8], version: u16) -> Result { + match version { + 1 => Ok(ParkedRecord::V1(serde_bare::from_slice(payload)?)), + _ => bail!("invalid parked record version: {version}"), + } + } + + fn serialize_version(self, _version: u16) -> Result> { + match self { + ParkedRecord::V1(data) => serde_bare::to_vec(&data).map_err(Into::into), + } + } + + fn deserialize_converters() -> Vec Result> { + vec![Ok] + } + + fn serialize_converters() -> Vec Result> { + vec![Ok] + } +} diff --git a/engine/sdks/schemas/v2-migration-protocol/v1.bare b/engine/sdks/schemas/v2-migration-protocol/v1.bare new file mode 100644 index 0000000000..3d98536011 --- /dev/null +++ b/engine/sdks/schemas/v2-migration-protocol/v1.bare @@ -0,0 +1,238 @@ +# V2 to V3 actor migration protocol. +# +# Every request and response body of the V2 public API's `/migration/v1/` routes is one of these +# types. The `/v1` path pins the version, so request and response bodies carry no version header. +# V3's migrator holds a copy of this file. `ParkedRecord` is persisted in V2 and is the one type +# stored with a vbare version header. + +# MARK: Candidates + +type Candidate struct { + actorId: data + workflowId: data + name: str + key: optional + poolName: str + createTs: i64 + # 1 is the old actor workflow, 2 is actor2. + version: u8 + # 0 when the actor has never been allocated. + generation: u32 + sleepTs: optional + # An envoy key or a connectable marker is present. + allocated: bool + destroyTs: optional + # The workflow's wake deadline: an alarm or a retry. + wakeDeadlineTs: optional + hibernating: bool + # The actor's SQLite still lives in the KV-backed v1 format, or its v1 import is unfinished. + sqliteV1: bool + # The actor was already migrated and parked. + parked: bool + # Pages in the published SQLite v2 head, 0 when the actor has none. + dbSizePages: u32 + # The datastore's sampled estimate of the actor's KV bytes. Small actors may read as 0. + kvBytesEstimate: u64 + # Exclusive cursor that resumes the listing right after this candidate, so a caller that admits + # only part of a page continues from the last candidate it handled. Empty for a read by id. + cursor: data +} + +type CandidatesResponse struct { + candidates: list + # Exclusive cursor for the next page. None means the listing reached the end. + next: optional +} + +# MARK: Export + +type SqliteHead struct { + headTxid: u64 + dbSizePages: u32 + pageSize: u32 +} + +type ExportHeader struct { + generation: u32 + sleepTs: i64 + wakeDeadlineTs: optional + name: str + key: optional + poolName: str + createTs: i64 + kvBytesEstimate: u64 + sqlite: optional +} + +type KvEntry struct { + key: data + value: data + version: data + updateTs: i64 +} + +type KvBatch struct { + entries: list +} + +type PageBatch struct { + firstPgno: u32 + pages: list +} + +# Emitted after each internal transaction. `cursor` is an encoded `ExportCursor` the client passes +# back as `resume` to continue a broken stream. +type ExportFence struct { + cursor: data +} + +type ExportEnd struct { + kvEntries: u64 + kvBytes: u64 + pages: u32 + # Chained xxh3-128 over every KvBatch and PageBatch frame, in stream order. + digest: data +} + +type AbortReason enum { + FENCE_MOVED + DESTROYED + INELIGIBLE +} + +type ExportAbort struct { + reason: AbortReason +} + +type Frame union { + ExportHeader | + KvBatch | + PageBatch | + ExportFence | + ExportEnd | + ExportAbort +} + +# Opaque to the client. The server checks the fence it carries before resuming. +type ExportCursor struct { + generation: u32 + sleepTs: i64 + headTxid: optional + # The last KV key already sent. None means no KV entry was sent yet. + afterKvKey: optional + kvDone: bool + # The next SQLite page to send. + nextPgno: u32 + digest: data + kvEntries: u64 + kvBytes: u64 + pages: u32 +} + +# MARK: Cutover + +type CutoverRequest struct { + generation: u32 + cutoverTs: i64 +} + +type IneligibleReason enum { + NOT_SLEEPING + ALLOCATED + HIBERNATING + ACTOR_V1 + SQLITE_V1 +} + +type Cut void + +type AlreadyCut void + +type Woke void + +type Destroyed void + +type Ineligible struct { + reason: IneligibleReason +} + +type CutoverResponse union { + Cut | + AlreadyCut | + Woke | + Destroyed | + Ineligible +} + +# MARK: Confirm + +type ConfirmRequest struct { + generation: u32 + sleepTs: i64 + wakeDeadlineTs: optional + cutoverTs: i64 + horizonMs: i64 + v3ActorId: data +} + +type WokeReason enum { + NOT_CUT + GENERATION_MOVED + SLEEP_MOVED + ALLOCATED + HIBERNATING + WORKER_RUNNING + PENDING_SIGNAL + DEADLINE_MOVED + DEADLINE_SOON + SILENCED +} + +type Confirmed void + +type AlreadyConfirmed void + +type ConfirmWoke struct { + reason: WokeReason +} + +type ConfirmResponse union { + Confirmed | + AlreadyConfirmed | + ConfirmWoke | + Destroyed +} + +# MARK: Restore + +# `cutoverTs` must match the parked record when set. Unset restores whatever is parked, for +# recovery, which knows the actor but not its cutover. +type RestoreRequest struct { + cutoverTs: optional + # When set, restore refuses unless the parked record names this V3 actor. + v3ActorId: optional +} + +type Restored void + +type NotParked void + +type RestoreResponse union { + Restored | + NotParked +} + +# MARK: Parked record + +# Stored at `[MIGRATION, PARKED, actor_id]` with a vbare version header. Holds the wake index rows +# that park removed so restore can write them back. +type ParkedRecord struct { + generation: u32 + cutoverTs: i64 + parkedAt: i64 + v3ActorId: data + workflowId: data + workflowName: str + wakeDeadlineTs: optional + wakeSignals: list +}