Golem custom snapshot rust

From golemcloud/golem · View interactive version

Golem custom snapshot rust is an AI agent skill from the GitHub repository golemcloud/golem. Enabling snapshot-based recovery and implementing custom snapshot save/load functions for Rust agents. Use when adding manual update support, custom state serialization, or — equally importantly — when a long-running agent's oplog is growing large and recovery/replay is becoming slow (heartbeats, po

How to use this skill

Skill file

Custom Snapshots in Rust

Golem agents can implement custom save_snapshot and load_snapshot functions to support manual (snapshot-based) updates and snapshot-based recovery.

When to Use Snapshotting

Snapshotting solves two distinct problems:

  1. Manual / snapshot-based component updates — required when updating agents between incompatible component versions.
  2. Fast recovery and reduced replay work — for long-running agents whose oplog grows over time (heartbeats, polling loops, recurring tasks, agents with frequent state changes). Without snapshotting, every recovery replays the full oplog from the beginning, which becomes increasingly expensive. With periodic snapshotting (every(N) or periodic(...)), recovery starts from the latest snapshot and replays only the entries after it.

You cannot opt out of oplog writes for a durable agent. Snapshots reduce recovery replay work; they do not reduce oplog writes or stored oplog volume. Do not try to skip persistence.

Enabling Snapshotting

Snapshotting must be enabled via the snapshotting attribute on #[agent_definition]. Without it, snapshotting is disabled:

#[agent_definition(mount = "/counters/{name}", snapshotting = "every(1)")]
pub trait CounterAgent {
    fn new(name: String) -> Self;

    #[endpoint(post = "/increment")]
    fn increment(&mut self) -> u32;
}

Snapshotting Modes

The snapshotting attribute accepts these values:

| Mode | Example | Description |

|------|---------|-------------|

| "disabled" | (default when omitted) | No snapshotting |

| "enabled" | snapshotting = "enabled" | Enable snapshot support with the server's default policy. The server default is disabled, so this may have no effect. Use "every(N)" or "periodic(…)" to guarantee snapshotting is active. |

| "every(N)" | snapshotting = "every(1)" | Snapshot every N successful function calls (use "every(1)" for every invocation) |

| "periodic(duration)" | snapshotting = "periodic(30s)" | Snapshot at most once per time interval (uses humantime durations) |

Snapshots are for durable agents only. An ephemeral agent takes no snapshots, and the SDK refuses an ephemeral agent definition whose snapshotting value is not disabled, with an error that names the agent.

#[agent_definition(mount = "/periodic/{name}", snapshotting = "periodic(30s)")]
pub trait PeriodicAgent { ... }

#[agent_definition(mount = "/batch/{name}", snapshotting = "every(10)")]
pub trait BatchAgent { ... }

Automatic Snapshotting (Default)

When snapshotting is enabled and the implementation has no custom save_snapshot/load_snapshot, the SDK provides JSON-based snapshotting — no custom code needed. The agent struct must then implement serde::Serialize and serde::de::DeserializeOwned; otherwise the build fails. The macros generate the snapshot handlers.

use serde::{Serialize, Deserialize};
use golem_rust::{agent_definition, agent_implementation, endpoint};

#[agent_definition(mount = "/counters/{name}", snapshotting = "every(1)")]
pub trait CounterAgent {
    fn new(name: String) -> Self;

    #[endpoint(post = "/increment")]
    fn increment(&mut self) -> u32;
}

#[derive(Serialize, Deserialize)]  // This enables automatic snapshotting
struct CounterImpl {
    name: String,
    count: u32,
}

#[agent_implementation(mount = "/counters/{name}")]
impl CounterAgent for CounterImpl {
    fn new(name: String) -> Self {
        Self { name, count: 0 }
    }

    #[endpoint(post = "/increment")]
    fn increment(&mut self) -> u32 {
        self.count += 1;
        self.count
    }
    // No save_snapshot/load_snapshot needed — serde handles it automatically
}

Custom Snapshotting

For custom binary formats, compatibility with non-Rust components, or migration between different state schemas, implement both save_snapshot and load_snapshot on the agent implementation:

use golem_rust::{agent_definition, agent_implementation, endpoint};

#[agent_definition(mount = "/snapshot-counters/{name}", snapshotting = "every(1)")]
pub trait CounterWithSnapshotAgent {
    fn new(name: String) -> Self;

    #[endpoint(post = "/increment")]
    fn increment(&mut self) -> u32;
}

struct CounterImpl {
    _name: String,
    count: u32,
}

#[agent_implementation(mount = "/snapshot-counters/{name}")]
impl CounterWithSnapshotAgent for CounterImpl {
    fn new(name: String) -> Self {
        Self {
            _name: name,
            count: 0,
        }
    }

    #[endpoint(post = "/increment")]
    fn increment(&mut self) -> u32 {
        self.count += 1;
        log::info!("The new value is {}", self.count);
        self.count
    }

    async fn load_snapshot(
        bytes: Vec<u8>,
        context: golem_rust::agentic::SnapshotRestoreContext,
    ) -> Result<Self, String> {
        let arr: [u8; 4] = bytes
            .try_into()
            .map_err(|_| "Expected a 4-byte long snapshot")?;
        let mut parameters = golem_rust::agentic::DirectAgentInput::new(context.parameters)
            .map_err(|error| error.to_string())?;
        let name: String = parameters
            .take()
            .map_err(|error| error.to_string())?;
        parameters.finish().map_err(|error| error.to_string())?;

        Ok(Self {
            _name: name,
            count: u32::from_be_bytes(arr),
        })
    }

    async fn save_snapshot(&self) -> Result<Vec<u8>, String> {
        Ok(self.count.to_be_bytes().to_vec())
    }
}

Rules

Method Signatures

// Save: serialize the agent's current state to bytes
async fn save_snapshot(&self) -> Result<Vec<u8>, String>

// Load: construct a complete agent from previously saved bytes and restore context
async fn load_snapshot(
    bytes: Vec<u8>,
    context: SnapshotRestoreContext,
) -> Result<Self, String>

Restoration Is Read-Only

load_snapshot is a specially supported SDK lifecycle operation, not an agent method. Golem runs it in read-only mode and does not write anything it does to the oplog. Decoding, local computation, fresh randomness, config reads, and other permitted reads can be used to build the returned value. Mutating host operations and outgoing HTTP or agent RPC calls are rejected before they take effect.

Do not initialize an ordinary instance and mutate it after loading. Construct and return the complete restored Self; the SDK installs it only after the factory succeeds.

A Restored Agent Must Behave Like the Live Agent

After load_snapshot, Golem replays the invocations recorded after the snapshot and compares every result with the oplog. The restored agent must give exactly the results that the live agent gave, for every later method result and host call. When a result differs, the replay diverges with Unexpected oplog entry at <index>: expected …, got …, and the error names the oplog index of the snapshot that the failing replay started from, if any, and the oplog indexes of the snapshots that recovery rejected before it. After an automatic snapshot, Golem rejects the snapshot and tries an older restore point. But once the agent has run live from a faulty restore, for example after a restart right after a snapshot, no older restore point reproduces the results it recorded, and the agent fails with a Recovery error, possibly long after the snapshot was taken.

So load_snapshot must rebuild every value that a later result depends on in the same way as the live code keeps it. This also applies to the automatic serde snapshotting when fields use #[serde(skip)] or a custom deserializer. Common mistakes:

Test restoration by behavior. Keep the encoding and decoding in plain functions over the state, apply the same operations to a live state and to the state decoded from its encoding, and compare the results of every method that reads state:

#[test]
fn restored_state_behaves_like_live_state() {
    let mut live = State::default();
    live.add("a");
    let mut restored = State::decode(&live.encode()).unwrap();
    assert_eq!(restored.add("bb"), live.add("bb"));
}

Comparing save(load(save(x))) with save(x) is not enough: it does not find a value that save_snapshot leaves out.

Agent Files

A snapshot holds only the agent's in-memory state: the serde form of the agent, or the bytes that save_snapshot returns. It does not hold the files that the agent wrote.

Filesystem snapshots are off by default on standalone executors and on local servers, except golem server run on macOS. See Agent files and snapshots.

Best Practices

  1. Prefer automatic (serde) snapshotting unless you need a compact binary format or cross-version migration logic.
  2. Keep snapshots small — large snapshots impact recovery and update time.
  3. Version your snapshot format — include a version byte or tag so load_snapshot can handle snapshots from older versions.
  4. Test round-trips by behavior — verify that the state that load_snapshot returns, without calling new, gives the same method results as the live state. See A Restored Agent Must Behave Like the Live Agent.
  5. Handle migration — when the state schema changes between versions, load_snapshot in the new version should be able to parse snapshots from the old version.

Project Template

A ready-made project with snapshotting can be created using:

golem new --yes --template rust/snapshotting my-project
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.