Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .agents/skills/understanding-durable-execution/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
11 changes: 7 additions & 4 deletions cli/golem-cli/src/command_handler/agent/invocation_session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}

Expand Down
147 changes: 114 additions & 33 deletions cli/golem-cli/src/command_handler/agent/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -145,6 +144,7 @@ pub struct LiveOutput {
options: AgentLogStreamOptions,
goal: Option<InvocationGoal>,
connection: std::sync::Mutex<Option<task::JoinHandle<anyhow::Result<()>>>>,
stop: CancellationToken,
}

impl LiveOutput {
Expand All @@ -161,6 +161,7 @@ impl LiveOutput {
options,
goal: wait_for_invocation.then(InvocationGoal::new),
connection: std::sync::Mutex::new(None),
stop: CancellationToken::new(),
}
}

Expand Down Expand Up @@ -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()));
Expand All @@ -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<anyhow::Result<()>>,
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;
}
}
}
}
Expand Down Expand Up @@ -331,6 +348,7 @@ pub struct AgentConnection {
agent_name: String,
goal: Option<InvocationGoal>,
ping_interval: Duration,
stop: CancellationToken,
}

impl AgentConnection {
Expand Down Expand Up @@ -370,6 +388,7 @@ impl AgentConnection {
agent_name,
goal: wait_for_invocation.then(InvocationGoal::new),
ping_interval,
stop: CancellationToken::new(),
})
}

Expand All @@ -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::<crate::error::service::ServiceError>()
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -630,7 +652,7 @@ impl AgentConnection {
}

async fn ping_loop(
mut write: SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>,
write: &mut SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>,
ping_interval: Duration,
) -> anyhow::Error {
let mut interval = time::interval(ping_interval);
Expand All @@ -653,7 +675,7 @@ impl AgentConnection {
}

async fn read_loop(
mut read: SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>,
read: &mut SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>,
output: AgentStreamOutput,
agent_name: String,
goal: Option<InvocationGoal>,
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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<AgentConnection> {
Expand Down Expand Up @@ -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();
}
}

Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
}
}
3 changes: 2 additions & 1 deletion golem-registry-service/src/grpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
7 changes: 4 additions & 3 deletions golem-registry-service/src/repo/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -127,7 +127,7 @@ impl<DBP: Pool> DbPluginRepo<DBP> {
#[golem_async_trait::region_simple]
impl PluginRepo for DbPluginRepo<PostgresPool> {
async fn create(&self, plugin: PluginRecord) -> RepoResult<Option<PluginRecord>> {
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,
Expand All @@ -138,6 +138,7 @@ impl PluginRepo for DbPluginRepo<PostgresPool> {
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,
Expand All @@ -163,7 +164,7 @@ impl PluginRepo for DbPluginRepo<PostgresPool> {
.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<Option<PluginRecord>> {
Expand Down
Loading
Loading