feat(vefaas-sandbox): add speculative prewarm, snapshots, pause/resume, and image precache (#8513)

* feat(vefaas-sandbox): add snapshots, pause/resume, and image precache

Implement Phase 2 of #8426 on top of #8449:
- Extend VeFaaSClient (OpenAPI Version=2024-06-06) with PauseSandbox,
  ResumeSandbox, CreateSandboxSnapshot, DescribeSandboxSnapshot,
  ListSandboxSnapshots (paginated), DeleteSandboxSnapshot,
  PrecacheSandboxImages, GetSandboxImagePrecacheTicket, plus SnapshotId
  and AutoPauseConfig support on CreateSandbox.
- Add opt-in lifecycle controls to VeFaaSSandboxProvider: pause_on_idle,
  auto_pause, snapshot_on_idle (with scoped metadata filtering and old
  snapshot pruning), base snapshot_id, precache_images, and off-loop
  precache_on_startup, plus public snapshot/precache helper methods.
- Preserve ownership lease fencing, dirty-sandbox exclusion, cross-tenant
  snapshot isolation, retryable shutdown, and non-blocking event-loop
  guarantees with offline unit and Blockbuster tests.

* fix(vefaas-sandbox): harden snapshot teardown lease, auto-pause reclaim, and manual snapshot shutdown fence

Address all review findings on #8513:
- Keep destructive teardown leases alive via a heartbeat and poll-tick
  refresh throughout idle pause/snapshot retirement, and re-verify
  claim(..., for_destroy=True) right before KillSandbox so a peer-adopted
  sandbox is never killed if the lease is lost mid-snapshot.
- Detect paused/transitioning warm instances in _reclaim_warm_pool via
  DescribeSandbox and hand them off to discovery/resume instead of
  killing them on failed HTTP readiness.
- Fence manual create_snapshot() source sandboxes via
  _snapshotting_remote_ids so concurrent shutdown() stays retryable and
  leaves the source alive until the snapshot settles.
- Move shared veFaaS offline test helpers into tests/support/vefaas_sandbox.py
  and add deterministic regression tests for all three scenarios.

* fix(vefaas-sandbox): keep paused warm sandboxes tracked during reacquire

Resume paused or transitioning warm-pool entries in place inside
_reclaim_warm_pool() instead of popping _warm_pool ahead of
ListSandboxes discovery:

- Keep the owned warm entry tracked in _warm_pool across transient 5xx
  control-plane errors (DescribeSandbox / ResumeSandbox), readiness
  timeouts, and ownership backend errors so shutdown() after recovery
  still sends KillSandbox and retry acquire() resumes without duplicates.
- Only discard a warm entry without teardown once the known remote
  instance is authoritatively confirmed absent/terminal (DescribeSandbox
  returning None/terminal or ResumeSandbox raising SandboxNotFound) or
  confirmed under a peer teardown lease.
- Move unadoptable resumed warm instances (e.g. invalid/mismatched init
  marker) atomically to _pending_destroys and tear them down via
  _destroy_tracked() rather than forgetting them.
- Handle concurrent shutdown rollback cleanly when resuming/publishing a
  paused warm entry and avoid falling through to discovery/create after
  shutdown starts.

* feat(vefaas-sandbox): support speculative sandbox prewarm

Fold speculative sandbox prewarm support for VeFaaSSandboxProvider (formerly
#8492) into #8513 so prewarm, snapshots, pause/resume, and image precache
land together on top of #8449.

* chore(vefaas-sandbox): address CodeQL quality findings

- Scope `needs_kill` inside the claimed teardown branch in `_retire_warm_entry`
  so the peer-owned branch does not write an unread local variable.
- Catch `Exception` rather than `BaseException` in the concurrent resume test
  helper thread.

* fix(vefaas-sandbox): retain teardown fence until async snapshots settle

When `create_snapshot(..., wait=False)` returns early or `wait=True` exits
without an authoritative terminal/ready state (such as `TimeoutError` or a
transient describe error), hand off the `_snapshotting_remote_ids` refcount
to a background completion watcher thread instead of releasing the fence in
`finally`. Keep warm-pool reaping/eviction, shutdown, and client teardown
fenced (while continuing ownership lease renewal) until the control plane
confirms Ready, terminal failure, or SnapshotNotFound.

* fix(benchmark): pass OpenSandbox instance to _invalidate_sandbox

Follow-up to #8507 (`6cefec0c9`), which changed
`OpenSandboxProvider._invalidate_sandbox` to accept an `OpenSandboxSandbox`
instance instead of `sandbox_id: str`. Look up the active or warm sandbox
instance under `self._lock` inside `BenchmarkOpenSandboxProvider.destroy()`
before calling `_invalidate_sandbox()`.

* fix(vefaas-sandbox): keep ownership lease renewal active during manual snapshots

Stop inserting `sandbox_id` into `_acquire_inflight` during `create_snapshot()`.
Local reaping, eviction, teardown, and shutdown are already fenced by
`_snapshotting_remote_ids`, whereas `_acquire_inflight` caused
`_renew_leases_once()` to skip renewing the ownership lease during long
synchronous `create_snapshot(..., wait=True)` waits.

* fix(vefaas-sandbox): hand off and refresh ownership leases across resume waits

- Use `take(sandbox_id)` when resuming a `Paused` sandbox so a turn landing on
  another worker can cleanly transfer a normal `own:` lease from a peer holding
  an auto-paused warm entry while still rejecting a destructive `del:` lease
  with `_PeerTeardownError`.
- Keep the normal `own:` lease refreshed throughout `ResumeSandbox`,
  `_wait_for_remote_running()`, and `wait_for_sandbox_ready()` via
  `_ownership_lease_heartbeat()` plus poll-tick `_refresh_owned_lease()`
  callbacks, and authoritatively verify ownership (`_verify_owned_lease_strict`)
  before adopting with `ownership_claimed=True`.

* fix(vefaas-sandbox): reserve cross-worker snapshot fence before manual snapshots

- Reject `create_snapshot()` on stale/peer-owned handles via `claim(sandbox_id)`
  before calling `CreateSandboxSnapshot`.
- Reserve a remote-scoped cross-worker snapshot fence
  (`snapshot-fence:<remote_id>` with `for_destroy=True`), perform a Dekker
  re-check on `claim(sandbox_id)` so teardown and snapshot admission cannot
  interleave, and keep the fence refreshed across synchronous waits
  (`_teardown_lease_heartbeat` + poll-tick refresh), async completion watchers,
  and `_renew_leases_once()` until the snapshot settles.
- Guard `_retire_warm_entry()`, `_destroy_tracked()`, and `shutdown()` against
  active cross-worker snapshot fences (unwinding any destructive `del:` lease
  and deferring teardown until the remote snapshot settles).

* fix(vefaas-sandbox): address P2 review findings on snapshot fencing, filtering, and restore

- Keep deferred warm-pool `AioSandbox` handles open in `_destroy_tracked()` and
  `_retire_warm_entry()`, closing the local handle only once teardown proceeds
  or the entry leaves `_warm_pool` (WillemJiang P2).
- Retain local and cross-worker snapshot fences after uncertain
  `CreateSandboxSnapshot` failures (timeouts, transport errors, 5xx) and
  reconcile via a background watcher polling `ListSandboxSnapshots(SandboxId=...)`
  and `DescribeSandbox` until no snapshot is in progress (WillemJiang P2).
- Serialize cross-worker `snapshot-fence:<remote_id>` last-key release with new
  reservations via a per-remote `_snapshot_fence_lock()` (Codex P2).
- Pass server-side `Filters` (`Metadata.*` and `Status`) in
  `_find_latest_ready_snapshot()`, `_prune_old_snapshots()`, and
  `list_snapshots()`, caching graceful fallback if a backend rejects filters
  while keeping strict client-side metadata verification (YukoOshima P2).
- Refresh `/mnt/skills` and host `uploads/` (without overwriting snapshot
  workspace/outputs) when booting from a snapshot that preserved
  `/tmp/.deerflow-vefaas-initialized`, and document snapshot retention/cleanup
  in `README.md` (YukoOshima questions).
This commit is contained in:
Kevin Hsiao 2026-11-25 22:08:41 +08:00 committed by GitHub
parent f9b7598fdd
commit 882063d83d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
13 changed files with 5510 additions and 430 deletions

View File

@ -1610,7 +1610,7 @@ is attempted, and the container is recycled instead of being returned to the
warm pool. Session-level cleanup does not clear that quarantine because a
timed-out create may commit after cleanup has already returned.
`prewarm` is disabled by default and applies only to asynchronous AIO runs with
`prewarm` is disabled by default and applies only to asynchronous AIO and veFaaS runs with
an unconditional outer execution-lease cleanup: the Gateway/embedded run worker
and native subagent executor. Direct `create_deerflow_agent(...).ainvoke()` and
`.astream()` calls retain ordinary lazy acquisition even when this setting is on.

View File

@ -29,3 +29,10 @@ uv run pytest tests/test_vefaas_sandbox_provider.py tests/blocking_io/test_vefaa
`redact_secret`, and `reject_url_userinfo` rather than restating them.
- **Scope TOS mounts by `derive_sandbox_scope_token`.** Never pass raw
`user_id` or `thread_id` segments into `InstanceTosMountConfig.BucketPath`.
- **Fence pause/snapshot/resume through ownership leases.** Hold and refresh
`claim(..., for_destroy=True)` across idle pause/snapshot transitions (re-checking
before `KillSandbox`), defer shutdown while manual snapshots settle, never pause
or snapshot dirty sandboxes, and verify `deer_flow_provider` + `deer_flow_sandbox_id`
client-side before restoring or pruning snapshots.
- **Keep startup image precaching off the event loop.** Run `precache_on_startup`
on a background daemon thread joined by `shutdown()` before closing the client.

View File

@ -6,6 +6,8 @@ Runs each DeerFlow thread sandbox on **BytePlus Function Service (veFaaS) Cloud
- **Data plane**: Reuses DeerFlow's `AioSandbox` HTTP client via the Sandbox App's unified access domain (`X-Faas-Instance-Name: <SandboxId>`) or a `{sandbox_id}` URL template.
- **Per-agent skills isolation**: Advertises `supports_agent_skill_isolation = True` and uploads bounded `tar.gz` skill projections into the remote sandbox.
- **Persistent storage**: Supports optional scoped `InstanceTosMountConfig` mounts (bucket prefix derived from `derive_sandbox_scope_token(user_id, thread_id)`) or automatic output mirroring on release.
- **Snapshots, pause/resume & image precache** (opt-in): Supports booting from a base `snapshot_id`, pausing idle sandboxes (`pause_on_idle` / `auto_pause`) with automatic `ResumeSandbox` discovery, creating/restoring thread-scoped snapshots on idle (`snapshot_on_idle`) with retention pruning, and asynchronous image precaching (`precache_images` / `precache_on_startup`).
- **Speculative prewarm**: Supports `sandbox.prewarm: true` (and `prewarm_max_concurrent`) to overlap veFaaS sandbox creation and readiness polling with the first model turn on shared-view runs.
If shutdown overlaps an output mirror, it reports incomplete cleanup and keeps
the sandbox available for the copy. Retry shutdown after release finishes.
@ -25,6 +27,17 @@ sandbox:
cpu_milli: 1000
memory_mb: 2048
timeout_minutes: 60
# Optional fast-resume, snapshot & image precache settings (all disabled by default)
# snapshot_id: snap-base-123
# pause_on_idle: false
# auto_pause: false
# snapshot_on_idle: false
# snapshot_type: disk # disk | full
# snapshot_retention_days: 7 # 1..365
# max_snapshots_per_sandbox: 3 # 1..100
# precache_images:
# - cr-ap-southeast-1.cr.bytepluses.com/namespace/all-in-one-sandbox:latest
# precache_on_startup: false
tos_mount:
enabled: false
bucket: $BYTEPLUS_TOS_BUCKET
@ -35,6 +48,12 @@ sandbox:
type: redis # required for multi-worker gateways
```
## Snapshot Retention & Cleanup
- When `snapshot_on_idle: true` is enabled, idle snapshots retain the thread's workspace filesystem. Restoring from a snapshot preserves the snapshot's workspace/outputs while still refreshing `/mnt/skills` and syncing host `uploads/` when `/tmp/.deerflow-vefaas-initialized` is already present.
- Set `snapshot_retention_days` (e.g. `7`) alongside `max_snapshots_per_sandbox` (default `3`) in multi-tenant deployments so veFaaS automatically expires snapshots for inactive threads; when `snapshot_retention_days` is omitted, veFaaS applies the platform default retention policy.
- DeerFlow's `SandboxProvider` interface does not currently expose a thread-deletion hook. To delete a thread's snapshots on demand (for example, on user/thread erasure), derive `sandbox_id = derive_sandbox_scope_token(user_id=..., thread_id=...)` and call `provider.delete_snapshot(snap.id)` for each record returned by `provider.list_snapshots(sandbox_id)`.
## Verification
```bash

View File

@ -3,8 +3,11 @@
from .client import (
VeFaaSApiError,
VeFaaSClient,
VeFaaSPrecacheTicket,
VeFaaSSandboxNotFoundError,
VeFaaSSandboxRecord,
VeFaaSSnapshotNotFoundError,
VeFaaSSnapshotRecord,
sign_v4_headers,
)
from .provider import VeFaaSSandboxProvider
@ -12,8 +15,11 @@ from .provider import VeFaaSSandboxProvider
__all__ = [
"VeFaaSApiError",
"VeFaaSClient",
"VeFaaSPrecacheTicket",
"VeFaaSSandboxNotFoundError",
"VeFaaSSandboxRecord",
"VeFaaSSnapshotNotFoundError",
"VeFaaSSnapshotRecord",
"VeFaaSSandboxProvider",
"sign_v4_headers",
]

View File

@ -13,7 +13,7 @@ import hmac
import json
import logging
import threading
from collections.abc import Mapping
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any
from urllib.parse import quote, urlsplit
@ -40,6 +40,30 @@ _NOT_FOUND_ERROR_CODES = frozenset(
"ResourceNotFound.Instance",
}
)
_SNAPSHOT_NOT_FOUND_ERROR_CODES = frozenset(
{
"SnapshotNotFound",
"SandboxSnapshotNotFound",
"InvalidSnapshotId.NotFound",
"ResourceNotFound.Snapshot",
"ResourceNotFound.SandboxSnapshot",
}
)
_TRANSITIONING_SANDBOX_STATUSES = frozenset(
{
"pending",
"creating",
"starting",
"pausing",
"resuming",
"snapshotting",
}
)
_TERMINAL_SANDBOX_STATUSES = frozenset({"failed", "error", "terminated", "deleted", "stopped"})
_READY_SNAPSHOT_STATUSES = frozenset({"ready", "available", "succeeded", "completed"})
_TERMINAL_SNAPSHOT_STATUSES = frozenset({"failed", "error", "deleted", "expired", "deleting"})
_SUCCEEDED_PRECACHE_STATUSES = frozenset({"success", "succeeded", "completed", "ready"})
_TERMINAL_PRECACHE_STATUSES = frozenset({"failed", "error", "canceled", "cancelled", "timeout"})
class VeFaaSApiError(RuntimeError):
@ -63,6 +87,10 @@ class VeFaaSSandboxNotFoundError(VeFaaSApiError):
"""Authoritative response proving a remote veFaaS sandbox does not exist."""
class VeFaaSSnapshotNotFoundError(VeFaaSApiError):
"""Authoritative response proving a remote veFaaS sandbox snapshot does not exist."""
@dataclass(frozen=True)
class VeFaaSSandboxRecord:
"""Normalized veFaaS cloud sandbox instance metadata."""
@ -75,14 +103,65 @@ class VeFaaSSandboxRecord:
error_code: str = ""
error_message: str = ""
expire_at: str = ""
paused_at: str = ""
@property
def is_running(self) -> bool:
return self.status.strip().lower() == "running" and not self.pending
@property
def is_paused(self) -> bool:
return self.status.strip().lower() == "paused" and not self.pending
@property
def is_transitioning(self) -> bool:
return self.pending or self.status.strip().lower() in _TRANSITIONING_SANDBOX_STATUSES
@property
def is_terminal_failure(self) -> bool:
return self.status.strip().lower() in {"failed", "error", "terminated", "deleted", "stopped"}
return self.status.strip().lower() in _TERMINAL_SANDBOX_STATUSES
@dataclass(frozen=True)
class VeFaaSSnapshotRecord:
"""Normalized veFaaS cloud sandbox snapshot metadata."""
id: str
sandbox_id: str
function_id: str
status: str
snapshot_type: str = ""
source: str = ""
created_at: str = ""
retention_days: int | None = None
retention_expires_at: str = ""
metadata: dict[str, str] = field(default_factory=dict)
@property
def is_ready(self) -> bool:
return self.status.strip().lower() in _READY_SNAPSHOT_STATUSES
@property
def is_terminal_failure(self) -> bool:
return self.status.strip().lower() in _TERMINAL_SNAPSHOT_STATUSES
@dataclass(frozen=True)
class VeFaaSPrecacheTicket:
"""Normalized veFaaS sandbox image precache ticket status."""
ticket_id: str
status: str
duration: int | None = None
progress: dict[str, Any] = field(default_factory=dict)
@property
def is_succeeded(self) -> bool:
return self.status.strip().lower() in _SUCCEEDED_PRECACHE_STATUSES
@property
def is_terminal_failure(self) -> bool:
return self.status.strip().lower() in _TERMINAL_PRECACHE_STATUSES
def validate_endpoint_url(url: str, *, allow_insecure_http: bool = False) -> str:
@ -225,6 +304,46 @@ def _parse_record(payload: Mapping[str, Any], *, fallback_function_id: str) -> V
error_code=str(payload.get("ErrorCode") or ""),
error_message=str(payload.get("ErrorMessage") or ""),
expire_at=str(payload.get("ExpireAt") or ""),
paused_at=str(payload.get("PausedAt") or ""),
)
def _parse_snapshot_record(payload: Mapping[str, Any], *, fallback_function_id: str) -> VeFaaSSnapshotRecord | None:
snapshot_id = payload.get("SnapshotId") or payload.get("Id")
if not isinstance(snapshot_id, str) or not snapshot_id.strip():
return None
raw_retention = payload.get("RetentionDays")
retention_days = raw_retention if isinstance(raw_retention, int) and not isinstance(raw_retention, bool) else None
return VeFaaSSnapshotRecord(
id=snapshot_id.strip(),
sandbox_id=str(payload.get("SandboxId") or ""),
function_id=str(payload.get("FunctionId") or fallback_function_id),
status=str(payload.get("Status") or ""),
snapshot_type=str(payload.get("SnapshotType") or payload.get("Type") or ""),
source=str(payload.get("Source") or ""),
created_at=str(payload.get("CreatedAt") or ""),
retention_days=retention_days,
retention_expires_at=str(payload.get("RetentionExpiresAt") or ""),
metadata=_parse_metadata(payload.get("Metadata")),
)
def _parse_precache_ticket(payload: Mapping[str, Any], *, fallback_ticket_id: str) -> VeFaaSPrecacheTicket | None:
raw_status = payload.get("Status")
if not isinstance(raw_status, str) or not raw_status.strip():
return None
raw_ticket_id = payload.get("TicketId") or fallback_ticket_id
if not isinstance(raw_ticket_id, str) or not raw_ticket_id.strip():
return None
raw_duration = payload.get("Duration")
duration = raw_duration if isinstance(raw_duration, int) and not isinstance(raw_duration, bool) else None
raw_progress = payload.get("Progress")
progress = dict(raw_progress) if isinstance(raw_progress, Mapping) else {}
return VeFaaSPrecacheTicket(
ticket_id=raw_ticket_id.strip(),
status=raw_status.strip(),
duration=duration,
progress=progress,
)
@ -336,7 +455,13 @@ class VeFaaSClient:
if isinstance(error_obj, dict) and (error_obj.get("Code") or error_obj.get("Message")):
error_code = str(error_obj.get("Code") or "")
error_msg = self._redact(error_obj.get("Message") or error_code)
err_cls: type[VeFaaSApiError] = VeFaaSSandboxNotFoundError if error_code in _NOT_FOUND_ERROR_CODES else VeFaaSApiError
err_cls: type[VeFaaSApiError]
if error_code in _NOT_FOUND_ERROR_CODES:
err_cls = VeFaaSSandboxNotFoundError
elif error_code in _SNAPSHOT_NOT_FOUND_ERROR_CODES:
err_cls = VeFaaSSnapshotNotFoundError
else:
err_cls = VeFaaSApiError
raise err_cls(
f"veFaaS {action} failed ({error_code}): {error_msg}",
status_code=response.status_code,
@ -374,6 +499,8 @@ class VeFaaSClient:
instance_image_info: Mapping[str, Any] | None = None,
instance_tos_mount_config: Mapping[str, Any] | None = None,
session_id: str | None = None,
snapshot_id: str | None = None,
auto_pause_config: Mapping[str, Any] | None = None,
) -> str:
"""Create a veFaaS cloud sandbox instance and return its remote ``SandboxId``."""
payload: dict[str, Any] = {"FunctionId": function_id}
@ -394,6 +521,10 @@ class VeFaaSClient:
payload["InstanceTosMountConfig"] = dict(instance_tos_mount_config)
if session_id:
payload["SessionId"] = session_id
if snapshot_id:
payload["SnapshotId"] = snapshot_id
if auto_pause_config:
payload["AutoPauseConfig"] = dict(auto_pause_config)
result = self._request("CreateSandbox", payload)
sandbox_id = result.get("SandboxId") or result.get("Id")
@ -505,6 +636,192 @@ class VeFaaSClient:
except VeFaaSSandboxNotFoundError:
logger.debug("veFaaS sandbox %s already absent during KillSandbox", sandbox_id)
def pause_sandbox(self, function_id: str, sandbox_id: str) -> None:
"""Pause a running veFaaS sandbox instance so its state can be resumed later."""
self._request(
"PauseSandbox",
{"FunctionId": function_id, "SandboxId": sandbox_id},
)
def resume_sandbox(
self,
function_id: str,
sandbox_id: str,
*,
snapshot_id: str | None = None,
timeout_minutes: int | None = None,
async_resume: bool | None = None,
) -> str:
"""Resume a paused veFaaS sandbox instance (or restore from ``snapshot_id``)."""
payload: dict[str, Any] = {"FunctionId": function_id, "SandboxId": sandbox_id}
if snapshot_id:
payload["SnapshotId"] = snapshot_id
if timeout_minutes is not None:
payload["Timeout"] = timeout_minutes
payload["TimeoutUnit"] = "minute"
if async_resume is not None:
payload["Async"] = bool(async_resume)
result = self._request("ResumeSandbox", payload)
return str(result.get("Status") or "")
def create_sandbox_snapshot(
self,
function_id: str,
sandbox_id: str,
*,
snapshot_type: str | None = None,
retention_days: int | None = None,
metadata: Mapping[str, str] | None = None,
) -> str:
"""Create a snapshot of a running veFaaS sandbox instance and return its ``SnapshotId``."""
payload: dict[str, Any] = {"FunctionId": function_id, "SandboxId": sandbox_id}
if snapshot_type:
payload["Type"] = snapshot_type
if retention_days is not None:
payload["RetentionDays"] = retention_days
if metadata:
payload["Metadata"] = {str(k): str(v) for k, v in metadata.items()}
result = self._request("CreateSandboxSnapshot", payload)
snapshot_id = result.get("SnapshotId") or result.get("Id")
if not isinstance(snapshot_id, str) or not snapshot_id.strip():
raise VeFaaSApiError("veFaaS CreateSandboxSnapshot response did not include a SnapshotId")
return snapshot_id.strip()
def describe_sandbox_snapshot(self, function_id: str, snapshot_id: str) -> VeFaaSSnapshotRecord | None:
"""Describe one sandbox snapshot; return ``None`` only on authoritative not-found."""
try:
result = self._request(
"DescribeSandboxSnapshot",
{"FunctionId": function_id, "SnapshotId": snapshot_id},
)
except VeFaaSSnapshotNotFoundError:
return None
raw_snapshot = result.get("Snapshot") if isinstance(result.get("Snapshot"), Mapping) else result
record = _parse_snapshot_record(raw_snapshot, fallback_function_id=function_id)
if record is None:
raise VeFaaSApiError(f"veFaaS DescribeSandboxSnapshot response for {snapshot_id} did not include a valid snapshot record")
return record
def list_sandbox_snapshots(
self,
function_id: str,
*,
sandbox_id: str | None = None,
filters: Sequence[Mapping[str, Any]] | None = None,
page_number: int | None = None,
page_size: int = 50,
max_pages: int = 100,
) -> list[VeFaaSSnapshotRecord]:
"""List snapshots belonging to ``function_id`` with optional sandbox/filter criteria."""
records: list[VeFaaSSnapshotRecord] = []
seen_ids: set[str] = set()
current_page = 1 if page_number is None else page_number
single_page = page_number is not None
pages_fetched = 0
raw_seen = 0
while True:
payload: dict[str, Any] = {
"FunctionId": function_id,
"PageNumber": current_page,
"PageSize": page_size,
}
if sandbox_id:
payload["SandboxId"] = sandbox_id
if filters:
payload["Filters"] = [dict(item) for item in filters]
result = self._request("ListSandboxSnapshots", payload)
raw_items = result.get("Snapshots")
if raw_items is None:
raw_items = result.get("Items")
if raw_items is None:
break
if not isinstance(raw_items, list):
raise VeFaaSApiError(f"veFaaS ListSandboxSnapshots returned malformed Snapshots of type {type(raw_items).__name__}")
for item in raw_items:
if not isinstance(item, Mapping):
continue
record = _parse_snapshot_record(item, fallback_function_id=function_id)
if record is not None and record.id not in seen_ids:
seen_ids.add(record.id)
records.append(record)
pages_fetched += 1
raw_seen += len(raw_items)
if single_page or len(raw_items) < page_size:
break
total = result.get("Total")
if isinstance(total, int) and not isinstance(total, bool) and raw_seen >= total:
break
if pages_fetched >= max_pages:
logger.warning(
"veFaaS ListSandboxSnapshots stopped after max_pages=%d (%d snapshots fetched for function %s)",
max_pages,
len(records),
function_id,
)
break
current_page += 1
return records
def delete_sandbox_snapshot(self, function_id: str, snapshot_id: str) -> None:
"""Delete a veFaaS sandbox snapshot; treat authoritative not-found as idempotent."""
try:
self._request(
"DeleteSandboxSnapshot",
{"FunctionId": function_id, "SnapshotId": snapshot_id},
)
except VeFaaSSnapshotNotFoundError:
logger.debug("veFaaS snapshot %s already absent during DeleteSandboxSnapshot", snapshot_id)
def precache_sandbox_images(
self,
image_urls: Sequence[str],
*,
client_token: str | None = None,
registry_type: str | None = None,
network_config: Mapping[str, Any] | None = None,
registry_auth_config: Mapping[str, Any] | None = None,
) -> str:
"""Submit a sandbox image precache job and return its ``TicketId``."""
if isinstance(image_urls, (str, bytes)):
raise ValueError("image_urls must be a sequence of non-empty image URLs")
cleaned: list[str] = []
seen: set[str] = set()
for item in image_urls:
if not isinstance(item, str) or not item.strip():
raise ValueError("image_urls must contain only non-empty strings")
url = item.strip()
if url not in seen:
seen.add(url)
cleaned.append(url)
if not cleaned:
raise ValueError("image_urls must contain at least one non-empty image URL")
payload: dict[str, Any] = {"ImageUrls": cleaned}
if client_token:
payload["ClientToken"] = client_token
if registry_type:
payload["RegistryType"] = registry_type
if network_config:
payload["NetworkConfig"] = dict(network_config)
if registry_auth_config:
payload["RegistryAuthConfig"] = dict(registry_auth_config)
result = self._request("PrecacheSandboxImages", payload)
ticket_id = result.get("TicketId")
if not isinstance(ticket_id, str) or not ticket_id.strip():
raise VeFaaSApiError("veFaaS PrecacheSandboxImages response did not include a TicketId")
return ticket_id.strip()
def get_sandbox_image_precache_ticket(self, ticket_id: str) -> VeFaaSPrecacheTicket:
"""Query the status and progress of a sandbox image precache ticket."""
result = self._request("GetSandboxImagePrecacheTicket", {"TicketId": ticket_id})
ticket = _parse_precache_ticket(result, fallback_ticket_id=ticket_id)
if ticket is None:
raise VeFaaSApiError(f"veFaaS GetSandboxImagePrecacheTicket response for {ticket_id} did not include a valid status")
return ticket
__all__ = [
"DEFAULT_REQUEST_TIMEOUT",
@ -513,8 +830,11 @@ __all__ = [
"VEFAAS_SERVICE",
"VeFaaSApiError",
"VeFaaSClient",
"VeFaaSPrecacheTicket",
"VeFaaSSandboxNotFoundError",
"VeFaaSSandboxRecord",
"VeFaaSSnapshotNotFoundError",
"VeFaaSSnapshotRecord",
"sign_v4_headers",
"validate_endpoint_url",
]

View File

@ -296,7 +296,11 @@ class SandboxConfig(BaseModel):
``access_key`` / ``secret_key`` / ``session_token`` (or ``*_env``),
``sandbox_access_token``, ``cpu_milli``, ``memory_mb``,
``timeout_minutes``, ``ready_timeout``, ``request_timeout``,
``allow_insecure_http``, ``tos_mount``, and ``metadata``.
``allow_insecure_http``, ``tos_mount``, ``metadata``,
``snapshot_id``, ``pause_on_idle``, ``auto_pause``,
``snapshot_on_idle``, ``snapshot_type``, ``snapshot_retention_days``,
``snapshot_timeout``, ``max_snapshots_per_sandbox``,
``precache_images``, and ``precache_on_startup``.
"""
use: str = Field(
@ -318,12 +322,12 @@ class SandboxConfig(BaseModel):
prewarm: bool = Field(
default=False,
description=("Start an AioSandboxProvider acquire in parallel with the first model call when the user input contains a strong sandbox-use signal. Disabled by default; ignored by other sandbox providers."),
description=("Start an AioSandboxProvider or VeFaaSSandboxProvider acquire in parallel with the first model call when the user input contains a strong sandbox-use signal. Disabled by default; ignored by other sandbox providers."),
)
prewarm_max_concurrent: int = Field(
default=1,
ge=1,
description=("Maximum pending or ready-but-unused AIO prewarms per provider instance in this process. When full, skip speculation without delaying foreground tools. This is not a total container or deployment-wide limit."),
description=("Maximum pending or ready-but-unused sandbox prewarms per provider instance in this process. When full, skip speculation without delaying foreground tools. This is not a total container or deployment-wide limit."),
)
image: str | None = Field(
default=None,

View File

@ -1,4 +1,4 @@
"""Optional AIO startup owned by the same lease as its agent execution."""
"""Optional AIO and veFaaS sandbox startup owned by the same lease as its agent execution."""
from __future__ import annotations
@ -29,6 +29,16 @@ from deerflow.utils.file_io import await_drained
logger = logging.getLogger(__name__)
_PREWARM_PROVIDER_SUFFIXES = (
":AioSandboxProvider",
":VeFaaSSandboxProvider",
)
def _supports_prewarm_provider(sandbox_use: object) -> bool:
return isinstance(sandbox_use, str) and sandbox_use.endswith(_PREWARM_PROVIDER_SUFFIXES)
_CODE_FENCE_RE = re.compile(r"```")
_URL_RE = re.compile(r"\b[a-zA-Z][a-zA-Z0-9+.-]*://[^\s<>]+")
_PATH_RE = re.compile(r"(?:^|[\s`\"'(])(?:~/(?:[\w.-]+/)*[\w.-]+|/(?:[\w.-]+)(?:/[\w.-]+)*|[A-Za-z]:\\)")
@ -117,15 +127,16 @@ class SandboxPrewarm:
if config is None:
config = await asyncio.to_thread(get_app_config)
sandbox = config.sandbox
if not getattr(sandbox, "prewarm", False) or not sandbox.use.endswith(":AioSandboxProvider"):
if not getattr(sandbox, "prewarm", False) or not _supports_prewarm_provider(getattr(sandbox, "use", None)):
return None
# Startup policy is run-scoped, but authorization must be fresh;
# claiming later does not replace the ordinary tool's fresh gate.
await authorize_sandbox_execution_async(context=self.context, app_config=await safe_app_config_async())
self.provider = get_initialized_sandbox_provider()
if self.provider is None:
# Only AIO opts in here; its constructor performs filesystem and
# backend setup, so keep that work off the model's event loop.
# Only AIO and veFaaS opt in here; their constructors perform
# filesystem/store/backend setup, so keep that work off the
# model's event loop.
self.provider = await run_sync_lifecycle_operation(get_sandbox_provider)
self.manager = get_sandbox_lease_manager(self.provider)
limit = getattr(sandbox, "prewarm_max_concurrent", 1)

View File

@ -10,15 +10,29 @@
from __future__ import annotations
import asyncio
import threading
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import httpx
import pytest
from blockbuster import BlockingError
from test_vefaas_sandbox_provider import _FakeVeFaaSServer, _install_provider
from langchain_core.messages import HumanMessage
from support.vefaas_sandbox import FakeAioSandbox, FakeVeFaaSServer, install_vefaas_provider, make_vefaas_app_config
from deerflow.community.aio_sandbox.ownership import RenewOutcome
from deerflow.community.vefaas_sandbox import VeFaaSClient
from deerflow.community.vefaas_sandbox import VeFaaSClient, VeFaaSSandboxProvider
from deerflow.community.vefaas_sandbox import provider as provider_mod
from deerflow.sandbox import prewarm
from deerflow.sandbox.identity import derive_sandbox_scope_token
from deerflow.sandbox.lease import (
ensure_sandbox_lease_owner,
register_sandbox_prewarm_cleanup,
release_sandbox_execution_lease_async,
)
from deerflow.sandbox.sandbox_provider import hold_sandbox_shutdown_ownership, reset_sandbox_provider, set_sandbox_provider
from deerflow.sandbox.tools import ensure_sandbox_initialized_async
pytestmark = pytest.mark.asyncio
@ -32,6 +46,7 @@ class _BlockingProbeOwnershipStore:
self._probe_path = probe_path
self._probe_path.write_text("owner", encoding="utf-8")
self.calls: list[str] = []
self._owned_keys: set[str] = set()
@property
def owner_id(self) -> str:
@ -43,10 +58,12 @@ class _BlockingProbeOwnershipStore:
def take(self, sandbox_id: str) -> bool:
self._touch("take")
self._owned_keys.add(sandbox_id)
return True
def claim(self, sandbox_id: str, *, for_destroy: bool = False) -> bool:
self._touch("claim")
self._owned_keys.add(sandbox_id)
return True
def renew(self, sandbox_id: str) -> RenewOutcome:
@ -55,15 +72,17 @@ class _BlockingProbeOwnershipStore:
def release(self, sandbox_id: str) -> None:
self._touch("release")
self._owned_keys.discard(sandbox_id)
def owner(self, sandbox_id: str) -> str | None:
return self._touch("owner")
self._touch("owner")
return self.owner_id if sandbox_id in self._owned_keys else None
def close(self) -> None:
pass
class _FileIOProbingVeFaaSServer(_FakeVeFaaSServer):
class _FileIOProbingVeFaaSServer(FakeVeFaaSServer):
"""Fake veFaaS control plane that performs real blocking file I/O on every request."""
def __init__(self, probe_dir: Path) -> None:
@ -77,7 +96,7 @@ class _FileIOProbingVeFaaSServer(_FakeVeFaaSServer):
async def test_get_and_get_scoped_do_no_blocking_io_on_event_loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
provider, _server, _aio = _install_provider(monkeypatch, tmp_path)
provider, _server, _aio = install_vefaas_provider(monkeypatch, tmp_path)
probe_store = await asyncio.to_thread(_BlockingProbeOwnershipStore, tmp_path / "ownership-probe")
provider._ownership = probe_store
try:
@ -97,7 +116,7 @@ async def test_get_and_get_scoped_do_no_blocking_io_on_event_loop(tmp_path: Path
async def test_contended_acquire_async_stays_off_event_loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
probing_server = _FileIOProbingVeFaaSServer(tmp_path)
provider, _server, _aio = _install_provider(monkeypatch, tmp_path, server=probing_server)
provider, _server, _aio = install_vefaas_provider(monkeypatch, tmp_path, server=probing_server)
provider._ownership = await asyncio.to_thread(_BlockingProbeOwnershipStore, tmp_path / "ownership-probe-2")
try:
first, second = await asyncio.gather(
@ -123,3 +142,147 @@ async def test_client_construction_is_non_blocking_on_event_loop() -> None:
)
assert client._client is None
client.close()
async def test_precache_on_startup_stays_off_event_loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Constructing VeFaaSSandboxProvider with precache_on_startup=True must stay off-loop."""
probing_server = _FileIOProbingVeFaaSServer(tmp_path)
submitted = threading.Event()
orig_handler = probing_server.handler
def tracking_handler(request: httpx.Request) -> httpx.Response:
resp = orig_handler(request)
if request.url.params.get("Action") == "PrecacheSandboxImages":
submitted.set()
return resp
probing_server.handler = tracking_handler # type: ignore[method-assign]
app_cfg = await asyncio.to_thread(
lambda: make_vefaas_app_config(
tmp_path,
sandbox_overrides={
"vefaas": {
"precache_images": ["cr.example.com/aio:latest"],
"precache_on_startup": True,
}
},
)
)
monkeypatch.setattr(provider_mod, "get_app_config", lambda: app_cfg)
mock_http = httpx.Client(transport=httpx.MockTransport(probing_server.handler))
client = VeFaaSClient(
endpoint="https://vefaas.ap-southeast-1.byteplusapi.com",
region="ap-southeast-1",
access_key="AK-TEST-KEY",
secret_key="SK-TEST-SECRET",
httpx_client=mock_http,
)
# Construct directly on the event loop: startup precache must run strictly on its daemon thread.
with hold_sandbox_shutdown_ownership():
provider = VeFaaSSandboxProvider(client=client)
try:
assert await asyncio.to_thread(submitted.wait, 5)
finally:
await asyncio.to_thread(provider.shutdown)
await asyncio.to_thread(mock_http.close)
async def test_acquire_async_resume_paused_and_restore_snapshot_stay_off_event_loop(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Resuming a paused sandbox or restoring a snapshot via acquire_async must stay off-loop."""
probing_server = _FileIOProbingVeFaaSServer(tmp_path)
sid_paused = derive_sandbox_scope_token(user_id="u-bio", thread_id="t-bio-paused")
sid_snap = derive_sandbox_scope_token(user_id="u-bio", thread_id="t-bio-snap")
probing_server.sandboxes["vefaas-bio-paused"] = {
"Id": "vefaas-bio-paused",
"FunctionId": "fn-demo-app",
"Status": "Paused",
"Pending": False,
"Metadata": {
provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER,
provider_mod.META_KEY_SANDBOX_ID: sid_paused,
},
}
probing_server.snapshots["snap-bio-1"] = {
"SnapshotId": "snap-bio-1",
"SandboxId": "vefaas-old",
"FunctionId": "fn-demo-app",
"Status": "Ready",
"SnapshotType": "disk",
"CreatedAt": "2026-11-23T01:00:00Z",
"Metadata": {
provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER,
provider_mod.META_KEY_SANDBOX_ID: sid_snap,
},
}
provider, _, _ = await asyncio.to_thread(
lambda: install_vefaas_provider(
monkeypatch,
tmp_path,
server=probing_server,
sandbox_overrides={"vefaas": {"snapshot_on_idle": True}},
)
)
provider._ownership = await asyncio.to_thread(_BlockingProbeOwnershipStore, tmp_path / "ownership-probe-3")
class _PreInitAio(FakeAioSandbox):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.uploaded_files[provider_mod._INIT_MARKER_PATH] = f"{self.id}\n".encode()
monkeypatch.setattr(provider_mod, "AioSandbox", _PreInitAio)
try:
resumed = await provider.acquire_async("t-bio-paused", user_id="u-bio")
assert resumed == sid_paused
restored = await provider.acquire_async("t-bio-snap", user_id="u-bio")
assert restored == sid_snap
assert any(action == "ResumeSandbox" for action, _, _ in probing_server.requests)
create_reqs = [payload for action, payload, _ in probing_server.requests if action == "CreateSandbox"]
assert create_reqs and create_reqs[-1]["SnapshotId"] == "snap-bio-1"
finally:
await asyncio.to_thread(provider.shutdown)
async def test_prewarm_acquire_and_claim_stay_off_event_loop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""Speculative veFaaS prewarm, tool claim, and lease cleanup must stay off the event loop."""
probing_server = _FileIOProbingVeFaaSServer(tmp_path)
provider, _server, _aio = await asyncio.to_thread(
lambda: install_vefaas_provider(
monkeypatch,
tmp_path,
server=probing_server,
sandbox_overrides={"prewarm": True, "prewarm_max_concurrent": 1, "idle_timeout": 0},
)
)
provider._ownership = await asyncio.to_thread(_BlockingProbeOwnershipStore, tmp_path / "ownership-probe-prewarm")
app_cfg = await asyncio.to_thread(
lambda: make_vefaas_app_config(
tmp_path,
sandbox_overrides={"prewarm": True, "prewarm_max_concurrent": 1, "idle_timeout": 0},
)
)
monkeypatch.setattr(prewarm, "get_app_config", lambda: app_cfg)
set_sandbox_provider(provider)
try:
context: dict[str, object] = {"user_id": "u-pw-bio", "thread_id": "t-pw-bio", "app_config": app_cfg}
ensure_sandbox_lease_owner(context)
register_sandbox_prewarm_cleanup(context)
rt = SimpleNamespace(context=context, state={})
prewarm.start_sandbox_prewarm({"messages": [HumanMessage(content="```sh\npytest tests\n```")]}, rt)
handle = context["__deerflow_sandbox_prewarm"]
sandbox_id = await handle.task
assert isinstance(sandbox_id, str) and sandbox_id
sandbox = await ensure_sandbox_initialized_async(rt)
assert sandbox.id == sandbox_id
await release_sandbox_execution_lease_async(context)
assert not prewarm._permits
finally:
await asyncio.to_thread(reset_sandbox_provider)
await asyncio.to_thread(provider.shutdown)

View File

@ -0,0 +1,509 @@
"""Shared offline test doubles and setup helpers for BytePlus veFaaS sandbox tests."""
from __future__ import annotations
import json
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import httpx
import pytest
from deerflow.community.vefaas_sandbox import VeFaaSClient, VeFaaSSandboxProvider
from deerflow.community.vefaas_sandbox import provider as provider_mod
from deerflow.config.sandbox_config import SandboxConfig
from deerflow.sandbox.sandbox_provider import hold_sandbox_shutdown_ownership
class FakeAioSandbox:
"""In-memory stand-in for AioSandbox recording data-plane calls."""
def __init__(
self,
id: str,
base_url: str,
request_headers: dict[str, str] | None = None,
default_command_timeout: float | None = None,
lark_cli_broker: bool | None = None,
) -> None:
self.id = id
self.base_url = base_url
self.request_headers = dict(request_headers or {})
self.default_command_timeout = default_command_timeout
self.lark_cli_broker = lark_cli_broker
self.commands: list[str] = []
self.uploaded_files: dict[str, bytes] = {}
self.remote_outputs: dict[str, bytes] = {}
self.closed = False
self.fail_upload_script = False
self.fail_bootstrap = False
self.bootstrap_output_override: str | None = None
self.init_marker_override: str | None = None
def execute_command(self, command: str) -> str:
self.commands.append(command)
if command == provider_mod._BOOTSTRAP_COMMAND:
if self.bootstrap_output_override is not None:
return self.bootstrap_output_override
if self.fail_bootstrap:
return "mkdir: cannot create directory '/mnt/user-data/workspace': Permission denied\n"
return f"{provider_mod._BOOTSTRAP_OK_MARKER}\n"
if "INIT_MARKER:" in command:
if self.init_marker_override is not None:
return self.init_marker_override
marker = self.uploaded_files.get(provider_mod._INIT_MARKER_PATH)
if marker is not None:
return f"INIT_MARKER:{marker.decode('utf-8').strip()}\n"
return "INIT_MARKER:MISSING\n"
if "UPLOAD_OK" in command:
return "" if self.fail_upload_script else "UPLOAD_OK\n"
if "find /mnt/user-data/outputs" in command:
return "\n".join(sorted(self.remote_outputs.keys()))
return ""
def update_file(self, path: str, content: bytes) -> None:
self.uploaded_files[path] = content
def download_file(self, path: str, *, max_bytes: int | None = None) -> bytes:
data = self.remote_outputs[path]
if max_bytes is not None and len(data) > max_bytes:
raise ValueError("download exceeded max_bytes")
return data
def release_command_scope(self, scope_id: str) -> None:
del scope_id
def close(self) -> None:
self.closed = True
class FakeVeFaaSServer:
"""In-memory BytePlus veFaaS OpenAPI simulator backing httpx.MockTransport."""
def __init__(self) -> None:
self.sandboxes: dict[str, dict[str, Any]] = {}
self.snapshots: dict[str, dict[str, Any]] = {}
self.precache_tickets: dict[str, dict[str, Any]] = {}
self.requests: list[tuple[str, dict[str, Any], dict[str, str]]] = []
self.next_seq = 1
self.next_snapshot_seq = 1
self.next_ticket_seq = 1
self.kill_error: tuple[int, str, str] | None = None
self.describe_after_kill_keeps_running = False
self.describe_error: tuple[int, str, str] | None = None
self.create_status_sequence: list[str] = ["Running"]
self.pause_error: tuple[int, str, str] | None = None
self.pause_status_sequence: list[str] = ["Paused"]
self.resume_error: tuple[int, str, str] | None = None
self.resume_status_sequence: list[str] = ["Running"]
self.snapshot_create_error: tuple[int, str, str] | None = None
self.snapshot_status_sequence: list[str] = ["Ready"]
self.precache_status_sequence: list[str] = ["Succeeded"]
self.validate_snapshot_on_create = False
self.ignore_list_metadata_filter = False
self.ignore_snapshot_filters = False
self.reject_snapshot_metadata_filters = False
self.reject_snapshot_status_filter = False
def handler(self, request: httpx.Request) -> httpx.Response:
action = request.url.params.get("Action", "")
version = request.url.params.get("Version", "")
assert version == "2024-06-06"
assert request.headers.get("Authorization", "").startswith("HMAC-SHA256 Credential=")
assert "X-Date" in request.headers
assert "X-Content-Sha256" in request.headers
payload = json.loads(request.content.decode("utf-8"))
self.requests.append((action, payload, dict(request.headers)))
if action == "CreateSandbox":
snapshot_id = payload.get("SnapshotId")
if self.validate_snapshot_on_create and snapshot_id and snapshot_id not in self.snapshots:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-create-snap-404", "Error": {"Code": "SnapshotNotFound", "Message": "snapshot not found"}}},
)
remote_id = f"vefaas-sb-{self.next_seq}"
self.next_seq += 1
self.sandboxes[remote_id] = {
"Id": remote_id,
"FunctionId": payload["FunctionId"],
"Status": self.create_status_sequence[0],
"_status_queue": list(self.create_status_sequence),
"Pending": False,
"Metadata": dict(payload.get("Metadata") or {}),
"Envs": list(payload.get("Envs") or []),
"Timeout": payload.get("Timeout"),
"InstanceTosMountConfig": payload.get("InstanceTosMountConfig"),
"SnapshotId": snapshot_id,
"AutoPauseConfig": payload.get("AutoPauseConfig"),
}
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-create"}, "Result": {"SandboxId": remote_id}},
)
if action == "DescribeSandbox":
if self.describe_error is not None:
code, err_code, err_msg = self.describe_error
return httpx.Response(
code,
json={"ResponseMetadata": {"RequestId": "req-desc-err", "Error": {"Code": err_code, "Message": err_msg}}},
)
remote_id = payload["SandboxId"]
record = self.sandboxes.get(remote_id)
if record is None:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-404", "Error": {"Code": "SandboxNotFound", "Message": "not found"}}},
)
queue = record.get("_status_queue")
if queue:
record["Status"] = queue.pop(0)
result_body: dict[str, Any] = {
"Id": record["Id"],
"FunctionId": record["FunctionId"],
"Status": record["Status"],
"Pending": record["Pending"],
"MetadataList": [{"MetaKey": k, "MetaValue": v} for k, v in record["Metadata"].items()],
}
if record.get("PausedAt"):
result_body["PausedAt"] = record["PausedAt"]
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-desc"}, "Result": result_body},
)
if action == "ListSandboxes":
wanted_meta = payload.get("Metadata") or {}
items = []
for record in self.sandboxes.values():
if record["FunctionId"] != payload["FunctionId"]:
continue
if self.ignore_list_metadata_filter or all(record["Metadata"].get(k) == v for k, v in wanted_meta.items()):
item: dict[str, Any] = {
"Id": record["Id"],
"FunctionId": record["FunctionId"],
"Status": record["Status"],
"Pending": record["Pending"],
"Metadata": dict(record["Metadata"]),
}
if record.get("PausedAt"):
item["PausedAt"] = record["PausedAt"]
items.append(item)
page_number = int(payload.get("PageNumber", 1))
page_size = int(payload.get("PageSize", 50))
start = (page_number - 1) * page_size
page_items = items[start : start + page_size]
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-list"}, "Result": {"Sandboxes": page_items, "Total": len(items)}},
)
if action == "SetSandboxTimeout":
remote_id = payload["SandboxId"]
if remote_id not in self.sandboxes:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-to-404", "Error": {"Code": "SandboxNotFound", "Message": "not found"}}},
)
self.sandboxes[remote_id]["Timeout"] = payload["Timeout"]
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-timeout"}, "Result": {"SandboxId": remote_id}},
)
if action == "KillSandbox":
if self.kill_error is not None:
code, err_code, err_msg = self.kill_error
return httpx.Response(
code,
json={"ResponseMetadata": {"RequestId": "req-kill-err", "Error": {"Code": err_code, "Message": err_msg}}},
)
remote_id = payload["SandboxId"]
if not self.describe_after_kill_keeps_running:
self.sandboxes.pop(remote_id, None)
return httpx.Response(200, json={"ResponseMetadata": {"RequestId": "req-kill"}, "Result": {}})
if action == "PauseSandbox":
if self.pause_error is not None:
code, err_code, err_msg = self.pause_error
return httpx.Response(
code,
json={"ResponseMetadata": {"RequestId": "req-pause-err", "Error": {"Code": err_code, "Message": err_msg}}},
)
remote_id = payload["SandboxId"]
record = self.sandboxes.get(remote_id)
if record is None:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-pause-404", "Error": {"Code": "SandboxNotFound", "Message": "not found"}}},
)
record["Status"] = self.pause_status_sequence[0]
record["_status_queue"] = list(self.pause_status_sequence)
record["PausedAt"] = "2026-11-23T01:00:00Z"
return httpx.Response(200, json={"ResponseMetadata": {"RequestId": "req-pause"}, "Result": {}})
if action == "ResumeSandbox":
if self.resume_error is not None:
code, err_code, err_msg = self.resume_error
return httpx.Response(
code,
json={"ResponseMetadata": {"RequestId": "req-resume-err", "Error": {"Code": err_code, "Message": err_msg}}},
)
remote_id = payload["SandboxId"]
record = self.sandboxes.get(remote_id)
if record is None:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-resume-404", "Error": {"Code": "SandboxNotFound", "Message": "not found"}}},
)
record["Status"] = self.resume_status_sequence[0]
record["_status_queue"] = list(self.resume_status_sequence)
if "Timeout" in payload:
record["Timeout"] = payload["Timeout"]
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-resume"}, "Result": {"Status": record["Status"]}},
)
if action == "CreateSandboxSnapshot":
if self.snapshot_create_error is not None:
code, err_code, err_msg = self.snapshot_create_error
return httpx.Response(
code,
json={"ResponseMetadata": {"RequestId": "req-snap-err", "Error": {"Code": err_code, "Message": err_msg}}},
)
remote_id = payload["SandboxId"]
if remote_id not in self.sandboxes:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-snap-sb-404", "Error": {"Code": "SandboxNotFound", "Message": "not found"}}},
)
seq = self.next_snapshot_seq
self.next_snapshot_seq += 1
snap_id = f"snap-{seq}"
self.snapshots[snap_id] = {
"SnapshotId": snap_id,
"SandboxId": remote_id,
"FunctionId": payload["FunctionId"],
"Status": self.snapshot_status_sequence[0],
"_status_queue": list(self.snapshot_status_sequence),
"SnapshotType": payload.get("Type") or "disk",
"Source": "manual",
"CreatedAt": f"2026-11-23T01:{seq:02d}:00Z",
"RetentionDays": payload.get("RetentionDays"),
"Metadata": dict(payload.get("Metadata") or {}),
}
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-snap-create"}, "Result": {"SnapshotId": snap_id}},
)
if action == "DescribeSandboxSnapshot":
snap_id = payload["SnapshotId"]
snap = self.snapshots.get(snap_id)
if snap is None:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-snap-404", "Error": {"Code": "SnapshotNotFound", "Message": "not found"}}},
)
queue = snap.get("_status_queue")
if queue:
snap["Status"] = queue.pop(0)
body = {k: v for k, v in snap.items() if not k.startswith("_")}
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-snap-desc"}, "Result": {"Snapshot": body}},
)
if action == "ListSandboxSnapshots":
wanted_sb = payload.get("SandboxId")
filters = payload.get("Filters") or []
if self.reject_snapshot_metadata_filters and any(isinstance(f, dict) and str(f.get("Name") or "").startswith("Metadata.") for f in filters):
return httpx.Response(
400,
json={"ResponseMetadata": {"RequestId": "req-snap-filter-400", "Error": {"Code": "InvalidParameter", "Message": "unsupported Metadata filter"}}},
)
if self.reject_snapshot_status_filter and any(isinstance(f, dict) and str(f.get("Name") or "") == "Status" for f in filters):
return httpx.Response(
400,
json={"ResponseMetadata": {"RequestId": "req-snap-status-400", "Error": {"Code": "InvalidParameter", "Message": "unsupported Status filter"}}},
)
items = []
for snap in self.snapshots.values():
if snap["FunctionId"] != payload["FunctionId"]:
continue
if wanted_sb and snap["SandboxId"] != wanted_sb:
continue
if not self.ignore_snapshot_filters and filters:
matched = True
for item in filters:
if not isinstance(item, dict):
continue
name = str(item.get("Name") or "")
values = [str(v) for v in (item.get("Values") or [])]
if name == "Status" and values:
if str(snap.get("Status") or "") not in values:
matched = False
break
elif name.startswith("Metadata.") and values:
meta_key = name.removeprefix("Metadata.")
if str((snap.get("Metadata") or {}).get(meta_key, "")) not in values:
matched = False
break
if not matched:
continue
items.append({k: v for k, v in snap.items() if not k.startswith("_")})
page_number = int(payload.get("PageNumber", 1))
page_size = int(payload.get("PageSize", 50))
start = (page_number - 1) * page_size
page_items = items[start : start + page_size]
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-snap-list"}, "Result": {"Snapshots": page_items, "Total": len(items)}},
)
if action == "DeleteSandboxSnapshot":
snap_id = payload["SnapshotId"]
if snap_id not in self.snapshots:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-snap-del-404", "Error": {"Code": "SnapshotNotFound", "Message": "not found"}}},
)
self.snapshots.pop(snap_id, None)
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-snap-del"}, "Result": {"SnapshotId": snap_id}},
)
if action == "PrecacheSandboxImages":
seq = self.next_ticket_seq
self.next_ticket_seq += 1
ticket_id = f"ticket-{seq}"
self.precache_tickets[ticket_id] = {
"TicketId": ticket_id,
"ImageUrls": list(payload.get("ImageUrls") or []),
"Status": self.precache_status_sequence[0],
"_status_queue": list(self.precache_status_sequence),
"Duration": 12,
"Progress": {"Total": len(payload.get("ImageUrls") or []), "Completed": len(payload.get("ImageUrls") or [])},
}
return httpx.Response(
200,
json={"ResponseMetadata": {"RequestId": "req-precache"}, "Result": {"TicketId": ticket_id}},
)
if action == "GetSandboxImagePrecacheTicket":
ticket_id = payload["TicketId"]
ticket = self.precache_tickets.get(ticket_id)
if ticket is None:
return httpx.Response(
404,
json={"ResponseMetadata": {"RequestId": "req-ticket-404", "Error": {"Code": "TicketNotFound", "Message": "not found"}}},
)
queue = ticket.get("_status_queue")
if queue:
ticket["Status"] = queue.pop(0)
return httpx.Response(
200,
json={
"ResponseMetadata": {"RequestId": "req-ticket"},
"Result": {
"TicketId": ticket["TicketId"],
"Status": ticket["Status"],
"Duration": ticket["Duration"],
"Progress": dict(ticket["Progress"]),
},
},
)
return httpx.Response(400, json={"ResponseMetadata": {"Error": {"Code": "InvalidAction", "Message": action}}})
def make_vefaas_app_config(
tmp_path: Path,
*,
sandbox_overrides: dict[str, Any] | None = None,
skills_container_path: str = "/mnt/skills",
) -> Any:
raw: dict[str, Any] = {
"use": "deerflow.community.vefaas_sandbox:VeFaaSSandboxProvider",
"idle_timeout": 0,
"replicas": 3,
"vefaas": {
"region": "ap-southeast-1",
"endpoint": "https://vefaas.ap-southeast-1.byteplusapi.com",
"function_id": "fn-demo-app",
"sandbox_base_url": "https://sandbox.ap-southeast-1.byteplus.example",
"access_key": "AK-TEST-KEY",
"secret_key": "SK-TEST-SECRET",
"timeout_minutes": 60,
"ready_timeout": 10,
},
}
if sandbox_overrides:
if "vefaas" in sandbox_overrides and isinstance(sandbox_overrides["vefaas"], dict):
raw["vefaas"] = {**raw["vefaas"], **sandbox_overrides["vefaas"]}
for k, v in sandbox_overrides.items():
if k != "vefaas":
raw[k] = v
sandbox_cfg = SandboxConfig(**raw)
skills_dir = tmp_path / "skills"
skills_dir.mkdir(parents=True, exist_ok=True)
return SimpleNamespace(
sandbox=sandbox_cfg,
skills=SimpleNamespace(
container_path=skills_container_path,
path=str(skills_dir),
get_skills_path=lambda: skills_dir,
),
stream_bridge=None,
)
def install_vefaas_provider(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
*,
server: FakeVeFaaSServer | None = None,
sandbox_overrides: dict[str, Any] | None = None,
ready_result: bool = True,
) -> tuple[VeFaaSSandboxProvider, FakeVeFaaSServer, list[FakeAioSandbox]]:
fake_server = server or FakeVeFaaSServer()
mock_http = httpx.Client(transport=httpx.MockTransport(fake_server.handler))
app_cfg = make_vefaas_app_config(tmp_path, sandbox_overrides=sandbox_overrides)
monkeypatch.setattr(provider_mod, "get_app_config", lambda: app_cfg)
monkeypatch.setenv("DEER_FLOW_HOME", str(tmp_path / "deer-flow-home"))
monkeypatch.setattr("deerflow.config.paths._paths", None)
created_aio: list[FakeAioSandbox] = []
def fake_aio_ctor(**kwargs: Any) -> FakeAioSandbox:
inst = FakeAioSandbox(**kwargs)
created_aio.append(inst)
return inst
monkeypatch.setattr(provider_mod, "AioSandbox", fake_aio_ctor)
monkeypatch.setattr(provider_mod, "wait_for_sandbox_ready", lambda url, timeout=30, headers=None: ready_result)
monkeypatch.setattr(provider_mod.time, "sleep", lambda _s: None)
client = VeFaaSClient(
endpoint="https://vefaas.ap-southeast-1.byteplusapi.com",
region="ap-southeast-1",
access_key="AK-TEST-KEY",
secret_key="SK-TEST-SECRET",
httpx_client=mock_http,
)
with hold_sandbox_shutdown_ownership():
provider = VeFaaSSandboxProvider(client=client)
return provider, fake_server, created_aio
__all__ = [
"FakeAioSandbox",
"FakeVeFaaSServer",
"install_vefaas_provider",
"make_vefaas_app_config",
]

View File

@ -791,3 +791,48 @@ async def test_execution_cleanup_revokes_prewarm_admission(setup):
await release_sandbox_execution_lease_async(rt.context)
assert not sandbox_prewarm_cleanup_registered(rt.context)
@pytest.mark.anyio
@pytest.mark.parametrize(
"provider_use",
[
"deerflow.community.vefaas_sandbox:VeFaaSSandboxProvider",
"deerflow.community.vefaas_sandbox.provider:VeFaaSSandboxProvider",
],
)
async def test_vefaas_provider_is_admitted_for_prewarm_and_claimed_once(setup, provider_use):
provider, config = setup
config.sandbox.use = provider_use
rt = runtime()
handle = start(rt)
assert await handle.task == "alice/thread"
client = await ensure_sandbox_initialized_async(rt)
assert client.id == "alice/thread"
assert handle.claimed
assert provider.calls == [("alice", "thread")]
await release_sandbox_execution_lease_async(rt.context)
assert provider.released == ["alice/thread"]
assert not prewarm._permits
@pytest.mark.anyio
@pytest.mark.parametrize(
"provider_use",
[
"deerflow.sandbox.local:LocalSandboxProvider",
"deerflow.community.e2b_sandbox:E2BSandboxProvider",
None,
],
)
async def test_non_opted_in_providers_skip_prewarm(setup, provider_use):
provider, config = setup
config.sandbox.use = provider_use
rt = runtime()
handle = start(rt)
assert await handle.task is None
assert provider.calls == []
await release_sandbox_execution_lease_async(rt.context)
assert not prewarm._permits

File diff suppressed because it is too large Load Diff

View File

@ -1783,8 +1783,9 @@ uploads:
# Serves workspace file operations
sandbox:
use: deerflow.sandbox.local:LocalSandboxProvider
# For AioSandboxProvider only: overlap likely sandbox work with the first
# model call. It is disabled by default and ignored by other providers.
# For AioSandboxProvider and VeFaaSSandboxProvider only: overlap likely
# sandbox work with the first model call. Disabled by default; ignored by
# other providers.
prewarm: false
# Bound pending/ready-unused speculation per provider instance, per process.
# A full budget skips prewarming; foreground tools still acquire normally.
@ -2093,12 +2094,24 @@ sandbox:
# # memory_mb: 2048 # 512..131072
# # timeout_minutes: 60 # 3..1440
# # ready_timeout: 60 # seconds to wait for Running + HTTP readiness
# # snapshot_id: "" # optional pre-baked base snapshot for new sandboxes
# # pause_on_idle: false # pause warm sandboxes on idle/eviction instead of killing
# # auto_pause: false # pass AutoPauseConfig on CreateSandbox
# # snapshot_on_idle: false # snapshot clean idle sandboxes before kill & auto-restore
# # snapshot_type: disk # disk | full
# # snapshot_retention_days: 7 # 1..365 (optional)
# # snapshot_timeout: 120 # seconds to wait for snapshot readiness
# # max_snapshots_per_sandbox: 3 # ready snapshots retained per thread (1..100)
# # precache_images: [] # optional image URLs to precache via PrecacheSandboxImages
# # precache_on_startup: false # trigger background image precache on provider startup
# # tos_mount: # optional per-thread scoped TOS mount
# # enabled: false
# # bucket: $BYTEPLUS_TOS_BUCKET
# # prefix: deerflow-user-data
# # replicas: 3 # active + warm soft cap per gateway process
# # idle_timeout: 600 # warm seconds before KillSandbox; 0 disables
# # prewarm: false # overlap likely sandbox startup with the first model call
# # prewarm_max_concurrent: 1 # pending/unused speculative prewarms per process
# # bash_command_timeout: 600 # default remote command timeout seconds
# # ownership:
# # type: redis # required for multi-worker gateways sharing one veFaaS app