diff --git a/.agents/skills/understanding-durable-execution/SKILL.md b/.agents/skills/understanding-durable-execution/SKILL.md index 7ebd39fd2cb..0d189fea75e 100644 --- a/.agents/skills/understanding-durable-execution/SKILL.md +++ b/.agents/skills/understanding-durable-execution/SKILL.md @@ -1649,6 +1649,7 @@ they remain `Retrying` without a semantic attempt limit. Known transient startup `RecoveryRequired`, so the durable loop backs off and reconstructs automatically while its callers wait. Infrastructure errors that stop the loop instead retry on the next demand (invoke, resume, scheduler activation, or shard reassignment). +Sandbox creation failures always request infrastructure recovery and retain rollback cleanup failures. Creation provisions an empty directory on the executor host; its failure does not establish a permanent fault in the agent or fail a pending update. After creation, filesystem startup preserves `FilesystemStorageError::is_terminal_failure`: permission denial, a read-only filesystem, invalid data and blocking-task panics fail the start with their cause instead of requesting unbounded recovery. `decide_seed_failure` selects a retry, a failure without invalidation, or invalidation through the effect policy and retry budget. Metadata reads invalidate the generation only for terminal storage errors. Both paths preserve the storage error, including a failed usage observation after a full-disk error. Permanent failures of a pending update take the outcome table's failed-update path with class `Operational`; transient filesystem failures retry the start. Cancelled blocking tasks retain infrastructure recovery. Rollback cleanup failures keep recovery classification and block startup until cleanup succeeds. Initial-file cache protection or sync failures return `Unavailable`; if removing the persisted file also fails, the error preserves both causes and the loader's cache directory owns the leftover file until shutdown cleanup. Invalid components, exports, snapshot baselines, replay divergence, and other permanent failures are terminal. An authoritative manual-update or promoted snapshot-assisted baseline that cannot be loaded is terminal, because recovery has no compatible replay fallback. A payload download failure is @@ -3676,6 +3677,8 @@ owner (`InvocationLoop::confirm_filesystem_snapshot_before_an_update`). The loop commands that arrive during the wait for the next generation. The unload deadline of the restart moves by the time of the wait, so the wait does not use it up. +Each filesystem restore run clears its destination first, even when the root is empty. Windows validates the opened root's canonical local-drive path before enumeration through that same retained handle; UNC and mapped network roots are unsupported. The walker pins ancestor directories against renames and deletes files, links and emptied directories by handle without clearing shared read-only attributes. It checks opened reparse tags and accepts only symbolic links and mount points. An unsupported root or unknown tag is a permanent restore failure. Windows snapshot restore sets times before read-only permissions. Capture does this for directories; regular files set times through their open handles. The initial-file loader persists its cache file before setting it read-only and syncing it, while the cache entry remains locked, so the first lease is read-only too. + `create_instance` restores the tree of the selected baseline. `StartFilesystem::load_and_plan` plans the baseline with `plan_start` and makes its restore, and `StartFilesystem::materialize` applies it to the new filesystem through `materialize_baseline`: the filesystem snapshot of a diff --git a/Cargo.lock b/Cargo.lock index 32dfa2d3f8a..f225ac744f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9830,7 +9830,7 @@ checksum = "fbcebf2228827bc4b61cb54dfd84cf43aacf06ca2dfe4c014b136a0e32b876e2" [[package]] name = "rustic_core" version = "0.13.0" -source = "git+https://github.com/golemcloud/rustic_core?rev=2269cbb0b2b89dc55cd4dca0172ead894b7b43fd#2269cbb0b2b89dc55cd4dca0172ead894b7b43fd" +source = "git+https://github.com/golemcloud/rustic_core?rev=a7001daf3f9e7230c4ad77c0c1395b38a3a602f6#a7001daf3f9e7230c4ad77c0c1395b38a3a602f6" dependencies = [ "aes256ctr_poly1305aes", "backon", diff --git a/Cargo.toml b/Cargo.toml index 8b2e4c91785..4e5ad633bc6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -391,8 +391,8 @@ wasmtime = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem wasmtime-wasi = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } wasmtime-wasi-http = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } wasmtime-wizer = { git = "https://github.com/golemcloud/wasmtime.git", branch = "golem-wasmtime-v50.0.1-p3" } -# The head of the branch `golem-rustic_core-v0.13.0` of the fork. -rustic_core = { git = "https://github.com/golemcloud/rustic_core", rev = "2269cbb0b2b89dc55cd4dca0172ead894b7b43fd" } +# Windows read-only metadata support on the fork's `fix-windows-permissions` branch. +rustic_core = { git = "https://github.com/golemcloud/rustic_core", rev = "a7001daf3f9e7230c4ad77c0c1395b38a3a602f6" } [profile.dev] panic = "abort" diff --git a/cli/golem-cli/src/command_handler/agent/invocation_session.rs b/cli/golem-cli/src/command_handler/agent/invocation_session.rs index bbd5c28e0c2..ac801c05948 100644 --- a/cli/golem-cli/src/command_handler/agent/invocation_session.rs +++ b/cli/golem-cli/src/command_handler/agent/invocation_session.rs @@ -1390,10 +1390,13 @@ fn write_checkpoint(path: &Path, checkpoint: &InvocationSessionCheckpoint) -> an error.error ) })?; - std::fs::File::open(parent) - .with_context(|| format!("failed to open session directory {}", parent.display()))? - .sync_all() - .with_context(|| format!("failed to sync session directory {}", parent.display()))?; + #[cfg(unix)] + { + std::fs::File::open(parent) + .with_context(|| format!("failed to open session directory {}", parent.display()))? + .sync_all() + .with_context(|| format!("failed to sync session directory {}", parent.display()))?; + } Ok(()) } diff --git a/cli/golem-cli/src/command_handler/agent/stream.rs b/cli/golem-cli/src/command_handler/agent/stream.rs index 6da9824db32..4dd3a9e1930 100644 --- a/cli/golem-cli/src/command_handler/agent/stream.rs +++ b/cli/golem-cli/src/command_handler/agent/stream.rs @@ -21,7 +21,6 @@ use crate::model::agent::AgentLogStreamOptions; use crate::model::format::Format; use anyhow::{Context, anyhow}; use bytes::Bytes; -use futures_util::future::Either; use futures_util::stream::{SplitSink, SplitStream}; use futures_util::{SinkExt, StreamExt, future}; use golem_common::model::InvocationId; @@ -45,7 +44,7 @@ use tokio_tungstenite::tungstenite::handshake::client::Request; use tokio_tungstenite::{ Connector, MaybeTlsStream, WebSocketStream, connect_async_tls_with_config, tungstenite, }; -use tokio_util::task::AbortOnDropHandle; +use tokio_util::sync::CancellationToken; use tracing::{debug, error, info, trace}; use url::Url; @@ -145,6 +144,7 @@ pub struct LiveOutput { options: AgentLogStreamOptions, goal: Option, connection: std::sync::Mutex>>>, + stop: CancellationToken, } impl LiveOutput { @@ -161,6 +161,7 @@ impl LiveOutput { options, goal: wait_for_invocation.then(InvocationGoal::new), connection: std::sync::Mutex::new(None), + stop: CancellationToken::new(), } } @@ -200,6 +201,7 @@ impl LiveOutput { ) .await?; connection.goal = self.goal.clone(); + connection.stop = self.stop.clone(); let mut slot = self.connection.lock().unwrap(); if slot.is_none() { *slot = Some(tokio::spawn(connection.run_forever())); @@ -214,12 +216,27 @@ impl LiveOutput { goal.set_output_written(); } let handle = self.connection.lock().unwrap().take(); - if let Some(mut handle) = handle - && time::timeout(Duration::from_secs(3), &mut handle) + if let Some(handle) = handle { + Self::finish_listener(handle, &self.stop).await; + } + } + + async fn finish_listener( + mut handle: task::JoinHandle>, + stop: &CancellationToken, + ) { + if time::timeout(Duration::from_secs(3), &mut handle) + .await + .is_err() + { + stop.cancel(); + if time::timeout(Duration::from_secs(2), &mut handle) .await .is_err() - { - handle.abort(); + { + handle.abort(); + let _ = handle.await; + } } } } @@ -331,6 +348,7 @@ pub struct AgentConnection { agent_name: String, goal: Option, ping_interval: Duration, + stop: CancellationToken, } impl AgentConnection { @@ -370,6 +388,7 @@ impl AgentConnection { agent_name, goal: wait_for_invocation.then(InvocationGoal::new), ping_interval, + stop: CancellationToken::new(), }) } @@ -382,7 +401,9 @@ impl AgentConnection { /// Creates a new worker connection and every time the connection is dropped tries to /// reconnect. The loop exits when the invocation goal is reached. pub async fn run_forever(self) -> anyhow::Result<()> { - while !self.goal.as_ref().is_some_and(InvocationGoal::is_reached) { + while !self.stop.is_cancelled() + && !self.goal.as_ref().is_some_and(InvocationGoal::is_reached) + { if let Err(error) = self.run().await && error .downcast_ref::() @@ -440,28 +461,29 @@ impl AgentConnection { Err(error) => return Err(anyhow!("Websocket connect failed, error: {}", error)), }; - let (write, read) = ws_stream.split(); - - let ping_interval = self.ping_interval; - let pings = AbortOnDropHandle::new(task::spawn(async move { - Self::ping_loop(write, ping_interval).await - })); - - let output = self.output.clone(); - let agent_name = self.agent_name.clone(); - let goal = self.goal.clone(); - let read_messages = AbortOnDropHandle::new(task::spawn(async move { - Self::read_loop(read, output, agent_name, goal).await; - })); - - // Both tasks end with this connection, also when the caller drops it: a detached read - // loop of a dropped connection would show events again after the reconnect. - match future::select(pings, read_messages).await { - Either::Left((Ok(result), _)) => Err(result), - Either::Left((Err(err), _)) => Err(anyhow!(err)), - Either::Right((Ok(_), _)) => Ok(()), - Either::Right((Err(err), _)) => Err(anyhow!(err)), - } + let (mut write, mut read) = ws_stream.split(); + // Poll both halves in this task, so neither can outlive the connection or keep sending + // pings after the invocation finishes. + let result = tokio::select! { + () = self.stop.cancelled() => Ok(()), + error = Self::ping_loop(&mut write, self.ping_interval) => Err(error), + () = Self::read_loop( + &mut read, self.output.clone(), self.agent_name.clone(), self.goal.clone(), + ) => Ok(()), + }; + // A missing peer close must not delay a completed invocation indefinitely. + let _ = time::timeout(Duration::from_secs(1), async { + write.close().await?; + while let Some(message) = read.next().await { + if let message @ Message::Close(_) = message? { + let _ = Self::parse_websocket_message(message); + break; + } + } + Ok::<_, tungstenite::Error>(()) + }) + .await; + result } async fn emit(output: &AgentStreamOutput, agent_name: &str, event: AgentEvent) { @@ -630,7 +652,7 @@ impl AgentConnection { } async fn ping_loop( - mut write: SplitSink>, Message>, + write: &mut SplitSink>, Message>, ping_interval: Duration, ) -> anyhow::Error { let mut interval = time::interval(ping_interval); @@ -653,7 +675,7 @@ impl AgentConnection { } async fn read_loop( - mut read: SplitStream>>, + read: &mut SplitStream>>, output: AgentStreamOutput, agent_name: String, goal: Option, @@ -681,6 +703,10 @@ impl AgentConnection { let message = match message { None => break Ok(()), Some(Err(error)) => break Err(error), + Some(Ok(message @ Message::Close(_))) => { + let _ = Self::parse_websocket_message(message); + break Ok(()); + } Some(Ok(message)) => message, }; match Self::parse_websocket_message(message) { @@ -779,6 +805,7 @@ mod tests { use test_r::test; use tokio::net::TcpListener; use tokio_tungstenite::accept_async; + use tokio_util::task::AbortOnDropHandle; use uuid::Uuid; async fn connection(url: Url) -> anyhow::Result { @@ -867,7 +894,14 @@ mod tests { if close { websocket.close(None).await.unwrap(); } else { - future::pending::<()>().await; + loop { + match websocket.next().await { + Some(Ok(Message::Close(_))) => break, + Some(Ok(_)) => {} + other => panic!("expected the client close handshake, got {other:?}"), + } + } + websocket.flush().await.unwrap(); } } @@ -1021,6 +1055,50 @@ mod tests { } } + #[test] + async fn peer_initiated_close_is_acknowledged() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap(); + let connection = connection(url).await.unwrap(); + + time::timeout(Duration::from_secs(5), async { + let (result, ()) = tokio::join!(connection.run(), async { + let (socket, _) = listener.accept().await.unwrap(); + let mut websocket = accept_async(socket).await.unwrap(); + websocket.close(None).await.unwrap(); + loop { + match websocket.next().await { + Some(Ok(Message::Close(_))) => break, + Some(Ok(Message::Ping(_) | Message::Pong(_))) => {} + other => panic!("expected the peer close acknowledgement, got {other:?}"), + } + } + }); + result.unwrap(); + }) + .await + .expect("the client must flush its reply to a peer-initiated close"); + } + + #[test] + async fn trigger_stream_timeout_sends_a_close_handshake() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap(); + let mut connection = connection(url).await.unwrap(); + connection.goal = None; + let stop = connection.stop.clone(); + let run = tokio::spawn(connection.run_forever()); + time::timeout(Duration::from_secs(6), async { + let ((), ()) = tokio::join!( + LiveOutput::finish_listener(run, &stop), + send_events(listener, Vec::new(), false), + ); + }) + .await + .expect("the trigger timeout must close the socket and finish the listener"); + assert!(stop.is_cancelled()); + } + #[test] async fn invocation_stream_waits_for_target_finish_after_nested_calls() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -1071,6 +1149,9 @@ mod tests { .expect("setting an already finished target must end the stream") .unwrap() .unwrap(); - server.abort(); + time::timeout(Duration::from_secs(2), server) + .await + .expect("the client must send a close frame") + .unwrap(); } } diff --git a/golem-registry-service/src/grpc/mod.rs b/golem-registry-service/src/grpc/mod.rs index 3226dd07e5d..8090b97f510 100644 --- a/golem-registry-service/src/grpc/mod.rs +++ b/golem-registry-service/src/grpc/mod.rs @@ -95,7 +95,8 @@ pub async fn start_grpc_server( services .component_compilation_service - .set_own_grpc_port(port); + .set_own_grpc_port(port) + .await; Ok(port) } diff --git a/golem-registry-service/src/repo/plugin.rs b/golem-registry-service/src/repo/plugin.rs index e73330309d1..819372c93a7 100644 --- a/golem-registry-service/src/repo/plugin.rs +++ b/golem-registry-service/src/repo/plugin.rs @@ -5,8 +5,8 @@ use conditional_trait_gen::trait_gen; use golem_service_base::db::postgres::PostgresPool; use golem_service_base::db::sqlite::SqlitePool; use golem_service_base::db::{Pool, PoolApi}; +use golem_service_base::repo::RepoResult; use golem_service_base::repo::SqlDateTime; -use golem_service_base::repo::{RepoResult, ResultExt}; use indoc::indoc; use tracing::{Instrument, Span, info_span}; use uuid::Uuid; @@ -127,7 +127,7 @@ impl DbPluginRepo { #[golem_async_trait::region_simple] impl PluginRepo for DbPluginRepo { async fn create(&self, plugin: PluginRecord) -> RepoResult> { - self.with_rw("create").fetch_one_as( + self.with_rw("create").fetch_optional_as( sqlx::query_as(indoc! {r#" INSERT INTO plugins (plugin_id, account_id, name, version, @@ -138,6 +138,7 @@ impl PluginRepo for DbPluginRepo { component_id, component_revision_id, wasm_content_hash) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19) + ON CONFLICT DO NOTHING RETURNING plugin_id, account_id, name, version, created_at, created_by, deleted_at, deleted_by, @@ -163,7 +164,7 @@ impl PluginRepo for DbPluginRepo { .bind(plugin.component_id) .bind(plugin.component_revision_id) .bind(plugin.wasm_content_hash), - ).await.none_on_unique_violation() + ).await } async fn delete(&self, plugin_id: Uuid, actor: Uuid) -> RepoResult> { diff --git a/golem-registry-service/src/services/component_compilation.rs b/golem-registry-service/src/services/component_compilation.rs index a6656985fcb..dc42bccde93 100644 --- a/golem-registry-service/src/services/component_compilation.rs +++ b/golem-registry-service/src/services/component_compilation.rs @@ -25,8 +25,7 @@ use golem_common::model::diff::Hash; use golem_common::model::environment::EnvironmentId; use golem_service_base::grpc::client::GrpcClient; use std::fmt::{Debug, Formatter}; -use std::sync::Arc; -use std::sync::atomic::{AtomicU16, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; use tonic::codec::CompressionEncoding; use tonic::transport::Channel; @@ -42,7 +41,7 @@ pub trait ComponentCompilationService: Debug + Send + Sync { wasm_hash: Hash, ); - fn set_own_grpc_port(&self, grpc_port: u16); + async fn set_own_grpc_port(&self, grpc_port: u16); } pub fn configured(config: &ComponentCompilationConfig) -> Arc { @@ -54,9 +53,45 @@ pub fn configured(config: &ComponentCompilationConfig) -> Arc }, + Ready { port: u16 }, +} + +enum Event { + Enqueue(Compilation), + SetPort(u16), +} + +fn transition(state: &mut State, event: Event) -> Vec<(Compilation, u16)> { + match event { + Event::Enqueue(request) => match state { + State::WaitingForPort { pending } => { + pending.push(request); + Vec::new() + } + State::Ready { port } => vec![(request, *port)], + }, + Event::SetPort(port) => { + let pending = match std::mem::replace(state, State::Ready { port }) { + State::WaitingForPort { pending } => pending, + State::Ready { .. } => Vec::new(), + }; + pending.into_iter().map(|request| (request, port)).collect() + } + } +} + pub struct GrpcComponentCompilationService { client: GrpcClient>>, - own_grpc_port: AtomicU16, + state: Mutex, enqueue_timeout: Duration, } @@ -76,34 +111,21 @@ impl GrpcComponentCompilationService { ); Self { client, - own_grpc_port: AtomicU16::new(0), + state: Mutex::new(State::WaitingForPort { + pending: Vec::new(), + }), enqueue_timeout: config.enqueue_timeout, } } -} - -impl Debug for GrpcComponentCompilationService { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - f.debug_struct("ComponentCompilationServiceDefault") - .finish() - } -} - -#[async_trait] -#[golem_async_trait::region_simple] -impl ComponentCompilationService for GrpcComponentCompilationService { - async fn enqueue_compilation( - &self, - environment_id: EnvironmentId, - component_id: ComponentId, - component_revision: ComponentRevision, - wasm_hash: Hash, - ) { - let component_service_port = match self.own_grpc_port.load(Ordering::Acquire) { - 0 => None, - port => Some(port as u32), - }; + async fn send_compilation(&self, request: Compilation, port: u16) { + let Compilation { + environment_id, + component_id, + component_revision, + wasm_hash, + } = request; + let component_service_port = Some(port as u32); let call = self.client.call("enqueue-compilation", move |client| { Box::pin(async move { let request = ComponentCompilationRequest { @@ -150,9 +172,44 @@ impl ComponentCompilationService for GrpcComponentCompilationService { .with_label_values(&[outcome]) .inc(); } +} + +impl Debug for GrpcComponentCompilationService { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ComponentCompilationServiceDefault") + .finish() + } +} + +#[async_trait] +#[golem_async_trait::region_simple] +impl ComponentCompilationService for GrpcComponentCompilationService { + async fn enqueue_compilation( + &self, + environment_id: EnvironmentId, + component_id: ComponentId, + component_revision: ComponentRevision, + wasm_hash: Hash, + ) { + let ready = transition( + &mut self.state.lock().unwrap(), + Event::Enqueue(Compilation { + environment_id, + component_id, + component_revision, + wasm_hash, + }), + ); + for (request, port) in ready { + self.send_compilation(request, port).await; + } + } - fn set_own_grpc_port(&self, grpc_port: u16) { - self.own_grpc_port.store(grpc_port, Ordering::Release); + async fn set_own_grpc_port(&self, grpc_port: u16) { + let ready = transition(&mut self.state.lock().unwrap(), Event::SetPort(grpc_port)); + for (request, port) in ready { + self.send_compilation(request, port).await; + } } } @@ -176,7 +233,7 @@ impl ComponentCompilationService for DisabledComponentCompilationService { _wasm_hash: Hash, ) { } - fn set_own_grpc_port(&self, _grpc_port: u16) {} + async fn set_own_grpc_port(&self, _grpc_port: u16) {} } #[cfg(test)] @@ -197,7 +254,7 @@ mod tests { use tokio_stream::wrappers::TcpListenerStream; use tonic::{Request, Response, Status}; - struct CompilationServer; + struct CompilationServer(tokio::sync::mpsc::UnboundedSender); #[async_trait] #[golem_async_trait::region_simple] @@ -206,7 +263,9 @@ mod tests { &self, request: Request, ) -> Result, Status> { - let result = match request.into_inner().component_revision { + let request = request.into_inner(); + self.0.send(request.clone()).unwrap(); + let result = match request.component_revision { 0 => Some(component_compilation_response::Result::Success(Empty {})), revision @ (1 | 2) => Some(component_compilation_response::Result::Failure( ComponentCompilationError { @@ -252,16 +311,43 @@ mod tests { multiplier: 1.0, max_jitter_factor: None, }; + let (sent, mut received) = tokio::sync::mpsc::unbounded_channel(); tasks.spawn( tonic::transport::Server::builder() .add_service( - ComponentCompilationServiceServer::new(CompilationServer) + ComponentCompilationServiceServer::new(CompilationServer(sent)) .accept_compressed(CompressionEncoding::Gzip) .send_compressed(CompressionEncoding::Gzip), ) .serve_with_incoming(TcpListenerStream::new(listener)), ); let service = GrpcComponentCompilationService::new(&config); + let initial = [ + (EnvironmentId::new(), ComponentId::new()), + (EnvironmentId::new(), ComponentId::new()), + ]; + for (environment_id, component_id) in initial { + service + .enqueue_compilation( + environment_id, + component_id, + ComponentRevision::INITIAL, + Hash::empty(), + ) + .await; + } + assert!( + received.try_recv().is_err(), + "bootstrap must not enqueue before the registry listens" + ); + service.set_own_grpc_port(12345).await; + for (environment_id, component_id) in initial { + let request = received.recv().await.unwrap(); + assert_eq!(request.environment_id, Some(environment_id.into())); + assert_eq!(request.component_id, Some(component_id.into())); + assert_eq!(request.component_service_port, Some(12345)); + assert_eq!(request.wasm_hash, Some(Hash::empty().into())); + } for (revision, outcome) in [ (0, "accepted"), (1, "rejected"), @@ -299,6 +385,7 @@ mod tests { let stalled_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); config.port = stalled_listener.local_addr().unwrap().port(); let stalled_service = GrpcComponentCompilationService::new(&config); + stalled_service.set_own_grpc_port(12345).await; let outcomes = ["accepted", "rejected", "failed", "timeout"]; let counters = outcomes .map(|label| crate::metrics::COMPILATION_ENQUEUE_TOTAL.with_label_values(&[label])); diff --git a/golem-registry-service/tests/repo/common.rs b/golem-registry-service/tests/repo/common.rs index 74a14d0f806..0fed79874d9 100644 --- a/golem-registry-service/tests/repo/common.rs +++ b/golem-registry-service/tests/repo/common.rs @@ -4235,7 +4235,8 @@ pub async fn test_component_stage(deps: &Deps) { let component_name = "test-component"; let component_id = new_repo_uuid(); - deps.plugin_repo + let plugin = deps + .plugin_repo .create(PluginRecord { plugin_id: new_repo_uuid(), account_id: app.account_id, @@ -4258,6 +4259,38 @@ pub async fn test_component_stage(deps: &Deps) { .unwrap() .unwrap(); + assert_eq!( + deps.plugin_repo + .create(PluginRecord { + plugin_id: new_repo_uuid(), + description: "must not overwrite the existing plugin".into(), + ..plugin.clone() + }) + .await + .unwrap(), + None + ); + assert_eq!( + deps.plugin_repo + .get_by_name_and_version(app.account_id, "a", "1.0.0") + .await + .unwrap() + .unwrap() + .plugin, + plugin + ); + + assert_eq!( + deps.plugin_repo + .create(PluginRecord { + name: "same-id-other-name".into(), + ..plugin.clone() + }) + .await + .unwrap(), + None + ); + deps.plugin_repo .create(PluginRecord { plugin_id: new_repo_uuid(), diff --git a/golem-worker-executor/Cargo.toml b/golem-worker-executor/Cargo.toml index 101ea99a851..c081a2102fa 100644 --- a/golem-worker-executor/Cargo.toml +++ b/golem-worker-executor/Cargo.toml @@ -125,7 +125,7 @@ wasmtime-wasi-http = { workspace = true } zstd = { workspace = true } [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Storage_FileSystem"] } +windows-sys = { workspace = true, features = ["Win32_Storage_FileSystem", "Win32_System_SystemServices"] } [target.'cfg(unix)'.dependencies] libc = { workspace = true } diff --git a/golem-worker-executor/src/filesystem/sandbox/host_adapter/directory_provisioning/mod.rs b/golem-worker-executor/src/filesystem/sandbox/host_adapter/directory_provisioning/mod.rs index 2e40f923452..60b59d42364 100644 --- a/golem-worker-executor/src/filesystem/sandbox/host_adapter/directory_provisioning/mod.rs +++ b/golem-worker-executor/src/filesystem/sandbox/host_adapter/directory_provisioning/mod.rs @@ -21,7 +21,6 @@ use super::{NativeNameModeSource, NativeRoot, QuotaAuthority, SandboxFilesystem} use crate::filesystem::sandbox::FilesystemStorageError; use crate::filesystem::volume::FilesystemVolume; use golem_common::model::RetryConfig; -use std::fs::File; use std::future::Future; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -131,17 +130,22 @@ impl DirectoryProvisioning { root: PathBuf, lifecycle: OwnedMutexGuard<()>, ) -> Result { - let directory = match File::open(&root) { - Ok(directory) => directory, - Err(error) => { - return Err(rollback_creation( - &root, - FilesystemStorageError::io("open fresh runtime directory", Some(&root), error), - &self.cleanup_retry, - ) - .await); - } - }; + let directory = + match cap_std::fs::Dir::open_ambient_dir(&root, cap_std::ambient_authority()) { + Ok(directory) => directory.into_std_file(), + Err(error) => { + return Err(rollback_creation( + &root, + FilesystemStorageError::io( + "open fresh runtime directory", + Some(&root), + error, + ), + &self.cleanup_retry, + ) + .await); + } + }; let native_root = match NativeRoot::initialize(root.clone(), directory).await { Ok(native_root) => native_root, Err(error) => { diff --git a/golem-worker-executor/src/filesystem/sandbox/host_adapter/mod.rs b/golem-worker-executor/src/filesystem/sandbox/host_adapter/mod.rs index c217d503b47..cb9b058b7f2 100644 --- a/golem-worker-executor/src/filesystem/sandbox/host_adapter/mod.rs +++ b/golem-worker-executor/src/filesystem/sandbox/host_adapter/mod.rs @@ -1435,7 +1435,7 @@ impl HostHandle { ) -> std::io::Result<()> { let file = match self { Self::File(file) => file.as_ref().try_clone()?.into_std(), - Self::Directory(directory) => directory.open(Component::CurDir)?.into_std(), + Self::Directory(directory) => return native_io::flush_directory(directory, level), }; let result = match level { SandboxFlushLevel::Data => file.sync_data(), @@ -1447,7 +1447,7 @@ impl HostHandle { #[cfg(unix)] mod native_io { - use super::{HostHandle, SandboxAccessMode}; + use super::{HostHandle, SandboxAccessMode, SandboxFlushLevel}; use cap_std::fs::{File, FileExt as _, OpenOptions}; pub(super) fn set_times_right(_options: &mut OpenOptions, _access: SandboxAccessMode) {} @@ -1460,6 +1460,17 @@ mod native_io { file.write_at(bytes, offset) } + pub(super) fn flush_directory( + directory: &cap_std::fs::Dir, + level: SandboxFlushLevel, + ) -> std::io::Result<()> { + let directory = directory.try_clone()?.into_std_file(); + match level { + SandboxFlushLevel::Data => directory.sync_data(), + SandboxFlushLevel::DataAndMetadata => directory.sync_all(), + } + } + pub(super) fn flush_result( _handle: &HostHandle, result: std::io::Result<()>, @@ -1470,7 +1481,7 @@ mod native_io { #[cfg(windows)] mod native_io { - use super::{HostHandle, SandboxAccessMode}; + use super::{HostHandle, SandboxAccessMode, SandboxFlushLevel}; use cap_std::fs::{File, FileExt as _, OpenOptions, OpenOptionsExt as _}; use windows_sys::Win32::Storage::FileSystem::{FILE_GENERIC_READ, FILE_WRITE_ATTRIBUTES}; @@ -1490,6 +1501,14 @@ mod native_io { file.seek_write(bytes, offset) } + pub(super) fn flush_directory( + _directory: &cap_std::fs::Dir, + _level: SandboxFlushLevel, + ) -> std::io::Result<()> { + // Windows does not support FlushFileBuffers on directories. + Ok(()) + } + pub(super) fn flush_result( handle: &HostHandle, result: std::io::Result<()>, diff --git a/golem-worker-executor/src/filesystem/sandbox/host_adapter/tests.rs b/golem-worker-executor/src/filesystem/sandbox/host_adapter/tests.rs index 36acb44f294..b3ea2eafde6 100644 --- a/golem-worker-executor/src/filesystem/sandbox/host_adapter/tests.rs +++ b/golem-worker-executor/src/filesystem/sandbox/host_adapter/tests.rs @@ -130,6 +130,173 @@ async fn only_bounded_work_on_known_local_storage_can_run_in_place() { filesystem.delete_and_verify().await.unwrap(); } +#[test] +#[test_r::timeout("30s")] +async fn directory_backends_support_guest_io_capture_and_cleanup() { + let parent = tempfile::tempdir().unwrap(); + for storage in [ + FilesystemStorageMode::Temporary, + FilesystemStorageMode::Directory { + root: parent.path().join("sandboxes").into(), + }, + ] { + let provisioning = + SandboxFilesystemProvisioning::new(&storage, RetryConfig::default()).unwrap(); + let filesystem = provisioning.create_fresh(sandbox_name()).await.unwrap(); + let root = filesystem.root().to_path_buf(); + let file = filesystem + .open( + SandboxPath::at_root("note"), + file_open( + SandboxAccessMode::ReadWrite, + SandboxFileDisposition::CreateExclusive, + ), + ) + .await + .unwrap(); + let SandboxHandle::File(opened) = &file else { + panic!("note must be a file") + }; + let written = filesystem + .write( + opened, + SandboxWritePlacement::At(0), + Bytes::from_static(b"contents"), + ) + .await + .unwrap(); + assert_eq!(written.written, 8); + written.result.unwrap(); + filesystem.close(file).await.unwrap(); + let modified = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000); + fs_set_times::set_times( + &root, + None, + Some(fs_set_times::SystemTimeSpec::Absolute(modified)), + ) + .unwrap(); + let directory = filesystem + .open( + SandboxPath::at_root("."), + existing_open(SandboxObjectKind::Directory, SandboxAccessMode::Read), + ) + .await + .unwrap(); + for level in [SandboxFlushLevel::Data, SandboxFlushLevel::DataAndMetadata] { + filesystem.flush(&directory, level).await.unwrap(); + } + let target = create_scratch_directory(parent.path()).await; + filesystem + .copy_contents( + SandboxPath::at_root("."), + Arc::new(TreeExclusions::new(std::iter::empty::())), + target.path(), + ) + .await + .unwrap(); + assert_eq!( + std::fs::read(target.path().as_path().join("note")).unwrap(), + b"contents" + ); + assert_eq!( + target + .path() + .as_path() + .metadata() + .unwrap() + .modified() + .unwrap(), + modified + ); + filesystem.close(directory).await.unwrap(); + target.discard().await.unwrap(); + filesystem.delete_and_verify().await.unwrap(); + assert!(!root.exists()); + } +} + +#[test] +#[test_r::timeout("30s")] +async fn capture_and_seed_preserve_readonly_nested_contents_and_times() { + let parent = tempfile::tempdir().unwrap(); + let provisioning = directory_sandbox_provisioning(parent.path().join("sandboxes")); + let name = |name: &str| { + SandboxFilesystemName::new("environment".into(), "component".into(), name.into()).unwrap() + }; + let source = provisioning.create_fresh(name("source")).await.unwrap(); + let nested = source.root().join("nested"); + std::fs::create_dir(&nested).unwrap(); + std::fs::write(nested.join("note"), b"saved contents").unwrap(); + std::fs::write(source.root().join("writable"), b"control").unwrap(); + let modified = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000); + let mut original = Vec::new(); + for path in [nested.join("note"), nested.clone()] { + fs_set_times::set_times( + &path, + None, + Some(fs_set_times::SystemTimeSpec::Absolute(modified)), + ) + .unwrap(); + let permissions = path.metadata().unwrap().permissions(); + original.push(permissions.clone()); + let mut readonly = permissions; + readonly.set_readonly(true); + std::fs::set_permissions(path, readonly).unwrap(); + } + let captured = create_scratch_directory(parent.path()).await; + source + .copy_contents( + SandboxPath::at_root("."), + Arc::new(TreeExclusions::new(std::iter::empty::())), + captured.path(), + ) + .await + .unwrap(); + let seeded = provisioning.create_fresh(name("seeded")).await.unwrap(); + seed_one_entry( + &seeded, + make_seed_entry( + captured.path().clone(), + "restored", + SeedAccess::FromSource, + SeedPlacement::Replace, + ), + ) + .await + .unwrap(); + let seeded_root = seeded.root().join("restored"); + for root in [captured.path().as_path(), seeded_root.as_path()] { + assert_eq!( + std::fs::read(root.join("nested/note")).unwrap(), + b"saved contents" + ); + assert!( + !root + .join("writable") + .metadata() + .unwrap() + .permissions() + .readonly() + ); + for path in [root.join("nested/note"), root.join("nested")] { + let metadata = path.metadata().unwrap(); + assert!(metadata.permissions().readonly()); + assert_eq!(metadata.modified().unwrap(), modified); + } + } + for root in [ + source.root(), + captured.path().as_path(), + seeded_root.as_path(), + ] { + std::fs::set_permissions(root.join("nested"), original[1].clone()).unwrap(); + std::fs::set_permissions(root.join("nested/note"), original[0].clone()).unwrap(); + } + source.delete_and_verify().await.unwrap(); + seeded.delete_and_verify().await.unwrap(); + captured.discard().await.unwrap(); +} + async fn spawned(future: F) -> F::Output { let (result, modes) = crate::filesystem::blocking::record_tasks(future).await; assert!(!modes.is_empty(), "the operation must dispatch native work"); @@ -827,8 +994,6 @@ async fn positioned_write_preserves_the_shared_file_cursor() { #[test] async fn path_attributes_report_write_permission_and_object_identity() { - use std::os::unix::fs::PermissionsExt as _; - let parent = tempfile::tempdir().unwrap(); let filesystem = directory_sandbox_provisioning(parent.path().to_path_buf()) .create_fresh(sandbox_name()) @@ -836,7 +1001,10 @@ async fn path_attributes_report_write_permission_and_object_identity() { .unwrap(); let root = filesystem.root().to_path_buf(); std::fs::write(root.join("file"), b"file").unwrap(); - std::fs::set_permissions(root.join("file"), std::fs::Permissions::from_mode(0o444)).unwrap(); + let permissions = std::fs::metadata(root.join("file")).unwrap().permissions(); + let mut read_only_permissions = permissions.clone(); + read_only_permissions.set_readonly(true); + std::fs::set_permissions(root.join("file"), read_only_permissions).unwrap(); std::fs::hard_link(root.join("file"), root.join("alias")).unwrap(); std::fs::write(root.join("other"), b"other").unwrap(); let read = |path: &'static str| { @@ -859,6 +1027,7 @@ async fn path_attributes_report_write_permission_and_object_identity() { assert_eq!(file.link_count, 2); assert_eq!(file.object, alias.object); assert_ne!(file.object, other.object); + std::fs::set_permissions(root.join("file"), permissions).unwrap(); SandboxFilesystem::delete_and_verify(filesystem) .await .unwrap(); diff --git a/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/mod.rs b/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/mod.rs index b687cc3f7c0..e0be99fd586 100644 --- a/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/mod.rs +++ b/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/mod.rs @@ -711,18 +711,6 @@ pub(in crate::filesystem::sandbox) fn set_copied_directory_attributes( ) } -/// Gives the host directory at `directory` the permissions `permissions` and, where it is given, -/// the modification time `modified`. -pub(in crate::filesystem::sandbox) fn set_host_directory_attributes( - directory: &Path, - permissions: &cap_std::fs::Permissions, - modified: Option, -) -> std::io::Result<()> { - let directory = File::open(directory)?; - directory.set_permissions(host_permissions(permissions, &directory)?)?; - modified.map_or(Ok(()), |modified| directory.set_modified(modified)) -} - /// What a seed entry needs to make objects in one sandbox. #[derive(Clone, Copy)] pub(in crate::filesystem::sandbox) struct SeedContext { diff --git a/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/non_unix.rs b/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/non_unix.rs index fd5d5aeaa5e..98c34bb2f19 100644 --- a/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/non_unix.rs +++ b/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/non_unix.rs @@ -36,6 +36,23 @@ pub(in crate::filesystem::sandbox) fn host_permissions( Ok(host) } +pub(in crate::filesystem::sandbox) fn set_host_directory_attributes( + directory: &Path, + permissions: &cap_std::fs::Permissions, + modified: Option, +) -> std::io::Result<()> { + if let Some(modified) = modified { + fs_set_times::set_times( + directory, + None, + Some(fs_set_times::SystemTimeSpec::Absolute(modified)), + )?; + } + let mut host = std::fs::metadata(directory)?.permissions(); + host.set_readonly(permissions.readonly()); + std::fs::set_permissions(directory, host) +} + pub(in crate::filesystem::sandbox) fn sync_ordinary_descriptor( _file: &F, ) -> std::io::Result<()> { diff --git a/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/unix.rs b/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/unix.rs index d54467a1f59..d5118a21f93 100644 --- a/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/unix.rs +++ b/golem-worker-executor/src/filesystem/sandbox/host_adapter/tree_copy/unix.rs @@ -37,6 +37,16 @@ pub(in crate::filesystem::sandbox) fn host_permissions( Ok(std::fs::Permissions::from_mode(permissions.mode())) } +pub(in crate::filesystem::sandbox) fn set_host_directory_attributes( + directory: &Path, + permissions: &cap_std::fs::Permissions, + modified: Option, +) -> std::io::Result<()> { + let directory = File::open(directory)?; + directory.set_permissions(host_permissions(permissions, &directory)?)?; + modified.map_or(Ok(()), |modified| directory.set_modified(modified)) +} + pub(in crate::filesystem::sandbox) fn sync_ordinary_descriptor( file: &F, ) -> std::io::Result<()> { diff --git a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/mod.rs b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/mod.rs index 931c7313156..875781a7191 100644 --- a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/mod.rs +++ b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/mod.rs @@ -31,6 +31,15 @@ //! directory with `O_DIRECTORY | O_NOFOLLOW` and changes the mode with `fchmod`, so a directory at //! mode `0000` gives `EACCES`. The clear does not enter a directory of another device than `into`, //! and a tree deeper than [`MOST_CLEAR_DEPTH`] levels makes it fail. +//! +//! On Windows, directory capabilities keep the ancestors open without delete sharing, so they +//! cannot be renamed during the walk. Each child is opened without following links. The clear +//! deletes files and links by handle without changing attributes shared by other hard links. +//! Before enumeration, the opened root must resolve to a canonical local drive path. Network +//! paths and other root forms are unsupported. +//! Unknown reparse points are refused. Each opened directory must be on the root volume, with +//! the same depth limit. It deletes an empty child directory through its pinned handle, +//! ignoring the read-only attribute, before closing it. /// The deepest level of directories that the clear enters. The clear holds one descriptor for /// each level. @@ -63,6 +72,12 @@ pub(super) fn clear_entry(directory: bool, same_device: bool) -> ClearEntry { pub(in crate::filesystem_snapshot::backend::rustic) trait ClearHook: Send + Sync { + /// Substitutes the final path of an opened Windows root for validation. + #[cfg(windows)] + fn final_root_path(&self, _root: &cap_std::fs::Dir) -> Option> { + None + } + /// Runs after the clear removed an entry. An error ends the clear with that error. fn after_entry(&self) -> std::io::Result<()> { Ok(()) @@ -117,6 +132,7 @@ impl Hooks<'_> { } /// Tells whether `into` has no entry. +#[cfg(test)] pub(super) fn is_empty(into: &std::path::Path) -> std::io::Result { Ok(std::fs::read_dir(into)?.next().transpose()?.is_none()) } @@ -140,9 +156,16 @@ pub(super) fn clear_with(into: &std::path::Path, hook: &dyn ClearHook) -> std::i walk(into, Hooks { hook }) } +#[cfg(not(windows))] use native::walk; -#[cfg(not(unix))] +#[cfg(any(windows, test))] +mod windows; + +#[cfg(windows)] +use windows::walk; + +#[cfg(not(any(unix, windows)))] mod native { use super::Hooks; @@ -150,7 +173,7 @@ mod native { pub(super) fn walk(_into: &std::path::Path, _hooks: Hooks<'_>) -> std::io::Result<()> { Err(std::io::Error::new( std::io::ErrorKind::Unsupported, - "the clear of the directory of a restore runs only on unix", + "the clear of the directory of a restore runs only on unix or Windows", )) } } @@ -390,14 +413,40 @@ pub(in crate::filesystem_snapshot::backend::rustic) fn destination_is_valid( "does not have a UTF-8 path", )); } - let metadata = std::fs::metadata(into)?; - if !metadata.is_dir() { - return Err(refused( - std::io::ErrorKind::NotADirectory, - "is not a directory", - )); - } - let first = std::fs::read_dir(into)?.next().transpose()?; + #[cfg(windows)] + let first = { + let root = cap_std::fs::Dir::open_ambient_dir(into, cap_std::ambient_authority()).map_err( + |error| { + if error.kind() == std::io::ErrorKind::NotADirectory { + refused(std::io::ErrorKind::NotADirectory, "is not a directory") + } else { + error + } + }, + )?; + windows::require_local_root( + &root, + into, + Hooks { + #[cfg(test)] + hook: &NoHook, + #[cfg(not(test))] + _none: std::marker::PhantomData, + }, + )?; + root.entries()?.next().transpose()? + }; + #[cfg(not(windows))] + let first = { + let metadata = std::fs::metadata(into)?; + if !metadata.is_dir() { + return Err(refused( + std::io::ErrorKind::NotADirectory, + "is not a directory", + )); + } + std::fs::read_dir(into)?.next().transpose()? + }; match first { Some(_) => Err(refused( std::io::ErrorKind::DirectoryNotEmpty, diff --git a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/tests.rs b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/tests.rs index a1ab8998caa..8788e41110e 100644 --- a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/tests.rs +++ b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/tests.rs @@ -16,6 +16,224 @@ use super::{ClearEntry, clear_entry}; use pretty_assertions::assert_eq; use test_r::test; +#[test] +fn the_windows_clear_accepts_only_canonical_local_drive_paths() { + use super::windows::require_local_path; + use std::path::Path; + + for path in [r"\\?\C:\", r"\\?\z:\some dir\restore", r"\\?\D:\UNC\share"] { + require_local_path( + &path.encode_utf16().collect::>(), + Path::new("restore"), + ) + .unwrap(); + } + for path in [ + r"\\?\UNC\server\share\restore", + r"\\server\share\restore", + r"\\?\Volume{01234567-89ab-cdef-0123-456789abcdef}\restore", + r"\Device\HarddiskVolume1\restore", + r"\\.\C:\restore", + r"C:\restore", + r"\\?\C:restore", + r"\\?\1:\restore", + r"\\?\C:/restore", + r"\\?\C:", + "", + ] { + let error = require_local_path( + &path.encode_utf16().collect::>(), + Path::new("requested-root"), + ) + .unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::Unsupported); + assert!(error.to_string().contains("requested-root")); + assert!( + error + .to_string() + .contains("only local paths are supported on Windows") + ); + } +} + +#[cfg(any(unix, windows))] +mod capabilities { + use crate::filesystem_snapshot::backend::rustic::restore::destination::{ + ClearHook, Hooks, MOST_CLEAR_DEPTH, NoHook, is_empty, windows::walk, + }; + use pretty_assertions::assert_eq; + use std::sync::atomic::{AtomicUsize, Ordering}; + use test_r::test; + + struct FailAfterOne(AtomicUsize); + + impl ClearHook for FailAfterOne { + fn after_entry(&self) -> std::io::Result<()> { + self.0.fetch_add(1, Ordering::SeqCst); + Err(std::io::Error::other("interrupted clear")) + } + } + + #[test] + fn the_capability_clear_retries_a_partial_clear_and_keeps_the_root() { + let into = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(into.path().join("nested/below")).unwrap(); + std::fs::write(into.path().join("nested/below/file"), b"partial").unwrap(); + std::fs::write(into.path().join("other"), b"leftover").unwrap(); + let hook = FailAfterOne(AtomicUsize::new(0)); + + let interrupted = walk(into.path(), Hooks { hook: &hook }).unwrap_err(); + assert_eq!(interrupted.to_string(), "interrupted clear"); + assert_eq!(hook.0.load(Ordering::SeqCst), 1); + assert!(!is_empty(into.path()).unwrap()); + walk(into.path(), Hooks { hook: &NoHook }).unwrap(); + assert!(into.path().is_dir()); + assert!(is_empty(into.path()).unwrap()); + walk(into.path(), Hooks { hook: &NoHook }).unwrap(); + } + + #[test] + fn the_capability_clear_enforces_the_depth_limit() { + for depth in [MOST_CLEAR_DEPTH, MOST_CLEAR_DEPTH + 1] { + let into = tempfile::tempdir().unwrap(); + let deepest = (0..depth).fold(into.path().to_path_buf(), |path, _| path.join("d")); + std::fs::create_dir_all(deepest).unwrap(); + let cleared = walk(into.path(), Hooks { hook: &NoHook }); + if depth == MOST_CLEAR_DEPTH { + cleared.unwrap(); + assert!(is_empty(into.path()).unwrap()); + } else { + assert_eq!( + cleared.unwrap_err().to_string(), + format!("the tree of the restore is deeper than {MOST_CLEAR_DEPTH} levels") + ); + } + } + } + + #[cfg(unix)] + #[test] + fn the_capability_clear_removes_links_without_touching_their_targets() { + let parent = tempfile::tempdir().unwrap(); + let into = parent.path().join("into"); + let outside = parent.path().join("outside"); + std::fs::create_dir(&into).unwrap(); + std::fs::create_dir(&outside).unwrap(); + std::fs::write(outside.join("kept"), b"unchanged").unwrap(); + std::os::unix::fs::symlink(&outside, into.join("directory-link")).unwrap(); + std::os::unix::fs::symlink(outside.join("kept"), into.join("file-link")).unwrap(); + std::os::unix::fs::symlink(outside.join("missing"), into.join("dangling-link")).unwrap(); + + walk(&into, Hooks { hook: &NoHook }).unwrap(); + + assert!(is_empty(&into).unwrap()); + assert_eq!(std::fs::read(outside.join("kept")).unwrap(), b"unchanged"); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 1); + } + + #[cfg(windows)] + #[test] + fn the_windows_clear_validates_the_opened_root_not_the_requested_path() { + let into = tempfile::tempdir().unwrap(); + let root = + cap_std::fs::Dir::open_ambient_dir(into.path(), cap_std::ambient_authority()).unwrap(); + + super::super::windows::require_local_root( + &root, + std::path::Path::new(r"\\server\share\diagnostic-path"), + Hooks { hook: &NoHook }, + ) + .unwrap(); + } + + #[cfg(windows)] + #[test] + fn the_windows_clear_removes_readonly_files_and_directories() { + let into = tempfile::tempdir().unwrap(); + let nested = into.path().join("nested"); + std::fs::create_dir(&nested).unwrap(); + let file = nested.join("file"); + std::fs::write(&file, b"partial").unwrap(); + for path in [&file, &nested] { + let mut permissions = std::fs::metadata(path).unwrap().permissions(); + permissions.set_readonly(true); + std::fs::set_permissions(path, permissions).unwrap(); + } + + super::super::clear(into.path()).unwrap(); + + assert!(is_empty(into.path()).unwrap()); + } + + #[cfg(windows)] + #[test] + fn the_windows_clear_preserves_readonly_attributes_of_an_outside_hard_link() { + let parent = tempfile::tempdir().unwrap(); + let into = parent.path().join("into"); + std::fs::create_dir(&into).unwrap(); + let outside = parent.path().join("outside"); + std::fs::write(&outside, b"unchanged").unwrap(); + std::fs::hard_link(&outside, into.join("link")).unwrap(); + let mut permissions = std::fs::metadata(&outside).unwrap().permissions(); + permissions.set_readonly(true); + std::fs::set_permissions(&outside, permissions).unwrap(); + + super::super::clear(&into).unwrap(); + + assert!(is_empty(&into).unwrap()); + let file = std::fs::File::open(&outside).unwrap(); + assert!(file.metadata().unwrap().permissions().readonly()); + assert_eq!(std::fs::read(&outside).unwrap(), b"unchanged"); + let mut permissions = file.metadata().unwrap().permissions(); + permissions.set_readonly(false); + std::fs::set_permissions(&outside, permissions).unwrap(); + } + + #[cfg(windows)] + #[test] + fn the_windows_clear_removes_links_without_touching_their_targets() { + let parent = tempfile::tempdir().unwrap(); + let into = parent.path().join("into"); + let outside = parent.path().join("outside"); + std::fs::create_dir(&into).unwrap(); + std::fs::create_dir(&outside).unwrap(); + std::fs::write(outside.join("kept"), b"unchanged").unwrap(); + std::os::windows::fs::symlink_dir(&outside, into.join("directory-link")).unwrap(); + std::os::windows::fs::symlink_file(outside.join("kept"), into.join("file-link")).unwrap(); + std::os::windows::fs::symlink_file(outside.join("missing"), into.join("dangling-link")) + .unwrap(); + + super::super::clear(&into).unwrap(); + + assert!(is_empty(&into).unwrap()); + assert_eq!(std::fs::read(outside.join("kept")).unwrap(), b"unchanged"); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 1); + } + + #[cfg(windows)] + #[test] + fn the_windows_clear_pins_open_directories_against_a_rename() { + use std::ffi::OsStr; + use std::path::Path; + + struct Rename; + impl ClearHook for Rename { + fn before_mode(&self, parent: &Path, name: &OsStr) { + std::fs::rename(parent.join(name), parent.join("moved")).unwrap_err(); + assert!(parent.join(name).is_dir()); + assert!(!parent.join("moved").exists()); + } + } + let into = tempfile::tempdir().unwrap(); + std::fs::create_dir(into.path().join("nested")).unwrap(); + std::fs::write(into.path().join("nested/file"), b"partial").unwrap(); + + super::super::clear_with(into.path(), &Rename).unwrap(); + + assert!(is_empty(into.path()).unwrap()); + } +} + #[test] fn the_clear_enters_only_a_directory_of_the_same_device_and_unlinks_each_other_entry() { assert_eq!( diff --git a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/windows.rs b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/windows.rs new file mode 100644 index 00000000000..c3b3e37bbec --- /dev/null +++ b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/destination/windows.rs @@ -0,0 +1,332 @@ +// Copyright 2024-2026 Golem Cloud +// +// Licensed under the Golem Source License v1.1 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://license.golem.cloud/LICENSE +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::{ClearEntry, Hooks, MOST_CLEAR_DEPTH, clear_entry}; +#[cfg(not(windows))] +use cap_fs_ext::DirExt; +use cap_fs_ext::MetadataExt; +use cap_std::fs::Dir; +use std::ffi::OsString; +use std::ops::ControlFlow; +use std::path::{Path, PathBuf}; + +struct Level { + directory: Dir, + path: PathBuf, + names: std::vec::IntoIter, +} + +impl Level { + fn new(directory: Dir, path: PathBuf) -> std::io::Result { + let names = directory + .entries()? + .map(|entry| entry.map(|entry| entry.file_name())) + .collect::>>()?; + Ok(Self { + directory, + path, + names: names.into_iter(), + }) + } +} + +pub(super) fn walk(into: &Path, hooks: Hooks<'_>) -> std::io::Result<()> { + let root = Dir::open_ambient_dir(into, cap_std::ambient_authority())?; + #[cfg(windows)] + require_local_root(&root, into, hooks)?; + let device = root.dir_metadata()?.dev(); + let stack = vec![Level::new(root, into.to_path_buf())?]; + match std::iter::repeat(()).try_fold(stack, |stack, ()| step(stack, device, hooks)) { + ControlFlow::Break(result) => result, + ControlFlow::Continue(_) => Ok(()), + } +} + +fn step( + mut stack: Vec, + device: u64, + hooks: Hooks<'_>, +) -> ControlFlow, Vec> { + let depth = stack.len(); + let Some(level) = stack.last_mut() else { + return ControlFlow::Break(Ok(())); + }; + match level.names.next() { + Some(name) => match entered(level, &name, device, depth, hooks) { + Ok(Some(below)) => { + stack.push(below); + ControlFlow::Continue(stack) + } + Ok(None) => match hooks.after_entry() { + Ok(()) => ControlFlow::Continue(stack), + Err(error) => ControlFlow::Break(Err(error)), + }, + Err(error) => ControlFlow::Break(Err(error)), + }, + None => { + let done = stack.pop().unwrap(); + if stack.is_empty() { + return ControlFlow::Break(Ok(())); + } + match remove_directory(done.directory).and_then(|()| hooks.after_entry()) { + Ok(()) => ControlFlow::Continue(stack), + Err(error) => ControlFlow::Break(Err(error)), + } + } + } +} + +fn entered( + level: &Level, + name: &std::ffi::OsStr, + device: u64, + depth: usize, + hooks: Hooks<'_>, +) -> std::io::Result> { + let metadata = level.directory.symlink_metadata(name)?; + if metadata.is_dir() && !metadata.is_symlink() { + hooks.before_open(&level.path, name); + let below = open_directory(&level.directory, Path::new(name))?; + reject_unknown_reparse_point(&below)?; + let metadata = below.dir_metadata()?; + match clear_entry(true, metadata.dev() == device) { + ClearEntry::OtherDevice => { + return Err(std::io::Error::other(format!( + "the directory {} of the restore is on another device", + level.path.join(name).display() + ))); + } + ClearEntry::ChmodThenEnter if depth > MOST_CLEAR_DEPTH => { + return Err(std::io::Error::other(format!( + "the tree of the restore is deeper than {MOST_CLEAR_DEPTH} levels" + ))); + } + _ => {} + } + hooks.before_mode(&level.path, name); + Level::new(below, level.path.join(name)).map(Some) + } else { + remove_leaf(&level.directory, Path::new(name))?; + Ok(None) + } +} + +pub(super) fn require_local_path(path: &[u16], into: &Path) -> std::io::Result<()> { + if matches!(path, [92, 92, 63, 92, 65..=90 | 97..=122, 58, 92, ..]) { + Ok(()) + } else { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + format!( + "the restore destination {} is not supported: only local paths are supported on Windows", + into.display() + ), + )) + } +} + +#[cfg(windows)] +pub(super) fn require_local_root(root: &Dir, into: &Path, hooks: Hooks<'_>) -> std::io::Result<()> { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Storage::FileSystem::{ + FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW, VOLUME_NAME_DOS, + }; + + #[cfg(test)] + if let Some(path) = hooks.hook.final_root_path(root) { + return require_local_path(&path, into); + } + #[cfg(not(test))] + let _ = hooks; + + let mut path = vec![0u16; 32768]; + // SAFETY: root stays open and the buffer holds the supplied number of UTF-16 code units. + // The final path resolves mapped drives and links, unlike the requested path. + let length = unsafe { + GetFinalPathNameByHandleW( + root.as_raw_handle(), + path.as_mut_ptr(), + path.len() as u32, + FILE_NAME_NORMALIZED | VOLUME_NAME_DOS, + ) + } as usize; + if length == 0 { + return Err(std::io::Error::last_os_error()); + } + if length >= path.len() { + return Err(std::io::Error::other(format!( + "the final path of restore destination {} exceeds the path buffer", + into.display() + ))); + } + require_local_path(&path[..length], into) +} + +#[cfg(windows)] +fn reject_unknown_reparse_point( + file: &impl std::os::windows::io::AsRawHandle, +) -> std::io::Result<()> { + use windows_sys::Win32::Storage::FileSystem::{ + FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_TAG_INFO, FileAttributeTagInfo, + GetFileInformationByHandleEx, + }; + use windows_sys::Win32::System::SystemServices::{ + IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK, + }; + + let mut info = FILE_ATTRIBUTE_TAG_INFO::default(); + // SAFETY: the handle stays open and info has the size and layout required by this class. + if unsafe { + GetFileInformationByHandleEx( + file.as_raw_handle(), + FileAttributeTagInfo, + std::ptr::from_mut(&mut info).cast(), + std::mem::size_of_val(&info) as u32, + ) + } == 0 + { + return Err(std::io::Error::last_os_error()); + } + if info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 + && !matches!( + info.ReparseTag, + IO_REPARSE_TAG_SYMLINK | IO_REPARSE_TAG_MOUNT_POINT + ) + { + return Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + "the restore destination contains an unsupported reparse point", + )); + } + Ok(()) +} + +#[cfg(not(windows))] +fn reject_unknown_reparse_point(_file: &T) -> std::io::Result<()> { + Ok(()) +} + +#[cfg(windows)] +fn open_directory(parent: &Dir, name: &Path) -> std::io::Result { + use cap_fs_ext::OpenOptionsFollowExt; + use cap_std::fs::{OpenOptions, OpenOptionsExt}; + use windows_sys::Win32::Storage::FileSystem::{ + DELETE, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_LIST_DIRECTORY, + FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE, + }; + + let mut options = OpenOptions::new(); + options + .access_mode(DELETE | FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .follow(cap_fs_ext::FollowSymlinks::No); + let file = parent.open_with(name, &options)?; + let metadata = file.metadata()?; + if !metadata.is_dir() || metadata.is_symlink() { + return Err(std::io::Error::other( + "a restore destination directory became a file or link", + )); + } + Ok(Dir::from_std_file(file.into_std())) +} + +#[cfg(not(windows))] +fn open_directory(parent: &Dir, name: &Path) -> std::io::Result { + parent.open_dir_nofollow(name) +} + +#[cfg(windows)] +fn remove_directory(directory: Dir) -> std::io::Result<()> { + delete_opened(&directory) +} + +#[cfg(not(windows))] +fn remove_directory(directory: Dir) -> std::io::Result<()> { + directory.remove_open_dir() +} + +#[cfg(windows)] +fn remove_leaf(parent: &Dir, name: &Path) -> std::io::Result<()> { + use cap_fs_ext::OpenOptionsFollowExt; + use cap_std::fs::{OpenOptions, OpenOptionsExt}; + use windows_sys::Win32::Storage::FileSystem::{ + DELETE, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, + FILE_SHARE_READ, FILE_SHARE_WRITE, + }; + + // Delete the opened name without changing attributes shared by its other hard links. + // No delete sharing pins it against renames; OPEN_REPARSE_POINT never opens a link's target. + let mut options = OpenOptions::new(); + options + .access_mode(DELETE | FILE_READ_ATTRIBUTES) + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .follow(cap_fs_ext::FollowSymlinks::No); + let file = parent.open_with(name, &options)?; + let metadata = file.metadata()?; + reject_unknown_reparse_point(&file)?; + if metadata.is_dir() && !metadata.is_symlink() { + return Err(std::io::Error::other( + "a restore destination entry became a directory", + )); + } + delete_opened(&file) +} + +#[cfg(windows)] +fn delete_opened(file: &impl std::os::windows::io::AsRawHandle) -> std::io::Result<()> { + use windows_sys::Win32::Storage::FileSystem::{ + FILE_DISPOSITION_FLAG_DELETE, FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE, + FILE_DISPOSITION_FLAG_POSIX_SEMANTICS, FILE_DISPOSITION_INFO_EX, FileDispositionInfoEx, + SetFileInformationByHandle, + }; + + let disposition = FILE_DISPOSITION_INFO_EX { + Flags: FILE_DISPOSITION_FLAG_DELETE + | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS + | FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE, + }; + // SAFETY: the handle remains open and disposition is valid for the supplied class and size. + let removed = unsafe { + SetFileInformationByHandle( + file.as_raw_handle(), + FileDispositionInfoEx, + std::ptr::from_ref(&disposition).cast(), + std::mem::size_of_val(&disposition) as u32, + ) + }; + if removed == 0 { + use windows_sys::Win32::Foundation::{ + ERROR_INVALID_FUNCTION, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, + }; + + let error = std::io::Error::last_os_error(); + if matches!( + error.raw_os_error().map(|code| code as u32), + Some(ERROR_INVALID_FUNCTION | ERROR_INVALID_PARAMETER | ERROR_NOT_SUPPORTED) + ) { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, error)) + } else { + Err(error) + } + } else { + Ok(()) + } +} + +#[cfg(not(windows))] +fn remove_leaf(parent: &Dir, name: &Path) -> std::io::Result<()> { + parent.remove_file_or_symlink(name) +} diff --git a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/mod.rs b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/mod.rs index af0430bbd0e..7fd0948ec5a 100644 --- a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/mod.rs +++ b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/mod.rs @@ -107,9 +107,8 @@ enum Stepped { impl RestoreRun { /// Runs the steps of the restore until one gives the end of the run. fn run(self) -> RunResult> { - // A directory that is not empty holds what an earlier run wrote, also when its clear failed - // part way. - self.clear_if_written()?; + // Remove an earlier run's output and validate the opened Windows root even when empty. + self.clear()?; let mut restoring = Restoring { listed: HashSet::new(), missed: HashSet::new(), @@ -173,19 +172,6 @@ impl RestoreRun { } } - /// Clears the directory when it is not empty. A failed clear ends the run: on unix a new run - /// clears again, and elsewhere no run can clear. - fn clear_if_written(&self) -> Result<(), Ended> { - match destination::is_empty(&self.into) { - Ok(true) => Ok(()), - Ok(false) => self.clear(), - Err(error) => Err(Ended::new( - RunEnd::CallFailed, - anyhow::Error::new(error).context("read the directory of the restore"), - )), - } - } - /// Removes every entry of the directory, as [`destination::clear`] says. fn clear(&self) -> Result<(), Ended> { #[cfg(test)] @@ -200,8 +186,7 @@ impl RestoreRun { }; Ended::new( end, - anyhow::Error::new(error) - .context("remove what an earlier run of the restore wrote"), + anyhow::Error::new(error).context("prepare the directory of the restore"), ) }) } diff --git a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/tests.rs b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/tests.rs index 3bb1ab0df49..b476dd0df46 100644 --- a/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/tests.rs +++ b/golem-worker-executor/src/filesystem_snapshot/backend/rustic/restore/tests.rs @@ -45,6 +45,55 @@ use tokio_util::task::AbortOnDropHandle; use golem_service_base::storage::blob::BlobStorage; +#[cfg(windows)] +#[test] +#[timeout("60s")] +async fn an_empty_unsupported_windows_root_fails_restore_permanently() { + use super::destination::ClearHook; + + #[derive(Default)] + struct UnsupportedRoot(AtomicBool); + + impl ClearHook for UnsupportedRoot { + fn final_root_path(&self, root: &cap_std::fs::Dir) -> Option> { + assert!(root.entries().unwrap().next().is_none()); + self.0.store(true, Ordering::SeqCst); + Some(r"\\?\UNC\server\share\empty".encode_utf16().collect()) + } + } + + let hook = Arc::new(UnsupportedRoot::default()); + let into = Scratch::new(); + let run = super::RestoreRun { + backend: crate::filesystem_snapshot::backend::rustic::test_support::backend_of( + Arc::new(InMemoryBlobStorage::new()), + &new_scope(), + STORAGE_CALL_DEADLINE, + ), + key: key(), + name: name("missing"), + into: into.path().into(), + options: super::restore_options(NonZeroUsize::new(1).unwrap()), + hook: hook.clone(), + }; + let failure = run + .run() + .err() + .expect("the root must be refused before loading a repository"); + assert!(hook.0.load(Ordering::SeqCst)); + assert_eq!(failure.end, super::RunEnd::Permanent); + assert_eq!( + failure + .failure + .downcast_ref::() + .unwrap() + .kind(), + std::io::ErrorKind::Unsupported + ); + assert!(format!("{:#}", failure.failure).contains("only local paths")); + assert!(std::fs::read_dir(into.path()).unwrap().next().is_none()); +} + #[test] #[timeout("60s")] async fn a_shutdown_during_a_restore_gives_stopped_and_clears_nothing() { @@ -594,8 +643,8 @@ async fn a_restore_of_a_name_deleted_during_it_gives_not_found() { ); } -#[cfg(unix)] -mod unix { +#[cfg(any(unix, windows))] +mod destination_retry { use super::*; use crate::filesystem_snapshot::backend::rustic::restore::destination::ClearHook; use pretty_assertions::assert_eq; @@ -671,6 +720,7 @@ mod unix { ); } + #[cfg(unix)] #[test] #[timeout("60s")] async fn a_restore_whose_run_failed_after_it_made_a_directory_read_only_clears_into_and_gives_the_whole_tree() @@ -756,6 +806,7 @@ mod unix { ); } + #[cfg(unix)] #[test] #[timeout("60s")] async fn a_restore_into_a_non_utf8_path_gives_destination_without_changing_its_parent() { @@ -784,6 +835,7 @@ mod unix { assert_eq!(listing(parent.path()), before); } + #[cfg(unix)] #[test] #[timeout("60s")] async fn a_local_io_error_of_a_restore_gives_destination_with_its_kind() { diff --git a/golem-worker-executor/src/filesystem_snapshot/test_support/fixture/mod.rs b/golem-worker-executor/src/filesystem_snapshot/test_support/fixture/mod.rs index 9fc855ac3c6..7d419fcb39f 100644 --- a/golem-worker-executor/src/filesystem_snapshot/test_support/fixture/mod.rs +++ b/golem-worker-executor/src/filesystem_snapshot/test_support/fixture/mod.rs @@ -338,6 +338,14 @@ mod native_fixture { }, ), ("empty-dir", Spec::Directory { mode: 0o755 }), + ("locked", Spec::Directory { mode: 0o555 }), + ( + "locked/inside.txt", + Spec::File { + content: Box::from(&b"inside"[..]), + mode: 0o444, + }, + ), ( "read-only.txt", Spec::File { diff --git a/golem-worker-executor/src/services/agent_filesystem/lifecycle/baseline.rs b/golem-worker-executor/src/services/agent_filesystem/lifecycle/baseline.rs index be759cc98f9..83909700eaf 100644 --- a/golem-worker-executor/src/services/agent_filesystem/lifecycle/baseline.rs +++ b/golem-worker-executor/src/services/agent_filesystem/lifecycle/baseline.rs @@ -1209,7 +1209,7 @@ async fn restore_from( .record_restore(RestoredTimes::of(saved_times, old == new)); let states = observe(sandbox, &old, &new, &seeded) .await - .map_err(|source| classify_query_error(generation, source))?; + .map_err(|source| classify_startup_error(generation, source))?; let installed = install(generation, sandbox, sources, &old, &seeded, &new, &states).await?; Ok(InitialFileState { initial: Arc::new(initial), diff --git a/golem-worker-executor/src/services/agent_filesystem/lifecycle/effects.rs b/golem-worker-executor/src/services/agent_filesystem/lifecycle/effects.rs index f647554bb77..b1285f735f0 100644 --- a/golem-worker-executor/src/services/agent_filesystem/lifecycle/effects.rs +++ b/golem-worker-executor/src/services/agent_filesystem/lifecycle/effects.rs @@ -41,6 +41,17 @@ pub(super) fn classify_query_error( } } +/// Invalidates a failed startup generation without losing the cause needed by the start policy. +pub(super) fn classify_startup_error( + generation: &FilesystemGeneration, + source: FilesystemStorageError, +) -> Error { + if invalidates_generation(&source) { + generation.invalidate(); + } + Error::Sandbox(source) +} + pub(super) async fn decide_generation_effect( generation: &FilesystemGeneration, error: &FilesystemStorageError, @@ -105,12 +116,57 @@ pub(super) async fn decide_write_effect( evidence: EffectEvidence, budget: RetryBudget, ) -> EffectDecision { + try_decide_write_effect(generation, error, evidence, budget) + .await + .unwrap_or(EffectDecision::Invalidate) +} + +pub(super) enum SeedDecision { + Retry(FilesystemStorageError), + Fail(Error), +} + +pub(super) async fn decide_seed_failure( + generation: &FilesystemGeneration, + error: FilesystemStorageError, + budget: &mut RetryBudget, +) -> SeedDecision { + match try_decide_write_effect(generation, &error, EffectEvidence::NoEffect, *budget).await { + Err(source) => SeedDecision::Fail(classify_startup_error(generation, source)), + Ok(EffectDecision::RetryAfterProvenNoEffect) if budget.consume() => { + SeedDecision::Retry(error) + } + Ok(EffectDecision::ReturnFailure(cause)) => { + SeedDecision::Fail(classified_error(cause, error)) + } + Ok(EffectDecision::ReclaimCapacityThenRetry) => { + SeedDecision::Fail(Error::PhysicalCapacity(error)) + } + Ok( + EffectDecision::Invalidate + | EffectDecision::RetryAfterProvenNoEffect + | EffectDecision::RetryUnwrittenSuffix + | EffectDecision::Succeed, + ) => { + generation.invalidate(); + SeedDecision::Fail(Error::Sandbox(error)) + } + } +} + +/// A failed usage observation returns its own error so seeding can retain the permanent cause. +async fn try_decide_write_effect( + generation: &FilesystemGeneration, + error: &FilesystemStorageError, + evidence: EffectEvidence, + budget: RetryBudget, +) -> Result { if !error.is_storage_exhaustion() { - return decide_effect( + return Ok(decide_effect( classify_failure(error, FailureFacts::default()), evidence, budget, - ); + )); } let quota_exhausted = match generation.observe_usage_sandbox().await { @@ -120,7 +176,7 @@ pub(super) async fn decide_write_effect( false } Ok(FilesystemUsage::Unsupported) => { - return EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo); + return Ok(EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo)); } Ok(FilesystemUsage::Authoritative { allocated_bytes, @@ -134,12 +190,12 @@ pub(super) async fn decide_write_effect( } }, Err(error) if error.is_terminal_failure() => { - return EffectDecision::Invalidate; + return Err(error); } - Err(_) => return EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo), + Err(_) => return Ok(EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo)), }; if quota_exhausted { - return EffectDecision::ReturnFailure(FailureCause::AgentQuota); + return Ok(EffectDecision::ReturnFailure(FailureCause::AgentQuota)); } let retry = match evidence { @@ -148,16 +204,16 @@ pub(super) async fn decide_write_effect( EffectDecision::RetryUnwrittenSuffix } EffectEvidence::NoEffect | EffectEvidence::CompletedPrefix(_) => { - return EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo); + return Ok(EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo)); } - EffectEvidence::DesiredPostconditionSatisfied => return EffectDecision::Succeed, - EffectEvidence::Unknown { .. } => return EffectDecision::Invalidate, + EffectEvidence::DesiredPostconditionSatisfied => return Ok(EffectDecision::Succeed), + EffectEvidence::Unknown { .. } => return Ok(EffectDecision::Invalidate), }; let Some(recovery) = &generation.pressure_recovery else { - return EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo); + return Ok(EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo)); }; let deadline = std::time::Instant::now() + WRITE_PRESSURE_RECOVERY_TIMEOUT; - match recovery.recover_write(deadline).await { + Ok(match recovery.recover_write(deadline).await { FilesystemWriteRecoveryOutcome::Recovered => retry, FilesystemWriteRecoveryOutcome::Denied => { EffectDecision::ReturnFailure(FailureCause::PhysicalCapacity) @@ -166,7 +222,7 @@ pub(super) async fn decide_write_effect( | FilesystemWriteRecoveryOutcome::Unavailable => { EffectDecision::ReturnFailure(FailureCause::UnclassifiedIo) } - } + }) } pub(super) async fn decide_resize_effect( diff --git a/golem-worker-executor/src/services/agent_filesystem/lifecycle/initial_files.rs b/golem-worker-executor/src/services/agent_filesystem/lifecycle/initial_files.rs index a43124d7d01..9d1e1c888ce 100644 --- a/golem-worker-executor/src/services/agent_filesystem/lifecycle/initial_files.rs +++ b/golem-worker-executor/src/services/agent_filesystem/lifecycle/initial_files.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use super::effects::{SeedDecision, decide_seed_failure}; use super::*; use crate::filesystem::errors::OperationContext; use crate::filesystem::host_directories::HostPath; @@ -534,38 +535,20 @@ pub(super) async fn seed_with_retry( let mut budget = budget?; let outcome = match sandbox.seed(Box::new([entry.clone()])).await { Ok(()) => Some(Ok(())), - Err(error) => { - match decide_write_effect(generation, &error, EffectEvidence::NoEffect, budget) - .await - { - EffectDecision::RetryAfterProvenNoEffect if budget.consume() => { - match prepare_retry(sandbox, preparation).await { - Ok(()) => None, - Err(failure) => { - tracing::warn!( - error = %failure, - "Failed to prepare the retry of an initial-file seed" - ); - generation.invalidate(); - Some(Err(Error::RuntimeInvalidated)) - } - } - } - EffectDecision::ReturnFailure(cause) => { - Some(Err(classified_error(cause, error))) - } - EffectDecision::ReclaimCapacityThenRetry => { - Some(Err(Error::PhysicalCapacity(error))) - } - EffectDecision::Invalidate - | EffectDecision::RetryAfterProvenNoEffect - | EffectDecision::RetryUnwrittenSuffix - | EffectDecision::Succeed => { + Err(error) => match decide_seed_failure(generation, error, &mut budget).await { + SeedDecision::Retry(error) => match prepare_retry(sandbox, preparation).await { + Ok(()) => None, + Err(failure) => { + tracing::warn!( + error = %failure, + "Failed to prepare the retry of an initial-file seed" + ); generation.invalidate(); - Some(Err(Error::RuntimeInvalidated)) + Some(Err(Error::Sandbox(error.with_cleanup_failure(failure)))) } - } - } + }, + SeedDecision::Fail(error) => Some(Err(error)), + }, }; let next = outcome.is_none().then_some(budget); Some((outcome, next)) @@ -1156,7 +1139,7 @@ async fn install_resident( let old = state.declarations(); let states = observe(sandbox.as_ref(), &old, new, &state.installed) .await - .map_err(|source| classify_query_error(generation, source))?; + .map_err(|source| classify_startup_error(generation, source))?; install( generation, sandbox.as_ref(), diff --git a/golem-worker-executor/src/services/agent_filesystem/lifecycle/mod.rs b/golem-worker-executor/src/services/agent_filesystem/lifecycle/mod.rs index 50ce0983005..ed042618dd9 100644 --- a/golem-worker-executor/src/services/agent_filesystem/lifecycle/mod.rs +++ b/golem-worker-executor/src/services/agent_filesystem/lifecycle/mod.rs @@ -78,6 +78,7 @@ use effects::classified_error; #[cfg(test)] use effects::classify_failure; use effects::classify_query_error; +use effects::classify_startup_error; use effects::decide_effect; use effects::decide_generation_effect; use effects::decide_resize_effect; diff --git a/golem-worker-executor/src/services/agent_filesystem/lifecycle/tests/capture_and_baseline.rs b/golem-worker-executor/src/services/agent_filesystem/lifecycle/tests/capture_and_baseline.rs index 139c229fd56..a5ae26b4ef0 100644 --- a/golem-worker-executor/src/services/agent_filesystem/lifecycle/tests/capture_and_baseline.rs +++ b/golem-worker-executor/src/services/agent_filesystem/lifecycle/tests/capture_and_baseline.rs @@ -1488,6 +1488,118 @@ async fn storage_full_while_seeding_a_restored_tree_is_classified_like_initial_f ); } +#[test] +async fn a_host_permission_failure_observing_initial_files_preserves_its_cause() { + let store = InitialFileStore::new().await; + let file = store + .declare("/refused", AgentFilePermissions::ReadWrite, b"refused") + .await; + for restoring in [false, true] { + let (filesystem, control, _) = + bound_reconstructing_with_recovery(ResolvedStorageLimits::Unlimited, None).await; + if restoring { + control.push_seed(Ok(())); + control.push_set_times(Ok(())); + control.push_get_attributes(Err(sandbox_error( + "observe restored initial file", + std::io::ErrorKind::PermissionDenied, + ))); + let capture_record = record(&[], serde_json::json!([]), serde_json::json!([])); + let failure = materialize_baseline( + filesystem, + store.prepare(std::slice::from_ref(&file)).await, + Some(FixtureRestore(move |into: &Path| { + write_capture_directory(into, &[], &capture_record); + Ok(()) + })), + ) + .await + .unwrap_err(); + assert!( + matches!(&failure.source, Error::Sandbox(source) + if source.io_kind() == Some(std::io::ErrorKind::PermissionDenied)), + "{}", + failure.source + ); + assert!( + failure + .filesystem + .generation + .as_ref() + .unwrap() + .registry + .is_invalidated() + ); + control.push_delete_and_verify(Ok(())); + delete(failure.filesystem).await.unwrap(); + } else { + let resident = scripted_resident(&control, filesystem, store.prepare(&[]).await).await; + control.push_get_attributes(Err(sandbox_error( + "observe updated initial file", + std::io::ErrorKind::PermissionDenied, + ))); + let error = update_initial_files( + &resident_generation_handle(&resident), + Arc::clone(&store.loader), + store.environment_id, + vec![file.clone()], + ) + .unwrap() + .await + .unwrap_err(); + assert!( + matches!(&error, Error::Sandbox(source) + if source.io_kind() == Some(std::io::ErrorKind::PermissionDenied)), + "{error}" + ); + assert!(filesystem_activity(&resident).has_terminal_failure()); + delete_scripted_resident(&control, resident).await; + } + } +} + +#[test] +async fn a_terminal_usage_failure_during_seed_retains_the_observation_error() { + let store = InitialFileStore::new().await; + let file = store + .declare("/full", AgentFilePermissions::ReadWrite, b"data") + .await; + let (filesystem, control, entry) = + bound_reconstructing_with_recovery(ResolvedStorageLimits::Finite(limits(4096, 8)), None) + .await; + let window = open_resource_usage_window(&filesystem, permit(&entry).await) + .await + .unwrap(); + control.push_seed(Err(sandbox_error("seed", std::io::ErrorKind::StorageFull))); + control.push_observe_allocation(Err(sandbox_error( + "observe usage", + std::io::ErrorKind::PermissionDenied, + ))); + let failure = materialize_baseline(filesystem, store.prepare(&[file]).await, NO_RESTORE) + .await + .unwrap_err(); + assert!( + matches!(&failure.source, Error::Sandbox(source) + if source.io_kind() == Some(std::io::ErrorKind::PermissionDenied)), + "{}", + failure.source + ); + assert!( + failure + .filesystem + .generation + .as_ref() + .unwrap() + .registry + .is_invalidated() + ); + close_window(window, Instant::now() + Duration::from_secs(1)) + .await + .unwrap(); + control.push_delete_and_verify(Ok(())); + delete(failure.filesystem).await.unwrap(); +} + #[test] async fn a_host_permission_failure_while_seeding_initial_files_invalidates_the_generation() { let store = InitialFileStore::new().await; @@ -1506,7 +1618,8 @@ async fn a_host_permission_failure_while_seeding_initial_files_invalidates_the_g .await .unwrap_err(); assert!( - matches!(failure.source, Error::RuntimeInvalidated), + matches!(&failure.source, Error::Sandbox(source) + if source.io_kind() == Some(std::io::ErrorKind::PermissionDenied)), "{}", failure.source ); @@ -1546,7 +1659,8 @@ async fn a_host_permission_failure_while_seeding_a_restored_tree_invalidates_the .await .unwrap_err(); assert!( - matches!(failure.source, Error::RuntimeInvalidated), + matches!(&failure.source, Error::Sandbox(source) + if source.io_kind() == Some(std::io::ErrorKind::PermissionDenied)), "{}", failure.source ); @@ -1598,6 +1712,41 @@ async fn a_failed_hard_link_of_a_restored_tree_returns_the_sealed_filesystem() { delete(failure.filesystem).await.unwrap(); } +#[test] +async fn a_failed_cleanup_before_retrying_a_restored_tree_preserves_both_causes() { + let store = InitialFileStore::new().await; + let capture_record = record(&[], serde_json::json!([]), serde_json::json!([])); + let (filesystem, control, _) = + bound_reconstructing_with_recovery(ResolvedStorageLimits::Unlimited, None).await; + control.push_seed(Err(sandbox_error( + "seed restored tree", + std::io::ErrorKind::WouldBlock, + ))); + control.push_open(Err(sandbox_error( + "open partial tree for cleanup", + std::io::ErrorKind::PermissionDenied, + ))); + let failure = materialize_baseline( + filesystem, + store.prepare(&[]).await, + Some(FixtureRestore(move |into: &Path| { + write_capture_directory(into, &[], &capture_record); + Ok(()) + })), + ) + .await + .unwrap_err(); + assert!(matches!(&failure.source, Error::Sandbox(source) if source.cleanup_failed())); + let details = failure.source.to_string(); + assert!(details.contains("seed restored tree"), "{details}"); + assert!( + details.contains("open partial tree for cleanup"), + "{details}" + ); + control.push_delete_and_verify(Ok(())); + delete(failure.filesystem).await.unwrap(); +} + #[test] async fn a_retry_of_the_restored_tree_seed_removes_what_the_failed_attempt_made() { let store = InitialFileStore::new().await; diff --git a/golem-worker-executor/src/services/agent_filesystem_snapshots/store_calls.rs b/golem-worker-executor/src/services/agent_filesystem_snapshots/store_calls.rs index f23889043ec..be7bd08f350 100644 --- a/golem-worker-executor/src/services/agent_filesystem_snapshots/store_calls.rs +++ b/golem-worker-executor/src/services/agent_filesystem_snapshots/store_calls.rs @@ -1218,8 +1218,8 @@ mod tests { RestoreFailure::NotFound, RestoreFailure::Corrupt(anyhow::anyhow!("corrupt")), RestoreFailure::Destination(std::io::Error::other("read-only")), - RestoreFailure::Destination(std::io::Error::from_raw_os_error(libc::ENOSPC)), - RestoreFailure::Destination(std::io::Error::from_raw_os_error(libc::EDQUOT)), + RestoreFailure::Destination(std::io::ErrorKind::StorageFull.into()), + RestoreFailure::Destination(std::io::ErrorKind::QuotaExceeded.into()), ] .map(|failure| restore_class(&failure)), [ diff --git a/golem-worker-executor/src/services/file_loader.rs b/golem-worker-executor/src/services/file_loader.rs index 4053390a12c..3c5dfed206b 100644 --- a/golem-worker-executor/src/services/file_loader.rs +++ b/golem-worker-executor/src/services/file_loader.rs @@ -155,6 +155,9 @@ pub struct FileLoader { // We need to ensure that no one else is using the file while we are deleting it. // To do that, give every file a unique number. item_counter: AtomicU64, + /// Runs after persistence so a test can make protection and removal fail. + #[cfg(test)] + before_protect: Option std::io::Result<()>>, } impl FileLoader { @@ -172,6 +175,8 @@ impl FileLoader { cache_dir: Arc::new(cache_dir), admission: WorkAdmission::default(), item_counter: AtomicU64::new(0), + #[cfg(test)] + before_protect: None, } } @@ -313,11 +318,38 @@ impl FileLoader { tempfile::NamedTempFile::new_in(self.cache_dir.path().as_path()).map_err(failed)?; self.download_file(environment_id, &temporary, key, expected_size) .await?; - set_initial_file_read_only(temporary.as_file()).map_err(failed)?; - temporary.as_file().sync_all().map_err(failed)?; - temporary + // Windows persistence clears attributes. The cache entry stays locked until protection + // and sync finish, so no lease can observe the writable persisted file. + let file = temporary .persist_noclobber(path) .map_err(|error| failed(error.error))?; + let protected = self + .before_protect(path) + .and_then(|()| set_initial_file_read_only(&file)) + .and_then(|()| file.sync_all()); + drop(file); + if let Err(error) = protected { + if let Err(cleanup_error) = platform::remove_initial_file(path) { + // The loader still owns this path through cache_dir, which shutdown removes. + return Err(InitialFileLoadError::unavailable( + key, + format!( + "{error}; failed to remove persisted initial file {}: {cleanup_error}; the cache directory retains the file", + path.display() + ), + )); + } + return Err(failed(error)); + } + Ok(()) + } + + /// Runs the test hook before protection. Production code has no hook. + fn before_protect(&self, _path: &Path) -> std::io::Result<()> { + #[cfg(test)] + if let Some(before_protect) = self.before_protect { + before_protect(_path)?; + } Ok(()) } @@ -427,7 +459,7 @@ impl InitializedCacheEntry { impl Drop for InitializedCacheEntry { fn drop(&mut self) { debug!("Removing file {}", self.path.as_path().display()); - std::fs::remove_file(self.path.as_path()).expect("Failed to remove cached component file — executor filesystem is in an inconsistent state"); + platform::remove_initial_file(self.path.as_path()).expect("Failed to remove cached component file — executor filesystem is in an inconsistent state"); } } @@ -740,6 +772,48 @@ mod tests { (loader, hash, env_id) } + #[test] + async fn a_failed_protection_and_cleanup_returns_unavailable_and_keeps_cache_ownership() { + let content = b"unprotected persisted source"; + let (mut loader, hash, environment) = setup(content).await; + let cache = loader.cache_dir.path().as_path().to_path_buf(); + loader.before_protect = Some(|path| { + let retained = path.with_extension("retained"); + std::fs::rename(path, retained)?; + std::fs::create_dir(path)?; + Err(std::io::Error::other("injected protection failure")) + }); + let error = loader + .get_source(environment, hash, content.len() as u64) + .await + .unwrap_err(); + assert_eq!(error.failure, InitialFileLoadFailure::Unavailable); + assert!(error.to_string().contains("injected protection failure")); + assert!( + error + .to_string() + .contains("failed to remove persisted initial file") + ); + assert!( + error + .to_string() + .contains("the cache directory retains the file") + ); + let cleanup_error = std::fs::remove_file(cache.join("0")).unwrap_err(); + assert!(error.to_string().contains(&cleanup_error.to_string())); + assert_eq!(std::fs::read(cache.join("0.retained")).unwrap(), content); + + loader.before_protect = None; + let source = loader + .get_source(environment, hash, content.len() as u64) + .await + .unwrap(); + assert_eq!(std::fs::read(source.path().as_path()).unwrap(), content); + drop(source); + loader.shut_down().await.unwrap(); + assert!(!cache.exists()); + } + #[test] async fn shutdown_joins_downloads_and_source_leases_before_removing_cache_and_refuses_later_loads() { @@ -756,12 +830,16 @@ mod tests { let source = loading.await.unwrap(); assert!(source.path().as_path().is_file()); + let source_path = source.path().as_path().to_path_buf(); + assert!(source_path.metadata().unwrap().permissions().readonly()); let other = source.clone(); assert!(futures::poll!(&mut closing).is_pending()); drop(source); assert!(futures::poll!(&mut closing).is_pending()); assert!(path.is_dir()); + assert!(source_path.metadata().unwrap().permissions().readonly()); drop(other); + assert!(!source_path.exists()); closing.await.unwrap(); assert!(!path.exists()); let reads = storage.reads(); @@ -817,13 +895,16 @@ mod tests { .await .unwrap(); assert_eq!(source2.path().as_path(), path); + assert!(path.metadata().unwrap().permissions().readonly()); drop(source1); assert!(path.exists()); + assert!(path.metadata().unwrap().permissions().readonly()); drop(loader); assert!( path.is_file(), "a source lease keeps its cache directory alive" ); + assert!(path.metadata().unwrap().permissions().readonly()); drop(source2); assert!(!path.exists()); } @@ -859,7 +940,11 @@ mod tests { assert_eq!(source.path().as_path().parent(), Some(cache.as_path())); assert_eq!(std::fs::read(source.path().as_path()).unwrap(), content); + let path = source.path().as_path().to_path_buf(); + assert!(path.metadata().unwrap().permissions().readonly()); drop(source); + assert!(!path.exists()); + assert!(cache.is_dir()); drop(loader); assert!( !cache.exists(), diff --git a/golem-worker-executor/src/services/file_loader/other.rs b/golem-worker-executor/src/services/file_loader/other.rs index d6b3608bf1e..b224b2f9290 100644 --- a/golem-worker-executor/src/services/file_loader/other.rs +++ b/golem-worker-executor/src/services/file_loader/other.rs @@ -17,3 +17,14 @@ pub(super) fn set_initial_file_read_only(file: &std::fs::File) -> std::io::Resul permissions.set_readonly(true); file.set_permissions(permissions) } + +pub(super) fn remove_initial_file(path: &std::path::Path) -> std::io::Result<()> { + #[cfg(windows)] + { + // Windows cannot delete a read-only file. Only its final owner may clear protection. + let mut permissions = std::fs::metadata(path)?.permissions(); + permissions.set_readonly(false); + std::fs::set_permissions(path, permissions)?; + } + std::fs::remove_file(path) +} diff --git a/golem-worker-executor/src/services/file_loader/unix.rs b/golem-worker-executor/src/services/file_loader/unix.rs index 7a0f9eca734..0b0fe08aaa7 100644 --- a/golem-worker-executor/src/services/file_loader/unix.rs +++ b/golem-worker-executor/src/services/file_loader/unix.rs @@ -19,3 +19,7 @@ pub(super) fn set_initial_file_read_only(file: &std::fs::File) -> std::io::Resul permissions.set_mode(0o444); file.set_permissions(permissions) } + +pub(super) fn remove_initial_file(path: &std::path::Path) -> std::io::Result<()> { + std::fs::remove_file(path) +} diff --git a/golem-worker-executor/src/worker/runtime.rs b/golem-worker-executor/src/worker/runtime.rs index b09f2cb74c2..8b83f527b82 100644 --- a/golem-worker-executor/src/worker/runtime.rs +++ b/golem-worker-executor/src/worker/runtime.rs @@ -785,14 +785,7 @@ impl RunningWorker { pressure_recovery, ) .await - .map_err(|failure| CreateWorkerInstanceError::Failed { - error: WorkerExecutorError::recovery_required(failure.source.to_string()), - filesystem_cleanup_failure: failure.source.cleanup_failed().then(|| { - UnloadCleanupFailure::Other(WorkerExecutorError::runtime( - failure.source.to_string(), - )) - }), - })?; + .map_err(CreateWorkerInstanceError::from)?; created.observe_release(&parent.release_scope()); let retained_memory_grant = parent.linear_memory_grant(); let admitted_startup_bytes = retained_memory_grant.lock().unwrap().bytes(); @@ -1424,6 +1417,19 @@ pub(in crate::worker) fn shared_linear_memory_error( ) } +impl From for CreateWorkerInstanceError { + fn from(failure: crate::services::agent_filesystem::CreateFailure) -> Self { + Self::Failed { + error: WorkerExecutorError::recovery_required(failure.source.to_string()), + filesystem_cleanup_failure: failure.source.cleanup_failed().then(|| { + UnloadCleanupFailure::Other(WorkerExecutorError::runtime( + failure.source.to_string(), + )) + }), + } + } +} + impl From for CreateWorkerInstanceError { fn from(error: WorkerExecutorError) -> Self { Self::Failed { diff --git a/golem-worker-executor/src/worker/start_outcome/mod.rs b/golem-worker-executor/src/worker/start_outcome/mod.rs index 9d84c0ed7cf..ff529b76092 100644 --- a/golem-worker-executor/src/worker/start_outcome/mod.rs +++ b/golem-worker-executor/src/worker/start_outcome/mod.rs @@ -21,6 +21,8 @@ //! with one of the causes below starts its details with a stable code. use crate::durable_host::revision_update::UpdateStateError; +use crate::filesystem::blocking::BlockingTaskError; +use crate::filesystem::sandbox::FilesystemStorageError; use crate::model::{FailureProvenance, SnapshotReplayPurpose}; use crate::services::agent_filesystem::{Error as FilesystemError, RestoreClass}; use crate::services::agent_filesystem_snapshots::SnapshotsDisabled; @@ -292,7 +294,8 @@ pub(crate) fn success_details_of(head: &PendingUpdateRef) -> Option WorkerExecutorError { match error { FilesystemError::AgentQuota(_) => WorkerExecutorError::Interrupted { @@ -310,10 +313,22 @@ pub(crate) fn reconstruction_startup_error(error: &FilesystemError) -> WorkerExe stderr: String::new(), } } + FilesystemError::Sandbox(source) if permanent_storage_failure(source) => { + WorkerExecutorError::InvocationFailed { + error: AgentError::InternalError(error.to_string()), + stderr: String::new(), + } + } error => WorkerExecutorError::recovery_required(error.to_string()), } } +fn permanent_storage_failure(source: &FilesystemStorageError) -> bool { + source.is_terminal_failure() + && !source.cleanup_failed() + && !matches!(source.task_error(), Some(BlockingTaskError::Join(error)) if error.is_cancelled()) +} + /// The error of a failed initial-file rule at the update point: a full quota suspends, an /// unavailable initial-file source retries as a recovery, and every other error is a /// reconstruction error ([`reconstruction_startup_error`]). A refused initial-file source reaches @@ -321,7 +336,8 @@ pub(crate) fn reconstruction_startup_error(error: &FilesystemError) -> WorkerExe /// for it. /// /// The update point can be inside a host call of a replayed invocation, where only a required -/// recovery stays off the guest's failure path. An unavailable source is transient: the install +/// recovery stays off the guest's failure path. The outcome table fails the pending update for a +/// permanent sandbox refusal. An unavailable source is transient: the install /// loads every source before its first change, so the agent filesystem and the frozen attempt /// stay as they were, and the same attempt runs again. pub(crate) fn update_point_filesystem_error(error: &FilesystemError) -> WorkerExecutorError { @@ -445,6 +461,8 @@ enum StartProblem { Disabled, Restore(RestoreClass), RestoreConflict, + PermanentStorage, + UpdateStorage, Quota, Reconstruction, /// The instance did not instantiate. `target_trap` tells that the core initializer of the @@ -511,6 +529,9 @@ impl StartProblem { FilesystemError::InitialFileRefused { refusal, .. } => { Self::InitialFileRefused(*refusal) } + FilesystemError::Sandbox(source) if permanent_storage_failure(source) => { + Self::PermanentStorage + } FilesystemError::AgentQuota(_) => Self::Quota, FilesystemError::Access(_) | FilesystemError::Sandbox(_) @@ -557,7 +578,8 @@ impl StartProblem { Self::UpdateState(FetchProblem::of(error)) } // The initial-file rule at the update point fails the update for a conflict, an invalid - // source or a source that the blob storage refuses; other filesystem errors retry the start, + // source, a permanent sandbox refusal or a source that the blob storage refuses; + // other filesystem errors retry the start, // as they do at the restore. The update point restores nothing, so a restore error // counts as a reconstruction error. `update_point_filesystem_error` gives the error of // each passed one. @@ -568,6 +590,9 @@ impl StartProblem { FilesystemError::InitialFileRefused { refusal, .. } => { Self::BlobStorageRefused(*refusal) } + FilesystemError::Sandbox(source) if permanent_storage_failure(source) => { + Self::UpdateStorage + } FilesystemError::AgentQuota(_) => Self::Quota, FilesystemError::Access(_) | FilesystemError::Sandbox(_) @@ -746,6 +771,8 @@ fn cell(column: Column, problem: StartProblem) -> Cell { } Problem::ModeChange | Problem::RestoreConflict + | Problem::PermanentStorage + | Problem::UpdateStorage | Problem::ManualLoadFailed | Problem::ManualLoadExited | Problem::LoadUnavailable @@ -774,10 +801,11 @@ fn cell(column: Column, problem: StartProblem) -> Cell { Problem::Target(fetch) | Problem::UpdateState(fetch) => target(fetch), Problem::TargetUnsupported => coded(Code::TargetUnsupported), Problem::BlobStorageRefused(refusal) => coded(Code::BlobStorageRefused(refusal)), - Problem::ModeChange => fail, + Problem::ModeChange | Problem::UpdateStorage => fail, Problem::Disabled | Problem::Restore(_) | Problem::RestoreConflict + | Problem::PermanentStorage | Problem::Quota | Problem::Reconstruction | Problem::InitialFileRefused(_) => cell(base.column(), problem), @@ -802,6 +830,8 @@ fn cell(column: Column, problem: StartProblem) -> Cell { Problem::StaleSource | Problem::ModeChange | Problem::RestoreConflict + | Problem::PermanentStorage + | Problem::UpdateStorage | Problem::Instantiation { interrupted: false, .. } @@ -941,6 +971,8 @@ fn problem_class(problem: StartProblem) -> UpdateFailureClass { | Problem::TargetExecutor | Problem::Quota | Problem::Reconstruction + | Problem::PermanentStorage + | Problem::UpdateStorage | Problem::Instantiation { interrupted: false, .. } diff --git a/golem-worker-executor/src/worker/start_outcome/tests.rs b/golem-worker-executor/src/worker/start_outcome/tests.rs index e1bf4ca7bc2..fa771342c14 100644 --- a/golem-worker-executor/src/worker/start_outcome/tests.rs +++ b/golem-worker-executor/src/worker/start_outcome/tests.rs @@ -344,6 +344,14 @@ fn storage() -> FilesystemStorageError { FilesystemStorageError::from(OperationContext::verification("seed initial file", None)) } +fn sandbox_io(kind: std::io::ErrorKind) -> FilesystemStorageError { + FilesystemStorageError::io( + "seed initial file", + None, + std::io::Error::new(kind, "seed failed"), + ) +} + fn restore(class: RestoreClass) -> FilesystemError { FilesystemError::Baseline(Box::new(RestoreError { class, @@ -447,7 +455,7 @@ fn the_outcome_table() { Column::AssistedPromoted, ]; let refused = FetchProblem::Refused(ComponentServiceRefusal::Unauthorized); - let table: [(Problem, [&str; 7]); 38] = [ + let table: [(Problem, [&str; 7]); 40] = [ (Problem::StaleSource, ["P", "P", "P", "P", "P", "F", "P"]), (Problem::TargetExecutor, ["P", "P", "P", "P", "P", "P", "P"]), ( @@ -492,6 +500,11 @@ fn the_outcome_table() { Problem::RestoreConflict, ["P", "F", "P", "P", "P", "F", "P"], ), + ( + Problem::PermanentStorage, + ["P", "F", "P", "P", "P", "F", "P"], + ), + (Problem::UpdateStorage, ["P", "F", "P", "P", "F", "F", "P"]), (Problem::Quota, ["P", "P", "P", "P", "P", "P", "P"]), (Problem::Reconstruction, ["P", "P", "P", "P", "P", "P", "P"]), ( @@ -581,6 +594,7 @@ fn the_outcome_table() { Problem::Restore(RestoreClass::DiskFull), Problem::Restore(RestoreClass::Transient), Problem::RestoreConflict, + Problem::PermanentStorage, Problem::Quota, Problem::Reconstruction, Problem::InitialFileRefused(BlobRefusal::AccessDenied), @@ -697,6 +711,16 @@ fn each_raw_error_has_its_problem() { Problem::Reconstruction, ), (FilesystemError::Sandbox(storage()), Problem::Reconstruction), + ( + FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::PermissionDenied)), + Problem::PermanentStorage, + ), + ( + FilesystemError::Sandbox( + sandbox_io(std::io::ErrorKind::PermissionDenied).during_cleanup(), + ), + Problem::Reconstruction, + ), ( FilesystemError::InitialFileUnavailable(storage()), Problem::Reconstruction, @@ -1406,8 +1430,12 @@ fn a_restore_into_a_full_disk_fails_a_pending_update_and_says_that_the_disk_is_f use crate::services::agent_filesystem_snapshots::restore_class; let manual = manual_head(); let assisted = assisted_head(); - let failures = [libc::ENOSPC, libc::EDQUOT].map(|code| { - let failure = RestoreFailure::Destination(std::io::Error::from_raw_os_error(code)); + let failures = [ + std::io::ErrorKind::StorageFull, + std::io::ErrorKind::QuotaExceeded, + ] + .map(|kind| { + let failure = RestoreFailure::Destination(kind.into()); FilesystemError::Baseline(Box::new(RestoreError { class: restore_class(&failure), source: anyhow::Error::new(failure), @@ -1448,10 +1476,9 @@ fn a_restore_into_a_full_disk_fails_a_pending_update_and_says_that_the_disk_is_f } /// The initial-file rule at the update point fails the update for a conflict and for an -/// initial-file source that is invalid or that the blob storage refuses. A full quota suspends the start, an -/// initial-file source that the blob storage cannot give now retries as a recovery, and every -/// other filesystem error retries the start; -/// none of them writes a failed update. +/// initial-file source that is invalid or that the blob storage refuses, and for a permanent +/// sandbox refusal. A full quota suspends the start; transient errors and failed cleanup retry +/// the start without writing a failed update. #[test] fn the_initial_file_rule_at_the_update_point_fails_the_update_for_a_conflict_or_a_refused_source() { let assisted = assisted_head(); @@ -1478,7 +1505,7 @@ fn the_initial_file_rule_at_the_update_point_fails_the_update_for_a_conflict_or_ _ => "other", }; type MakeError = fn() -> FilesystemError; - let errors: [(MakeError, &str); 9] = [ + let errors: [(MakeError, &str); 13] = [ ( || FilesystemError::InitialFileConflict(Box::new(conflict())), "fail", @@ -1487,6 +1514,26 @@ fn the_initial_file_rule_at_the_update_point_fails_the_update_for_a_conflict_or_ (|| FilesystemError::InitialFileFailed(storage()), "fail"), (|| FilesystemError::AgentQuota(storage()), "suspend"), (|| FilesystemError::Sandbox(storage()), "recovery"), + ( + || FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::PermissionDenied)), + "fail", + ), + ( + || FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::ReadOnlyFilesystem)), + "fail", + ), + ( + || FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::InvalidData)), + "fail", + ), + ( + || { + FilesystemError::Sandbox( + sandbox_io(std::io::ErrorKind::PermissionDenied).during_cleanup(), + ) + }, + "recovery", + ), ( || FilesystemError::InitialFileUnavailable(storage()), "recovery", @@ -1950,13 +1997,17 @@ fn a_pending_baseline_fails_its_own_update_and_a_failed_load_names_its_record() ); } -/// Transient filesystem errors retry reconstruction, permanent file sources and baselines +/// Transient filesystem errors and failed cleanup retry reconstruction; permanent storage, +/// file sources and baselines /// fail the agent, and an agent quota suspends the start. #[test] fn reconstruction_startup_error_for_every_filesystem_error() { let transient = [ FilesystemError::Access(AccessError::Revoked), FilesystemError::Sandbox(storage()), + FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::TimedOut)), + FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::StorageFull)), + FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::PermissionDenied).during_cleanup()), FilesystemError::InitialFileUnavailable(storage()), FilesystemError::PhysicalCapacity(storage()), restore(RestoreClass::Transient), @@ -1968,6 +2019,16 @@ fn reconstruction_startup_error_for_every_filesystem_error() { FilesystemError::InitialFileConflict(Box::new(conflict())), restore(RestoreClass::Fixed), restore(RestoreClass::Lost), + FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::PermissionDenied)), + FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::ReadOnlyFilesystem)), + FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::InvalidData)), + FilesystemError::Sandbox(FilesystemStorageError::from( + OperationContext::task_failure( + "seed initial file", + None, + crate::filesystem::blocking::BlockingTaskError::Panicked, + ), + )), ]; assert!(matches!( @@ -1991,6 +2052,117 @@ fn reconstruction_startup_error_for_every_filesystem_error() { } ); }); + for (original, cleanup) in [ + ( + std::io::ErrorKind::WouldBlock, + std::io::ErrorKind::PermissionDenied, + ), + ( + std::io::ErrorKind::PermissionDenied, + std::io::ErrorKind::TimedOut, + ), + ] { + let error = FilesystemError::Sandbox( + sandbox_io(original).with_cleanup_failure(sandbox_io(cleanup)), + ); + assert_eq!( + reconstruction_startup_error(&error), + WorkerExecutorError::recovery_required(error.to_string()) + ); + assert_eq!( + StartProblem::of(&RawStartError::Filesystem(&error)), + StartProblem::Reconstruction + ); + } +} + +#[test] +fn permanent_storage_failures_of_pending_updates_are_operational() { + let assisted = assisted_head(); + let manual = manual_head(); + let automatic = automatic_head(); + for (role, head) in [ + ( + BaselineRole::AssistedPending(Arc::new(assisted.clone())), + assisted, + ), + ( + BaselineRole::ManualPending(Arc::new(manual.clone())), + manual, + ), + (BaselineRole::InitialFiles, automatic), + ] { + let error = FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::PermissionDenied)); + let update = UpdateStateError::InitialFiles(error); + assert_eq!( + StartProblem::of(&RawStartError::UpdateState(&update)), + StartProblem::UpdateStorage + ); + assert_eq!( + class_and_divergence(decide_now( + &role, + Some(&head), + RawStartError::UpdateState(&update) + )), + (UpdateFailureClass::Operational, None) + ); + if !matches!(role, BaselineRole::InitialFiles) { + let error = + FilesystemError::Sandbox(sandbox_io(std::io::ErrorKind::ReadOnlyFilesystem)); + assert_eq!( + class_and_divergence(decide_now( + &role, + Some(&head), + RawStartError::Filesystem(&error) + )), + (UpdateFailureClass::Operational, None) + ); + } + } +} + +#[test] +async fn cancelled_filesystem_work_keeps_the_update_pending() { + let task = tokio::spawn(std::future::pending::<()>()); + task.abort(); + let cancelled = task.await.unwrap_err(); + assert!(cancelled.is_cancelled()); + let error = FilesystemError::Sandbox(FilesystemStorageError::from( + OperationContext::task_failure( + "seed initial file", + None, + BlockingTaskError::Join(cancelled), + ), + )); + assert_eq!( + reconstruction_startup_error(&error), + WorkerExecutorError::recovery_required(error.to_string()) + ); + assert_eq!( + StartProblem::of(&RawStartError::Filesystem(&error)), + StartProblem::Reconstruction + ); + let update = UpdateStateError::InitialFiles(error); + assert_eq!( + StartProblem::of(&RawStartError::UpdateState(&update)), + StartProblem::Reconstruction + ); + for (role, head) in [ + (BaselineRole::InitialFiles, automatic_head()), + ( + BaselineRole::ManualPending(Arc::new(manual_head())), + manual_head(), + ), + ( + BaselineRole::AssistedPending(Arc::new(assisted_head())), + assisted_head(), + ), + ] { + assert!(matches!( + decide_now(&role, Some(&head), RawStartError::UpdateState(&update)), + StartAction::Error(WorkerExecutorError::RecoveryRequired { .. }) + )); + } } #[test] diff --git a/golem-worker-executor/src/worker/tests.rs b/golem-worker-executor/src/worker/tests.rs index 2869025a371..3d09a9e2b49 100644 --- a/golem-worker-executor/src/worker/tests.rs +++ b/golem-worker-executor/src/worker/tests.rs @@ -796,6 +796,109 @@ fn recovery_error_classification_keeps_only_transient_failures_retryable() { )); } +#[test] +fn sandbox_creation_failures_require_host_recovery_and_keep_cleanup_failures() { + use crate::filesystem::sandbox::FilesystemStorageError; + use crate::services::agent_filesystem::CreateFailure; + use std::io::{Error, ErrorKind}; + + let errors = vec![ + Error::from(ErrorKind::PermissionDenied), + Error::from(ErrorKind::ReadOnlyFilesystem), + Error::from(ErrorKind::InvalidData), + Error::from(ErrorKind::TimedOut), + ]; + #[cfg(any(target_os = "linux", target_os = "macos"))] + let errors = errors + .into_iter() + .chain([libc::EIO, libc::ESTALE, libc::ENODEV].map(Error::from_raw_os_error)); + + for error in errors { + for cleanup_failed in [false, true] { + let source = FilesystemStorageError::io( + "create fresh runtime directory", + None, + error + .raw_os_error() + .map_or_else(|| Error::from(error.kind()), Error::from_raw_os_error), + ); + let source = if cleanup_failed { + source.during_cleanup() + } else { + source + }; + let details = source.to_string(); + let CreateWorkerInstanceError::Failed { + error, + filesystem_cleanup_failure, + } = CreateWorkerInstanceError::from(CreateFailure { source }) + else { + panic!("sandbox creation failure must retain its error"); + }; + assert_eq!(error, WorkerExecutorError::recovery_required(details)); + assert!(is_infrastructure_recovery_error(&error)); + assert_eq!(filesystem_cleanup_failure.is_some(), cleanup_failed); + } + } +} + +#[cfg(unix)] +#[test] +#[test_r::timeout("30s")] +async fn an_unwritable_sandbox_root_retries_creation_after_host_repair() { + use crate::filesystem::sandbox::{SandboxFilesystemName, SandboxFilesystemProvisioning}; + use crate::services::agent_filesystem::CreateFailure; + use crate::services::golem_config::FilesystemStorageMode; + use std::os::unix::fs::PermissionsExt; + + if unsafe { libc::geteuid() == 0 } { + return; + } + + let parent = tempfile::tempdir().unwrap(); + let root = parent.path().join("sandboxes"); + std::fs::create_dir(&root).unwrap(); + let provisioning = SandboxFilesystemProvisioning::new( + &FilesystemStorageMode::Directory { + root: root.clone().into(), + }, + golem_common::model::RetryConfig::default(), + ) + .unwrap(); + let name = || { + SandboxFilesystemName::new( + "environment".to_string(), + "component".to_string(), + "agent".to_string(), + ) + .unwrap() + }; + let permissions = std::fs::metadata(&root).unwrap().permissions(); + std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o555)).unwrap(); + let failed = provisioning.create_fresh(name()).await; + std::fs::set_permissions(&root, permissions).unwrap(); + let source = match failed { + Err(error) => error, + Ok(_) => panic!("creation must fail on an unwritable root"), + }; + assert_eq!(source.io_kind(), Some(std::io::ErrorKind::PermissionDenied)); + let details = source.to_string(); + let CreateWorkerInstanceError::Failed { + error, + filesystem_cleanup_failure, + } = CreateWorkerInstanceError::from(CreateFailure { source }) + else { + panic!("sandbox creation failure must retain its error"); + }; + assert_eq!(error, WorkerExecutorError::recovery_required(details)); + assert!(is_infrastructure_recovery_error(&error)); + assert!(filesystem_cleanup_failure.is_none()); + let filesystem = provisioning.create_fresh(name()).await.unwrap(); + ::delete_and_verify(filesystem) + .await + .unwrap(); +} + #[test] fn recovery_error_classification_unwraps_failed_resume() { let error = WorkerExecutorError::failed_to_resume_worker( diff --git a/golem-worker-executor/worker-executor-walkthrough.html b/golem-worker-executor/worker-executor-walkthrough.html index 74e6de6e333..89354d4da83 100644 --- a/golem-worker-executor/worker-executor-walkthrough.html +++ b/golem-worker-executor/worker-executor-walkthrough.html @@ -578,6 +578,7 @@

Code & files services/{component,file_loader,agent_typ

On SIGTERM, the existing InvocationLoops watcher closes construction admission, fences oplogs and cancels worker tasks as soon as the shutdown token trips. gRPC stays open until the tracked shutdown wait ends and the server join set stops, so requests can be refused in that interval. wait_for_exit() actively stops worker roots and joins cleanup. Concurrent callers serialize this drain and can retry after failure. bootstrap::epoch_ticker::EpochTicker owns its thread from creation, so an early failure in snapshot binding or service construction stops and joins it. Failed bootstrap cancels only this executor's token and waits at most SHUTDOWN_GRACE for tracked cleanup. It does not abort tasks in the caller's join set. Cleanup can outlive the returned error if the grace expires. Cancelling the bootstrap future instead relies on the Drop fallback.

The test helper shutdown_and_wait_for_invocation_loops() keeps its invocation timeout separate from the later cleanup grace. Only a successful return proves both completed. It does not drop the service graph. A replacement over the same root must also wait for that graph to release its root lock.

filesystem::errors::OperationContext shares construction, formatting and cause access for an operation, optional path and typed failure. It owns no cleanup policy. The domain marks rollback failures as cleanup failures and retains both diagnostics when an operation and its cleanup fail. Preflight stale-probe removal is primary work, not cleanup. If a probe and its later removal both fail, the actual removal error supplies the cleanup classification. Task errors keep BlockingTaskError, have no I/O kind, and remain terminal. Any failed rollback deletion sets cleanup_failed so worker startup retains its cleanup obligation.

+

On Windows, sandbox creation opens a directory capability, not an ordinary file handle. Capture sets directory times before permissions through path-based operations; regular files set times through an open handle. Snapshot restore also sets times before the Windows read-only attribute. Guest directory sync is a no-op because Windows has no supported directory flush; regular files keep their existing sync policy. The initial-file loader persists each cache file before setting it read-only and syncing it, while holding the cache entry locked. No lease can observe the writable persisted file. Only its final owner clears the Windows read-only attribute before deleting it.

filesystem::errors::CleanupFailure<E> shares diagnostic-chain bookkeeping while each domain chooses classification. The type parameter keeps each original error's type, and conversion consumes and maps the chain. Bootstrap failure and process termination share Shutdown::cancel_and_wait_for_tracked; ownership of the server join set stays with the caller.

component downloads component bytes and precompiled artifacts from the registry and caches them; engines are built through the shared golem_common::wasmtime_config so precompiled artifacts stay loadable. file_loader fetches content-addressed initial files. Each agent gets its own filesystem (§6). services/agent_filesystem holds its lifecycle: the start, the baseline, the initial-file rule, the read-only checks and the storage errors. filesystem::sandbox owns each isolated tree and its confined operations. filesystem::volume owns the shared storage and its XFS or APFS implementation. Production uses XFS with project quotas, ManagedXfs, or XFS with reflink and without project quotas, ReflinkXfs. Local development uses plain directories, Temporary or Directory, or Apfs on macOS. Apfs adds file clones and volume free-space checks to a root that the executor creates as Directory does. The sandbox has the operations of each call, and two tree operations. seed puts host files into a sandbox. copy_contents takes sandbox files out to a host directory. Both make copy-on-write copies on XFS or Apfs, and byte copies on other storage. Each storage mode states how it accounts for the files of each agent. ReflinkXfs and Apfs state AgentAccounting::Unaccounted. resolve_storage_limits accepts unlimited policy on these modes but rejects finite Registry limits instead of silently dropping enforcement. Neither mode reports per-agent usage. The executor refuses to start with resource_usage_metering.filesystem = true on either mode through check_filesystem_metering, because filesystem metering reads the project quota of each agent. Pressure monitoring is in filesystem_pressure/mod.rs. WASI filesystem p2 and p3 expose the filesystem to the guest. environment_state caches deployments, secrets, retry policies and which tools an agent may reach. registry_event_subscriber invalidates those caches when the registry changes.

@@ -1323,9 +1324,9 @@

Each start builds the agent filesystem

Every start of an agent instance builds a new agent filesystem before it makes the Store and the instance. The lifecycle in services/agent_filesystem/lifecycle moves the filesystem through typed stages. Before the baseline is in place, the filesystem accepts no call of the guest. Replay access opens after the baseline and ends at finish_replay:

  1. Worker::decide_start selects the baseline record (§17), and StartFilesystem::load_and_plan plans it with filesystem_snapshots::plan_start and loads its restore, before the filesystem exists.
  2. -
  3. create_fresh_with_pressure_recovery makes an empty generation (Created), and the start binds its resource usage metering (Reconstructing). When the bind fails, the start deletes the Created filesystem (delete_created).
  4. -
  5. prepare_initial_files checks the declarations of the replay revision and loads their content into the .initial-files cache.
  6. -
  7. materialize_baseline puts the baseline in place and then enables replay access.
  8. +
  9. create_fresh_with_pressure_recovery makes an empty generation (Created), and the start binds its resource usage metering (Reconstructing). Every creation failure keeps infrastructure recovery and backoff, including permission denial, a read-only filesystem and device errors. This provisions an empty directory on the executor host, so a failure does not permanently fail a durable agent or its pending update. Any rollback cleanup failure is retained. When the bind fails, the start deletes the Created filesystem (delete_created).
  10. +
  11. prepare_initial_files checks the declarations of the replay revision and loads their content into the .initial-files cache. If protection or sync of a persisted cache file fails, the loader attempts to remove it. A failed removal returns Unavailable with both errors; the loader's cache directory still owns the leftover file until shutdown cleanup.
  12. +
  13. materialize_baseline puts the baseline in place and then enables replay access. decide_seed_failure selects a retry, a failure without invalidation, or invalidation through the effect policy and retry budget. A metadata read invalidates the generation only for a terminal storage error. Both paths preserve the storage error, including a failed usage observation after a full-disk error. A permanent storage refusal fails the start or its pending update through the outcome table; failed updates carry class Operational. Transient failures and cancelled blocking tasks retain recovery and backoff. Failed rollback cleanup remains recoverable until cleanup succeeds.
  14. prepare_instance replays. The filesystem calls of the guest during replay change the tree as they did live.
  15. Only Ok(None) from preparation continues to finish_replay, which ends replay access. Then finish_reconstruction checks the usage against the limits and makes the filesystem Resident.
@@ -2706,7 +2707,7 @@

Two public update modes

UpdateDescription::Automatic

PendingUpdate { target revision r2 } (hint) is appended, the worker is unloaded and reconstructed. Because an update is pending, automatic snapshots are ignored; the new instance is created for r2. prepare_instance runs try_load_snapshot on the baseline, then replay replays the remaining old history against the r2 component. Success appends SuccessfulUpdate during that replay.

-

If replay fails while the update is pending, on_worker_update_failed appends FailedUpdate and returns RetryDecision::Immediate: the outer loop rebuilds on the old revision, automatic snapshot eligible again. A conflict of the initial-file rule from r1 to r2 at the end of the replay fails the update the same way. An initial file of r2 that the blob storage refuses fails the update too (below). Another filesystem error there retries the start.

+

If replay fails while the update is pending, on_worker_update_failed appends FailedUpdate and returns RetryDecision::Immediate: the outer loop rebuilds on the old revision, automatic snapshot eligible again. A conflict of the initial-file rule from r1 to r2 at the end of the replay fails the update the same way. An initial file of r2 that the blob storage refuses fails the update too (below). Other filesystem errors follow the startup outcome table: a permanent storage refusal fails the pending update, while a transient failure retries the start.

The admission entry P records target r2 and is the update attempt's durable identity. When the agent is loaded at admission and its newest periodic record is not confirmed, the agent waits for the upload of that record, at most confirmation_wait, or asks the store once when no upload runs, before the restart, so the update can select that record (Worker::confirm_filesystem_snapshot_before_an_update). A Delayed retry does not wait. A stop, a revert, a retirement of the owner or a terminal interrupt ends that wait, and the wait does not count against the unload deadline of the restart. When that request reaches the head of the update queue, decide_start gives PersistStrategy, and create_instance appends a correlated pending entry with update_attempt_index: Some(P) that freezes the strategy. With no record that passes the selection below, the strategy is plain Automatic, a full replay. The status fold (worker/status/update_queue.rs) refines admission P with that entry instead of adding a second request. A failure of the load or the replay writes FailedUpdate with UPDATE_REPLAY_FAILED, also a divergence at a host call, and the agent runs on its source revision. At the update point, an initial file of the target that the blob storage refuses (an S3 4xx other than 408, 416 and 429 and without a code that asks for one more attempt, such as a 400 RequestTimeout, or PermissionDenied of the filesystem backend) writes FailedUpdate with UPDATE_BLOB_STORAGE_REFUSED; the install changed no file, so the agent runs on its source revision. A transient blob error writes nothing and retries as a recovery.

The replay for the pending update is speculative (SnapshotReplayPurpose::AutomaticUpdate): a trap while it replays recorded entries writes no invocation Error. An out-of-memory trap, in the load of the baseline or in the replay, keeps its retry (ReacquirePermits, DurableWorkerCtx::speculative_retry): the start runs again with new permits, writes no FailedUpdate, and the update stays pending. During the startup replay the status stays the one before the restart. An idle agent stays Idle, so interrupt_decision ignores an API interrupt: no Interrupted entry and no FailedUpdate are written, and the update completes without a resume. Only a Running, Suspended or Retrying status lets the interrupt through; the replay then writes no Interrupted entry, and the invocation loop records the request after the start (record_retry_interrupt_failure). A lost shard writes nothing, and the new owner runs the attempt again. The replay of a snapshot-assisted attempt and the replay after a periodic record do the same.

@@ -2818,6 +2819,7 @@

Local development on macOS

  • The next start (Worker::confirm_filesystem_snapshot_before_start, before the start takes permits, with AgentFilesystemSnapshots::prepare_start for the wait and the store check). When the start would select the last record if it were confirmed, it waits for an upload of that record on this executor for at most confirmation_wait, then asks the store once whether the snapshot is whole, for at most the rest of confirmation_wait, or for at most store_check_limit when it did not wait. A terminal interrupt ends the wait.
  • A start that finds no confirmed snapshot falls back to the previous usable record and replays from there. StartFilesystem::load_and_plan then plans the baseline of the selected record with plan_start and makes its restore, and StartFilesystem::materialize applies it to the new filesystem: the filesystem snapshot of a named record, or the initial files for a record without a name. §6 describes what the restore rebuilds.

    +

    Every filesystem restore run clears its destination first, including a root that is already empty. If a failed run leaves entries behind, the next run clears them before it restores again. On Unix and Windows the clear keeps the destination root, never follows links below it, refuses directories on another device or volume, and stops at 256 directory levels. On Windows it validates the opened root's final path before enumerating through that same retained handle. Only local drive paths are supported, not UNC or mapped network paths. It pins open ancestor directories against renames and deletes files, links and emptied child directories by handle without changing read-only attributes shared with other hard links. It checks each opened entry's reparse tag and accepts only symbolic links and mount points. An unsupported root or unknown reparse tag ends the restore permanently. A failure partway through a clear leaves the remaining entries for the next run.

    What a capture holds

    A periodic capture (lifecycle/baseline.rs::capture) stops new filesystem calls and waits up to capture_wait (5 s by default) for the calls that are open. A call that is still open then makes the capture give up with Busy: the loop writes no record, and the agent continues. A manual update captures with capture_whole, which never gives Unchanged; there a failed capture, Busy included, fails the update. A guest can hold a call across an invocation boundary with a wasi:io stream write that it never polls, so the wait needs a limit.

    While the calls are stopped, the capture finds one of three outcomes: Unchanged when the change counters of the generation equal the mark that the worker slot gives (the last confirmed snapshot, or the last tree of initial files, while a start would select its record now), InitialFiles when the tree is what a start from the initial files gives, and otherwise Captured. InitialFiles needs all of these: each declaration is a read-only initial file, nothing is provisioned, each declared file is the initial file with a single name and every stored path component has the declaration's exact spelling, no call set a chosen modification time, and the tree holds nothing else except the directories on the way to the files (holds_only_initial_files). A rename or hard link of any file, or a given time that the agent sets, counts as a change; a time that Golem puts back from a recorded stat does not. Only Captured copies. The copy_contents operation puts the copy into a new directory in .scratch. It makes one copy-on-write copy for each file on XFS or Apfs. With XFS project quotas, the capture adds nothing to the quota of the agent. The directory holds tree/ and the capture record, record.json.

    diff --git a/golem-worker-service/src/service/worker/connect_proxy.rs b/golem-worker-service/src/service/worker/connect_proxy.rs index 64e47e9781d..4d9a4466fd8 100644 --- a/golem-worker-service/src/service/worker/connect_proxy.rs +++ b/golem-worker-service/src/service/worker/connect_proxy.rs @@ -120,10 +120,17 @@ pub async fn proxy_worker_connection( info!("Closing websocket connection"); if let Err(error) = websocket.close().await { - error!( - error = error.to_string(), - "Error closing WebSocket connection" - ); + if matches!( + error.kind(), + std::io::ErrorKind::ConnectionReset + | std::io::ErrorKind::ConnectionAborted + | std::io::ErrorKind::BrokenPipe + | std::io::ErrorKind::NotConnected + ) { + info!(error = error.to_string(), "WebSocket peer disconnected before close completed"); + } else { + error!(error = error.to_string(), "Error closing WebSocket connection"); + } } else { info!("WebSocket connection successfully closed"); }