Golem custom snapshot go

From golemcloud/golem · View interactive version

Golem custom snapshot go is an AI agent skill from the GitHub repository golemcloud/golem. Configures custom snapshot recovery for Go agents and explains unresolved default JSON recovery and manual update limitations. Use when asked about custom snapshots, snapshot-based updates, or slow recovery in Go agents.

How to use this skill

Skill file

Custom Snapshots in Go

Availability

Use Snapshotter with an explicit policy to restore state after a restart.

Rebuild transient state in OnRestore. There is no go/snapshotting CLI template.

Default JSON recovery remains unresolved because of Go runtime clock-read

divergence. Use custom snapshots instead.

Do not use manual snapshot-based component updates: runtime startup host

calls remain a separate limitation.

Overview

Snapshotting serializes a running Go agent's state so the host can save it and later restore it. Custom snapshots reduce recovery replay for long-running agents: recovery loads a restore point and replays subsequent oplog entries. This recovery workflow is distinct from changing the component through a manual update.

You cannot opt out of oplog writes for a durable agent. Do not skip persistence to reduce oplog volume or replay cost. Use custom snapshot recovery when reducing replay cost, with the limitations above.

Two things to set

  1. A snapshot policy on the agent's Spec — whether and how often the platform snapshots. Without a policy, no snapshots are taken.
  2. A custom serializer — implement golem.Snapshotter to save and restore the agent's state.

Step 1: enable a snapshot policy (`Spec.Snapshot`)

Set Snapshot on the agent definition's Spec. The zero value is golem.SnapshotDisabled.

var Agent = golem.DefineAgent[ID](golem.Spec{
    Name:     "SessionAgent",
    Snapshot: golem.SnapshotEveryN(5), // snapshot every 5 invocations
})

Policy builders (from `golem.go`)

| Builder | Meaning |

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

| golem.SnapshotDisabled | Zero value — never snapshot |

| golem.SnapshotDefault | Platform's default cadence (note: the server default may itself be disabled — prefer an explicit policy) |

| golem.SnapshotPeriodic(d time.Duration) | Snapshot at most once per interval |

| golem.SnapshotEveryN(n uint16) | Snapshot every n invocations (SnapshotEveryN(1) = every invocation) |

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

Snapshot: golem.SnapshotEveryN(1)                     // every invocation
Snapshot: golem.SnapshotPeriodic(30 * time.Second)    // at most once per 30s

Step 2a: automatic (default) snapshotting

If you set a policy and do nothing else, the SDK JSON-encodes the state's exported fields. Because of the default JSON recovery limitation above, use the custom path below for recovery.

Caveat: Go reflection cannot see unexported fields. The idiomatic private state (e.g. an unexported count) is invisible to the default snapshot and would be dropped. To capture unexported state, implement golem.Snapshotter (Step 2b).

Step 2b: custom snapshotting (`golem.Snapshotter`)

Implement Save/Load on the state type (pointer receiver) for custom recovery, including unexported fields or a compact binary format:

type Snapshotter interface {
    Save() ([]byte, error)
    Load([]byte) error
}

When the state implements Snapshotter, its bytes are stored verbatim by the host (opaque payload) and handed back on restore — bypassing the reflective JSON path entirely.

Step 2c: JSON state and named bytes (`golem.MultipartSnapshotter`)

Multipart serialization is available, but restart recovery remains unverified. Use the binary

Snapshotter recipe above unless you validate multipart recovery on your runtime.

When the state holds binary data that should not go through JSON (an index, an image), implement SaveParts/LoadParts instead of Snapshotter. The snapshot is a small JSON projection plus named parts of opaque bytes with a bare MIME type:

type savedState struct {
    Revision uint32 `json:"revision"`
}

func (s *state) SaveParts() (golem.MultipartSnapshot, error) {
    return golem.NewMultipartSnapshot(savedState{Revision: s.revision}, map[string]golem.SnapshotPart{
        "index": {Bytes: s.index, ContentType: "application/octet-stream"},
    })
}

func (s *state) LoadParts(snapshot golem.MultipartSnapshot) error {
    var saved savedState
    if err := snapshot.DecodeState(&saved); err != nil {
        return err
    }
    index, err := snapshot.RequirePart("index", "application/octet-stream")
    if err != nil {
        return err
    }
    *s = state{revision: saved.Revision, index: index}
    return nil
}

Part names start with a letter, a digit or _, and continue with those, . or -. A state that implements both Snapshotter and MultipartSnapshotter is a definition error.

Step 3 (optional): rebuild runtime-only state (`OnRestore`)

A restore does not run the constructor passed to Implement: whatever it did (an RPC, an HTTP request) is already in the history the snapshot replaces, and the restore runs read-only. The state starts from its zero value, the snapshot is loaded into it, and then the OnRestore hook runs, if registered. Use it to rebuild what the snapshot does not carry (clients, caches, derived fields):

agent.OnRestore(func(ic *golem.InitContext[session.ID, state, golem.NoConfig], s *state) error {
    // rebuild runtime-only fields of s, e.g. from ic.ID().User;
    // ic also has AgentID(), Principal() and Config()
    return nil
})

An error from the hook fails the restore, like an error from Load. The restored state must behave like the state it replaces: the calls recorded after the snapshot are replayed on it, and a different result is a divergence.

Agent Files

A snapshot holds only the agent's in-memory state: the JSON of the exported fields, or what Save or SaveParts 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.

Full example: session agent with custom snapshot

Definition (`agents/session/session.go`)

// Package session is the DEFINITION of the session agent. Its behaviour, private
// state, and custom snapshot serialization live in the impl subpackage.
package session

import "github.com/golemcloud/golem/sdks/go/golem"

type ID struct{ User string }

type SpendIn struct{ Amount int64 }

// Snapshot every 5 invocations instead of the default cadence. Mode defaults to Durable.
var Agent = golem.DefineAgent[ID](golem.Spec{
    Name:        "SessionAgent",
    Description: "A session that snapshots its running total every few invocations",
    Snapshot:    golem.SnapshotEveryN(5),
})

var (
    Spend = Agent.Method[SpendIn, int64]("spend", golem.Description("Add to the running total"))
    Total = Agent.Method[golem.Unit, int64]("total", golem.Description("Return the running total"))
)

Implementation (`agents/session/impl/impl.go`)

// Package impl holds the session agent's private state, method handlers, and
// custom snapshot serialization. Importing it registers the agent.
package impl

import (
    "encoding/binary"
    "fmt"

    "myapp/agents/session"

    "github.com/golemcloud/golem/sdks/go/golem"
)

// state keeps a running total in an UNEXPORTED field. Reflection cannot see it,
// so the default snapshot (JSON of exported fields) would drop it — implementing
// golem.Snapshotter below is what makes the state survive.
type state struct{ total int64 }

// Save/Load make *state a golem.Snapshotter: the returned bytes are stored
// verbatim by the host and handed back on restore, so unexported state is kept.
func (s *state) Save() ([]byte, error) {
    b := make([]byte, 8)
    binary.LittleEndian.PutUint64(b, uint64(s.total))
    return b, nil
}
func (s *state) Load(b []byte) error {
    if len(b) != 8 {
        return fmt.Errorf("invalid snapshot length: got %d, want 8", len(b))
    }
    s.total = int64(binary.LittleEndian.Uint64(b))
    return nil
}

var agent = session.Agent.Implement(func(session.ID) *state { return &state{} })

func init() {
    agent.Handle(session.Spend, func(ctx *golem.Context[state], in session.SpendIn) int64 {
        ctx.State.total += in.Amount
        return ctx.State.total
    })
    agent.Handle(session.Total, func(ctx *golem.Context[state], _ golem.Unit) int64 {
        return ctx.State.total
    })
}

Best practices

  1. Use Snapshotter for recovery — do not rely on the default JSON serializer.
  2. Validate your format — reject malformed or unexpected snapshot data in Load.
  3. Keep snapshots small — large snapshots slow recovery.
  4. Test round-trips — Save → Load should reproduce equivalent state (this is native, host-free, so it unit-tests easily).

Key Constraints

Related Skills

| Skill | When to Load |

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

| golem-add-agent-go | Define the agent whose state is snapshotted |

| golem-configure-durability-go | Other durability controls on an agent |

| golem-recurring-task-go | Long-running agents that benefit most from snapshotting |

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.