Snapshot, fork and restore sandboxes
Save a sandbox’s workspace, roll it back after a bad change, start new sandboxes from it, or split a running sandbox into copies that each try something different.
Snapshot, break, revert
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
// A snapshot is the whole workspace. Revert to it and the damage is gone.
const box = await client.create({
git: { url: "https://github.com/tangle-network/sandbox-demo" },
});
let ownedSnapshotId: string | undefined;
try {
const clean = await box.snapshot({ tags: ["clean"] });
ownedSnapshotId = clean.snapshotId;
await box.exec("rm -rf packages test");
console.log("after", (await box.exec("ls")).stdout.trim().split("\n"));
await box.revertToSnapshot(clean.snapshotId);
console.log("reverted", (await box.exec("ls")).stdout.trim().split("\n"));
} finally {
try {
if (ownedSnapshotId) await box.deleteSnapshot(ownedSnapshotId);
} finally {
await box.delete();
}
}snapshot() captures the whole workspace and returns { snapshotId, createdAt, sizeBytes, tags }. Snapshots of a single path are not supported; take a whole snapshot and restore the paths you need.
Restore all or part of a workspace
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const box = await client.create({ agent: false, maxLifetimeSeconds: 600 });
let ownedSnapshotId: string | undefined;
try {
await box.write("src/version.txt", "original\n");
await box.write("package.json", '{"name":"snapshot-example"}\n');
const snapshot = await box.snapshot();
ownedSnapshotId = snapshot.snapshotId;
await box.write("src/version.txt", "damaged\n");
await box.revertToSnapshot(snapshot.snapshotId);
assert.equal(await box.read("src/version.txt"), "original\n");
await box.write("src/version.txt", "changed again\n");
await box.write("keep.txt", "keep this change\n");
await box.restorePaths(snapshot.snapshotId, ["src", "package.json"]);
assert.equal(await box.read("src/version.txt"), "original\n");
assert.equal(await box.read("keep.txt"), "keep this change\n");
console.log("Verified whole and selected-path restoration");
} finally {
try {
if (ownedSnapshotId) await box.deleteSnapshot(ownedSnapshotId);
} finally {
await box.delete();
}
}restorePaths replaces the listed workspace-relative paths and leaves every other file as it is. The paths resolve from the workspace root, like read and write, not from the cloned repository that exec starts in when the sandbox was created with git.
Start a new sandbox from a snapshot
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const box = await client.create({ agent: false, maxLifetimeSeconds: 600 });
let ownedSnapshotId: string | undefined;
try {
await box.write("base.txt", "shared setup\n");
const snapshot = await box.snapshot();
ownedSnapshotId = snapshot.snapshotId;
const copy = await client.create({ agent: false, fromSnapshot: snapshot.snapshotId, fromSandboxId: box.id, maxLifetimeSeconds: 300 });
try {
assert.notEqual(copy.id, box.id);
assert.equal(await copy.read("base.txt"), "shared setup\n");
await copy.write("base.txt", "copy only\n");
assert.equal(await box.read("base.txt"), "shared setup\n");
console.log(copy.id, await copy.read("base.txt"));
} finally {
await copy.delete();
}
} finally {
try {
if (ownedSnapshotId) await box.deleteSnapshot(ownedSnapshotId);
} finally {
await box.delete();
}
}fromSandboxId is required with fromSnapshot. The source sandbox is untouched. In the CLI, tangle snapshot restore <sandbox-id> <snapshot-id> creates the new sandbox and waits for it to run; the first argument must be a sandbox id, not a name.
To publish a snapshot so others can start from it, see Templates and images.
List and delete snapshots
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const box = await client.create({ agent: false, maxLifetimeSeconds: 600 });
let ownedSnapshotId: string | undefined;
try {
await box.write("notes.md", "saved draft\n");
const snapshot = await box.snapshot({ tags: ["docs-cleanup"] });
ownedSnapshotId = snapshot.snapshotId;
const deadline = Date.now() + 60_000;
let listed = await box.listSnapshots();
while (!listed.some((item) => item.snapshotId === snapshot.snapshotId) && Date.now() < deadline) {
await new Promise((resolve) => setTimeout(resolve, 500));
listed = await box.listSnapshots();
}
assert(listed.some((item) => item.snapshotId === snapshot.snapshotId));
for (const item of listed) console.log(item.snapshotId, item.tags, item.sizeBytes);
const { outcome } = await box.deleteSnapshot(snapshot.snapshotId);
assert(["deleted", "already_absent"].includes(outcome));
console.log(outcome);
} finally {
try {
if (ownedSnapshotId) await box.deleteSnapshot(ownedSnapshotId);
} finally {
await box.delete();
}
}tangle snapshot list demo
tangle snapshot delete demo <snapshot-id>Snapshot without waiting
box.snapshot({ wait: false }) returns a SandboxOperation once the snapshot is accepted. await op.wait() resolves when it finishes. Pass idempotencyKey so a retried request answers with the same snapshot. In the CLI, tangle snapshot create --no-wait prints the operation id and status URL.
Keep data after delete or share it between sandboxes
Write snapshots to your own S3, GCS or R2 bucket, and they stay there until you delete them, whatever happens to the sandbox.
const storage = {
type: "s3" as const,
bucket: "acme-sandbox-snapshots",
region: "us-east-1",
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
},
prefix: "checkout-service/",
};
const box = await client.create({ storage });
await box.exec("npm ci");
await box.snapshot({ storage, tags: ["deps-installed"] });
await box.delete();
// Later, in a new sandbox:
const next = await client.create({ storage });
await next.restoreFromStorage(storage); // the latest snapshot in the bucket, or nullstorage field | Meaning |
|---|---|
type | "s3", "gcs" or "r2". |
bucket | Bucket name. |
endpoint | Required for R2, optional for S3 and GCS. |
region | Bucket region. |
credentials | { accessKeyId, secretAccessKey }. Required. |
prefix | Path inside the bucket. |
listSnapshots(storage) lists what is in your bucket. A snapshot to your own storage refuses idempotencyKey and wait: false. The CLI takes the same settings as --storage-type, --storage-bucket, --storage-region, --storage-endpoint, --storage-prefix, --storage-access-key-id and --storage-secret-access-key-env on tangle sandbox create.
Within the platform, any sandbox you own can start from another sandbox’s snapshot with fromSnapshot and fromSandboxId.
What a delete keeps
Deleting a sandbox keeps its snapshots. Ones the platform keeps for you stay for about 30 days after the sandbox is deleted, then are removed automatically; there is no command to remove them sooner once the sandbox is gone. You can still create a new sandbox from a kept snapshot during that window, by its snapshot id:
tangle snapshot restore <old-sandbox-id> <snapshot-id>Note the snapshot id before you delete the sandbox: after the sandbox is gone, tangle snapshot list <old-sandbox-id> and tangle snapshot delete answer Sandbox not found, so the id is how you reach a kept snapshot.
A snapshot copies the whole home folder of the sandbox. If a tool in the box wrote a credential to a file there (for example a model or CLI token on disk), that file is in the snapshot. Keep real credentials out of the box so they cannot be captured: with proxy custody the box holds only a placeholder and the real value stays at the proxy, so it is never in a snapshot.
To not keep a sandbox’s snapshots at all, delete each one while the sandbox still exists, before you delete the sandbox:
tangle snapshot list <id>
tangle snapshot delete <id> <snapshot-id>Snapshots you wrote to your own storage are separate: they stay in your bucket until you delete them, whatever happens to the sandbox.
Branch a running sandbox
branch(count) makes copy-on-write copies of a running sandbox. The parent keeps running, and each child starts with the parent’s files.
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const parent = await client.create();
try {
await parent.exec("echo 'shared setup' > base.txt");
const [a, b] = await parent.branch(2);
try {
await a.exec("echo 'child a' >> base.txt");
await b.exec("echo 'child b' >> base.txt");
for (const child of [a, b]) {
const { stdout } = await child.exec("cat base.txt");
console.log(child.id, stdout.trim().split("\n"));
}
} finally {
await Promise.all([a.delete(), b.delete()]);
}
} finally {
await parent.delete();
}What a child inherits depends on the runtime:
| Runtime | The child gets |
|---|---|
firecracker | The parent’s disk and memory, so running processes carry over. |
docker | A copy-on-write fork of the disk. Processes start fresh. |
fork(count) does the same and reports the whole fan-out: { children, requestedCount, materializedCount, complete }. complete: false means fewer children started than you asked for. Pass idempotencyKey so a retry returns the same children instead of making more.
import assert from "node:assert/strict";
import { Sandbox } from "@tangle-network/sandbox";
const client = new Sandbox({
apiKey: process.env.TANGLE_API_KEY!,
baseUrl: "https://sandbox.tangle.tools",
});
const box = await client.create({ agent: false, runtime: "firecracker", maxLifetimeSeconds: 600 });
try {
await box.write("base.txt", "shared setup\n");
const forked = await box.fork(2, { idempotencyKey: `fork-${crypto.randomUUID()}`, metadata: { experiment: "a" } });
try {
assert.equal(forked.complete, true);
assert.equal(forked.materializedCount, 2);
assert.equal(forked.requestedCount, 2);
for (const child of forked.children) assert.equal(await child.read("base.txt"), "shared setup\n");
console.log(forked.materializedCount, "of", forked.requestedCount);
} finally {
const deleted = await Promise.allSettled(forked.children.map((child) => child.delete()));
const failures = deleted.filter((result) => result.status === "rejected");
assert.equal(failures.length, 0, "A fork child could not be deleted");
}
} finally {
await box.delete();
}A fan-out larger than the host can hold fails with BRANCH_FANOUT_EXCEEDS_HOST, and the error’s maxChildren says how many fit. The allowed count is on Limits.
A parent with live children cannot be deleted: the delete answers 409 CHILDREN_EXIST. Delete the children first, or delete the lineage with cascade=true through REST or client.deleteMatching(filter, { cascade: true }). See Delete.
tangle branch create demo --count 2 --idempotency-key run-42Python and REST
Python has snapshot(SnapshotOptions(tags, storage)), list_snapshots(), restore_paths(snapshot_id, paths), and from_snapshot with from_sandbox_id on create. It has no revert, snapshot delete, restore from storage, branch or fork. Call those routes with client.fetch, which returns the raw response and does not raise on an error status:
from contextlib import ExitStack
import os
import time
import uuid
from tangle_sandbox import Sandbox, SandboxStatus, SnapshotOptions
with Sandbox(
api_key=os.environ["TANGLE_API_KEY"],
base_url="https://sandbox.tangle.tools",
) as client, ExitStack() as cleanup:
created = client.fetch("POST", "/v1/sandboxes", json={
"agent": False, "runtime": "firecracker", "maxLifetimeSeconds": 600,
}).raise_for_status().json()
cleanup.callback(lambda: client.fetch("DELETE", f"/v1/sandboxes/{created['id']}").raise_for_status())
box = client.get(created["id"])
assert box is not None
box.wait_for(SandboxStatus.RUNNING)
box.write("version.txt", "original\n")
snapshot_id = box.snapshot(SnapshotOptions(tags=["rest-example"])).snapshot_id
def delete_owned_snapshot():
if snapshot_id is None:
return
deadline = time.monotonic() + 30
while True:
deleted = client.fetch("DELETE", f"/v1/sandboxes/{box.id}/snapshots/{snapshot_id}", timeout=10)
if deleted.status_code == 409:
hold = deleted.json()
if (hold.get("code") == "RESUME_SNAPSHOT_RETAINED"
and hold.get("reason") in ("resume_generation_unconfirmed", "snapshot_delete_in_flight")
and time.monotonic() < deadline):
time.sleep(max(0, min(2, deadline - time.monotonic())))
continue
deleted.raise_for_status()
assert deleted.json()["outcome"] in ("deleted", "already_absent")
return
cleanup.callback(delete_owned_snapshot)
box.write("version.txt", "edited\n")
restored = client.fetch("POST", f"/v1/sandboxes/{box.id}/snapshots/{snapshot_id}/restore", json={},
headers={"Idempotency-Key": "restore-" + uuid.uuid4().hex}, timeout=120)
restored.raise_for_status()
if restored.status_code == 202:
job = restored.json()
job_id = job["jobId"]
deadline = time.monotonic() + 120
while job["status"] in ("pending", "running") and time.monotonic() < deadline:
time.sleep(0.5)
job = client.fetch("GET", f"/v1/sandboxes/{box.id}/snapshots/jobs/{job_id}", timeout=10).raise_for_status().json()
assert job["status"] == "completed", "Restore status: " + str(job.get("status"))
assert job["result"]["success"] is True
else:
assert restored.status_code == 200
assert restored.json()["snapshotId"] == snapshot_id
box.refresh()
box.wait_for(SandboxStatus.RUNNING)
assert box.read("version.txt") == "original\n"
delete_owned_snapshot()
snapshot_id = None
forked = client.fetch("POST", f"/v1/sandboxes/{box.id}/branch", json={"count": 2},
headers={"Idempotency-Key": "branch-" + uuid.uuid4().hex}, timeout=120).raise_for_status().json()
children = forked["children"]
for child in children:
cleanup.callback(lambda child_id=child["id"]: client.fetch("DELETE", f"/v1/sandboxes/{child_id}").raise_for_status())
assert len(children) == 2
assert len({child["id"] for child in children}) == 2
for child in children:
copy = client.get(child["id"])
assert copy is not None
copy.wait_for(SandboxStatus.RUNNING)
assert copy.read("version.txt") == "original\n"
print("Restored the workspace, deleted its snapshot, and checked both branches")