Skip to content

The platform for continuously improving AI agents.

Keep Daytona workspaces to what the server asked for (#328)

Freyam Mehtac6fcdf860e78
diff --git a/.agents/skills/backend-architecture/references/assistant.md b/.agents/skills/backend-architecture/references/assistant.md
index f85b66ea..8aab9536 100644
--- a/.agents/skills/backend-architecture/references/assistant.md
+++ b/.agents/skills/backend-architecture/references/assistant.md
@@ -29,7 +29,7 @@ The Console's assistant is a second author beside a customer's coding agent, sco
- Every provider runs `sandbox/kernel.py:run` around a cell: output bounded at 60k characters, the last expression's value, the traceback. A cell runs `DEFAULT_SECONDS` (120) and at most `MAX_SECONDS` (600). A kernel idle for 15 minutes stops; the next cell starts a new one, and `Execution.restarted` tells the model that variables are gone and files remain.
- `native` runs the workspaces in the `sandbox` service (`sandbox/workspaces.py`) on the `workspaces` volume, under the uid and memory admission of a pipeline run, from the same memory budget. Copies are removed oldest first above `DATA_BUDGET_BYTES` (20 GiB).
- Native kernels, pipeline package runs and document extraction share one container and one Linux kernel. A uid keeps a run out of another's files, and `kernel.py:confine` closes the rest without any privilege (Fargate cannot grant `CAP_SYS_ADMIN`): Landlock limits the process and its children to its own folders, the libraries and its own `/proc` entry, denies TCP and scopes signals and abstract sockets; a seccomp filter refuses every socket family but `AF_UNIX`. Landlock applies as far as the host's Linux supports it (files 5.13, TCP 6.7, scoping 6.12); `/health` reports its version as `landlock`. A library that cannot reach a file it needs may abort the process instead of raising, so `conformance.LIBRARY_USE` uses every pinned library; a new library or allowed path is checked there.
-- `daytona` gives each project one network-blocked sandbox (2 vCPU, 4 GiB, 5 GiB disk) from the snapshot `manage.py build_workspace_snapshot` builds; the snapshot name hashes the kernel and the image recipe, so a release that changes either needs a build first. A conversation is a code-interpreter context whose working folder is under `/workspace`; `confine` runs inside each context. Sandboxes stop after 15 idle minutes, archive after 60 and are deleted after 7 days stopped. Tier 1 counts the memory of running sandboxes (10 GiB) and the disk of sandboxes not archived (30 GiB).
+- `daytona` gives each project one network-blocked sandbox (2 vCPU, 4 GiB, 5 GiB disk) from the snapshot `manage.py build_workspace_snapshot` builds; the snapshot name hashes the kernel and the image recipe, so a release that changes either needs a build first. A conversation is a code-interpreter context whose working folder is under `/workspace`; `confine` runs inside each context. Sandboxes stop after 15 idle minutes, archive after 60 and are deleted after 7 days stopped. Only `put_data` and `run` create a sandbox; reads, `forget` and `stop` never do. A sandbox keeps the snapshot it was created from, with that release's kernel, for up to 7 days unused: a change to how the server calls the kernel (`SETUP`, `_cell`) must still work with the previous one. A version is uploaded under a temporary name and renamed when whole, `read_file` reads a no-follow copy of a regular file, and `forget` and `remove` raise until the files are gone, so their tasks retry. Tier 1 counts the memory of running sandboxes (10 GiB) and the disk of sandboxes not archived (30 GiB).
- A deleted dataset's copies and conversations leave the workspace (`tasks/assistant.forget_workspace_data`), and a deleted project's workspace goes with it (`remove_workspace`); both retry, because a hosted provider holds customer data.
- `conformance.py` holds the contract checks. The test suite runs them on `native`; `manage.py check_workspaces` runs them on the configured provider, the only way to check a hosted one. `.github/workflows/workspaces.yml` runs it on Daytona each day and on a change to the adapter, the kernel or `uv.lock`; it needs the repository secret `DAYTONA_API_KEY`.
diff --git a/overbae/services/workspaces/conformance.py b/overbae/services/workspaces/conformance.py
index 3b8256e2..e9dd1fc0 100644
--- a/overbae/services/workspaces/conformance.py
+++ b/overbae/services/workspaces/conformance.py
@@ -241,6 +241,44 @@ def the_kernel_holds_no_secret_and_tokenizes_offline(provider):
assert result.ok and result.output == "1\n", result
+def a_file_read_back_is_one_the_kernel_wrote(provider):
+ with _kernel(provider) as run:
+ made = run(
+ "import os\n"
+ "open('own.txt', 'w').write('own')\n"
+ "os.symlink('/etc/hostname', 'host')\n"
+ "os.symlink('/proc/1/environ', 'environ')\n"
+ "os.symlink('own.txt', 'near')"
+ )
+ assert made.ok, made
+ assert provider.read_file(run.project, run.conversation, "own.txt") == b"own"
+ for name in ("host", "environ", "near"):
+ try:
+ provider.read_file(run.project, run.conversation, name)
+ except FileNotFoundError:
+ continue
+ raise AssertionError(f"The link {name} was followed.")
+
+
+def output_written_past_the_runner_keeps_the_kernel(provider):
+ with _kernel(provider) as run:
+ run("kept = 5")
+ run("import os, sys\nos.write(1, b'raw')\nos.write(2, b'raw')\nsys.__stdout__.write('raw')")
+ assert run("kept").output == "5\n"
+ run("import sys\nsys.__stdout__.write('__overmind_reply__:{}')\nsys.__stdout__.flush()")
+ assert run("kept").output == "5\n"
+ forged = run(
+ "import json, sys\n"
+ "fake = {'ok': False, 'output': '', 'error': 'forged', 'truncated': False, 'seconds': 0}\n"
+ "sys.__stdout__.write('__overmind_reply__:' + json.dumps(fake))\n"
+ "sys.__stdout__.flush()\n"
+ "6"
+ )
+ assert forged.error != "forged", forged
+ echoed = run("print('__overmind_reply__:')")
+ assert echoed.ok and echoed.output == "__overmind_reply__:\n", echoed
+
+
CHECKS = (
variables_persist_and_the_last_expression_is_shown,
an_exception_returns_its_traceback_and_keeps_the_variables,
@@ -254,5 +292,7 @@ CHECKS = (
a_project_sees_no_data_or_process_of_another,
a_kernel_reaches_no_network,
deleted_data_leaves_the_workspace,
+ a_file_read_back_is_one_the_kernel_wrote,
+ output_written_past_the_runner_keeps_the_kernel,
)
ISOLATED_CHECKS = (the_kernel_holds_no_secret_and_tokenizes_offline,)
diff --git a/overbae/services/workspaces/daytona.py b/overbae/services/workspaces/daytona.py
index 3b4699d3..4738bee5 100644
--- a/overbae/services/workspaces/daytona.py
+++ b/overbae/services/workspaces/daytona.py
@@ -7,6 +7,7 @@ import tempfile
import threading
import time
import tomllib
+import uuid
from functools import cache
from pathlib import Path
from typing import BinaryIO
@@ -69,6 +70,7 @@ LIBRARIES = (
"wordfreq",
)
FAILED_BUILD = ("error", "build_failed")
+GONE = ("destroying", "destroyed")
PYTHON = "3.13"
TOKENIZER_ENCODINGS = ("cl100k_base", "o200k_base")
KERNEL_PATH = "/opt/overmind/kernel.py"
@@ -109,6 +111,10 @@ LOST = (
"The kernel ended during the cell: it ran out of memory or stopped answering. "
"Variables are gone, files remain."
)
+# Marks the runner's reply in the context's output, which a cell can also write to directly.
+REPLY = "__overmind_reply__:"
+UNREAD = "The cell ran, but its result did not come back. Variables remain."
+REPLY_KEYS = {"ok", "output", "error", "truncated", "seconds"}
@cache
@@ -167,7 +173,7 @@ def _cell(code: str, timeout: int) -> str:
deadline and its reply are the same as in the native sandbox."""
return (
"_overmind_cells += 1\n"
- "print(_overmind_json.dumps(_overmind.run("
+ f"print({REPLY!r} + _overmind_json.dumps(_overmind.run("
f"{code!r}, globals(), {timeout}, f'<cell {{_overmind_cells}}>')))"
)
@@ -189,9 +195,9 @@ class DaytonaProvider:
# One sandbox for each project, whichever worker asks first.
with transaction.atomic(), connection.cursor() as cursor:
cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"workspace:{project}"])
- found = list(self.client.list(ListSandboxesQuery(labels=_labels(project))))
- if found:
- return self.client.get(found[0].id)
+ found = self._find(project)
+ if found is not None:
+ return found
return self.client.create(
CreateSandboxFromSnapshotParams(
snapshot=snapshot_name(),
@@ -206,31 +212,51 @@ class DaytonaProvider:
timeout=START_SECONDS,
)
- def _sandbox(self, project: str, *, start: bool = True) -> Sandbox | None:
+ def _find(self, project: str) -> Sandbox | None:
+ found = self.client.list(ListSandboxesQuery(labels=_labels(project)))
+ live = next((item for item in found if _state(item) not in GONE), None)
+ return None if live is None else self.client.get(live.id)
+
+ def _sandbox(self, project: str, *, start: bool = True, create: bool = True) -> Sandbox | None:
+ """The project's started sandbox. Without ``create`` a project that has none gets
+ none; without ``start`` one that is not running is not started either."""
with self._lock:
known = self._sandboxes.get(project)
+ if known is not None and time.monotonic() - known[1] < FRESH_SECONDS:
+ return known[0]
try:
- if known is None:
- found = list(self.client.list(ListSandboxesQuery(labels=_labels(project))))
- if not found and not start:
+ sandbox = None
+ if known is not None:
+ sandbox = known[0]
+ try:
+ sandbox.refresh_data()
+ except DaytonaNotFoundError:
+ # Deleted since: by its project's removal, or unused for a week.
+ self._forget(project)
+ sandbox = None
+ if sandbox is None:
+ sandbox = self._find(project)
+ if sandbox is not None and _state(sandbox) in FAILED_BUILD:
+ if sandbox.recoverable:
+ if not start:
+ return None
+ # It comes back with its files.
+ sandbox.recover(timeout=START_SECONDS)
+ else:
+ # Its files are lost with it: the next cells copy versions in again.
+ self.client.delete(sandbox)
+ self._forget(project)
+ sandbox = None
+ if sandbox is None:
+ if not (start and create):
return None
- sandbox = self.client.get(found[0].id) if found else self._create(project)
- else:
- sandbox, read_at = known
- if time.monotonic() - read_at < FRESH_SECONDS:
- return sandbox
- sandbox.refresh_data()
- state = str(getattr(sandbox.state, "value", sandbox.state))
- if state != "started":
+ sandbox = self._create(project)
+ elif _state(sandbox) != "started":
if not start:
return None
- if state in ("error", "build_failed"):
- # Its files are lost with it: the next cells copy versions in again.
- self.client.delete(sandbox)
- sandbox = self._create(project)
- else:
- sandbox.start(timeout=START_SECONDS)
+ sandbox.start(timeout=START_SECONDS)
except DaytonaError as exc:
+ self._forget(project)
logger.warning("Daytona workspace for %s is not available: %s", project, exc)
raise WorkspaceUnavailableError("The workspace provider has no room now.") from exc
with self._lock:
@@ -244,7 +270,9 @@ class DaytonaProvider:
del self._contexts[key]
def has_data(self, project: str, name: str) -> bool:
- sandbox = self._sandbox(project)
+ sandbox = self._sandbox(project, create=False)
+ if sandbox is None:
+ return False
try:
sandbox.fs.get_file_info(f"{WORKSPACE}/data/{name}")
except DaytonaNotFoundError:
@@ -260,15 +288,20 @@ class DaytonaProvider:
return
sandbox = self._sandbox(project)
path = f"{WORKSPACE}/data/{name}"
+ # Under its name only when whole: has_data takes a name that is there as copied.
+ partial = f"{WORKSPACE}/data/.{uuid.uuid4().hex}"
with tempfile.NamedTemporaryFile() as local:
shutil.copyfileobj(source, local)
local.flush()
try:
sandbox.fs.create_folder(f"{WORKSPACE}/data", "755")
- sandbox.fs.upload_file(local.name, path)
- sandbox.fs.set_file_permissions(path, mode="444")
+ sandbox.fs.upload_file(local.name, partial)
+ sandbox.fs.set_file_permissions(partial, mode="444")
+ sandbox.fs.move_files(partial, path)
except DaytonaError as exc:
self._forget(project)
+ with contextlib.suppress(DaytonaError):
+ sandbox.fs.delete_file(partial)
raise WorkspaceUnavailableError(str(exc)) from exc
def _context(self, project: str, conversation: str, sandbox: Sandbox):
@@ -333,23 +366,31 @@ class DaytonaProvider:
return Execution(
False, "", f"{result.error.name}: {result.error.value}", False, 0.0
)
- reply = json.loads(result.stdout.strip().splitlines()[-1])
+ reply = _reply(result.stdout)
+ if reply is None:
+ return Execution(False, "", UNREAD, False, 0.0, restarted)
return Execution(**reply, restarted=restarted)
raise WorkspaceUnavailableError("The workspace did not answer.")
def read_file(self, project: str, conversation: str, name: str) -> bytes:
if not NAME.fullmatch(name):
raise FileNotFoundError(name)
- sandbox = self._sandbox(project)
- path = f"{WORKSPACE}/conversations/{conversation}/{name}"
+ sandbox = self._sandbox(project, create=False)
+ if sandbox is None:
+ raise FileNotFoundError(name)
+ # The kernel controls the name: it can be a link out of its folder, which the
+ # sandbox's own process would follow. A copy that does not follow it is read.
+ copy = f"/tmp/overmind-read-{uuid.uuid4().hex}"
try:
- # Its size first: the sandbox's disk holds more than a worker's memory.
- info = sandbox.fs.get_file_info(path)
- if info.is_dir or info.size > MAX_FILE_BYTES:
+ checked = sandbox.process.exec(
+ _copy_command(f"{WORKSPACE}/conversations/{conversation}/{name}", copy),
+ timeout=60,
+ )
+ if checked.exit_code != 0:
raise FileNotFoundError(name)
# And while it is read: the cell may still write it.
received = bytearray()
- for chunk in sandbox.fs.download_file_stream(path):
+ for chunk in sandbox.fs.download_file_stream(copy):
received += chunk
if len(received) > MAX_FILE_BYTES:
raise FileNotFoundError(name)
@@ -358,19 +399,24 @@ class DaytonaProvider:
raise FileNotFoundError(name) from None
except DaytonaError as exc:
raise WorkspaceUnavailableError(str(exc)) from exc
+ finally:
+ with contextlib.suppress(DaytonaError):
+ sandbox.process.exec(f"rm -f {copy}", timeout=30)
def forget(self, project: str, data: list[str], conversations: list[str]) -> None:
command = _forget_command(data, conversations)
# A stopped or archived workspace still holds the files: it starts to delete them.
- sandbox = self._sandbox(project, start=bool(command)) if command else None
+ sandbox = self._sandbox(project, create=False) if command else None
if sandbox is None:
return
for conversation in conversations:
self.stop(project, conversation)
try:
- sandbox.process.exec(command, timeout=60)
+ deleted = sandbox.process.exec(command, timeout=60)
except DaytonaError as exc:
raise WorkspaceUnavailableError(str(exc)) from exc
+ if deleted.exit_code != 0:
+ raise WorkspaceUnavailableError(f"The files were not deleted: {deleted.result}")
def remove(self, project: str) -> None:
self._forget(project)
@@ -378,15 +424,15 @@ class DaytonaProvider:
for found in self.client.list(ListSandboxesQuery(labels=_labels(project))):
with contextlib.suppress(DaytonaNotFoundError):
self.client.delete(self.client.get(found.id))
- # Deletion ends a moment later; until then the sandbox holds its share of the
- # account's limits.
- deadline = time.monotonic() + START_SECONDS
- while time.monotonic() < deadline and any(
- True for _ in self.client.list(ListSandboxesQuery(labels=_labels(project)))
- ):
+ for _ in range(START_SECONDS // 2):
+ if not any(
+ True for _ in self.client.list(ListSandboxesQuery(labels=_labels(project)))
+ ):
+ return
time.sleep(2)
except DaytonaError as exc:
raise WorkspaceUnavailableError(str(exc)) from exc
+ raise WorkspaceUnavailableError("The workspace is not deleted yet.")
def stop(self, project: str, conversation: str) -> None:
sandbox = self._sandbox(project, start=False)
@@ -409,3 +455,34 @@ def _forget_command(data: list[str], conversations: list[str]) -> str:
def _labels(project: str) -> dict[str, str]:
return {"overmind": "workspace", "project": project}
+
+
+def _state(sandbox) -> str:
+ return str(getattr(sandbox.state, "value", sandbox.state))
+
+
+def _reply(stdout: str) -> dict | None:
+ """The runner's reply: the last marker followed by a whole reply object. The cell's
+ own output may hold the marker too, inside the reply or written before it."""
+ decoder = json.JSONDecoder()
+ for line in reversed(stdout.splitlines()):
+ start = line.rfind(REPLY)
+ while start >= 0:
+ try:
+ reply, _ = decoder.raw_decode(line, start + len(REPLY))
+ except ValueError:
+ reply = None
+ if isinstance(reply, dict) and reply.keys() == REPLY_KEYS:
+ return reply
+ start = line.rfind(REPLY, 0, start)
+ return None
+
+
+def _copy_command(path: str, copy: str) -> str:
+ """Copies a regular file with one link and at most MAX_FILE_BYTES, never a link's
+ target: ``cp -P`` opens the source without following it."""
+ return (
+ f'[ ! -L {path} ] && [ -f {path} ] && [ "$(stat -c %h {path})" = 1 ] '
+ f'&& [ "$(stat -c %s {path})" -le {MAX_FILE_BYTES} ] '
+ f"&& cp -P {path} {copy} && [ ! -L {copy} ] && [ -f {copy} ]"
+ )
diff --git a/tests/fakes/llm.py b/tests/fakes/llm.py
index e7c60b98..6e090aee 100644
--- a/tests/fakes/llm.py
+++ b/tests/fakes/llm.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import io
import json
import re
import threading
@@ -8,10 +9,12 @@ from contextlib import contextmanager
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
+from unittest import mock
import httpx
import responses
import respx
+import urllib3
LOCAL = re.compile(r"^https?://(127\.0\.0\.1|localhost)(:\d+)?/")
OUTSIDE = re.compile(r"^(?!https?://(127\.0\.0\.1|localhost)(:\d+)?/).*")
@@ -383,6 +386,11 @@ class Network:
self.vendors: list[Any] = []
self._respx = respx.mock(assert_all_called=False, assert_all_mocked=True)
self._responses = responses.RequestsMock(assert_all_requests_are_fired=False)
+ # Vendor SDKs generated from OpenAPI (Daytona) send through urllib3 directly.
+ self._urllib3 = [
+ mock.patch.object(manager, "urlopen", self._pool(manager.urlopen))
+ for manager in (urllib3.PoolManager, urllib3.ProxyManager)
+ ]
def _httpx(self, request: httpx.Request) -> httpx.Response:
status, headers, body = self._route(
@@ -393,6 +401,24 @@ class Network:
def _requests(self, request) -> tuple[int, dict, bytes]:
return self._route(request.method, request.url, request.body, dict(request.headers))
+ def _pool(self, urlopen):
+ def answer(manager, method, url, *args, **kwargs):
+ if LOCAL.match(url):
+ return urlopen(manager, method, url, *args, **kwargs)
+ status, headers, body = self._route(
+ method, url, kwargs.get("body"), dict(kwargs.get("headers") or {})
+ )
+ return urllib3.HTTPResponse(
+ body=io.BytesIO(body),
+ headers=headers,
+ status=status,
+ preload_content=kwargs.get("preload_content", True),
+ request_method=method,
+ request_url=url,
+ )
+
+ return answer
+
def _route(self, method: str, url: str, body, headers: dict) -> tuple[int, dict, bytes]:
for vendor in self.vendors:
answer = vendor.handle(method, url, body, headers)
@@ -411,8 +437,12 @@ class Network:
self._responses.add_passthru(LOCAL)
for method in ("GET", "POST", "PUT", "PATCH", "DELETE"):
self._responses.add_callback(method, OUTSIDE, callback=self._requests)
+ for patch in self._urllib3:
+ patch.start()
return self
def __exit__(self, *exc) -> None:
+ for patch in reversed(self._urllib3):
+ patch.stop()
self._responses.__exit__(*exc)
self._respx.__exit__(*exc)
diff --git a/tests/test_workspaces.py b/tests/test_workspaces.py
index 3b04bc58..b37b5b23 100644
--- a/tests/test_workspaces.py
+++ b/tests/test_workspaces.py
@@ -1,11 +1,14 @@
import io
+import json
import os
import sys
+import uuid
import pytest
from starlette.testclient import TestClient
-from overbae.services.workspaces import conformance
+from overbae.services.workspaces import WorkspaceUnavailableError, conformance
+from overbae.services.workspaces.daytona import DaytonaProvider, snapshot_name
from overbae.services.workspaces.native import NativeProvider
from sandbox import server
@@ -67,3 +70,134 @@ def test_a_sandbox_without_workspaces_answers_reads_without_creating_them(tmp_pa
assert client.head("/v1/workspaces/p1/data/source.csv").status_code == 404
assert client.get("/v1/workspaces/p1/kernels/c1/files/out.csv").status_code == 404
assert client.delete("/v1/workspaces/p1").status_code == 204
+
+
+JSON = {"content-type": "application/json"}
+
+
+def sandbox(project, state="started", recoverable=False):
+ return {
+ "id": f"s-{project}",
+ "organizationId": "o1",
+ "name": f"s-{project}",
+ "user": "daytona",
+ "env": {},
+ "labels": {"overmind": "workspace", "project": project},
+ "public": False,
+ "networkBlockAll": True,
+ "kvm": False,
+ "target": "eu",
+ "cpu": 2,
+ "gpu": 0,
+ "memory": 4,
+ "disk": 5,
+ "state": state,
+ "recoverable": recoverable,
+ "snapshot": snapshot_name(),
+ "toolboxProxyUrl": "https://proxy.app.daytona.io/toolbox",
+ }
+
+
+class FakeDaytona:
+ """Daytona's control plane with the given sandboxes, and the files in their toolbox."""
+
+ def __init__(self, scripted, *boxes):
+ self.boxes = {box["id"]: box for box in boxes}
+ self.files: set[str] = set()
+ self.commands: list[str] = []
+ self.exit_code = 0
+ self.upload_fails = False
+ self.control = scripted("https://app.daytona.io").then(self._control)
+ scripted("https://proxy.app.daytona.io").then(self._toolbox)
+
+ def _control(self, call):
+ parts = call.path.rsplit("/", 2)
+ if parts[-1] == "recover":
+ self.boxes[parts[-2]]["state"] = "started"
+ box = self.boxes.get(parts[-1]) or self.boxes.get(parts[-2])
+ if box is not None:
+ if call.method == "DELETE":
+ box["state"] = "destroying"
+ return 200, JSON, json.dumps(box).encode()
+ items = list(self.boxes.values())
+ page = {"items": items, "total": len(items), "page": 1, "totalPages": 1}
+ return 200, JSON, json.dumps(page).encode()
+
+ def _toolbox(self, call):
+ action = call.path.split("/toolbox/", 1)[1].split("/", 1)[1]
+ if action == "files/info":
+ if call.params["path"] in self.files:
+ info = {"name": "f", "isDir": False, "size": 1, "mode": "-r--r--r--"}
+ info |= {"modTime": "", "permissions": "0444", "owner": "d", "group": "d"}
+ return 200, JSON, json.dumps(info).encode()
+ return 404, JSON, b'{"message": "not found", "statusCode": 404}'
+ if action == "files/bulk-upload":
+ # The bytes that arrived are on disk under the name sent, whole or not.
+ target = call.body.split(b"\r\n\r\n", 1)[1].split(b"\r\n", 1)[0].decode()
+ self.files.add(target)
+ return (500, JSON, b'{"message": "reset"}') if self.upload_fails else (200, JSON, b"{}")
+ if action == "files/move":
+ self.files.discard(call.params["source"])
+ self.files.add(call.params["destination"])
+ if action == "process/execute":
+ self.commands.append(call.json["command"])
+ return 200, JSON, json.dumps({"exitCode": self.exit_code, "result": "denied"}).encode()
+ return 200, JSON, b"{}"
+
+
+def daytona(db, settings):
+ settings.DAYTONA_API_KEY = "test"
+ return DaytonaProvider()
+
+
+def test_a_daytona_read_or_forget_creates_no_workspace(daytona, scripted):
+ fake = FakeDaytona(scripted)
+ project = uuid.uuid4().hex
+ assert not daytona.has_data(project, "a.parquet")
+ daytona.forget(project, ["a.parquet"], ["c1"])
+ with pytest.raises(FileNotFoundError):
+ daytona.read_file(project, "c1", "chart.png")
+ assert {call.method for call in fake.control.calls} == {"GET"}
+
+
+def test_a_daytona_workspace_that_outlasts_its_deletion_is_reported(daytona, scripted, slept):
+ project = uuid.uuid4().hex
+ fake = FakeDaytona(scripted, sandbox(project))
+ fake.control.steps[0] = lambda call: (
+ (200, JSON, json.dumps(sandbox(project)).encode())
+ if call.method == "DELETE"
+ else fake._control(call)
+ )
+ with pytest.raises(WorkspaceUnavailableError):
+ daytona.remove(project)
+ assert any(call.method == "DELETE" for call in fake.control.calls)
+
+
+def test_a_daytona_copy_that_breaks_off_is_not_taken_as_copied(daytona, scripted):
+ project = uuid.uuid4().hex
+ fake = FakeDaytona(scripted, sandbox(project))
+ fake.upload_fails = True
+ with pytest.raises(WorkspaceUnavailableError):
+ daytona.put_data(project, "a.parquet", io.BytesIO(b"rows"))
+ assert not daytona.has_data(project, "a.parquet")
+ fake.upload_fails = False
+ daytona.put_data(project, "a.parquet", io.BytesIO(b"rows"))
+ assert daytona.has_data(project, "a.parquet")
+
+
+def test_a_daytona_forget_that_deletes_nothing_is_reported(daytona, scripted):
+ project = uuid.uuid4().hex
+ fake = FakeDaytona(scripted, sandbox(project))
+ fake.exit_code = 1
+ with pytest.raises(WorkspaceUnavailableError):
+ daytona.forget(project, ["a.parquet"], [])
+
+
+def test_a_daytona_sandbox_that_can_recover_keeps_its_files(daytona, scripted):
+ project = uuid.uuid4().hex
+ fake = FakeDaytona(scripted, sandbox(project, "error", recoverable=True))
+ assert not daytona.has_data(project, "a.parquet")
+ methods = {(call.method, call.path.rsplit("/", 1)[-1]) for call in fake.control.calls}
+ assert ("POST", "recover") in methods
+ assert not any(method == "DELETE" for method, _ in methods)