The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
"""Exercise checkpoint serialization and result ownership through native REST."""
import asyncio
import importlib.util
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import boxlite
# Unit jobs do not build the extension; the native coverage job requires it.
# A present but unloadable extension must still fail rather than be skipped.
pytestmark = pytest.mark.skipif(
importlib.util.find_spec("boxlite.boxlite") is None,
reason="native extension module not built",
)
INFO = {
"id": "checkpoint-1",
"name": "base",
"source_box_id": "source-1",
"created_at": "2026-11-06T00:00:00Z",
"size_bytes": 4096,
"state": "ready",
}
BOX = {
"box_id": "target-1",
"name": "worker",
"status": "stopped",
"created_at": INFO["created_at"],
"updated_at": INFO["created_at"],
"image": "alpine:latest",
"cpus": 2,
"memory_mib": 512,
}
@pytest.mark.asyncio
@pytest.mark.parametrize(
"overrides",
[
{"detach": False},
{"tty": False},
{"auto_remove": True},
{"advanced": "default"},
{"network": "default"},
{"env": []},
{"volumes": []},
{"ports": []},
{"secrets": []},
],
)
async def test_checkpoint_rejects_explicit_defaults(checkpoint_server, overrides):
"""Reject supplied defaults before the native conversion loses their presence."""
url, requests = checkpoint_server
if overrides.get("advanced") == "default":
overrides = {"advanced": boxlite.AdvancedBoxOptions(privileged=False)}
if overrides.get("network") == "default":
overrides = {"network": boxlite.NetworkSpec(mode="enabled")}
runtime = boxlite.Boxlite.rest(boxlite.BoxliteRestOptions(url=url))
with pytest.raises(boxlite.InvalidArgumentError):
await runtime.create(boxlite.BoxOptions(checkpoint="base", **overrides))
assert requests == []
@pytest.mark.asyncio
@pytest.mark.parametrize("field", ["env", "secrets"])
async def test_checkpoint_rejects_mutated_empty_collections(checkpoint_server, field):
"""Property setters must preserve presence just like constructor arguments."""
url, requests = checkpoint_server
options = boxlite.BoxOptions(checkpoint="base")
setattr(options, field, [])
runtime = boxlite.Boxlite.rest(boxlite.BoxliteRestOptions(url=url))
with pytest.raises(boxlite.InvalidArgumentError):
await runtime.create(options)
assert requests == []
@pytest.fixture
def checkpoint_settings():
return {"enabled": True, "memory": {}}
@pytest.fixture
def checkpoint_server(checkpoint_settings):
requests = []
class Handler(BaseHTTPRequestHandler):
def dispatch(self):
size = int(self.headers.get("Content-Length", "0"))
body = json.loads(self.rfile.read(size)) if size else None
requests.append((self.command, self.path, body))
if self.command == "DELETE":
self.send_response(204)
self.end_headers()
return
payload = INFO
if self.path == "/v1/config":
payload = {
"capabilities": {
"memory_checkpoints_enabled": checkpoint_settings["enabled"]
}
}
elif self.path == "/v1/checkpoints" and self.command == "GET":
payload = {"checkpoints": [{**INFO, "kind": "future"}]}
elif self.path == "/v1/checkpoints" and (body or {}).get("kind") == "full":
payload = {**INFO, "kind": "full", **checkpoint_settings["memory"]}
elif self.path.startswith("/v1/boxes"):
payload = BOX
if self.command == "GET" and self.path == "/v1/checkpoints/checkpoint-1":
payload = {
**INFO,
"kind": "future",
"state": "failed",
"error_reason": "archive upload failed",
}
encoded = json.dumps(payload).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
do_POST = do_GET = do_DELETE = dispatch
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield f"http://127.0.0.1:{server.server_address[1]}", requests
server.shutdown()
server.server_close()
thread.join()
@pytest.mark.asyncio
async def test_checkpoint_native_rest_management_and_box_creation(checkpoint_server):
url, requests = checkpoint_server
runtime = boxlite.Boxlite.rest(boxlite.BoxliteRestOptions(url=url))
checkpoints = runtime.checkpoints
captured = await checkpoints.create("source-1", "base")
assert isinstance(captured, boxlite.CheckpointInfo)
assert (captured.name, captured.size_bytes, captured.state) == (
"base",
4096,
"ready",
)
listed = (await checkpoints.list())[0]
assert (listed.source_box_id, listed.kind) == ("source-1", "unknown")
detail = await checkpoints.get("checkpoint-1")
assert detail.kind == "unknown"
assert (detail.id, detail.state, detail.error_reason) == (
"checkpoint-1",
"failed",
"archive upload failed",
)
assert not hasattr(checkpoints, "import_box")
created = await runtime.create(
boxlite.BoxOptions(checkpoint="checkpoint-1"), name="worker"
)
assert (created.id, created.name) == ("target-1", "worker")
await checkpoints.remove("checkpoint-1", True)
await checkpoints.remove("checkpoint-1")
await checkpoints.remove("checkpoint-1", False)
await checkpoints.create("source-1")
await runtime.create(boxlite.BoxOptions(checkpoint="checkpoint-1"))
for overridden in (
boxlite.BoxOptions(checkpoint="checkpoint-1", cpus=2),
boxlite.BoxOptions(checkpoint="checkpoint-1", image="alpine:latest"),
boxlite.BoxOptions(checkpoint="checkpoint-1", rootfs_path="/tmp/rootfs"),
):
with pytest.raises(boxlite.InvalidArgumentError):
await runtime.create(overridden)
assert requests == [
("POST", "/v1/checkpoints", {"source_box_id": "source-1", "name": "base"}),
("GET", "/v1/checkpoints", None),
("GET", "/v1/checkpoints/checkpoint-1", None),
(
"POST",
"/v1/boxes",
{"checkpoint_id": "checkpoint-1", "name": "worker"},
),
("DELETE", "/v1/checkpoints/checkpoint-1?force=true", None),
("DELETE", "/v1/checkpoints/checkpoint-1", None),
("DELETE", "/v1/checkpoints/checkpoint-1", None),
("POST", "/v1/checkpoints", {"source_box_id": "source-1"}),
("POST", "/v1/boxes", {"checkpoint_id": "checkpoint-1"}),
]
def test_checkpoint_sync_bridge_returns_managed_box_handles(checkpoint_server):
url, requests = checkpoint_server
with boxlite.SyncBoxlite.rest(boxlite.BoxliteRestOptions(url=url)) as runtime:
assert runtime.checkpoints.list()[0].id == "checkpoint-1"
target = runtime.create(
boxlite.BoxOptions(checkpoint="checkpoint-1"), name="worker"
)
assert isinstance(target, boxlite.SyncBox)
assert target.id == "target-1"
assert requests[1][2] == {"checkpoint_id": "checkpoint-1", "name": "worker"}
@pytest.mark.parametrize("sync", [False, True], ids=["async", "sync"])
@pytest.mark.parametrize(
"kwargs, enabled, memory, error",
[
(None, False, None, None),
({}, False, None, None),
({"kind": "disk"}, False, None, None),
({"kind": "full"}, True, None, None),
({"kind": "full"}, True, 0, None),
({"kind": "full"}, True, 8192, None),
({"kind": "full"}, False, None, "UnsupportedError"),
({"kind": "bogus"}, True, None, "InvalidArgumentError"),
({"kind": ""}, True, None, "InvalidArgumentError"),
],
)
def test_checkpoint_create_options(
checkpoint_server, checkpoint_settings, sync, kwargs, enabled, memory, error
):
url, requests = checkpoint_server
checkpoint_settings["enabled"] = enabled
if memory is not None:
checkpoint_settings["memory"]["memory_size_bytes"] = memory
rest = boxlite.BoxliteRestOptions(url=url)
options = None if kwargs is None else boxlite.CheckpointOptions(**kwargs)
full = (kwargs or {}).get("kind") == "full"
name = "base" if memory == 0 else None
async def capture_async():
return await boxlite.Boxlite.rest(rest).checkpoints.create(
"source-1", name, options=options
)
def capture():
if sync:
with boxlite.SyncBoxlite.rest(rest) as runtime:
return runtime.checkpoints.create("source-1", name, options=options)
return asyncio.run(capture_async())
expected = [("GET", "/v1/config", None)] if full else []
if error:
with pytest.raises(getattr(boxlite, error)):
capture()
else:
info = capture()
assert (info.kind, info.memory_size_bytes) == (
"full" if full else "disk",
memory,
)
body = {"source_box_id": "source-1"}
if full:
body["kind"] = "full"
if name is not None:
body["name"] = name
expected.append(("POST", "/v1/checkpoints", body))
assert requests == expected