Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 32 additions & 5 deletions server/opensandbox_server/services/snapshot_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
from concurrent.futures import Future, ThreadPoolExecutor
from datetime import datetime, timezone
import logging
from collections.abc import Callable
from contextlib import AbstractContextManager
from threading import Event, Lock, Thread
import time
from uuid import uuid4
Expand Down Expand Up @@ -129,6 +131,7 @@ def __init__(
snapshot_executor=None,
*,
recover_unfinished_snapshots: bool = True,
lifecycle_lock_factory: Callable[[str], AbstractContextManager] | None = None,
) -> None:
self._snapshot_repository = snapshot_repository
self._sandbox_service = sandbox_service
Expand All @@ -137,6 +140,16 @@ def __init__(
max_workers=SNAPSHOT_WORKER_MAX_WORKERS,
thread_name_prefix="snapshot-create",
)
# Serializes the background docker commit with the per-sandbox
# lifecycle mutations (pause/resume/renew/delete/expiry) of the
# sandbox service (#3121): docker commit pauses the container while
# it writes, so an unserialized commit against a Running sandbox
# corrupts pause/resume reporting and can renew a concurrently
# deleted sandbox. Injected by the Docker assembly as
# `docker_service._sandbox_lifecycle_lock`. Other runtimes (K8s,
# Fast Sandbox) snapshot outside the container lifecycle and pass
# None.
self._lifecycle_lock_factory = lifecycle_lock_factory
self._inflight_snapshot_ids: set[str] = set()
self._inflight_lock = Lock()
if recover_unfinished_snapshots:
Expand Down Expand Up @@ -585,11 +598,17 @@ def _submit_snapshot_worker(self, record: SnapshotRecord) -> None:
self._inflight_snapshot_ids.add(record.id)

def run_tracked_worker() -> None:
try:
self._create_snapshot_worker(record)
finally:
with self._inflight_lock:
self._inflight_snapshot_ids.discard(record.id)
# Take the source sandbox's lifecycle lock so the commit below
# cannot interleave with pause/resume/renew/delete/expiry of the
# same sandbox (#3121). No factory (K8s, Fast Sandbox) means the
# runtime snapshots outside the container lifecycle and needs no
# serialization.
lock_factory = self._lifecycle_lock_factory
if lock_factory is None:
self._run_snapshot_worker_untracked(record)
return
with lock_factory(record.source_sandbox_id):
self._run_snapshot_worker_untracked(record)
Comment on lines +610 to +611

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Coordinate sandbox status reads with the commit lock

When a running Docker sandbox is snapshotted, container.commit() temporarily exposes Docker's Paused state. This scope only excludes operations that acquire _sandbox_lifecycle_lock; DockerSandboxService.get_sandbox() and list_sandboxes() never acquire it, and _container_to_sandbox() maps container.attrs["State"] directly. Consequently GET/list requests during a long commit still report Paused and then Running, so the user-visible state-flip scenario remains; status reads must either participate in the coordination or mask the commit's internal pause.

AGENTS.md reference: server/AGENTS.md:L42-L42

Useful? React with 👍 / 👎.


try:
future = self._snapshot_executor.submit(run_tracked_worker)
Expand All @@ -599,6 +618,13 @@ def run_tracked_worker() -> None:
raise
future.add_done_callback(self._log_worker_failure)

def _run_snapshot_worker_untracked(self, record: SnapshotRecord) -> None:
try:
self._create_snapshot_worker(record)
finally:
with self._inflight_lock:
self._inflight_snapshot_ids.discard(record.id)

def _complete_snapshot(self, record: SnapshotRecord, runtime_status) -> None:
current_record = self._snapshot_repository.get(record.id)
if current_record is None:
Expand Down Expand Up @@ -982,6 +1008,7 @@ def create_snapshot_service(sandbox_service) -> SnapshotService:
snapshot_repository=get_snapshot_repository(),
sandbox_service=sandbox_service,
snapshot_runtime=snapshot_runtime,
lifecycle_lock_factory=getattr(sandbox_service, "_sandbox_lifecycle_lock", None),
)


Expand Down
110 changes: 109 additions & 1 deletion server/tests/test_docker_snapshot_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@

from __future__ import annotations

from concurrent.futures import ThreadPoolExecutor
from types import SimpleNamespace
from unittest.mock import MagicMock
from unittest.mock import MagicMock, patch
import pytest

from opensandbox_server.services.docker.snapshot_runtime import (
Expand Down Expand Up @@ -435,3 +436,110 @@ def commit(*, repository: str, tag: str) -> None:
assert status.reason == "snapshot_runtime_unsupported"
assert "diff API is unavailable" in (status.message or "")



def test_snapshot_worker_serializes_with_lifecycle_lock(monkeypatch):
"""#3121: the background docker commit must hold the source sandbox's
lifecycle lock, so a concurrent pause/resume/delete/expiry waits instead
of racing the container-pausing `docker commit`."""
import threading

from opensandbox_server.services import snapshot_service as ss

order = []
release = threading.Event()

class FakeRepo:
def get(self, snapshot_id):
return None

def create(self, record):
pass

class FakeRuntime:
def supports_create_snapshot(self):
return True

def preflight_create_snapshot(self, *a, **k):
return None

def create_snapshot(self, *a, **k):
# Hold while the test asserts the lifecycle lock is busy
release.wait(timeout=5)
return SimpleNamespace(resource_limits=None)

lifecycle_held = threading.Event()
# One lock per sandbox_id — the same semantics the real
# `_sandbox_lifecycle_lock` implements via WeakValueDictionary.
locks = {}

def fake_lock_factory(sandbox_id):
class _Ctx:
def __enter__(self):
order.append("ENTER")
lifecycle_held.set()
return self

def __exit__(self, *exc):
order.append("lifecycle released")
return False

return locks.setdefault(sandbox_id, _Ctx())

service = ss.PersistedSnapshotService(
snapshot_repository=FakeRepo(),
sandbox_service=SimpleNamespace(
get_sandbox=lambda *_: SimpleNamespace(status="Running"),
docker_client=None,
),
snapshot_runtime=FakeRuntime(),
snapshot_executor=ThreadPoolExecutor(max_workers=1),
recover_unfinished_snapshots=False,
lifecycle_lock_factory=fake_lock_factory,
)

# bypass tenant machinery via a direct worker submission
record = SimpleNamespace(
id="snap-1",
source_sandbox_id="sbx-1",
namespace="default",
image=None,
)

# While the worker holds the lifecycle lock, a competing acquire must block
acquired_other = threading.Event()
competitor_done = threading.Event()

def competitor_body():
with fake_lock_factory("sbx-1"):
acquired_other.set()
competitor_done.set()

competitor = threading.Thread(target=competitor_body)

def worker_side_effect(self, rec):
lifecycle_held.wait(timeout=5) # worker inside the lock
competitor.start() # competitor tries while held
blocked = not acquired_other.wait(timeout=2) # it must be blocked
release.set() # let the worker finish; competitor
return blocked # proceeds after the lock is released
Comment on lines +523 to +525

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make the serialization test exercise an actual lock

fake_lock_factory's _Ctx never acquires a synchronization primitive, so the competitor immediately sets acquired_other and blocked is false. That boolean is only returned from the patched _create_snapshot_worker, whose return is discarded, so the test still passes if the lifecycle context is released before the snapshot work; use a real per-ID lock and assert that acquisition remains blocked until the worker releases it.

AGENTS.md reference: server/AGENTS.md:L42-L42

Useful? React with 👍 / 👎.


with patch.object(
ss.PersistedSnapshotService,
"_create_snapshot_worker",
autospec=True,
side_effect=worker_side_effect,
):
service._submit_snapshot_worker(record)
assert lifecycle_held.wait(timeout=5), "worker never took the lifecycle lock"

service_worker = next(
(t for t in threading.enumerate() if t.name.startswith("snapshot-create")), None
)
if service_worker is not None:
service_worker.join(timeout=5)
assert competitor_done.wait(timeout=5), (
f"competitor never finished after release; order={order}, "
f"acquired={acquired_other.is_set()}"
)
assert order[-1] == "lifecycle released"
Loading