Skip to navigation

Handle restarts

Pick up where your integration left off after a restart or a lost connection.

Integrations at the edge restart often: a vehicle powers down, a process crashes, a new version rolls out. Lattice can’t tell a planned shutdown from a failure, so everything your integration created stays as it was:

  • Entities stay until their expiry_time passes.
  • Tasks stay in their last reported status. Lattice doesn’t close a task your agent has started.
  • Video ingress streams stay, and show STREAM_STATUS_INACTIVE once frames stop arriving.

An integration that starts over with new IDs leaves operators with duplicate assets, tasks stuck in STATUS_EXECUTING, and several feeds for one camera. To avoid that, make sure your integration can find everything it owns after a restart, and reconcile it with Lattice before it resumes work.

Before you begin

Decide which IDs to keep

You can only reconcile a resource if you know its ID after the restart. If you choose the ID, derive it from something that never changes for the asset, such as a serial number, so there’s nothing to save. If someone else chooses it, save it as soon as you receive it.

ResourceIDChosen byApproach
Entityentity_idYour integrationDerive it.
Video ingress streamingress_idYour integration, or Lattice if you omit itDerive it and pass it to CreateIngressStream. Keep it to 4–36 characters.
Task your agent executestask_idThe task’s creatorSave it when your agent starts the task.
Task your integration createstask_idYour integration, or Lattice if you omit itSave it when you create the task.

Each step in Recover on startup starts with its ID: how the example derives the ingress and entity IDs from one asset name, and how it saves task IDs.

Recover on startup

Run these steps once at startup, before your publish loop or agent stream starts. Recovery makes several calls in a row, often while the network is still coming up, so wrap them in a retry utility. The code samples are excerpts from one script.

1

Reconnect your video stream

Derive the ingress ID from the asset name. The readable <group>.<name> pattern is the one Lattice recommends:

// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"slices"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/core"
"github.com/anduril/lattice-sdk-go/v5/option"
"github.com/google/uuid"
)
// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()
const (
// RTSP source that Lattice pulls video from. Replace before running.
rtspURL = "rtsp://<rtsp-host>:<port>/cam"
// Local file that stores the IDs of tasks this agent is executing.
stateFile = "agent_state.json"
)
var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
Lattice.TaskStatusStatusStatusDoneOk: true,
Lattice.TaskStatusStatusStatusDoneNotOk: true,
}
type agentState struct {
TaskIDs []string `json:"task_ids"`
}
func loadTaskIDs() (map[string]bool, error) {
taskIDs := map[string]bool{}
data, err := os.ReadFile(stateFile)
if errors.Is(err, os.ErrNotExist) {
return taskIDs, nil
}
if err != nil {
return nil, err
}
var state agentState
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
for _, taskID := range state.TaskIDs {
taskIDs[taskID] = true
}
return taskIDs, nil
}
func saveTaskIDs(taskIDs map[string]bool) error {
ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
slices.Sort(ids)
data, err := json.Marshal(agentState{TaskIDs: ids})
if err != nil {
return err
}
// Write to a temporary file, then rename it over the original. A power loss during the
// write leaves the previous file intact instead of a truncated one.
f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), stateFile)
}
// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
taskIDs[taskID] = true
return saveTaskIDs(taskIDs)
}
// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
delete(taskIDs, taskID)
return saveTaskIDs(taskIDs)
}
func reconnectVideo(ctx context.Context, client *client.Client) error {
response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
IngressID: ingressID,
})
var apiErr *core.APIError
if err == nil {
// The stream survived the restart. Reuse it instead of creating a duplicate.
status := ""
if s := response.GetIngressStream().GetStatus(); s != nil {
status = string(*s)
}
fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
return nil
}
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
return err
}
// Lattice returns not found both for a stream that never existed and for one that was deleted.
_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
IngressID: Lattice.String(ingressID),
Title: Lattice.String(assetName),
Rtsp: &Lattice.RtspSettings{
URL: Lattice.String(rtspURL),
},
})
if err != nil {
return err
}
fmt.Printf("Created stream %s\n", ingressID)
return nil
}
func publishEntity(ctx context.Context, client *client.Client) error {
now := time.Now().UTC()
_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
EntityID: Lattice.String(entityID),
IsLive: Lattice.Bool(true),
ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
Aliases: &Lattice.Aliases{Name: Lattice.String(assetName)},
MilView: &Lattice.MilView{
Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
},
Ontology: &Lattice.Ontology{
Template: Lattice.OntologyTemplateTemplateAsset.Ptr(),
PlatformType: Lattice.String("CAMERA"),
},
Location: &Lattice.Location{
Position: &Lattice.Position{
LatitudeDegrees: Lattice.Float64(33.6411),
LongitudeDegrees: Lattice.Float64(-117.9187),
},
},
// Because ingressID never changes, the entity can reference the stream on every publish.
Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
ItemIdentifier: Lattice.String(ingressID),
Type: Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
}}},
// Include every other component your integration publishes, such as its TaskCatalog.
Provenance: &Lattice.Provenance{
IntegrationName: Lattice.String("my-integration"),
DataType: Lattice.String("asset"),
SourceUpdateTime: Lattice.Time(now),
},
})
if err != nil {
return err
}
fmt.Printf("Republished entity %s\n", entityID)
return nil
}
func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
var apiErr *core.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
// The task no longer exists in Lattice, so there's nothing to resolve.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
if err != nil {
return err
}
if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
continue
}
status := *task.Status.Status
if terminalStatuses[status] {
// An operator or another system closed the task while the agent was offline.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
var taskError *Lattice.TaskError
cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
(task.GetDeliveryState().GetStatus() != nil &&
*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
if cancelled {
// An operator cancelled the task while the agent was offline. Lattice records the cancel
// in delivery_state, not in the task status. Accept the cancellation.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
Message: Lattice.String("Cancelled while the agent was offline."),
}
} else {
// The agent lost its execution context, so report the task as failed rather than
// leave it active with nothing working on it.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
Message: Lattice.String("Agent restarted and could not resume the task."),
}
}
// Read the status version from GetTask, not from local state: the status might have
// changed while the agent was offline, and Lattice ignores updates with a stale version.
statusVersion := *task.Version.StatusVersion + 1
_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
TaskID: taskID,
StatusVersion: &statusVersion,
NewStatus: &Lattice.TaskStatus{
Status: Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
TaskError: taskError,
},
Author: author,
})
if err != nil {
return err
}
fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
}
return nil
}
func main() {
// Get environment variables
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
// Check required environment variables
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Initialize headers for sandbox authorization
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
// Create the client
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
ctx := context.Background()
taskIDs, err := loadTaskIDs()
if err != nil {
fmt.Printf("Failed to load saved task IDs: %v\n", err)
os.Exit(1)
}
if err := reconnectVideo(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to reconnect video: %v\n", err)
os.Exit(1)
}
if err := publishEntity(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to republish entity: %v\n", err)
os.Exit(1)
}
if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
os.Exit(1)
}
// Recovery is complete. Start your regular publish loop and agent stream here, and call
// trackTask and untrackTask as tasks start and finish.
}

Call GetIngressStream with your ingress ID:

  • Found: Reuse the stream. For SRT and MPEG-TS, resume pushing to the stream’s url. For RTSP, Lattice pulls from the source URL you gave it, so make sure your source serves video there again.
  • Not found (404 in REST, NOT_FOUND in gRPC): Create the stream with the same ingress ID.
// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"slices"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/core"
"github.com/anduril/lattice-sdk-go/v5/option"
"github.com/google/uuid"
)
// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()
const (
// RTSP source that Lattice pulls video from. Replace before running.
rtspURL = "rtsp://<rtsp-host>:<port>/cam"
// Local file that stores the IDs of tasks this agent is executing.
stateFile = "agent_state.json"
)
var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
Lattice.TaskStatusStatusStatusDoneOk: true,
Lattice.TaskStatusStatusStatusDoneNotOk: true,
}
type agentState struct {
TaskIDs []string `json:"task_ids"`
}
func loadTaskIDs() (map[string]bool, error) {
taskIDs := map[string]bool{}
data, err := os.ReadFile(stateFile)
if errors.Is(err, os.ErrNotExist) {
return taskIDs, nil
}
if err != nil {
return nil, err
}
var state agentState
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
for _, taskID := range state.TaskIDs {
taskIDs[taskID] = true
}
return taskIDs, nil
}
func saveTaskIDs(taskIDs map[string]bool) error {
ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
slices.Sort(ids)
data, err := json.Marshal(agentState{TaskIDs: ids})
if err != nil {
return err
}
// Write to a temporary file, then rename it over the original. A power loss during the
// write leaves the previous file intact instead of a truncated one.
f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), stateFile)
}
// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
taskIDs[taskID] = true
return saveTaskIDs(taskIDs)
}
// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
delete(taskIDs, taskID)
return saveTaskIDs(taskIDs)
}
func reconnectVideo(ctx context.Context, client *client.Client) error {
response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
IngressID: ingressID,
})
var apiErr *core.APIError
if err == nil {
// The stream survived the restart. Reuse it instead of creating a duplicate.
status := ""
if s := response.GetIngressStream().GetStatus(); s != nil {
status = string(*s)
}
fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
return nil
}
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
return err
}
// Lattice returns not found both for a stream that never existed and for one that was deleted.
_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
IngressID: Lattice.String(ingressID),
Title: Lattice.String(assetName),
Rtsp: &Lattice.RtspSettings{
URL: Lattice.String(rtspURL),
},
})
if err != nil {
return err
}
fmt.Printf("Created stream %s\n", ingressID)
return nil
}
func publishEntity(ctx context.Context, client *client.Client) error {
now := time.Now().UTC()
_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
EntityID: Lattice.String(entityID),
IsLive: Lattice.Bool(true),
ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
Aliases: &Lattice.Aliases{Name: Lattice.String(assetName)},
MilView: &Lattice.MilView{
Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
},
Ontology: &Lattice.Ontology{
Template: Lattice.OntologyTemplateTemplateAsset.Ptr(),
PlatformType: Lattice.String("CAMERA"),
},
Location: &Lattice.Location{
Position: &Lattice.Position{
LatitudeDegrees: Lattice.Float64(33.6411),
LongitudeDegrees: Lattice.Float64(-117.9187),
},
},
// Because ingressID never changes, the entity can reference the stream on every publish.
Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
ItemIdentifier: Lattice.String(ingressID),
Type: Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
}}},
// Include every other component your integration publishes, such as its TaskCatalog.
Provenance: &Lattice.Provenance{
IntegrationName: Lattice.String("my-integration"),
DataType: Lattice.String("asset"),
SourceUpdateTime: Lattice.Time(now),
},
})
if err != nil {
return err
}
fmt.Printf("Republished entity %s\n", entityID)
return nil
}
func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
var apiErr *core.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
// The task no longer exists in Lattice, so there's nothing to resolve.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
if err != nil {
return err
}
if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
continue
}
status := *task.Status.Status
if terminalStatuses[status] {
// An operator or another system closed the task while the agent was offline.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
var taskError *Lattice.TaskError
cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
(task.GetDeliveryState().GetStatus() != nil &&
*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
if cancelled {
// An operator cancelled the task while the agent was offline. Lattice records the cancel
// in delivery_state, not in the task status. Accept the cancellation.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
Message: Lattice.String("Cancelled while the agent was offline."),
}
} else {
// The agent lost its execution context, so report the task as failed rather than
// leave it active with nothing working on it.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
Message: Lattice.String("Agent restarted and could not resume the task."),
}
}
// Read the status version from GetTask, not from local state: the status might have
// changed while the agent was offline, and Lattice ignores updates with a stale version.
statusVersion := *task.Version.StatusVersion + 1
_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
TaskID: taskID,
StatusVersion: &statusVersion,
NewStatus: &Lattice.TaskStatus{
Status: Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
TaskError: taskError,
},
Author: author,
})
if err != nil {
return err
}
fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
}
return nil
}
func main() {
// Get environment variables
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
// Check required environment variables
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Initialize headers for sandbox authorization
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
// Create the client
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
ctx := context.Background()
taskIDs, err := loadTaskIDs()
if err != nil {
fmt.Printf("Failed to load saved task IDs: %v\n", err)
os.Exit(1)
}
if err := reconnectVideo(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to reconnect video: %v\n", err)
os.Exit(1)
}
if err := publishEntity(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to republish entity: %v\n", err)
os.Exit(1)
}
if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
os.Exit(1)
}
// Recovery is complete. Start your regular publish loop and agent stream here, and call
// trackTask and untrackTask as tasks start and finish.
}

Reconnect the stream before you republish the entity, so the entity’s media never points at a missing stream.

Keep your stream

Don’t delete your stream when your integration stops or loses its link. Delete it only when you retire the camera. GetIngressStream returns not found for a deleted stream, so your integration would create it again on the next startup. If operators need to turn a feed off, give them a setting in your integration instead.

2

Republish your entity

Derive the entity ID from the same asset name. A version 5 UUID is a hash of its input, so every language produces the same ID:

// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"slices"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/core"
"github.com/anduril/lattice-sdk-go/v5/option"
"github.com/google/uuid"
)
// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()
const (
// RTSP source that Lattice pulls video from. Replace before running.
rtspURL = "rtsp://<rtsp-host>:<port>/cam"
// Local file that stores the IDs of tasks this agent is executing.
stateFile = "agent_state.json"
)
var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
Lattice.TaskStatusStatusStatusDoneOk: true,
Lattice.TaskStatusStatusStatusDoneNotOk: true,
}
type agentState struct {
TaskIDs []string `json:"task_ids"`
}
func loadTaskIDs() (map[string]bool, error) {
taskIDs := map[string]bool{}
data, err := os.ReadFile(stateFile)
if errors.Is(err, os.ErrNotExist) {
return taskIDs, nil
}
if err != nil {
return nil, err
}
var state agentState
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
for _, taskID := range state.TaskIDs {
taskIDs[taskID] = true
}
return taskIDs, nil
}
func saveTaskIDs(taskIDs map[string]bool) error {
ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
slices.Sort(ids)
data, err := json.Marshal(agentState{TaskIDs: ids})
if err != nil {
return err
}
// Write to a temporary file, then rename it over the original. A power loss during the
// write leaves the previous file intact instead of a truncated one.
f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), stateFile)
}
// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
taskIDs[taskID] = true
return saveTaskIDs(taskIDs)
}
// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
delete(taskIDs, taskID)
return saveTaskIDs(taskIDs)
}
func reconnectVideo(ctx context.Context, client *client.Client) error {
response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
IngressID: ingressID,
})
var apiErr *core.APIError
if err == nil {
// The stream survived the restart. Reuse it instead of creating a duplicate.
status := ""
if s := response.GetIngressStream().GetStatus(); s != nil {
status = string(*s)
}
fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
return nil
}
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
return err
}
// Lattice returns not found both for a stream that never existed and for one that was deleted.
_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
IngressID: Lattice.String(ingressID),
Title: Lattice.String(assetName),
Rtsp: &Lattice.RtspSettings{
URL: Lattice.String(rtspURL),
},
})
if err != nil {
return err
}
fmt.Printf("Created stream %s\n", ingressID)
return nil
}
func publishEntity(ctx context.Context, client *client.Client) error {
now := time.Now().UTC()
_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
EntityID: Lattice.String(entityID),
IsLive: Lattice.Bool(true),
ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
Aliases: &Lattice.Aliases{Name: Lattice.String(assetName)},
MilView: &Lattice.MilView{
Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
},
Ontology: &Lattice.Ontology{
Template: Lattice.OntologyTemplateTemplateAsset.Ptr(),
PlatformType: Lattice.String("CAMERA"),
},
Location: &Lattice.Location{
Position: &Lattice.Position{
LatitudeDegrees: Lattice.Float64(33.6411),
LongitudeDegrees: Lattice.Float64(-117.9187),
},
},
// Because ingressID never changes, the entity can reference the stream on every publish.
Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
ItemIdentifier: Lattice.String(ingressID),
Type: Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
}}},
// Include every other component your integration publishes, such as its TaskCatalog.
Provenance: &Lattice.Provenance{
IntegrationName: Lattice.String("my-integration"),
DataType: Lattice.String("asset"),
SourceUpdateTime: Lattice.Time(now),
},
})
if err != nil {
return err
}
fmt.Printf("Republished entity %s\n", entityID)
return nil
}
func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
var apiErr *core.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
// The task no longer exists in Lattice, so there's nothing to resolve.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
if err != nil {
return err
}
if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
continue
}
status := *task.Status.Status
if terminalStatuses[status] {
// An operator or another system closed the task while the agent was offline.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
var taskError *Lattice.TaskError
cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
(task.GetDeliveryState().GetStatus() != nil &&
*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
if cancelled {
// An operator cancelled the task while the agent was offline. Lattice records the cancel
// in delivery_state, not in the task status. Accept the cancellation.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
Message: Lattice.String("Cancelled while the agent was offline."),
}
} else {
// The agent lost its execution context, so report the task as failed rather than
// leave it active with nothing working on it.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
Message: Lattice.String("Agent restarted and could not resume the task."),
}
}
// Read the status version from GetTask, not from local state: the status might have
// changed while the agent was offline, and Lattice ignores updates with a stale version.
statusVersion := *task.Version.StatusVersion + 1
_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
TaskID: taskID,
StatusVersion: &statusVersion,
NewStatus: &Lattice.TaskStatus{
Status: Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
TaskError: taskError,
},
Author: author,
})
if err != nil {
return err
}
fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
}
return nil
}
func main() {
// Get environment variables
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
// Check required environment variables
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Initialize headers for sandbox authorization
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
// Create the client
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
ctx := context.Background()
taskIDs, err := loadTaskIDs()
if err != nil {
fmt.Printf("Failed to load saved task IDs: %v\n", err)
os.Exit(1)
}
if err := reconnectVideo(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to reconnect video: %v\n", err)
os.Exit(1)
}
if err := publishEntity(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to republish entity: %v\n", err)
os.Exit(1)
}
if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
os.Exit(1)
}
// Recovery is complete. Start your regular publish loop and agent stream here, and call
// trackTask and untrackTask as tasks start and finish.
}

Publish your entity with the same entity_id. This extends its expiry_time and replaces stale components with current data. Because the ingress ID doesn’t change, the entity lists the same stream in media every time.

// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"slices"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/core"
"github.com/anduril/lattice-sdk-go/v5/option"
"github.com/google/uuid"
)
// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()
const (
// RTSP source that Lattice pulls video from. Replace before running.
rtspURL = "rtsp://<rtsp-host>:<port>/cam"
// Local file that stores the IDs of tasks this agent is executing.
stateFile = "agent_state.json"
)
var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
Lattice.TaskStatusStatusStatusDoneOk: true,
Lattice.TaskStatusStatusStatusDoneNotOk: true,
}
type agentState struct {
TaskIDs []string `json:"task_ids"`
}
func loadTaskIDs() (map[string]bool, error) {
taskIDs := map[string]bool{}
data, err := os.ReadFile(stateFile)
if errors.Is(err, os.ErrNotExist) {
return taskIDs, nil
}
if err != nil {
return nil, err
}
var state agentState
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
for _, taskID := range state.TaskIDs {
taskIDs[taskID] = true
}
return taskIDs, nil
}
func saveTaskIDs(taskIDs map[string]bool) error {
ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
slices.Sort(ids)
data, err := json.Marshal(agentState{TaskIDs: ids})
if err != nil {
return err
}
// Write to a temporary file, then rename it over the original. A power loss during the
// write leaves the previous file intact instead of a truncated one.
f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), stateFile)
}
// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
taskIDs[taskID] = true
return saveTaskIDs(taskIDs)
}
// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
delete(taskIDs, taskID)
return saveTaskIDs(taskIDs)
}
func reconnectVideo(ctx context.Context, client *client.Client) error {
response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
IngressID: ingressID,
})
var apiErr *core.APIError
if err == nil {
// The stream survived the restart. Reuse it instead of creating a duplicate.
status := ""
if s := response.GetIngressStream().GetStatus(); s != nil {
status = string(*s)
}
fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
return nil
}
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
return err
}
// Lattice returns not found both for a stream that never existed and for one that was deleted.
_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
IngressID: Lattice.String(ingressID),
Title: Lattice.String(assetName),
Rtsp: &Lattice.RtspSettings{
URL: Lattice.String(rtspURL),
},
})
if err != nil {
return err
}
fmt.Printf("Created stream %s\n", ingressID)
return nil
}
func publishEntity(ctx context.Context, client *client.Client) error {
now := time.Now().UTC()
_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
EntityID: Lattice.String(entityID),
IsLive: Lattice.Bool(true),
ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
Aliases: &Lattice.Aliases{Name: Lattice.String(assetName)},
MilView: &Lattice.MilView{
Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
},
Ontology: &Lattice.Ontology{
Template: Lattice.OntologyTemplateTemplateAsset.Ptr(),
PlatformType: Lattice.String("CAMERA"),
},
Location: &Lattice.Location{
Position: &Lattice.Position{
LatitudeDegrees: Lattice.Float64(33.6411),
LongitudeDegrees: Lattice.Float64(-117.9187),
},
},
// Because ingressID never changes, the entity can reference the stream on every publish.
Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
ItemIdentifier: Lattice.String(ingressID),
Type: Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
}}},
// Include every other component your integration publishes, such as its TaskCatalog.
Provenance: &Lattice.Provenance{
IntegrationName: Lattice.String("my-integration"),
DataType: Lattice.String("asset"),
SourceUpdateTime: Lattice.Time(now),
},
})
if err != nil {
return err
}
fmt.Printf("Republished entity %s\n", entityID)
return nil
}
func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
var apiErr *core.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
// The task no longer exists in Lattice, so there's nothing to resolve.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
if err != nil {
return err
}
if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
continue
}
status := *task.Status.Status
if terminalStatuses[status] {
// An operator or another system closed the task while the agent was offline.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
var taskError *Lattice.TaskError
cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
(task.GetDeliveryState().GetStatus() != nil &&
*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
if cancelled {
// An operator cancelled the task while the agent was offline. Lattice records the cancel
// in delivery_state, not in the task status. Accept the cancellation.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
Message: Lattice.String("Cancelled while the agent was offline."),
}
} else {
// The agent lost its execution context, so report the task as failed rather than
// leave it active with nothing working on it.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
Message: Lattice.String("Agent restarted and could not resume the task."),
}
}
// Read the status version from GetTask, not from local state: the status might have
// changed while the agent was offline, and Lattice ignores updates with a stale version.
statusVersion := *task.Version.StatusVersion + 1
_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
TaskID: taskID,
StatusVersion: &statusVersion,
NewStatus: &Lattice.TaskStatus{
Status: Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
TaskError: taskError,
},
Author: author,
})
if err != nil {
return err
}
fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
}
return nil
}
func main() {
// Get environment variables
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
// Check required environment variables
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Initialize headers for sandbox authorization
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
// Create the client
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
ctx := context.Background()
taskIDs, err := loadTaskIDs()
if err != nil {
fmt.Printf("Failed to load saved task IDs: %v\n", err)
os.Exit(1)
}
if err := reconnectVideo(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to reconnect video: %v\n", err)
os.Exit(1)
}
if err := publishEntity(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to republish entity: %v\n", err)
os.Exit(1)
}
if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
os.Exit(1)
}
// Recovery is complete. Start your regular publish loop and agent stream here, and call
// trackTask and untrackTask as tasks start and finish.
}

Publish with is_live set to true; setting it to false deletes a live entity. After recovery, republish at least every 5 minutes. After a Lattice service restart, Lattice restores only the entities published in the previous 5 minutes, even if they set noExpiry.

3

Resolve the tasks your agent was executing

For each saved task ID, call GetTask and act on the result:

  • STATUS_DONE_OK or STATUS_DONE_NOT_OK: Someone closed the task while your agent was offline. Remove the ID.
  • A pending cancellation: Lattice records an operator’s cancel in the task’s delivery_state as DELIVERY_STATUS_PENDING_CANCEL, and leaves the status as your agent last reported it. Your agent may also have reported STATUS_CANCEL_REQUESTED itself before it stopped. Either way, accept the cancellation: set STATUS_DONE_NOT_OK with ERROR_CODE_CANCELLED.
  • Any other status: Resume the task if your agent can, or set STATUS_DONE_NOT_OK with ERROR_CODE_FAILED. The example takes the safe path and fails it.
  • Not found (404 in REST, NOT_FOUND in gRPC): Remove the ID.

Use the status_version from GetTask, not from local state. The task might have changed while your agent was offline, and Lattice rejects an update with an old version.

// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"slices"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/core"
"github.com/anduril/lattice-sdk-go/v5/option"
"github.com/google/uuid"
)
// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()
const (
// RTSP source that Lattice pulls video from. Replace before running.
rtspURL = "rtsp://<rtsp-host>:<port>/cam"
// Local file that stores the IDs of tasks this agent is executing.
stateFile = "agent_state.json"
)
var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
Lattice.TaskStatusStatusStatusDoneOk: true,
Lattice.TaskStatusStatusStatusDoneNotOk: true,
}
type agentState struct {
TaskIDs []string `json:"task_ids"`
}
func loadTaskIDs() (map[string]bool, error) {
taskIDs := map[string]bool{}
data, err := os.ReadFile(stateFile)
if errors.Is(err, os.ErrNotExist) {
return taskIDs, nil
}
if err != nil {
return nil, err
}
var state agentState
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
for _, taskID := range state.TaskIDs {
taskIDs[taskID] = true
}
return taskIDs, nil
}
func saveTaskIDs(taskIDs map[string]bool) error {
ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
slices.Sort(ids)
data, err := json.Marshal(agentState{TaskIDs: ids})
if err != nil {
return err
}
// Write to a temporary file, then rename it over the original. A power loss during the
// write leaves the previous file intact instead of a truncated one.
f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), stateFile)
}
// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
taskIDs[taskID] = true
return saveTaskIDs(taskIDs)
}
// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
delete(taskIDs, taskID)
return saveTaskIDs(taskIDs)
}
func reconnectVideo(ctx context.Context, client *client.Client) error {
response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
IngressID: ingressID,
})
var apiErr *core.APIError
if err == nil {
// The stream survived the restart. Reuse it instead of creating a duplicate.
status := ""
if s := response.GetIngressStream().GetStatus(); s != nil {
status = string(*s)
}
fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
return nil
}
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
return err
}
// Lattice returns not found both for a stream that never existed and for one that was deleted.
_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
IngressID: Lattice.String(ingressID),
Title: Lattice.String(assetName),
Rtsp: &Lattice.RtspSettings{
URL: Lattice.String(rtspURL),
},
})
if err != nil {
return err
}
fmt.Printf("Created stream %s\n", ingressID)
return nil
}
func publishEntity(ctx context.Context, client *client.Client) error {
now := time.Now().UTC()
_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
EntityID: Lattice.String(entityID),
IsLive: Lattice.Bool(true),
ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
Aliases: &Lattice.Aliases{Name: Lattice.String(assetName)},
MilView: &Lattice.MilView{
Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
},
Ontology: &Lattice.Ontology{
Template: Lattice.OntologyTemplateTemplateAsset.Ptr(),
PlatformType: Lattice.String("CAMERA"),
},
Location: &Lattice.Location{
Position: &Lattice.Position{
LatitudeDegrees: Lattice.Float64(33.6411),
LongitudeDegrees: Lattice.Float64(-117.9187),
},
},
// Because ingressID never changes, the entity can reference the stream on every publish.
Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
ItemIdentifier: Lattice.String(ingressID),
Type: Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
}}},
// Include every other component your integration publishes, such as its TaskCatalog.
Provenance: &Lattice.Provenance{
IntegrationName: Lattice.String("my-integration"),
DataType: Lattice.String("asset"),
SourceUpdateTime: Lattice.Time(now),
},
})
if err != nil {
return err
}
fmt.Printf("Republished entity %s\n", entityID)
return nil
}
func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
var apiErr *core.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
// The task no longer exists in Lattice, so there's nothing to resolve.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
if err != nil {
return err
}
if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
continue
}
status := *task.Status.Status
if terminalStatuses[status] {
// An operator or another system closed the task while the agent was offline.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
var taskError *Lattice.TaskError
cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
(task.GetDeliveryState().GetStatus() != nil &&
*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
if cancelled {
// An operator cancelled the task while the agent was offline. Lattice records the cancel
// in delivery_state, not in the task status. Accept the cancellation.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
Message: Lattice.String("Cancelled while the agent was offline."),
}
} else {
// The agent lost its execution context, so report the task as failed rather than
// leave it active with nothing working on it.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
Message: Lattice.String("Agent restarted and could not resume the task."),
}
}
// Read the status version from GetTask, not from local state: the status might have
// changed while the agent was offline, and Lattice ignores updates with a stale version.
statusVersion := *task.Version.StatusVersion + 1
_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
TaskID: taskID,
StatusVersion: &statusVersion,
NewStatus: &Lattice.TaskStatus{
Status: Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
TaskError: taskError,
},
Author: author,
})
if err != nil {
return err
}
fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
}
return nil
}
func main() {
// Get environment variables
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
// Check required environment variables
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Initialize headers for sandbox authorization
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
// Create the client
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
ctx := context.Background()
taskIDs, err := loadTaskIDs()
if err != nil {
fmt.Printf("Failed to load saved task IDs: %v\n", err)
os.Exit(1)
}
if err := reconnectVideo(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to reconnect video: %v\n", err)
os.Exit(1)
}
if err := publishEntity(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to republish entity: %v\n", err)
os.Exit(1)
}
if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
os.Exit(1)
}
// Recovery is complete. Start your regular publish loop and agent stream here, and call
// trackTask and untrackTask as tasks start and finish.
}
Resume only when it's safe

Resume a task only if your agent can confirm its conditions still hold, for example that the target is still there. If you’re unsure, fail it. An operator can reassign it.

4

Resume normal operation

Start your publish loop and agent stream as described in Integrate an agent. From now on, save each task ID before you report STATUS_EXECUTING, and remove it after you report STATUS_DONE_OK or STATUS_DONE_NOT_OK. That way a crash can’t leave a task executing in Lattice with no record of it in your integration:

// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"slices"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/core"
"github.com/anduril/lattice-sdk-go/v5/option"
"github.com/google/uuid"
)
// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()
const (
// RTSP source that Lattice pulls video from. Replace before running.
rtspURL = "rtsp://<rtsp-host>:<port>/cam"
// Local file that stores the IDs of tasks this agent is executing.
stateFile = "agent_state.json"
)
var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
Lattice.TaskStatusStatusStatusDoneOk: true,
Lattice.TaskStatusStatusStatusDoneNotOk: true,
}
type agentState struct {
TaskIDs []string `json:"task_ids"`
}
func loadTaskIDs() (map[string]bool, error) {
taskIDs := map[string]bool{}
data, err := os.ReadFile(stateFile)
if errors.Is(err, os.ErrNotExist) {
return taskIDs, nil
}
if err != nil {
return nil, err
}
var state agentState
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
for _, taskID := range state.TaskIDs {
taskIDs[taskID] = true
}
return taskIDs, nil
}
func saveTaskIDs(taskIDs map[string]bool) error {
ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
slices.Sort(ids)
data, err := json.Marshal(agentState{TaskIDs: ids})
if err != nil {
return err
}
// Write to a temporary file, then rename it over the original. A power loss during the
// write leaves the previous file intact instead of a truncated one.
f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), stateFile)
}
// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
taskIDs[taskID] = true
return saveTaskIDs(taskIDs)
}
// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
delete(taskIDs, taskID)
return saveTaskIDs(taskIDs)
}
func reconnectVideo(ctx context.Context, client *client.Client) error {
response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
IngressID: ingressID,
})
var apiErr *core.APIError
if err == nil {
// The stream survived the restart. Reuse it instead of creating a duplicate.
status := ""
if s := response.GetIngressStream().GetStatus(); s != nil {
status = string(*s)
}
fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
return nil
}
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
return err
}
// Lattice returns not found both for a stream that never existed and for one that was deleted.
_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
IngressID: Lattice.String(ingressID),
Title: Lattice.String(assetName),
Rtsp: &Lattice.RtspSettings{
URL: Lattice.String(rtspURL),
},
})
if err != nil {
return err
}
fmt.Printf("Created stream %s\n", ingressID)
return nil
}
func publishEntity(ctx context.Context, client *client.Client) error {
now := time.Now().UTC()
_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
EntityID: Lattice.String(entityID),
IsLive: Lattice.Bool(true),
ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
Aliases: &Lattice.Aliases{Name: Lattice.String(assetName)},
MilView: &Lattice.MilView{
Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
},
Ontology: &Lattice.Ontology{
Template: Lattice.OntologyTemplateTemplateAsset.Ptr(),
PlatformType: Lattice.String("CAMERA"),
},
Location: &Lattice.Location{
Position: &Lattice.Position{
LatitudeDegrees: Lattice.Float64(33.6411),
LongitudeDegrees: Lattice.Float64(-117.9187),
},
},
// Because ingressID never changes, the entity can reference the stream on every publish.
Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
ItemIdentifier: Lattice.String(ingressID),
Type: Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
}}},
// Include every other component your integration publishes, such as its TaskCatalog.
Provenance: &Lattice.Provenance{
IntegrationName: Lattice.String("my-integration"),
DataType: Lattice.String("asset"),
SourceUpdateTime: Lattice.Time(now),
},
})
if err != nil {
return err
}
fmt.Printf("Republished entity %s\n", entityID)
return nil
}
func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
var apiErr *core.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
// The task no longer exists in Lattice, so there's nothing to resolve.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
if err != nil {
return err
}
if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
continue
}
status := *task.Status.Status
if terminalStatuses[status] {
// An operator or another system closed the task while the agent was offline.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
var taskError *Lattice.TaskError
cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
(task.GetDeliveryState().GetStatus() != nil &&
*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
if cancelled {
// An operator cancelled the task while the agent was offline. Lattice records the cancel
// in delivery_state, not in the task status. Accept the cancellation.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
Message: Lattice.String("Cancelled while the agent was offline."),
}
} else {
// The agent lost its execution context, so report the task as failed rather than
// leave it active with nothing working on it.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
Message: Lattice.String("Agent restarted and could not resume the task."),
}
}
// Read the status version from GetTask, not from local state: the status might have
// changed while the agent was offline, and Lattice ignores updates with a stale version.
statusVersion := *task.Version.StatusVersion + 1
_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
TaskID: taskID,
StatusVersion: &statusVersion,
NewStatus: &Lattice.TaskStatus{
Status: Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
TaskError: taskError,
},
Author: author,
})
if err != nil {
return err
}
fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
}
return nil
}
func main() {
// Get environment variables
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
// Check required environment variables
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Initialize headers for sandbox authorization
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
// Create the client
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
ctx := context.Background()
taskIDs, err := loadTaskIDs()
if err != nil {
fmt.Printf("Failed to load saved task IDs: %v\n", err)
os.Exit(1)
}
if err := reconnectVideo(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to reconnect video: %v\n", err)
os.Exit(1)
}
if err := publishEntity(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to republish entity: %v\n", err)
os.Exit(1)
}
if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
os.Exit(1)
}
// Recovery is complete. Start your regular publish loop and agent stream here, and call
// trackTask and untrackTask as tasks start and finish.
}

Save the file safely. A power loss in the middle of a write can leave a truncated file, so write to a temporary file in the same directory, flush it to disk, then rename it over the original. A rename on the same file system is atomic, so the file on disk is always complete:

// This Go example uses the Lattice REST SDK (lattice-sdk-go) to recover an integration's video
// stream, entity, and tasks after the integration restarts.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"os"
"path/filepath"
"slices"
"time"
Lattice "github.com/anduril/lattice-sdk-go/v5"
"github.com/anduril/lattice-sdk-go/v5/client"
"github.com/anduril/lattice-sdk-go/v5/core"
"github.com/anduril/lattice-sdk-go/v5/option"
"github.com/google/uuid"
)
// A name that is unique to this asset and never changes, such as a serial number read from
// hardware or configuration. Replace before running.
const assetName = "<ASSET-NAME>"
// The ingress ID uses the readable <group>.<name> pattern. It's derived from the asset name,
// so it's the same after every restart.
var ingressID = assetName + ".cam"
// The entity ID is a version 5 UUID of the asset name, so it's the same after every restart
// and in every language.
var entityID = uuid.NewSHA1(uuid.NameSpaceURL, []byte("urn:my-integration:"+assetName)).String()
const (
// RTSP source that Lattice pulls video from. Replace before running.
rtspURL = "rtsp://<rtsp-host>:<port>/cam"
// Local file that stores the IDs of tasks this agent is executing.
stateFile = "agent_state.json"
)
var terminalStatuses = map[Lattice.TaskStatusStatus]bool{
Lattice.TaskStatusStatusStatusDoneOk: true,
Lattice.TaskStatusStatusStatusDoneNotOk: true,
}
type agentState struct {
TaskIDs []string `json:"task_ids"`
}
func loadTaskIDs() (map[string]bool, error) {
taskIDs := map[string]bool{}
data, err := os.ReadFile(stateFile)
if errors.Is(err, os.ErrNotExist) {
return taskIDs, nil
}
if err != nil {
return nil, err
}
var state agentState
if err := json.Unmarshal(data, &state); err != nil {
return nil, err
}
for _, taskID := range state.TaskIDs {
taskIDs[taskID] = true
}
return taskIDs, nil
}
func saveTaskIDs(taskIDs map[string]bool) error {
ids := slices.AppendSeq([]string{}, maps.Keys(taskIDs))
slices.Sort(ids)
data, err := json.Marshal(agentState{TaskIDs: ids})
if err != nil {
return err
}
// Write to a temporary file, then rename it over the original. A power loss during the
// write leaves the previous file intact instead of a truncated one.
f, err := os.CreateTemp(filepath.Dir(stateFile), "agent_state-*.tmp")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
f.Close()
return err
}
if err := f.Sync(); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), stateFile)
}
// trackTask saves a task ID. Call it before reporting STATUS_EXECUTING, so the ID is on disk
// before work starts.
func trackTask(taskIDs map[string]bool, taskID string) error {
taskIDs[taskID] = true
return saveTaskIDs(taskIDs)
}
// untrackTask removes a task ID. Call it after reporting STATUS_DONE_OK or STATUS_DONE_NOT_OK.
func untrackTask(taskIDs map[string]bool, taskID string) error {
delete(taskIDs, taskID)
return saveTaskIDs(taskIDs)
}
func reconnectVideo(ctx context.Context, client *client.Client) error {
response, err := client.Video.GetIngressStream(ctx, &Lattice.GetIngressStreamRequest{
IngressID: ingressID,
})
var apiErr *core.APIError
if err == nil {
// The stream survived the restart. Reuse it instead of creating a duplicate.
status := ""
if s := response.GetIngressStream().GetStatus(); s != nil {
status = string(*s)
}
fmt.Printf("Reusing stream %s with status %s\n", ingressID, status)
return nil
}
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
return err
}
// Lattice returns not found both for a stream that never existed and for one that was deleted.
_, err = client.Video.CreateIngressStream(ctx, &Lattice.CreateIngressStreamRequest{
IngressID: Lattice.String(ingressID),
Title: Lattice.String(assetName),
Rtsp: &Lattice.RtspSettings{
URL: Lattice.String(rtspURL),
},
})
if err != nil {
return err
}
fmt.Printf("Created stream %s\n", ingressID)
return nil
}
func publishEntity(ctx context.Context, client *client.Client) error {
now := time.Now().UTC()
_, err := client.Entities.PublishEntity(ctx, &Lattice.Entity{
EntityID: Lattice.String(entityID),
IsLive: Lattice.Bool(true),
ExpiryTime: Lattice.Time(now.Add(5 * time.Minute)),
Aliases: &Lattice.Aliases{Name: Lattice.String(assetName)},
MilView: &Lattice.MilView{
Disposition: Lattice.MilViewDispositionDispositionFriendly.Ptr(),
Environment: Lattice.MilViewEnvironmentEnvironmentLand.Ptr(),
},
Ontology: &Lattice.Ontology{
Template: Lattice.OntologyTemplateTemplateAsset.Ptr(),
PlatformType: Lattice.String("CAMERA"),
},
Location: &Lattice.Location{
Position: &Lattice.Position{
LatitudeDegrees: Lattice.Float64(33.6411),
LongitudeDegrees: Lattice.Float64(-117.9187),
},
},
// Because ingressID never changes, the entity can reference the stream on every publish.
Media: &Lattice.Media{Media: []*Lattice.MediaItem{{
ItemIdentifier: Lattice.String(ingressID),
Type: Lattice.MediaItemTypeMediaTypeVideo.Ptr(),
}}},
// Include every other component your integration publishes, such as its TaskCatalog.
Provenance: &Lattice.Provenance{
IntegrationName: Lattice.String("my-integration"),
DataType: Lattice.String("asset"),
SourceUpdateTime: Lattice.Time(now),
},
})
if err != nil {
return err
}
fmt.Printf("Republished entity %s\n", entityID)
return nil
}
func resolveTrackedTasks(ctx context.Context, client *client.Client, taskIDs map[string]bool) error {
author := &Lattice.Principal{System: &Lattice.System{EntityID: Lattice.String(entityID)}}
for _, taskID := range slices.Sorted(maps.Keys(taskIDs)) {
task, err := client.Tasks.GetTask(ctx, &Lattice.GetTaskRequest{TaskID: taskID})
var apiErr *core.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
// The task no longer exists in Lattice, so there's nothing to resolve.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
if err != nil {
return err
}
if task.Status == nil || task.Status.Status == nil || task.Version == nil || task.Version.StatusVersion == nil {
fmt.Printf("Task %s is missing its status or version. Skipping.\n", taskID)
continue
}
status := *task.Status.Status
if terminalStatuses[status] {
// An operator or another system closed the task while the agent was offline.
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
continue
}
var taskError *Lattice.TaskError
cancelled := status == Lattice.TaskStatusStatusStatusCancelRequested ||
(task.GetDeliveryState().GetStatus() != nil &&
*task.GetDeliveryState().GetStatus() == Lattice.DeliveryStateStatusDeliveryStatusPendingCancel)
if cancelled {
// An operator cancelled the task while the agent was offline. Lattice records the cancel
// in delivery_state, not in the task status. Accept the cancellation.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeCancelled.Ptr(),
Message: Lattice.String("Cancelled while the agent was offline."),
}
} else {
// The agent lost its execution context, so report the task as failed rather than
// leave it active with nothing working on it.
taskError = &Lattice.TaskError{
Code: Lattice.TaskErrorCodeErrorCodeFailed.Ptr(),
Message: Lattice.String("Agent restarted and could not resume the task."),
}
}
// Read the status version from GetTask, not from local state: the status might have
// changed while the agent was offline, and Lattice ignores updates with a stale version.
statusVersion := *task.Version.StatusVersion + 1
_, err = client.Tasks.UpdateTaskStatus(ctx, &Lattice.TaskStatusUpdate{
TaskID: taskID,
StatusVersion: &statusVersion,
NewStatus: &Lattice.TaskStatus{
Status: Lattice.TaskStatusStatusStatusDoneNotOk.Ptr(),
TaskError: taskError,
},
Author: author,
})
if err != nil {
return err
}
fmt.Printf("Closed task %s with %s\n", taskID, *taskError.Code)
if err := untrackTask(taskIDs, taskID); err != nil {
return err
}
}
return nil
}
func main() {
// Get environment variables
latticeEndpoint := os.Getenv("LATTICE_ENDPOINT")
environmentToken := os.Getenv("ENVIRONMENT_TOKEN")
// Remove sandboxesToken from the following statements if you are not developing on Sandboxes.
sandboxesToken := os.Getenv("SANDBOXES_TOKEN")
// Check required environment variables
if latticeEndpoint == "" || environmentToken == "" || sandboxesToken == "" {
fmt.Println("Missing required environment variables")
os.Exit(1)
}
// Initialize headers for sandbox authorization
headers := http.Header{}
headers.Add("Anduril-Sandbox-Authorization", fmt.Sprintf("Bearer %s", sandboxesToken))
// Create the client
LatticeClient := client.NewClient(
option.WithToken(environmentToken),
option.WithBaseURL(fmt.Sprintf("https://%s", latticeEndpoint)),
option.WithHTTPHeader(headers),
)
ctx := context.Background()
taskIDs, err := loadTaskIDs()
if err != nil {
fmt.Printf("Failed to load saved task IDs: %v\n", err)
os.Exit(1)
}
if err := reconnectVideo(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to reconnect video: %v\n", err)
os.Exit(1)
}
if err := publishEntity(ctx, LatticeClient); err != nil {
fmt.Printf("Failed to republish entity: %v\n", err)
os.Exit(1)
}
if err := resolveTrackedTasks(ctx, LatticeClient, taskIDs); err != nil {
fmt.Printf("Failed to resolve tracked tasks: %v\n", err)
os.Exit(1)
}
// Recovery is complete. Start your regular publish loop and agent stream here, and call
// trackTask and untrackTask as tasks start and finish.
}

Find tasks your agent never received

Lattice counts a task as delivered as soon as it sends the task over your agent’s stream, before your agent confirms it. If your integration crashes at that moment, your agent has no record of the task.

After you reconnect, look up the open tasks assigned to your agent, and treat any you don’t recognize as new:

  • gRPC: Call QueryTasks with assignee set to your agent’s entity and a status_filter that excludes STATUS_DONE_OK and STATUS_DONE_NOT_OK.
  • REST: The REST QueryTasks can’t filter by assignee, so call StreamTasks with assignee set to your agent’s entity. When it connects, it first replays matching tasks, including ones that finished in the last hour, then sends live updates. Skip the finished ones.

If you create tasks for agents that restart often, set delivery_constraints.require_acknowledgement when you call CreateTask. Lattice then re-sends the task until the agent confirms receipt, up to the deliver_before deadline that this option requires.

Recover after a lost connection

A network outage affects tasks the same way a restart does, even though your integration keeps running. While your agent is disconnected, operators can cancel or close its tasks and Lattice can send it new ones, and Lattice doesn’t re-send what your agent missed.

Each time your agent stream reconnects:

  1. Call GetTask for each task your agent is working on. Stop work on any task that’s closed, not found, or has a pending cancellation, and handle it as in Recover on startup. Keep working on the rest. If one finished while you were disconnected, report it with the status_version from GetTask.
  2. Find tasks your agent never received.

Keep your publish loop running through the outage, with retries. If the outage outlasts your entity’s expiry_time, the entity disappears until your next successful publish. For SRT and MPEG-TS video, resume pushing to the stream’s url when the link returns.

Recover tasks you created

If your integration assigns tasks to other agents, save the ID of each one. On startup, call GetTask for each saved ID to catch up and remove the finished ones, then call StreamTasks to follow the rest. Cancel any task whose result your integration can no longer use, so it doesn’t run unmonitored.

What’s next