From 9982c9199832b6956eaf75083c6dcad8d9017c26 Mon Sep 17 00:00:00 2001 From: Kevin Hsiao Date: Tue, 24 Nov 2026 09:27:50 +0800 Subject: [PATCH] feat(sandbox): add BytePlus veFaaS cloud sandbox provider (#8449) * feat(sandbox): add BytePlus veFaaS cloud sandbox provider * fix(vefaas-sandbox): address review findings on describe, rollback shutdown, and guidance inventory * fix(vefaas-sandbox): harden upload subshell, teardown exclusion, pagination, and 404 handling * fix(vefaas-sandbox): keep recycling teardowns visible to shutdown and verify init before adoption * fix(vefaas-sandbox): serialize init adoption, verify bootstrap success, and guard deferred teardown * fix(vefaas): protect output mirroring during teardown --------- Co-authored-by: Willem Jiang --- README.md | 1 + .../community/vefaas_sandbox/AGENTS.md | 31 + .../community/vefaas_sandbox/README.md | 44 + .../community/vefaas_sandbox/__init__.py | 19 + .../community/vefaas_sandbox/client.py | 520 +++++ .../community/vefaas_sandbox/provider.py | 1710 +++++++++++++++++ .../harness/deerflow/config/sandbox_config.py | 8 + .../tests/blocking_io/test_vefaas_sandbox.py | 125 ++ backend/tests/test_agent_guidance_check.py | 1 + backend/tests/test_vefaas_sandbox_provider.py | 1651 ++++++++++++++++ config.example.yaml | 31 + 11 files changed, 4141 insertions(+) create mode 100644 backend/packages/harness/deerflow/community/vefaas_sandbox/AGENTS.md create mode 100644 backend/packages/harness/deerflow/community/vefaas_sandbox/README.md create mode 100644 backend/packages/harness/deerflow/community/vefaas_sandbox/__init__.py create mode 100644 backend/packages/harness/deerflow/community/vefaas_sandbox/client.py create mode 100644 backend/packages/harness/deerflow/community/vefaas_sandbox/provider.py create mode 100644 backend/tests/blocking_io/test_vefaas_sandbox.py create mode 100644 backend/tests/test_vefaas_sandbox_provider.py diff --git a/README.md b/README.md index 540bea2a9b..bc7606bf28 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,7 @@ Each guide is the full reference for its topic. Open the one you need. | Docker, local development, upgrades, production deployment | [Running the Application](docs/guide/deployment.md) | | Workspace file tools, isolated shell providers, uploads and outputs | [Sandbox](docs/guide/sandbox.md) | | boxd machines, bounded output copies and cleanup retries | [boxd sandbox provider](backend/packages/harness/deerflow/community/boxd_sandbox/README.md) | +| BytePlus veFaaS cloud sandboxes, SigV4 control plane and optional TOS mounts | [veFaaS sandbox provider](backend/packages/harness/deerflow/community/vefaas_sandbox/README.md) | | Skills, built-in tools, script workflows, Claude Code integration | [Skills & Tools](docs/guide/skills-and-tools.md) | | MCP servers | [MCP Server](docs/guide/mcp.md) | | Sub-agents, task delegation and optional SQLite checkpoint history | [Sub-Agents](docs/guide/subagents.md), [Inspect one thread's child history](docs/guide/subagents.md#inspect-one-threads-child-history), [Tool restrictions](docs/guide/subagents.md#tool-restrictions) | diff --git a/backend/packages/harness/deerflow/community/vefaas_sandbox/AGENTS.md b/backend/packages/harness/deerflow/community/vefaas_sandbox/AGENTS.md new file mode 100644 index 0000000000..78ea8736c2 --- /dev/null +++ b/backend/packages/harness/deerflow/community/vefaas_sandbox/AGENTS.md @@ -0,0 +1,31 @@ +# veFaaS cloud sandbox provider (`deerflow/community/vefaas_sandbox/`) + +Provisions managed BytePlus Function Service (veFaaS) Cloud Sandbox instances +over OpenAPI v4 (`Version=2024-06-06`) and reuses `AioSandbox` for the data +plane. General sandbox rules are in [sandbox guide](../../sandbox/AGENTS.md); +operator setup is in [README.md](README.md). + +## Verify + +```bash +cd backend +uv run pytest tests/test_vefaas_sandbox_provider.py tests/blocking_io/test_vefaas_sandbox.py -q +``` + +## Rules + +- **Sign OpenAPI v4 with raw `sk.encode("utf-8")`.** BytePlus/Volcengine SigV4 + does not prepend `"AWS4"` or `"V4"` to the secret key before deriving + `k_date`; `tests/test_vefaas_sandbox_provider.py` cross-checks parity with + `volcenginesdkcore.signv4.SignerV4`. +- **Keep `get()` and `get_scoped()` strictly in-memory.** Never touch the + ownership store or HTTP client on the event loop; `acquire_async()` runs its + blocking work on the serializer's executor. +- **Confirm absence via `DescribeSandbox` before clearing quarantine.** An + accepted `KillSandbox` or a failed probe never proves absence. +- **Fence output mirrors from teardown.** Keep clients and lease renewal active + until release finishes the copy. Shutdown remains retryable during the mirror. +- **Route credentials through `provider_credentials`.** Use `resolve_api_key`, + `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`. diff --git a/backend/packages/harness/deerflow/community/vefaas_sandbox/README.md b/backend/packages/harness/deerflow/community/vefaas_sandbox/README.md new file mode 100644 index 0000000000..21ea8248b1 --- /dev/null +++ b/backend/packages/harness/deerflow/community/vefaas_sandbox/README.md @@ -0,0 +1,44 @@ +# BytePlus veFaaS Cloud Sandbox Provider (`deerflow/community/vefaas_sandbox/`) + +Runs each DeerFlow thread sandbox on **BytePlus Function Service (veFaaS) Cloud Sandbox** using the All-in-One Sandbox (`all-in-one-sandbox`) image. + +- **Control plane**: BytePlus veFaaS OpenAPI (`Version=2024-06-06`, SigV4 HMAC-SHA256) over `httpx` — no extra cloud SDK dependency required. +- **Data plane**: Reuses DeerFlow's `AioSandbox` HTTP client via the Sandbox App's unified access domain (`X-Faas-Instance-Name: `) 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. + +If shutdown overlaps an output mirror, it reports incomplete cleanup and keeps +the sandbox available for the copy. Retry shutdown after release finishes. + +## Configuration + +```yaml +sandbox: + use: deerflow.community.vefaas_sandbox:VeFaaSSandboxProvider + vefaas: + region: ap-southeast-1 + endpoint: https://vefaas.ap-southeast-1.byteplusapi.com + function_id: $BYTEPLUS_VEFAAS_SANDBOX_APP_ID + sandbox_base_url: $BYTEPLUS_VEFAAS_SANDBOX_BASE_URL + access_key_env: BYTEPLUS_ACCESS_KEY_ID + secret_key_env: BYTEPLUS_SECRET_ACCESS_KEY + cpu_milli: 1000 + memory_mb: 2048 + timeout_minutes: 60 + tos_mount: + enabled: false + bucket: $BYTEPLUS_TOS_BUCKET + prefix: deerflow-user-data + replicas: 3 + idle_timeout: 600 + ownership: + type: redis # required for multi-worker gateways +``` + +## Verification + +```bash +cd backend +uv run pytest tests/test_vefaas_sandbox_provider.py -q +uv run pytest tests/blocking_io/test_vefaas_sandbox.py -q +``` diff --git a/backend/packages/harness/deerflow/community/vefaas_sandbox/__init__.py b/backend/packages/harness/deerflow/community/vefaas_sandbox/__init__.py new file mode 100644 index 0000000000..2846eb0143 --- /dev/null +++ b/backend/packages/harness/deerflow/community/vefaas_sandbox/__init__.py @@ -0,0 +1,19 @@ +"""BytePlus Function Service (veFaaS) Cloud Sandbox community provider.""" + +from .client import ( + VeFaaSApiError, + VeFaaSClient, + VeFaaSSandboxNotFoundError, + VeFaaSSandboxRecord, + sign_v4_headers, +) +from .provider import VeFaaSSandboxProvider + +__all__ = [ + "VeFaaSApiError", + "VeFaaSClient", + "VeFaaSSandboxNotFoundError", + "VeFaaSSandboxRecord", + "VeFaaSSandboxProvider", + "sign_v4_headers", +] diff --git a/backend/packages/harness/deerflow/community/vefaas_sandbox/client.py b/backend/packages/harness/deerflow/community/vefaas_sandbox/client.py new file mode 100644 index 0000000000..e0965ffe9f --- /dev/null +++ b/backend/packages/harness/deerflow/community/vefaas_sandbox/client.py @@ -0,0 +1,520 @@ +"""BytePlus Function Service (veFaaS) Cloud Sandbox OpenAPI client. + +Implements the BytePlus/Volcengine OpenAPI v4 HMAC-SHA256 signing protocol and +the Cloud Sandbox instance lifecycle actions (``Version=2024-06-06``) directly +over ``httpx``, requiring no external cloud SDK package. +""" + +from __future__ import annotations + +import datetime +import hashlib +import hmac +import json +import logging +import threading +from collections.abc import Mapping +from dataclasses import dataclass, field +from typing import Any +from urllib.parse import quote, urlsplit + +import httpx +from pydantic import AnyHttpUrl, TypeAdapter + +from deerflow.community.provider_credentials import redact_secret, reject_url_userinfo + +logger = logging.getLogger(__name__) + +VEFAAS_API_VERSION = "2024-06-06" +VEFAAS_SERVICE = "vefaas" +DEFAULT_VEFAAS_REGION = "ap-southeast-1" +DEFAULT_REQUEST_TIMEOUT = 30.0 + +_URL_ADAPTER = TypeAdapter(AnyHttpUrl) +_NOT_FOUND_ERROR_CODES = frozenset( + { + "SandboxNotFound", + "InstanceNotFound", + "InvalidSandboxId.NotFound", + "ResourceNotFound.Sandbox", + "ResourceNotFound.Instance", + } +) + + +class VeFaaSApiError(RuntimeError): + """Error returned by the BytePlus veFaaS control plane.""" + + def __init__( + self, + message: str, + *, + status_code: int | None = None, + error_code: str | None = None, + request_id: str | None = None, + ) -> None: + super().__init__(message) + self.status_code = status_code + self.error_code = error_code + self.request_id = request_id + + +class VeFaaSSandboxNotFoundError(VeFaaSApiError): + """Authoritative response proving a remote veFaaS sandbox does not exist.""" + + +@dataclass(frozen=True) +class VeFaaSSandboxRecord: + """Normalized veFaaS cloud sandbox instance metadata.""" + + id: str + function_id: str + status: str + pending: bool = False + metadata: dict[str, str] = field(default_factory=dict) + error_code: str = "" + error_message: str = "" + expire_at: str = "" + + @property + def is_running(self) -> bool: + return self.status.strip().lower() == "running" and not self.pending + + @property + def is_terminal_failure(self) -> bool: + return self.status.strip().lower() in {"failed", "error", "terminated", "deleted", "stopped"} + + +def validate_endpoint_url(url: str, *, allow_insecure_http: bool = False) -> str: + """Validate an HTTP(S) endpoint URL, forbidding embedded credentials.""" + raw = url.strip().rstrip("/") + if not raw: + raise ValueError("URL must not be empty") + validated = reject_url_userinfo(_URL_ADAPTER.validate_python(raw)) + parsed = urlsplit(str(validated)) + scheme = parsed.scheme.lower() + if scheme != "https" and not (allow_insecure_http and scheme == "http"): + raise ValueError(f"Endpoint URL must use HTTPS (set allow_insecure_http: true only for local testing): {raw!r}") + return str(validated).rstrip("/") + + +def _hmac_sha256(key: bytes, message: str) -> bytes: + return hmac.new(key, message.encode("utf-8"), hashlib.sha256).digest() + + +def _canonical_query(params: Mapping[str, str]) -> str: + pairs = sorted((quote(str(k), safe="-_.~"), quote(str(v), safe="-_.~")) for k, v in params.items()) + return "&".join(f"{k}={v}" for k, v in pairs) + + +def _normalize_host_for_signing(host: str) -> str: + if ":" not in host: + return host + hostname, port = host.rsplit(":", 1) + if port in {"80", "443"}: + return hostname + return host + + +def sign_v4_headers( + *, + method: str, + path: str, + query: Mapping[str, str], + host: str, + body: str, + access_key: str, + secret_key: str, + region: str, + service: str = VEFAAS_SERVICE, + session_token: str | None = None, + content_type: str = "application/json; charset=utf-8", + now: datetime.datetime | None = None, +) -> dict[str, str]: + """Produce BytePlus/Volcengine OpenAPI v4 HMAC-SHA256 signed headers. + + Matches ``volcenginesdkcore.signv4.SignerV4`` byte-for-byte: key derivation + uses ``HMAC-SHA256(sk, short_date)`` (without an AWS prefix) and signs + ``Content-Type``, ``Content-Md5``, ``Host``, and ``X-*`` headers. + """ + canonical_path = path or "/" + utc_now = (now or datetime.datetime.now(datetime.UTC)).astimezone(datetime.UTC) + x_date = utc_now.strftime("%Y%m%dT%H%M%SZ") + short_date = x_date[:8] + + body_hash = hashlib.sha256(body.encode("utf-8")).hexdigest() + headers: dict[str, str] = { + "Host": host, + "X-Date": x_date, + "X-Content-Sha256": body_hash, + } + if method.upper() != "GET": + headers["Content-Type"] = content_type + if session_token: + headers["X-Security-Token"] = session_token + + signed_map: dict[str, str] = {} + for key, value in headers.items(): + if key in {"Content-Type", "Content-Md5", "Host"} or key.startswith("X-"): + signed_map[key.lower()] = _normalize_host_for_signing(value) if key == "Host" else value + + sorted_keys = sorted(signed_map.keys()) + canonical_headers = "".join(f"{k}:{signed_map[k]}\n" for k in sorted_keys) + signed_headers = ";".join(sorted_keys) + + canonical_request = "\n".join( + [ + method.upper(), + canonical_path, + _canonical_query(query), + canonical_headers, + signed_headers, + body_hash, + ] + ) + credential_scope = f"{short_date}/{region}/{service}/request" + string_to_sign = "\n".join( + [ + "HMAC-SHA256", + x_date, + credential_scope, + hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(), + ] + ) + + k_date = _hmac_sha256(secret_key.encode("utf-8"), short_date) + k_region = _hmac_sha256(k_date, region) + k_service = _hmac_sha256(k_region, service) + k_signing = _hmac_sha256(k_service, "request") + signature = hmac.new(k_signing, string_to_sign.encode("utf-8"), hashlib.sha256).hexdigest() + + headers["Authorization"] = f"HMAC-SHA256 Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}" + return headers + + +def _parse_metadata(raw: Any) -> dict[str, str]: + """Normalize veFaaS Metadata (dict in ListSandboxes) and MetadataList (list in DescribeSandbox).""" + if isinstance(raw, Mapping): + return {str(k): str(v) for k, v in raw.items() if k is not None and v is not None} + if isinstance(raw, list): + parsed: dict[str, str] = {} + for item in raw: + if not isinstance(item, Mapping): + continue + key = item.get("MetaKey") + value = item.get("MetaValue") + if isinstance(key, str) and value is not None: + parsed[key] = str(value) + return parsed + return {} + + +def _parse_record(payload: Mapping[str, Any], *, fallback_function_id: str) -> VeFaaSSandboxRecord | None: + sandbox_id = payload.get("Id") or payload.get("SandboxId") + if not isinstance(sandbox_id, str) or not sandbox_id.strip(): + return None + metadata = _parse_metadata(payload.get("Metadata")) + if not metadata and "MetadataList" in payload: + metadata = _parse_metadata(payload.get("MetadataList")) + return VeFaaSSandboxRecord( + id=sandbox_id.strip(), + function_id=str(payload.get("FunctionId") or fallback_function_id), + status=str(payload.get("Status") or ""), + pending=bool(payload.get("Pending", False)), + metadata=metadata, + error_code=str(payload.get("ErrorCode") or ""), + error_message=str(payload.get("ErrorMessage") or ""), + expire_at=str(payload.get("ExpireAt") or ""), + ) + + +class VeFaaSClient: + """Thread-safe BytePlus veFaaS Cloud Sandbox OpenAPI client. + + The underlying ``httpx.Client`` is created lazily on first request so + constructing the client (or provider) does no synchronous TLS setup on an + async event loop. + """ + + def __init__( + self, + *, + endpoint: str, + region: str, + access_key: str, + secret_key: str, + session_token: str | None = None, + timeout: float = DEFAULT_REQUEST_TIMEOUT, + allow_insecure_http: bool = False, + httpx_client: httpx.Client | None = None, + ) -> None: + self._endpoint = validate_endpoint_url(endpoint, allow_insecure_http=allow_insecure_http) + parsed = urlsplit(self._endpoint) + self._host = parsed.netloc + self._base_path = parsed.path.rstrip("/") or "/" + self._region = region.strip() + self._access_key = access_key + self._secret_key = secret_key + self._session_token = session_token + self._timeout = float(timeout) + self._lock = threading.Lock() + self._owns_client = httpx_client is None + self._client: httpx.Client | None = httpx_client + self._closed = False + + def _redact(self, value: object) -> str: + text = redact_secret(value, self._secret_key) + text = redact_secret(text, self._access_key) + text = redact_secret(text, self._session_token) + return text + + def _get_client(self) -> httpx.Client: + with self._lock: + if self._closed: + raise RuntimeError("VeFaaSClient has been closed") + if self._client is None: + self._client = httpx.Client(timeout=self._timeout) + return self._client + + def close(self) -> None: + with self._lock: + if self._closed: + return + self._closed = True + client = self._client + self._client = None + if client is not None and self._owns_client: + try: + client.close() + except Exception as exc: + logger.warning("Error closing VeFaaSClient HTTP client: %s", self._redact(exc)) + + def _request(self, action: str, payload: dict[str, Any]) -> dict[str, Any]: + query = {"Action": action, "Version": VEFAAS_API_VERSION} + body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False) + headers = sign_v4_headers( + method="POST", + path=self._base_path, + query=query, + host=self._host, + body=body, + access_key=self._access_key, + secret_key=self._secret_key, + region=self._region, + service=VEFAAS_SERVICE, + session_token=self._session_token, + ) + client = self._get_client() + try: + response = client.post( + self._endpoint, + params=query, + content=body.encode("utf-8"), + headers=headers, + timeout=self._timeout, + ) + except httpx.HTTPError as exc: + raise VeFaaSApiError(f"veFaaS {action} request failed: {self._redact(exc)}") from exc + + try: + data = response.json() + except ValueError as exc: + raise VeFaaSApiError( + f"veFaaS {action} returned non-JSON response (HTTP {response.status_code})", + status_code=response.status_code, + ) from exc + + if not isinstance(data, dict): + raise VeFaaSApiError( + f"veFaaS {action} returned malformed payload of type {type(data).__name__}", + status_code=response.status_code, + ) + + meta = data.get("ResponseMetadata") + request_id = meta.get("RequestId") if isinstance(meta, dict) else None + error_obj = meta.get("Error") if isinstance(meta, dict) else None + 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 + raise err_cls( + f"veFaaS {action} failed ({error_code}): {error_msg}", + status_code=response.status_code, + error_code=error_code, + request_id=str(request_id) if request_id else None, + ) + + if response.status_code >= 400: + raise VeFaaSApiError( + f"veFaaS {action} returned HTTP {response.status_code}", + status_code=response.status_code, + request_id=str(request_id) if request_id else None, + ) + + result = data.get("Result") + if result is None: + return {} + if not isinstance(result, dict): + raise VeFaaSApiError( + f"veFaaS {action} returned malformed Result of type {type(result).__name__}", + status_code=response.status_code, + request_id=str(request_id) if request_id else None, + ) + return result + + def create_sandbox( + self, + function_id: str, + *, + cpu_milli: int | None = None, + memory_mb: int | None = None, + timeout_minutes: int | None = None, + metadata: Mapping[str, str] | None = None, + envs: Mapping[str, str] | None = None, + instance_image_info: Mapping[str, Any] | None = None, + instance_tos_mount_config: Mapping[str, Any] | None = None, + session_id: str | None = None, + ) -> str: + """Create a veFaaS cloud sandbox instance and return its remote ``SandboxId``.""" + payload: dict[str, Any] = {"FunctionId": function_id} + if cpu_milli is not None: + payload["CpuMilli"] = cpu_milli + if memory_mb is not None: + payload["MemoryMB"] = memory_mb + if timeout_minutes is not None: + payload["Timeout"] = timeout_minutes + payload["TimeoutUnit"] = "minute" + if metadata: + payload["Metadata"] = {str(k): str(v) for k, v in metadata.items()} + if envs: + payload["Envs"] = [{"Key": str(k), "Value": str(v)} for k, v in envs.items()] + if instance_image_info: + payload["InstanceImageInfo"] = dict(instance_image_info) + if instance_tos_mount_config: + payload["InstanceTosMountConfig"] = dict(instance_tos_mount_config) + if session_id: + payload["SessionId"] = session_id + + result = self._request("CreateSandbox", payload) + sandbox_id = result.get("SandboxId") or result.get("Id") + if not isinstance(sandbox_id, str) or not sandbox_id.strip(): + raise VeFaaSApiError("veFaaS CreateSandbox response did not include a SandboxId") + return sandbox_id.strip() + + def describe_sandbox(self, function_id: str, sandbox_id: str) -> VeFaaSSandboxRecord | None: + """Describe one sandbox instance; return ``None`` only on authoritative not-found.""" + try: + result = self._request( + "DescribeSandbox", + {"FunctionId": function_id, "SandboxId": sandbox_id}, + ) + except VeFaaSSandboxNotFoundError: + return None + record = _parse_record(result, fallback_function_id=function_id) + if record is None: + raise VeFaaSApiError(f"veFaaS DescribeSandbox response for {sandbox_id} did not include a valid sandbox record") + return record + + def list_sandboxes( + self, + function_id: str, + *, + metadata: Mapping[str, str] | None = None, + status: str | None = None, + page_number: int | None = None, + page_size: int = 50, + max_pages: int = 100, + ) -> list[VeFaaSSandboxRecord]: + """List sandbox instances belonging to ``function_id`` with optional metadata filters. + + When ``page_number`` is omitted, paginates across pages until a short page + or the reported ``Total`` count is reached (bounded by ``max_pages``). + """ + records: list[VeFaaSSandboxRecord] = [] + 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 metadata: + payload["Metadata"] = {str(k): str(v) for k, v in metadata.items()} + if status: + payload["Status"] = status + + result = self._request("ListSandboxes", payload) + raw_items = result.get("Sandboxes") + 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 ListSandboxes returned malformed Sandboxes of type {type(raw_items).__name__}") + + for item in raw_items: + if not isinstance(item, Mapping): + continue + record = _parse_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 ListSandboxes stopped after max_pages=%d (%d records fetched for function %s)", + max_pages, + len(records), + function_id, + ) + break + current_page += 1 + return records + + def set_sandbox_timeout(self, function_id: str, sandbox_id: str, *, timeout_minutes: int) -> None: + """Extend the active lifetime of a running veFaaS sandbox instance.""" + self._request( + "SetSandboxTimeout", + { + "FunctionId": function_id, + "SandboxId": sandbox_id, + "Timeout": timeout_minutes, + "TimeoutUnit": "minute", + }, + ) + + def kill_sandbox(self, function_id: str, sandbox_id: str) -> None: + """Terminate a veFaaS sandbox instance; treat authoritative not-found as idempotent.""" + try: + self._request( + "KillSandbox", + {"FunctionId": function_id, "SandboxId": sandbox_id}, + ) + except VeFaaSSandboxNotFoundError: + logger.debug("veFaaS sandbox %s already absent during KillSandbox", sandbox_id) + + +__all__ = [ + "DEFAULT_REQUEST_TIMEOUT", + "DEFAULT_VEFAAS_REGION", + "VEFAAS_API_VERSION", + "VEFAAS_SERVICE", + "VeFaaSApiError", + "VeFaaSClient", + "VeFaaSSandboxNotFoundError", + "VeFaaSSandboxRecord", + "sign_v4_headers", + "validate_endpoint_url", +] diff --git a/backend/packages/harness/deerflow/community/vefaas_sandbox/provider.py b/backend/packages/harness/deerflow/community/vefaas_sandbox/provider.py new file mode 100644 index 0000000000..408b775129 --- /dev/null +++ b/backend/packages/harness/deerflow/community/vefaas_sandbox/provider.py @@ -0,0 +1,1710 @@ +"""``VeFaaSSandboxProvider`` — DeerFlow :class:`SandboxProvider` for BytePlus veFaaS Cloud Sandbox. + +Runs each DeerFlow thread sandbox as a managed BytePlus Function Service +(veFaaS) Cloud Sandbox instance running the All-in-One Sandbox image. The +control plane calls the BytePlus veFaaS OpenAPI (``Version=2024-06-06``) with +SigV4 authentication, while the data plane reuses :class:`AioSandbox` over the +sandbox application's unified access domain (routing to each instance via +``X-Faas-Instance-Name``) or an instance URL template. +""" + +from __future__ import annotations + +import atexit +import io +import logging +import math +import os +import posixpath +import shlex +import signal +import stat +import tarfile +import tempfile +import threading +import time +import uuid +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass +from functools import partial +from pathlib import Path, PurePosixPath +from typing import TYPE_CHECKING, Any, Literal + +from deerflow.community.provider_credentials import redact_secret, resolve_api_key +from deerflow.config import get_app_config +from deerflow.sandbox.acquire_serialization import AcquireSerializer, AcquireSerializerClosed +from deerflow.sandbox.download import DEFAULT_DOWNLOAD_LIMIT +from deerflow.sandbox.identity import derive_sandbox_scope_token +from deerflow.sandbox.sandbox import Sandbox, _validate_extra_env +from deerflow.sandbox.sandbox_provider import SandboxProvider, host_owns_sandbox_shutdown + +from ..aio_sandbox.aio_sandbox import AioSandbox +from ..aio_sandbox.backend import wait_for_sandbox_ready +from ..aio_sandbox.ownership import ( + OwnershipBackendError, + RenewOutcome, + SandboxOwnershipStore, + generate_owner_id, + make_sandbox_ownership_store, + resolve_ownership_config, +) +from ..warm_pool_lifecycle import WarmPoolLifecycleMixin +from .client import ( + DEFAULT_REQUEST_TIMEOUT, + DEFAULT_VEFAAS_REGION, + VeFaaSClient, + VeFaaSSandboxRecord, + validate_endpoint_url, +) + +if TYPE_CHECKING: + from deerflow.skills.projection import SkillProjectionPaths + +logger = logging.getLogger(__name__) + +DEFAULT_TIMEOUT_MINUTES = 60 +MIN_TIMEOUT_MINUTES = 3 +MAX_TIMEOUT_MINUTES = 1440 +MIN_CPU_MILLI = 250 +MAX_CPU_MILLI = 16000 +MIN_MEMORY_MB = 512 +MAX_MEMORY_MB = 131072 +DEFAULT_READY_TIMEOUT = 60.0 +DEFAULT_COMMAND_TIMEOUT = 600.0 +DEFAULT_SANDBOX_ACCESS_HEADER = "Authorization" +INSTANCE_ROUTING_HEADER = "X-Faas-Instance-Name" +USER_DATA_ROOT = "/mnt/user-data" +OUTPUTS_ROOT = f"{USER_DATA_ROOT}/outputs" +SKILL_CATEGORIES = ("public", "custom", "legacy", "integrations") +META_KEY_PROVIDER = "deer_flow_provider" +META_KEY_SANDBOX_ID = "deer_flow_sandbox_id" +META_VAL_PROVIDER = "vefaas_sandbox" + +_PROTECTED_ROOTS = ( + "/bin", + "/boot", + "/dev", + "/etc", + "/lib", + "/lib32", + "/lib64", + "/libx32", + "/proc", + "/root", + "/run", + "/sbin", + "/sys", + "/usr", + "/var", +) +_WINDOWS_RESERVED_NAMES = frozenset({"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"} | {f"{prefix}{digit}" for prefix in ("COM", "LPT") for digit in "123456789¹²³"}) +_BOOTSTRAP_OK_MARKER = "DEERFLOW_VEFAAS_BOOTSTRAP_OK" +# Use a split printf format so PTY echo of the command string cannot satisfy the marker check, +# and run in a subshell with ``set +e`` outside so persistent shell state is never poisoned. +_BOOTSTRAP_COMMAND = "set +e; ( mkdir -p -- /mnt/user-data/workspace /mnt/user-data/uploads /mnt/user-data/outputs && printf 'DEERFLOW_VEFAAS_%s\\n' 'BOOTSTRAP_OK' )" +_INIT_MARKER_PATH = "/tmp/.deerflow-vefaas-initialized" +_ADOPT_INIT_WAIT_SECONDS = 10.0 +_ADOPT_INIT_POLL_INTERVAL_SECONDS = 0.2 +_REMOTE_INIT_LOCKS_GUARD = threading.Lock() +_REMOTE_INIT_LOCKS: dict[tuple[str, str, str], tuple[threading.RLock, int]] = {} +_MAX_UPLOAD_FILES = 5000 +_MAX_UPLOAD_BYTES = 64 * 1024 * 1024 +_MAX_SYNC_FILES = 2000 +_MAX_SYNC_TOTAL_BYTES = 512 * 1024 * 1024 +_MAX_SYNC_LISTING_BYTES = 512 * 1024 +_SYNC_DEADLINE_SECONDS = 120.0 +_POLL_STATUS_INTERVAL_SECONDS = 1.0 + +VEFAAS_EXTRA_CONFIG_KEYS = frozenset( + { + "vefaas", + "region", + "endpoint", + "function_id", + "sandbox_base_url", + "access_key", + "secret_key", + "session_token", + "access_key_env", + "secret_key_env", + "session_token_env", + "sandbox_access_token", + "sandbox_access_header", + "cpu_milli", + "memory_mb", + "timeout_minutes", + "ready_timeout", + "request_timeout", + "allow_insecure_http", + "tos_mount", + "metadata", + } +) +_TOS_MOUNT_KEYS = frozenset({"enabled", "bucket", "prefix", "local_mount_path", "read_only", "endpoint"}) + + +class _VeFaaSShutdownIncompleteError(RuntimeError): + """Raised when shutdown leaves unconfirmed teardowns or running workers.""" + + +@dataclass +class _TrackedVeFaaSSandbox: + """In-memory handle pairing a DeerFlow logical ID with its remote veFaaS instance.""" + + sandbox_id: str + remote_sandbox_id: str + sandbox: AioSandbox + thread_id: str | None + user_id: str | None + + +@dataclass(frozen=True) +class _PendingRollback: + """Failed provisioning generation retained for retryable teardown and shutdown.""" + + sandbox_id: str + remote_sandbox_id: str + release_ownership: bool + + +@dataclass +class _UploadBudget: + """Aggregate file-count and byte ceiling for one tar upload pass.""" + + max_files: int + max_bytes: int + files: int = 0 + bytes: int = 0 + + def admit(self, size: int) -> bool: + if self.files + 1 > self.max_files or self.bytes + size > self.max_bytes: + return False + self.files += 1 + self.bytes += size + return True + + +def _validate_skills_root(container_path: str) -> str: + """Validate that the managed skills root is an isolated, non-system absolute path.""" + raw = (container_path or "").rstrip("/") + normalized = posixpath.normpath(raw) if raw else "" + if not normalized.startswith("/") or normalized == "/" or normalized != raw: + raise ValueError(f"skills.container_path {container_path!r} is not a safe veFaaS skills root: use a normalized absolute path such as /mnt/skills") + if normalized in {"/home", "/mnt", "/tmp"} or any(normalized == root or normalized.startswith(f"{root}/") for root in _PROTECTED_ROOTS): + raise ValueError(f"skills.container_path {container_path!r} is not a safe veFaaS skills root: it is a system directory") + if normalized == USER_DATA_ROOT or normalized.startswith(f"{USER_DATA_ROOT}/") or USER_DATA_ROOT.startswith(f"{normalized}/"): + raise ValueError(f"skills.container_path {container_path!r} must not overlap {USER_DATA_ROOT}") + return normalized + + +def _validate_sandbox_url_template(raw_url: str, *, allow_insecure_http: bool) -> str: + """Validate a unified sandbox URL or a ``{sandbox_id}`` URL template.""" + trimmed = raw_url.strip().rstrip("/") + if not trimmed: + raise ValueError("sandbox.sandbox_base_url must not be empty") + probe = trimmed.replace("{sandbox_id}", "sandbox-placeholder") + validate_endpoint_url(probe, allow_insecure_http=allow_insecure_http) + return trimmed + + +def _sanitize_tos_prefix(raw_prefix: str) -> str: + """Normalize a TOS bucket prefix while rejecting path traversal.""" + cleaned = raw_prefix.strip().strip("/") + if not cleaned: + return "" + parts = cleaned.split("/") + if any(part in {"", ".", ".."} or "\\" in part for part in parts): + raise ValueError(f"sandbox.tos_mount.prefix {raw_prefix!r} contains invalid path segments") + return "/".join(parts) + + +class VeFaaSSandboxProvider(WarmPoolLifecycleMixin[_TrackedVeFaaSSandbox], SandboxProvider): + """Manage BytePlus veFaaS Cloud Sandbox instances reusing :class:`AioSandbox`.""" + + uses_thread_data_mounts = False + needs_upload_permission_adjustment = True + supports_agent_skill_isolation = True + supports_lazy_agent_skill_isolation = False + _idle_checker_thread_name = "vefaas-sandbox-idle-reaper" + + def __init__(self, *, client: VeFaaSClient | None = None) -> None: + self._lock = threading.Lock() + self._shutdown_lock = threading.Lock() + self._sandboxes: dict[str, _TrackedVeFaaSSandbox] = {} + self._thread_sandboxes: dict[tuple[str, str], str] = {} + self._warm_pool: dict[str, tuple[_TrackedVeFaaSSandbox, float]] = {} + self._quarantined_remote_ids: dict[str, set[str]] = {} + self._pending_destroys: dict[str, _TrackedVeFaaSSandbox] = {} + self._pending_rollbacks: dict[str, _PendingRollback] = {} + self._destroying_remote_ids: set[str] = set() + self._mirroring_output_ids: set[str] = set() + # Same-process exclusion against warm-pool reaping and stale lease renewals: + # - _local_teardown: refcount of teardowns currently active in this process + # - _acquire_inflight: refcount of acquires currently publishing ownership + # - _acquire_epoch: monotonic generation bumped whenever this process publishes an acquire + # - _acquires: total in-flight acquire() calls gated by shutdown() + self._local_teardown: dict[str, int] = {} + self._acquire_inflight: dict[str, int] = {} + self._acquire_epoch: dict[str, int] = {} + self._acquire_epoch_counter = 0 + self._acquires = 0 + self._acquire_serializer: AcquireSerializer[str] = AcquireSerializer(thread_name_prefix="vefaas-sandbox-acquire-wait") + self._idle_checker_stop = threading.Event() + self._idle_checker_thread: threading.Thread | None = None + self._renewal_stop = threading.Event() + self._renewal_thread: threading.Thread | None = None + self._shutdown_called = False + self._shutdown_complete = False + self._accepting = True + self._owner_id = generate_owner_id() + self._client_override = client + self._client: VeFaaSClient | None = client + self._config = self._load_config() + + self._ownership_config = resolve_ownership_config( + self._config.get("ownership"), + stream_bridge=self._config.get("stream_bridge"), + ) + self._ownership: SandboxOwnershipStore = make_sandbox_ownership_store( + self._ownership_config, + owner_id=self._owner_id, + ) + + atexit.register(self._shutdown_at_exit) + self._register_signal_handlers() + self._start_idle_checker() + self._start_renewal_thread() + + # ── Config ─────────────────────────────────────────────────────────── + + @staticmethod + def _bounded_int(name: str, value: Any, *, minimum: int, maximum: int, default: int | None = None) -> int | None: + if value is None: + return default + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"sandbox.{name} must be an integer") + if value < minimum or value > maximum: + raise ValueError(f"sandbox.{name} must be between {minimum} and {maximum}") + return value + + @staticmethod + def _positive_float(name: str, value: Any, default: float) -> float: + if value is not None and isinstance(value, bool): + raise ValueError(f"sandbox.{name} must be a positive number") + try: + resolved = float(default if value is None else value) + except (TypeError, ValueError) as exc: + raise ValueError(f"sandbox.{name} must be a positive number") from exc + if not math.isfinite(resolved) or resolved <= 0: + raise ValueError(f"sandbox.{name} must be a positive number") + return resolved + + @staticmethod + def _bool_option(name: str, value: Any, default: bool = False) -> bool: + if value is None: + return default + if not isinstance(value, bool): + raise ValueError(f"sandbox.{name} must be true or false") + return value + + def _load_config(self) -> dict[str, Any]: + app_config = get_app_config() + sandbox_config = app_config.sandbox + model_extra = dict(getattr(sandbox_config, "model_extra", None) or {}) + unknown_top = sorted(set(model_extra) - VEFAAS_EXTRA_CONFIG_KEYS) + if unknown_top: + logger.warning("VeFaaSSandboxProvider: unknown sandbox config fields: %s", ", ".join(unknown_top)) + + nested = model_extra.get("vefaas") + if nested is not None and not isinstance(nested, Mapping): + raise ValueError("sandbox.vefaas must be a mapping") + nested_map = dict(nested or {}) + unknown_nested = sorted(set(nested_map) - (VEFAAS_EXTRA_CONFIG_KEYS - {"vefaas"})) + if unknown_nested: + logger.warning("VeFaaSSandboxProvider: unknown sandbox.vefaas config fields: %s", ", ".join(unknown_nested)) + + def opt(name: str, default: Any = None) -> Any: + if name in nested_map and nested_map[name] is not None: + return nested_map[name] + val = getattr(sandbox_config, name, None) + return default if val is None else val + + allow_insecure_http = self._bool_option("allow_insecure_http", opt("allow_insecure_http"), default=False) + region = str(opt("region") or os.environ.get("BYTEPLUS_REGION") or DEFAULT_VEFAAS_REGION).strip() + if not region: + raise ValueError("sandbox.region must not be empty") + + raw_endpoint = str(opt("endpoint") or os.environ.get("BYTEPLUS_VEFAAS_ENDPOINT") or f"https://vefaas.{region}.byteplusapi.com").strip() + endpoint = validate_endpoint_url(raw_endpoint, allow_insecure_http=allow_insecure_http) + + function_id = str(opt("function_id") or os.environ.get("BYTEPLUS_VEFAAS_SANDBOX_APP_ID") or os.environ.get("VEFAAS_FUNCTION_ID") or "").strip() + raw_sandbox_base_url = str(opt("sandbox_base_url") or os.environ.get("BYTEPLUS_VEFAAS_SANDBOX_BASE_URL") or os.environ.get("VEFAAS_SANDBOX_BASE_URL") or "").strip() + sandbox_base_url = _validate_sandbox_url_template(raw_sandbox_base_url, allow_insecure_http=allow_insecure_http) if raw_sandbox_base_url else "" + + ak_env = str(opt("access_key_env") or "BYTEPLUS_ACCESS_KEY_ID").strip() + sk_env = str(opt("secret_key_env") or "BYTEPLUS_SECRET_ACCESS_KEY").strip() + st_env = str(opt("session_token_env") or "BYTEPLUS_SESSION_TOKEN").strip() + + access_key = resolve_api_key(opt("access_key")) or resolve_api_key(os.environ.get(ak_env)) + secret_key = resolve_api_key(opt("secret_key")) or resolve_api_key(os.environ.get(sk_env)) + session_token = resolve_api_key(opt("session_token")) or resolve_api_key(os.environ.get(st_env)) + sandbox_access_token = resolve_api_key(opt("sandbox_access_token")) or resolve_api_key(os.environ.get("BYTEPLUS_VEFAAS_SANDBOX_ACCESS_TOKEN")) + sandbox_access_header = str(opt("sandbox_access_header") or DEFAULT_SANDBOX_ACCESS_HEADER).strip() + if not sandbox_access_header: + raise ValueError("sandbox.sandbox_access_header must not be empty") + + cpu_milli = self._bounded_int("cpu_milli", opt("cpu_milli"), minimum=MIN_CPU_MILLI, maximum=MAX_CPU_MILLI) + memory_mb = self._bounded_int("memory_mb", opt("memory_mb"), minimum=MIN_MEMORY_MB, maximum=MAX_MEMORY_MB) + timeout_minutes = self._bounded_int( + "timeout_minutes", + opt("timeout_minutes"), + minimum=MIN_TIMEOUT_MINUTES, + maximum=MAX_TIMEOUT_MINUTES, + default=DEFAULT_TIMEOUT_MINUTES, + ) + assert timeout_minutes is not None + + raw_metadata = opt("metadata") or {} + if not isinstance(raw_metadata, Mapping) or not all(isinstance(k, str) and isinstance(v, str) for k, v in raw_metadata.items()): + raise ValueError("sandbox.metadata must map strings to strings") + + tos_mount_cfg = self._parse_tos_mount(opt("tos_mount"), allow_insecure_http=allow_insecure_http) + + environment = dict(getattr(sandbox_config, "environment", None) or {}) + _validate_extra_env(environment) + + replicas = getattr(sandbox_config, "replicas", None) + idle_timeout = getattr(sandbox_config, "idle_timeout", None) + command_timeout = self._positive_float( + "bash_command_timeout", + getattr(sandbox_config, "bash_command_timeout", None), + DEFAULT_COMMAND_TIMEOUT, + ) + + return { + "region": region, + "endpoint": endpoint, + "function_id": function_id, + "sandbox_base_url": sandbox_base_url, + "access_key": access_key, + "secret_key": secret_key, + "session_token": session_token, + "sandbox_access_token": sandbox_access_token, + "sandbox_access_header": sandbox_access_header, + "cpu_milli": cpu_milli, + "memory_mb": memory_mb, + "timeout_minutes": timeout_minutes, + "ready_timeout": self._positive_float("ready_timeout", opt("ready_timeout"), DEFAULT_READY_TIMEOUT), + "request_timeout": self._positive_float("request_timeout", opt("request_timeout"), DEFAULT_REQUEST_TIMEOUT), + "allow_insecure_http": allow_insecure_http, + "image": getattr(sandbox_config, "image", None), + "port": getattr(sandbox_config, "port", None), + "tos_mount": tos_mount_cfg, + "metadata": dict(raw_metadata), + "environment": environment, + "skills_container_path": _validate_skills_root(app_config.skills.container_path), + "replicas": replicas if replicas is not None else self.DEFAULT_REPLICAS, + "idle_timeout": idle_timeout if idle_timeout is not None else self.DEFAULT_IDLE_TIMEOUT, + "command_timeout": command_timeout, + "ownership": getattr(sandbox_config, "ownership", None), + "stream_bridge": getattr(app_config, "stream_bridge", None), + } + + def _parse_tos_mount(self, raw: Any, *, allow_insecure_http: bool) -> dict[str, Any] | None: + if raw is None: + return None + if not isinstance(raw, Mapping): + raise ValueError("sandbox.tos_mount must be a mapping") + unknown = sorted(set(raw) - _TOS_MOUNT_KEYS) + if unknown: + logger.warning("VeFaaSSandboxProvider: unknown sandbox.tos_mount fields: %s", ", ".join(unknown)) + enabled = self._bool_option("tos_mount.enabled", raw.get("enabled"), default=False) + if not enabled: + return None + bucket = str(raw.get("bucket") or "").strip() + if not bucket: + raise ValueError("sandbox.tos_mount.bucket is required when tos_mount.enabled is true") + prefix = _sanitize_tos_prefix(str(raw.get("prefix") or "")) + local_mount_path = posixpath.normpath(str(raw.get("local_mount_path") or USER_DATA_ROOT).strip()) + if not local_mount_path.startswith("/") or local_mount_path == "/": + raise ValueError("sandbox.tos_mount.local_mount_path must be a non-root absolute path") + read_only = self._bool_option("tos_mount.read_only", raw.get("read_only"), default=False) + tos_endpoint = raw.get("endpoint") + validated_endpoint = validate_endpoint_url(str(tos_endpoint), allow_insecure_http=allow_insecure_http) if tos_endpoint else None + return { + "enabled": True, + "bucket": bucket, + "prefix": prefix, + "local_mount_path": local_mount_path, + "read_only": read_only, + "endpoint": validated_endpoint, + } + + def _get_client(self) -> VeFaaSClient: + with self._lock: + if self._client is not None: + return self._client + access_key = self._config["access_key"] + secret_key = self._config["secret_key"] + if not access_key or not secret_key: + raise ValueError("VeFaaSSandboxProvider requires BytePlus credentials: set sandbox.access_key / sandbox.secret_key or BYTEPLUS_ACCESS_KEY_ID / BYTEPLUS_SECRET_ACCESS_KEY") + client = VeFaaSClient( + endpoint=self._config["endpoint"], + region=self._config["region"], + access_key=access_key, + secret_key=secret_key, + session_token=self._config["session_token"], + timeout=self._config["request_timeout"], + allow_insecure_http=self._config["allow_insecure_http"], + ) + with self._lock: + if self._client is None: + self._client = client + return client + existing = self._client + client.close() + return existing + + def _require_provisioning_settings(self) -> tuple[str, str]: + function_id = self._config["function_id"] + sandbox_base_url = self._config["sandbox_base_url"] + if not function_id: + raise ValueError("VeFaaSSandboxProvider requires sandbox.function_id (or BYTEPLUS_VEFAAS_SANDBOX_APP_ID)") + if not sandbox_base_url: + raise ValueError("VeFaaSSandboxProvider requires sandbox.sandbox_base_url (or BYTEPLUS_VEFAAS_SANDBOX_BASE_URL)") + return function_id, sandbox_base_url + + # ── Identity & data-plane construction ─────────────────────────────── + + @staticmethod + def _sandbox_id(thread_id: str, user_id: str | None) -> str: + return derive_sandbox_scope_token(user_id=user_id or "", thread_id=thread_id) + + @staticmethod + def _thread_key(thread_id: str, user_id: str | None) -> tuple[str, str]: + return (user_id or "", thread_id) + + def _resolve_data_plane(self, remote_sandbox_id: str) -> tuple[str, dict[str, str]]: + """Build the data-plane URL and ephemeral headers for one veFaaS instance.""" + _, template = self._require_provisioning_settings() + headers: dict[str, str] = {} + if "{sandbox_id}" in template: + url = template.replace("{sandbox_id}", remote_sandbox_id) + else: + url = template + headers[INSTANCE_ROUTING_HEADER] = remote_sandbox_id + + token = self._config["sandbox_access_token"] + if token: + header_name = self._config["sandbox_access_header"] + if header_name.lower() == "authorization" and " " not in token: + headers[header_name] = f"Bearer {token}" + else: + headers[header_name] = token + return url, headers + + def _build_aio_sandbox(self, sandbox_id: str, remote_sandbox_id: str) -> AioSandbox: + url, headers = self._resolve_data_plane(remote_sandbox_id) + return AioSandbox( + id=sandbox_id, + base_url=url, + request_headers=headers or None, + default_command_timeout=self._config["command_timeout"], + lark_cli_broker=False, + ) + + def _build_tos_mount_config(self, sandbox_id: str) -> dict[str, Any] | None: + tos_cfg = self._config["tos_mount"] + if not tos_cfg: + return None + prefix = tos_cfg["prefix"] + bucket_path = f"/{prefix}/{sandbox_id}" if prefix else f"/{sandbox_id}" + mount_point: dict[str, Any] = { + "BucketName": tos_cfg["bucket"], + "BucketPath": bucket_path, + "LocalMountPath": tos_cfg["local_mount_path"], + "ReadOnly": tos_cfg["read_only"], + } + if tos_cfg.get("endpoint"): + mount_point["Endpoint"] = tos_cfg["endpoint"] + return { + "Enable": True, + "TosMountPoints": [mount_point], + } + + def _uses_tos_for_user_data(self) -> bool: + tos_cfg = self._config["tos_mount"] + return bool(tos_cfg and tos_cfg["local_mount_path"] == USER_DATA_ROOT) + + # ── Non-blocking lookups (event-loop hot path) ─────────────────────── + + def get(self, sandbox_id: str) -> Sandbox | None: + """Return an active sandbox purely from process memory (never blocks).""" + with self._lock: + tracked = self._sandboxes.get(sandbox_id) + return tracked.sandbox if tracked is not None else None + + def get_scoped( + self, + sandbox_id: str, + *, + thread_id: str, + user_id: str, + ) -> Sandbox | None: + """Return an active sandbox only when it matches ``(user_id, thread_id)``.""" + expected_id = self._sandbox_id(thread_id, user_id) + if sandbox_id != expected_id: + return None + with self._lock: + tracked = self._sandboxes.get(sandbox_id) + if tracked is None: + return None + if (tracked.user_id or "") != (user_id or "") or tracked.thread_id != thread_id: + return None + return tracked.sandbox + + # ── Warm pool & ownership maintenance ──────────────────────────────── + + def _start_idle_checker(self) -> None: + if self._config["idle_timeout"] <= 0: + return + super()._start_idle_checker() + + def _active_count_locked(self) -> int: + return len(self._sandboxes) + len(self._pending_destroys) + + def _bump_acquire_epoch_locked(self, sandbox_id: str) -> int: + self._acquire_epoch_counter += 1 + self._acquire_epoch[sandbox_id] = self._acquire_epoch_counter + return self._acquire_epoch_counter + + @contextmanager + def _acquiring(self) -> Iterator[None]: + with self._lock: + if not self._accepting or self._shutdown_called: + raise RuntimeError("VeFaaSSandboxProvider has been shut down") + self._acquires += 1 + try: + yield + finally: + with self._lock: + self._acquires -= 1 + + def _cleanup_idle_resources(self, idle_timeout: float) -> None: + self._retry_pending_destroys() + self._reap_expired_warm(idle_timeout) + + def _destroy_warm_entry(self, sandbox_id: str, entry: _TrackedVeFaaSSandbox, *, reason: str) -> bool: + return self._destroy_tracked( + entry, + reason=f"warm_pool:{reason}", + still_reapable=lambda sid=sandbox_id, expected=entry: self._warm_pool.get(sid, (None, 0.0))[0] is expected and sid not in self._sandboxes and sid not in self._acquire_inflight, + pop_warm=True, + ) + + def _evict_oldest_warm(self) -> str | None: + """Evict the oldest eligible warm entry while keeping it fenced until teardown reserves it.""" + attempted: set[str] = set() + while True: + with self._lock: + candidates = [(sid, entry, ts) for sid, (entry, ts) in self._warm_pool.items() if sid not in attempted and sid not in self._local_teardown and sid not in self._acquire_inflight and sid not in self._sandboxes] + if not candidates: + return None + sandbox_id, entry, _ = min(candidates, key=lambda item: item[2]) + attempted.add(sandbox_id) + if self._destroy_warm_entry(sandbox_id, entry, reason="replica_enforcement"): + return sandbox_id + + def _reap_expired_warm(self, idle_timeout: float | None = None) -> None: + """Reap expired warm entries using per-sandbox local teardown reservations.""" + timeout = float(self._config.get("idle_timeout", self.DEFAULT_IDLE_TIMEOUT) if idle_timeout is None else idle_timeout) + if timeout <= 0: + return + now = time.monotonic() + with self._lock: + expired = [(sandbox_id, entry) for sandbox_id, (entry, timestamp) in self._warm_pool.items() if now - timestamp > timeout and sandbox_id not in self._local_teardown and sandbox_id not in self._acquire_inflight] + for sandbox_id, entry in expired: + self._destroy_warm_entry(sandbox_id, entry, reason="idle_timeout") + + def _start_renewal_thread(self) -> None: + if not self._ownership.supports_cross_process: + return + if self._renewal_thread is not None and self._renewal_thread.is_alive(): + return + self._renewal_stop.clear() + self._renewal_thread = threading.Thread( + target=self._renewal_loop, + name="vefaas-sandbox-lease-renewer", + daemon=True, + ) + self._renewal_thread.start() + + def _stop_renewal_thread(self) -> None: + self._renewal_stop.set() + thread = self._renewal_thread + if thread is not None and thread.is_alive() and thread is not threading.current_thread(): + thread.join(timeout=5) + if thread.is_alive(): + raise RuntimeError("veFaaS ownership renewal thread is still running after stop timeout") + + def _renewal_loop(self) -> None: + interval = self._ownership_config.renewal_interval_seconds + while not self._renewal_stop.wait(interval): + try: + self._renew_leases_once() + except Exception: + logger.exception("Error in veFaaS sandbox ownership renewal loop") + + def _renew_leases_once(self) -> None: + with self._lock: + tracked_ids = sorted(set(self._sandboxes) | set(self._warm_pool)) + for sandbox_id in tracked_ids: + with self._lock: + if sandbox_id in self._local_teardown or sandbox_id in self._acquire_inflight: + continue + epoch = self._acquire_epoch.get(sandbox_id, 0) + try: + outcome = self._ownership.renew(sandbox_id) + except OwnershipBackendError as exc: + logger.warning("Failed to renew ownership lease for veFaaS sandbox %s: %s", sandbox_id, exc) + continue + if outcome is RenewOutcome.RENEWED: + continue + if outcome is RenewOutcome.LAPSED: + try: + reclaimed = self._ownership.claim(sandbox_id) + except OwnershipBackendError as exc: + logger.warning("Failed to re-claim lapsed lease for veFaaS sandbox %s: %s", sandbox_id, exc) + continue + if not reclaimed: + self._forget_lost_sandbox(sandbox_id, expected_epoch=epoch) + elif outcome is RenewOutcome.LOST: + self._forget_lost_sandbox(sandbox_id, expected_epoch=epoch) + + def _forget_lost_sandbox(self, sandbox_id: str, *, expected_epoch: int | None = None) -> None: + """Stop tracking a sandbox whose ownership moved to a peer (never kill it).""" + with self._lock: + if sandbox_id in self._local_teardown: + logger.debug("Not dropping veFaaS sandbox %s: this instance is tearing it down", sandbox_id) + return + if sandbox_id in self._acquire_inflight: + logger.info("Not dropping veFaaS sandbox %s: an acquire is publishing ownership for it", sandbox_id) + return + if expected_epoch is not None and self._acquire_epoch.get(sandbox_id, 0) != expected_epoch: + logger.info("Not dropping veFaaS sandbox %s: this instance re-acquired it after the lease check", sandbox_id) + return + active = self._sandboxes.pop(sandbox_id, None) + warm = self._warm_pool.pop(sandbox_id, None) + self._acquire_epoch.pop(sandbox_id, None) + for key in [k for k, v in self._thread_sandboxes.items() if v == sandbox_id]: + self._thread_sandboxes.pop(key, None) + tracked = active or (warm[0] if warm is not None else None) + if tracked is not None: + logger.info("Forgetting veFaaS sandbox %s after ownership moved to a peer", sandbox_id) + tracked.sandbox.close() + + def _register_signal_handlers(self) -> None: + if host_owns_sandbox_shutdown(): + return + if threading.current_thread() is not threading.main_thread(): + return + for sig_name in ("SIGTERM", "SIGINT"): + sig = getattr(signal, sig_name, None) + if sig is None: + continue + prev = signal.getsignal(sig) + + def _handler(signum: int, frame: Any, _prev: Any = prev) -> None: + try: + self.shutdown() + except Exception: + logger.exception("veFaaS sandbox shutdown failed while handling signal %s; forwarding signal", signum) + if callable(_prev): + _prev(signum, frame) + elif _prev == signal.SIG_DFL: + signal.signal(signum, signal.SIG_DFL) + signal.raise_signal(signum) + + try: + signal.signal(sig, _handler) + except (OSError, ValueError): + # Signal registration is unsupported outside the main thread or in restricted runtimes. + logger.debug("Skipping %s handler registration for VeFaaSSandboxProvider", sig_name) + + # ── Acquisition ────────────────────────────────────────────────────── + + def acquire(self, thread_id: str | None = None, *, user_id: str | None = None) -> str: + with self._acquiring(): + if thread_id is None: + sandbox_id = str(uuid.uuid4())[:8] + with self._lock: + self._acquire_inflight[sandbox_id] = self._acquire_inflight.get(sandbox_id, 0) + 1 + try: + tracked = self._create_new_sandbox(sandbox_id, thread_id=None, user_id=user_id) + with self._lock: + if not self._accepting or self._shutdown_called or sandbox_id in self._local_teardown: + self._pending_destroys[tracked.remote_sandbox_id] = tracked + rollback = True + else: + self._sandboxes[sandbox_id] = tracked + self._bump_acquire_epoch_locked(sandbox_id) + rollback = False + finally: + with self._lock: + remaining = self._acquire_inflight.get(sandbox_id, 1) - 1 + if remaining <= 0: + self._acquire_inflight.pop(sandbox_id, None) + else: + self._acquire_inflight[sandbox_id] = remaining + if rollback: + self._destroy_tracked(tracked, reason="created_during_shutdown", require_pending=True) + raise RuntimeError("VeFaaSSandboxProvider shut down during acquire") + return sandbox_id + + key = self._thread_key(thread_id, user_id) + sandbox_id = self._sandbox_id(thread_id, user_id) + with self._acquire_serializer.hold(sandbox_id): + return self._acquire_scope_locked(key, sandbox_id, thread_id=thread_id, user_id=user_id) + + async def acquire_async(self, thread_id: str | None = None, *, user_id: str | None = None) -> str: + """Acquire a veFaaS sandbox off the event loop via the serializer's dedicated executor.""" + fn = partial(self.acquire, thread_id, user_id=user_id) + return await self._acquire_serializer.run_on_executor(fn) + + def _acquire_scope_locked( + self, + key: tuple[str, str], + sandbox_id: str, + *, + thread_id: str, + user_id: str | None, + ) -> str: + with self._lock: + if not self._accepting or self._shutdown_called: + raise RuntimeError("VeFaaSSandboxProvider has been shut down") + if sandbox_id in self._local_teardown: + raise RuntimeError(f"veFaaS sandbox {sandbox_id} is currently being torn down") + existing_id = self._thread_sandboxes.get(key) + active = self._sandboxes.get(existing_id) if existing_id is not None else None + if active is not None: + return active.sandbox_id + self._acquire_inflight[sandbox_id] = self._acquire_inflight.get(sandbox_id, 0) + 1 + + try: + reclaimed = self._reclaim_warm_pool(sandbox_id, key=key) + if reclaimed is not None: + return reclaimed + + # Fence any quarantined remote generations before creating or adopting a replacement. + self._drain_quarantine_for_scope(sandbox_id) + + discovered = self._discover_existing_sandbox(sandbox_id, thread_id=thread_id, user_id=user_id) + if discovered is not None: + with self._lock: + if not self._accepting or self._shutdown_called or sandbox_id in self._local_teardown: + rollback = True + else: + self._sandboxes[sandbox_id] = discovered + self._thread_sandboxes[key] = sandbox_id + self._bump_acquire_epoch_locked(sandbox_id) + rollback = False + if rollback: + discovered.sandbox.close() + raise RuntimeError("VeFaaSSandboxProvider shut down during acquire") + return sandbox_id + + tracked = self._create_new_sandbox(sandbox_id, thread_id=thread_id, user_id=user_id) + with self._lock: + if not self._accepting or self._shutdown_called or sandbox_id in self._local_teardown: + self._pending_destroys[tracked.remote_sandbox_id] = tracked + rollback = True + else: + self._sandboxes[sandbox_id] = tracked + self._thread_sandboxes[key] = sandbox_id + self._bump_acquire_epoch_locked(sandbox_id) + rollback = False + if rollback: + self._destroy_tracked(tracked, reason="created_during_shutdown", require_pending=True) + raise RuntimeError("VeFaaSSandboxProvider shut down during acquire") + return sandbox_id + finally: + with self._lock: + remaining = self._acquire_inflight.get(sandbox_id, 1) - 1 + if remaining <= 0: + self._acquire_inflight.pop(sandbox_id, None) + else: + self._acquire_inflight[sandbox_id] = remaining + + def _reclaim_warm_pool(self, sandbox_id: str, *, key: tuple[str, str]) -> str | None: + with self._lock: + if sandbox_id in self._local_teardown: + raise RuntimeError(f"veFaaS sandbox {sandbox_id} is currently being torn down") + warm_entry = self._warm_pool.get(sandbox_id) + if warm_entry is None: + return None + tracked = warm_entry[0] + url, headers = self._resolve_data_plane(tracked.remote_sandbox_id) + healthy = wait_for_sandbox_ready(url, timeout=5, headers=headers) + if not healthy: + with self._lock: + removed = self._warm_pool.pop(sandbox_id, None) + if removed is not None: + self._pending_destroys[removed[0].remote_sandbox_id] = removed[0] + if removed is not None: + self._destroy_tracked(removed[0], reason="warm_health_check_failed", require_pending=True) + return None + + if not self._ownership.take(sandbox_id): + with self._lock: + removed = self._warm_pool.pop(sandbox_id, None) + if removed is not None: + removed[0].sandbox.close() + raise RuntimeError(f"veFaaS sandbox {sandbox_id} is currently being destroyed by a peer") + + function_id, _ = self._require_provisioning_settings() + try: + self._get_client().set_sandbox_timeout( + function_id, + tracked.remote_sandbox_id, + timeout_minutes=self._config["timeout_minutes"], + ) + except Exception as exc: + logger.warning("Failed to extend veFaaS timeout for %s on reclaim: %s", tracked.remote_sandbox_id, exc) + + with self._lock: + removed = self._warm_pool.pop(sandbox_id, None) + if removed is None: + return None + if not self._accepting or self._shutdown_called or sandbox_id in self._local_teardown: + self._pending_destroys[removed[0].remote_sandbox_id] = removed[0] + rollback = True + else: + self._sandboxes[sandbox_id] = removed[0] + self._thread_sandboxes[key] = sandbox_id + self._bump_acquire_epoch_locked(sandbox_id) + rollback = False + if rollback: + self._destroy_tracked(removed[0], reason="reclaimed_during_shutdown", require_pending=True) + raise RuntimeError("VeFaaSSandboxProvider shut down during acquire") + logger.info("Reclaimed warm veFaaS sandbox %s (remote=%s)", sandbox_id, tracked.remote_sandbox_id) + return sandbox_id + + @contextmanager + def _remote_init_lock(self, remote_sandbox_id: str) -> Iterator[None]: + """Serialize marker checks and initialization for the same remote instance in-process.""" + key = (str(self._config.get("endpoint") or ""), str(self._config.get("function_id") or ""), remote_sandbox_id) + with _REMOTE_INIT_LOCKS_GUARD: + lock, refs = _REMOTE_INIT_LOCKS.get(key, (threading.RLock(), 0)) + _REMOTE_INIT_LOCKS[key] = (lock, refs + 1) + try: + with lock: + yield + finally: + with _REMOTE_INIT_LOCKS_GUARD: + entry = _REMOTE_INIT_LOCKS.get(key) + if entry is not None: + cur_lock, cur_refs = entry + if cur_refs <= 1: + _REMOTE_INIT_LOCKS.pop(key, None) + else: + _REMOTE_INIT_LOCKS[key] = (cur_lock, cur_refs - 1) + + @staticmethod + def _write_init_marker(sandbox: AioSandbox, sandbox_id: str) -> None: + """Persist an ephemeral marker proving DeerFlow finished sandbox initialization.""" + sandbox.update_file(_INIT_MARKER_PATH, f"{sandbox_id}\n".encode()) + + @staticmethod + def _probe_init_marker(sandbox: AioSandbox, sandbox_id: str) -> Literal["initialized", "missing", "invalid"]: + """Check whether an existing remote instance completed DeerFlow initialization.""" + quoted_marker = shlex.quote(_INIT_MARKER_PATH) + output = sandbox.execute_command(f"set +e; ( if [ -f {quoted_marker} ] && [ ! -L {quoted_marker} ]; then printf 'INIT_MARKER:%s\\n' \"$(cat {quoted_marker})\"; else echo 'INIT_MARKER:MISSING'; fi )") + for line in output.splitlines(): + stripped = line.strip() + if stripped == f"INIT_MARKER:{sandbox_id}": + return "initialized" + if stripped == "INIT_MARKER:MISSING": + return "missing" + return "invalid" + + def _initialize_remote_sandbox( + self, + sandbox: AioSandbox, + *, + sandbox_id: str, + thread_id: str | None, + user_id: str | None, + ) -> None: + """Create workspace directories, restore host thread files/skills, and write init marker.""" + bootstrap_output = sandbox.execute_command(_BOOTSTRAP_COMMAND) + if not any(line.strip() == _BOOTSTRAP_OK_MARKER for line in bootstrap_output.splitlines()): + raise RuntimeError(f"veFaaS sandbox bootstrap failed for {sandbox_id}: {bootstrap_output[:200]}") + + if thread_id is not None and user_id: + if not self._uses_tos_for_user_data(): + self._restore_thread_files(sandbox, thread_id=thread_id, user_id=user_id) + self._upload_shared_skills(sandbox, thread_id=thread_id, user_id=user_id) + + self._write_init_marker(sandbox, sandbox_id) + + def _discover_existing_sandbox( + self, + sandbox_id: str, + *, + thread_id: str, + user_id: str | None, + ) -> _TrackedVeFaaSSandbox | None: + function_id, _ = self._require_provisioning_settings() + client = self._get_client() + expected_metadata = { + META_KEY_PROVIDER: META_VAL_PROVIDER, + META_KEY_SANDBOX_ID: sandbox_id, + } + records = client.list_sandboxes(function_id, metadata=expected_metadata) + with self._lock: + quarantined = set(self._quarantined_remote_ids.get(sandbox_id, set())) + + for record in records: + if record.id in quarantined or not record.is_running: + continue + if any(record.metadata.get(k) != v for k, v in expected_metadata.items()): + continue + url, headers = self._resolve_data_plane(record.id) + if not wait_for_sandbox_ready(url, timeout=5, headers=headers): + continue + sandbox = self._build_aio_sandbox(sandbox_id, record.id) + adopt_deadline = time.monotonic() + min(self._config["ready_timeout"], _ADOPT_INIT_WAIT_SECONDS) + adopted = False + while True: + with self._remote_init_lock(record.id): + try: + init_state = self._probe_init_marker(sandbox, sandbox_id) + except Exception as exc: + logger.warning("Failed to verify initialization state for veFaaS sandbox %s (remote=%s): %s", sandbox_id, record.id, self._redact(exc)) + break + if init_state == "invalid": + logger.warning("Refusing to adopt veFaaS sandbox %s (remote=%s): invalid or mismatched initialization marker", sandbox_id, record.id) + break + if init_state == "initialized": + try: + taken = self._ownership.take(sandbox_id) + except OwnershipBackendError: + sandbox.close() + raise + if not taken: + sandbox.close() + raise RuntimeError(f"veFaaS sandbox {sandbox_id} is being destroyed by a peer") + adopted = True + break + + # Marker is missing: only an exclusive claim (never a takeover from a live + # peer) may initialize this remote instance, preventing a second worker from + # restoring older host files over a peer's live workspace. + try: + claimed = self._ownership.claim(sandbox_id) + except OwnershipBackendError: + sandbox.close() + raise + if claimed: + try: + init_state = self._probe_init_marker(sandbox, sandbox_id) + except Exception as exc: + logger.warning("Failed to re-verify initialization state for veFaaS sandbox %s (remote=%s): %s", sandbox_id, record.id, self._redact(exc)) + try: + self._ownership.release(sandbox_id) + except OwnershipBackendError as rel_exc: + logger.warning("Failed to release ownership after failed probe on veFaaS sandbox %s: %s", sandbox_id, rel_exc) + break + if init_state == "invalid": + logger.warning("Refusing to adopt veFaaS sandbox %s (remote=%s): invalid or mismatched initialization marker", sandbox_id, record.id) + try: + self._ownership.release(sandbox_id) + except OwnershipBackendError as rel_exc: + logger.warning("Failed to release ownership after refusing invalid veFaaS sandbox %s: %s", sandbox_id, rel_exc) + break + if init_state == "missing": + logger.info("Completing DeerFlow initialization before adopting veFaaS sandbox %s (remote=%s)", sandbox_id, record.id) + try: + self._initialize_remote_sandbox( + sandbox, + sandbox_id=sandbox_id, + thread_id=thread_id, + user_id=user_id, + ) + except Exception: + sandbox.close() + self._rollback_remote_sandbox(sandbox_id, record.id, release_ownership=True) + raise + adopted = True + break + + # Outside _remote_init_lock: another live worker holds ownership while this + # sandbox is still uninitialized. Wait briefly for it to publish the marker + # or drop ownership instead of stealing and restoring over live files. + remaining = adopt_deadline - time.monotonic() + if remaining <= 0: + sandbox.close() + raise RuntimeError(f"Timed out waiting for peer to initialize veFaaS sandbox {sandbox_id} (remote={record.id})") + time.sleep(min(_ADOPT_INIT_POLL_INTERVAL_SECONDS, remaining)) + + if not adopted: + sandbox.close() + continue + try: + client.set_sandbox_timeout( + function_id, + record.id, + timeout_minutes=self._config["timeout_minutes"], + ) + except Exception as exc: + logger.warning("Failed to refresh timeout on discovered veFaaS sandbox %s: %s", record.id, exc) + logger.info("Adopted existing veFaaS sandbox %s (remote=%s)", sandbox_id, record.id) + return _TrackedVeFaaSSandbox( + sandbox_id=sandbox_id, + remote_sandbox_id=record.id, + sandbox=sandbox, + thread_id=thread_id, + user_id=user_id, + ) + return None + + def _wait_for_remote_running(self, function_id: str, remote_sandbox_id: str, *, deadline: float) -> VeFaaSSandboxRecord: + client = self._get_client() + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError(f"Timed out waiting for veFaaS sandbox {remote_sandbox_id} to reach Running state") + record = client.describe_sandbox(function_id, remote_sandbox_id) + if record is None: + raise RuntimeError(f"veFaaS sandbox {remote_sandbox_id} disappeared before becoming ready") + if record.is_running: + return record + if record.is_terminal_failure: + detail = record.error_message or record.error_code or record.status + raise RuntimeError(f"veFaaS sandbox {remote_sandbox_id} entered terminal state {record.status!r}: {detail}") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise TimeoutError(f"Timed out waiting for veFaaS sandbox {remote_sandbox_id} to reach Running state") + time.sleep(min(_POLL_STATUS_INTERVAL_SECONDS, remaining)) + + def _create_new_sandbox( + self, + sandbox_id: str, + *, + thread_id: str | None, + user_id: str | None, + ) -> _TrackedVeFaaSSandbox: + function_id, _ = self._require_provisioning_settings() + replicas, total = self._replica_count() + if total >= replicas: + evicted = self._evict_oldest_warm() + self._log_replicas_soft_cap(replicas, sandbox_id, evicted) + + client = self._get_client() + metadata = dict(self._config["metadata"]) + metadata[META_KEY_PROVIDER] = META_VAL_PROVIDER + metadata[META_KEY_SANDBOX_ID] = sandbox_id + + image_info: dict[str, Any] | None = None + if self._config["image"] or self._config["port"]: + image_info = {} + if self._config["image"]: + image_info["Image"] = self._config["image"] + if self._config["port"]: + image_info["Port"] = self._config["port"] + + tos_mount_config = self._build_tos_mount_config(sandbox_id) + remote_sandbox_id = client.create_sandbox( + function_id, + cpu_milli=self._config["cpu_milli"], + memory_mb=self._config["memory_mb"], + timeout_minutes=self._config["timeout_minutes"], + metadata=metadata, + envs=self._config["environment"] or None, + instance_image_info=image_info, + instance_tos_mount_config=tos_mount_config, + session_id=sandbox_id, + ) + + sandbox: AioSandbox | None = None + ownership_taken = False + try: + # Publish ownership immediately after CreateSandbox (while the instance is + # still starting up) so a concurrent peer cannot claim and initialize it + # before this worker finishes bootstrapping. + if not self._ownership.take(sandbox_id): + raise RuntimeError(f"Refused to hand out veFaaS sandbox {sandbox_id}: peer holds teardown lease") + ownership_taken = True + + deadline = time.monotonic() + self._config["ready_timeout"] + self._wait_for_remote_running(function_id, remote_sandbox_id, deadline=deadline) + + url, headers = self._resolve_data_plane(remote_sandbox_id) + remaining = max(1, int(math.ceil(deadline - time.monotonic()))) + if not wait_for_sandbox_ready(url, timeout=remaining, headers=headers): + raise TimeoutError(f"veFaaS sandbox {remote_sandbox_id} did not become HTTP-ready within {self._config['ready_timeout']}s") + + with self._remote_init_lock(remote_sandbox_id): + sandbox = self._build_aio_sandbox(sandbox_id, remote_sandbox_id) + init_state = self._probe_init_marker(sandbox, sandbox_id) + if init_state == "invalid": + raise RuntimeError(f"Refused to hand out veFaaS sandbox {sandbox_id}: invalid initialization marker") + if init_state == "missing": + self._initialize_remote_sandbox( + sandbox, + sandbox_id=sandbox_id, + thread_id=thread_id, + user_id=user_id, + ) + + return _TrackedVeFaaSSandbox( + sandbox_id=sandbox_id, + remote_sandbox_id=remote_sandbox_id, + sandbox=sandbox, + thread_id=thread_id, + user_id=user_id, + ) + except Exception: + if sandbox is not None: + sandbox.close() + self._rollback_remote_sandbox(sandbox_id, remote_sandbox_id, release_ownership=ownership_taken) + raise + + def _rollback_remote_sandbox(self, sandbox_id: str, remote_sandbox_id: str, *, release_ownership: bool) -> None: + entry = _PendingRollback( + sandbox_id=sandbox_id, + remote_sandbox_id=remote_sandbox_id, + release_ownership=release_ownership, + ) + self._cleanup_rollback(entry, reason="rollback") + + def _cleanup_rollback(self, entry: _PendingRollback, *, reason: str, require_pending: bool = False) -> bool: + """Kill and confirm absence of a failed provisioning generation. + + Returns ``True`` only once the remote instance is authoritatively absent + (and any owned lease released). Failed rollbacks remain queued in + ``_pending_rollbacks`` and ``_quarantined_remote_ids`` so background + retries and ``shutdown()`` keep retrying until deletion is confirmed. + """ + sandbox_id = entry.sandbox_id + remote_id = entry.remote_sandbox_id + with self._lock: + if require_pending and self._pending_rollbacks.get(remote_id) is not entry: + return False + self._pending_rollbacks[remote_id] = entry + if remote_id in self._destroying_remote_ids: + return False + self._destroying_remote_ids.add(remote_id) + + confirmed = False + try: + function_id = self._config["function_id"] + self._get_client().kill_sandbox(function_id, remote_id) + if self._confirm_remote_absent(function_id, remote_id): + confirmed = True + else: + logger.warning( + "veFaaS rollback sandbox %s (remote=%s) still present after KillSandbox (%s); keeping quarantine fence", + sandbox_id, + remote_id, + reason, + ) + except Exception as exc: + logger.warning( + "Failed to roll back veFaaS sandbox %s (remote=%s, %s): %s", + sandbox_id, + remote_id, + reason, + self._redact(exc), + ) + finally: + if confirmed and entry.release_ownership: + try: + self._ownership.release(sandbox_id) + except OwnershipBackendError as exc: + logger.warning("Failed to release ownership after veFaaS rollback for %s: %s", sandbox_id, exc) + confirmed = False + with self._lock: + self._destroying_remote_ids.discard(remote_id) + if confirmed: + self._pending_rollbacks.pop(remote_id, None) + bucket = self._quarantined_remote_ids.get(sandbox_id) + if bucket is not None: + bucket.discard(remote_id) + if not bucket: + self._quarantined_remote_ids.pop(sandbox_id, None) + else: + self._quarantined_remote_ids.setdefault(sandbox_id, set()).add(remote_id) + return confirmed + + def _redact(self, value: object) -> str: + text = redact_secret(value, self._config.get("secret_key")) + text = redact_secret(text, self._config.get("access_key")) + text = redact_secret(text, self._config.get("session_token")) + text = redact_secret(text, self._config.get("sandbox_access_token")) + return text + + # ── Quarantine & authoritative teardown ────────────────────────────── + + def _confirm_remote_absent(self, function_id: str, remote_sandbox_id: str) -> bool: + """Confirm absence authoritatively via ``DescribeSandbox`` (API errors raise).""" + record = self._get_client().describe_sandbox(function_id, remote_sandbox_id) + if record is None: + return True + return record.is_terminal_failure + + def _drain_quarantine_for_scope(self, sandbox_id: str) -> None: + with self._lock: + quarantined = sorted(self._quarantined_remote_ids.get(sandbox_id, set())) + if not quarantined: + return + function_id, _ = self._require_provisioning_settings() + client = self._get_client() + still_present: list[str] = [] + for remote_id in quarantined: + with self._lock: + pending_rollback = self._pending_rollbacks.get(remote_id) + pending_destroy = self._pending_destroys.get(remote_id) + if pending_rollback is not None: + if not self._cleanup_rollback(pending_rollback, reason="drain_quarantine", require_pending=True): + with self._lock: + if remote_id in self._quarantined_remote_ids.get(sandbox_id, set()): + still_present.append(remote_id) + continue + if pending_destroy is not None: + self._destroy_tracked(pending_destroy, reason="drain_quarantine", require_pending=True) + with self._lock: + if remote_id in self._quarantined_remote_ids.get(sandbox_id, set()): + still_present.append(remote_id) + continue + try: + client.kill_sandbox(function_id, remote_id) + if self._confirm_remote_absent(function_id, remote_id): + with self._lock: + bucket = self._quarantined_remote_ids.get(sandbox_id) + if bucket is not None: + bucket.discard(remote_id) + if not bucket: + self._quarantined_remote_ids.pop(sandbox_id, None) + else: + still_present.append(remote_id) + except Exception as exc: + raise RuntimeError(f"Cannot replace quarantined veFaaS sandbox {sandbox_id} (remote={remote_id}): {self._redact(exc)}") from exc + if still_present: + raise RuntimeError(f"Quarantined veFaaS sandbox generation(s) still active for {sandbox_id}: {', '.join(still_present)}") + + def _destroy_tracked( + self, + tracked: _TrackedVeFaaSSandbox, + *, + reason: str, + still_reapable: Callable[[], bool] | None = None, + pop_warm: bool = False, + require_pending: bool = False, + ) -> bool: + remote_id = tracked.remote_sandbox_id + sandbox_id = tracked.sandbox_id + with self._lock: + if require_pending and self._pending_destroys.get(remote_id) is not tracked: + return False + if still_reapable is not None and (sandbox_id in self._local_teardown or not still_reapable()): + return False + if remote_id in self._destroying_remote_ids or remote_id in self._mirroring_output_ids: + return False + self._local_teardown[sandbox_id] = self._local_teardown.get(sandbox_id, 0) + 1 + self._destroying_remote_ids.add(remote_id) + self._pending_destroys[remote_id] = tracked + + tracked.sandbox.close() + confirmed = False + release_lease = False + try: + claimed = self._ownership.claim(sandbox_id, for_destroy=True) + if not claimed: + # Owned by a live peer: never destroy remotely; drop local pending state. + logger.info("Skipping remote kill for veFaaS sandbox %s (%s): owned by a peer", sandbox_id, reason) + confirmed = True + else: + release_lease = True + function_id = self._config["function_id"] + self._get_client().kill_sandbox(function_id, remote_id) + if self._confirm_remote_absent(function_id, remote_id): + confirmed = True + else: + logger.warning("veFaaS sandbox %s (remote=%s) still present after KillSandbox (%s); keeping quarantine fence", sandbox_id, remote_id, reason) + except Exception as exc: + logger.warning("Failed to destroy veFaaS sandbox %s (remote=%s, %s): %s", sandbox_id, remote_id, reason, self._redact(exc)) + finally: + if confirmed and release_lease: + try: + self._ownership.release(sandbox_id) + except OwnershipBackendError as exc: + logger.warning("Failed to release ownership lease for destroyed veFaaS sandbox %s: %s", sandbox_id, exc) + confirmed = False + with self._lock: + remaining_teardowns = self._local_teardown.get(sandbox_id, 1) - 1 + if remaining_teardowns <= 0: + self._local_teardown.pop(sandbox_id, None) + else: + self._local_teardown[sandbox_id] = remaining_teardowns + if pop_warm and self._warm_pool.get(sandbox_id, (None, 0.0))[0] is tracked: + self._warm_pool.pop(sandbox_id, None) + self._destroying_remote_ids.discard(remote_id) + if confirmed: + self._pending_destroys.pop(remote_id, None) + bucket = self._quarantined_remote_ids.get(sandbox_id) + if bucket is not None: + bucket.discard(remote_id) + if not bucket: + self._quarantined_remote_ids.pop(sandbox_id, None) + else: + self._quarantined_remote_ids.setdefault(sandbox_id, set()).add(remote_id) + return True + + def _retry_pending_destroys(self) -> None: + with self._lock: + pending = list(self._pending_destroys.values()) + pending_rollbacks = list(self._pending_rollbacks.values()) + for tracked in pending: + self._destroy_tracked(tracked, reason="retry_destroy", require_pending=True) + for rollback in pending_rollbacks: + self._cleanup_rollback(rollback, reason="retry_rollback", require_pending=True) + + # ── Upload-based file restoration & per-agent skills isolation ─────── + + @staticmethod + def _add_tree_to_tar(archive: tarfile.TarFile, source: Path, arc_prefix: str, budget: _UploadBudget) -> bool: + for dirpath, dirnames, filenames in os.walk(source, followlinks=False): + dirnames.sort() + filenames.sort() + current_dir = Path(dirpath) + rel_dir = current_dir.relative_to(source) + # Prune symlinked directories so a local link cannot smuggle host files. + kept_dirs: list[str] = [] + for dname in dirnames: + candidate = current_dir / dname + if candidate.is_symlink(): + continue + kept_dirs.append(dname) + dirnames[:] = kept_dirs + + for fname in filenames: + file_path = current_dir / fname + if file_path.is_symlink(): + continue + try: + st = file_path.stat() + except OSError: + continue + if not stat.S_ISREG(st.st_mode): + continue + if not budget.admit(st.st_size): + return False + rel_file = (rel_dir / fname).as_posix() if rel_dir != Path(".") else fname + arcname = f"{arc_prefix}/{rel_file}" + archive.add(file_path, arcname=arcname, recursive=False) + return True + + def _upload_trees( + self, + sandbox: AioSandbox, + sources: list[tuple[Path, str]], + *, + dest_root: str, + replace: tuple[str, ...] = (), + ) -> bool: + budget = _UploadBudget(max_files=_MAX_UPLOAD_FILES, max_bytes=_MAX_UPLOAD_BYTES) + complete = True + buffer = io.BytesIO() + with tarfile.open(fileobj=buffer, mode="w:gz") as archive: + for source, arc_prefix in sources: + for part in (source, *source.parents): + if part.is_symlink(): + raise ValueError(f"Refusing symlinked upload root for {arc_prefix}") + if not source.is_dir(): + continue + if not self._add_tree_to_tar(archive, source, arc_prefix, budget): + complete = False + break + + if not complete and replace: + return False + if budget.files == 0 and not replace: + return complete + + token = uuid.uuid4().hex + remote_tar = f"/tmp/deerflow-vefaas-{token}.tar.gz" + sandbox.update_file(remote_tar, buffer.getvalue()) + + quoted_root = shlex.quote(dest_root) + quoted_tar = shlex.quote(remote_tar) + # Always run in a subshell with ``set +e`` outside so ``set -e``, ``trap EXIT``, + # and ``exit`` never poison AioSandbox's persistent PTY shell session. + if replace: + staging_dir = f"{dest_root}/.vefaas-stage-{token}" + quoted_stage = shlex.quote(staging_dir) + stage_dirs = " ".join(shlex.quote(f"{staging_dir}/{name}") for name in replace) + swap_steps = " ".join(f"rm -rf -- {shlex.quote(f'{dest_root}/{name}')}; mv -- {shlex.quote(f'{staging_dir}/{name}')} {shlex.quote(f'{dest_root}/{name}')};" for name in replace) + script = ( + f"set +e; ( set -e; trap 'rm -rf -- {quoted_tar} {quoted_stage}' EXIT; " + f"if [ -L {quoted_root} ]; then echo 'Refusing symlinked destination' >&2; exit 2; fi; " + f"mkdir -p -- {quoted_root} {quoted_stage} {stage_dirs}; " + f"tar -xzf {quoted_tar} -C {quoted_stage} --no-same-owner; " + f"{swap_steps} echo UPLOAD_OK )" + ) + else: + script = ( + f"set +e; ( set -e; trap 'rm -f -- {quoted_tar}' EXIT; " + f"if [ -L {quoted_root} ]; then echo 'Refusing symlinked destination' >&2; exit 2; fi; " + f"mkdir -p -- {quoted_root}; " + f"tar -xzf {quoted_tar} -C {quoted_root} --no-same-owner; " + f"echo UPLOAD_OK )" + ) + output = sandbox.execute_command(script) + if "UPLOAD_OK" not in output: + raise RuntimeError(f"veFaaS upload into {dest_root} failed: {output[:200]}") + return complete + + def _restore_thread_files(self, sandbox: AioSandbox, *, thread_id: str, user_id: str) -> None: + from deerflow.config.paths import get_paths + + paths = get_paths() + sources = [ + (paths.sandbox_uploads_dir(thread_id, user_id=user_id), "uploads"), + (paths.sandbox_work_dir(thread_id, user_id=user_id), "workspace"), + (paths.sandbox_outputs_dir(thread_id, user_id=user_id), "outputs"), + ] + if not self._upload_trees(sandbox, sources, dest_root=USER_DATA_ROOT): + logger.warning( + "Thread files for veFaaS sandbox %s exceed %d files or %d bytes; remaining files were skipped", + sandbox.id, + _MAX_UPLOAD_FILES, + _MAX_UPLOAD_BYTES, + ) + + def _upload_shared_skills(self, sandbox: AioSandbox, *, thread_id: str, user_id: str) -> None: + from deerflow.config.paths import get_paths + from deerflow.skills.projection import ensure_skill_projections + from deerflow.skills.storage import get_or_new_user_skill_storage + + try: + if get_paths().thread_skills_view_dir(thread_id, user_id=user_id).exists(): + return + storage = get_or_new_user_skill_storage(user_id, app_config=get_app_config()) + projection = ensure_skill_projections(storage) + self._upload_skills(sandbox, projection) + except Exception as exc: + logger.warning("Could not upload shared skills projection for veFaaS sandbox %s: %s", sandbox.id, exc) + + def _upload_skills(self, sandbox: AioSandbox, projection: SkillProjectionPaths) -> None: + sources = [(Path(getattr(projection, category)), category) for category in SKILL_CATEGORIES] + if not self._upload_trees( + sandbox, + sources, + dest_root=self._config["skills_container_path"], + replace=SKILL_CATEGORIES, + ): + raise RuntimeError("Skills projection exceeds the veFaaS upload limit") + + def sync_agent_skills( + self, + sandbox_id: str, + *, + thread_id: str, + user_id: str, + projection: SkillProjectionPaths, + ) -> None: + """Atomically replace the managed skills tree inside the veFaaS sandbox.""" + with self._acquire_serializer.hold(sandbox_id): + with self._lock: + tracked = self._sandboxes.get(sandbox_id) + if tracked is None: + raise RuntimeError(f"veFaaS sandbox {sandbox_id} is not available for skill synchronization") + if (tracked.user_id or "") != (user_id or "") or tracked.thread_id != thread_id: + raise RuntimeError(f"veFaaS sandbox {sandbox_id} does not match target identity ({user_id}, {thread_id})") + self._upload_skills(tracked.sandbox, projection) + + # ── Release & bounded output mirroring ─────────────────────────────── + + def release(self, sandbox_id: str) -> None: + """Mirror outputs (when not TOS-mounted) and park the sandbox in the warm pool.""" + with self._lock: + if sandbox_id not in self._sandboxes: + return + try: + with self._acquire_serializer.hold(sandbox_id): + self._release_scope_locked(sandbox_id) + except AcquireSerializerClosed: + with self._lock: + untracked = sandbox_id not in self._sandboxes + if not untracked: + raise + + def _release_scope_locked(self, sandbox_id: str) -> None: + with self._lock: + tracked = self._sandboxes.get(sandbox_id) + if tracked is None: + return + # Read pending session creates before requires_container_recycle so a + # pending -> ambiguous transition cannot slip into the warm pool. + needs_recycle = getattr(tracked.sandbox, "has_pending_session_creates", False) is True or getattr(tracked.sandbox, "requires_container_recycle", False) is True + if not needs_recycle and not self._uses_tos_for_user_data() and tracked.thread_id and tracked.user_id: + remote_id = tracked.remote_sandbox_id + with self._lock: + if self._shutdown_called or self._sandboxes.get(sandbox_id) is not tracked: + return + self._mirroring_output_ids.add(remote_id) + try: + self._sync_outputs_to_host(tracked.sandbox, thread_id=tracked.thread_id, user_id=tracked.user_id) + except Exception: + logger.warning("Failed to synchronize veFaaS outputs for %s", sandbox_id, exc_info=True) + finally: + with self._lock: + self._mirroring_output_ids.remove(remote_id) + needs_recycle = getattr(tracked.sandbox, "has_pending_session_creates", False) is True or getattr(tracked.sandbox, "requires_container_recycle", False) is True + + with self._lock: + if self._sandboxes.get(sandbox_id) is not tracked: + return + self._sandboxes.pop(sandbox_id) + for key in [k for k, v in self._thread_sandboxes.items() if v == sandbox_id]: + self._thread_sandboxes.pop(key, None) + destroy_now = needs_recycle or self._shutdown_called or not self._accepting + if destroy_now: + # Register pending teardown in the same critical section as removing the active + # entry so a concurrent shutdown() cannot miss this sandbox or close the client early. + self._pending_destroys[tracked.remote_sandbox_id] = tracked + else: + self._warm_pool[sandbox_id] = (tracked, time.monotonic()) + if destroy_now: + reason = "recycle_corrupted" if needs_recycle else "released_during_shutdown" + if needs_recycle: + logger.warning("Recycling veFaaS sandbox %s instead of returning it to the warm pool", sandbox_id) + self._destroy_tracked(tracked, reason=reason, require_pending=True) + else: + logger.info("Released veFaaS sandbox %s to the warm pool", sandbox_id) + + @staticmethod + def _output_parts(remote_path: str) -> tuple[str, ...]: + prefix = f"{OUTPUTS_ROOT}/" + if not remote_path.startswith(prefix) or "\\" in remote_path: + raise ValueError("Output path is outside the outputs directory") + parts = remote_path[len(prefix) :].split("/") + if any(part in {"", ".", ".."} or ":" in part or part.partition(".")[0].rstrip(" ").upper() in _WINDOWS_RESERVED_NAMES or part.endswith((" ", ".")) for part in parts): + raise ValueError("Unsafe output path") + return tuple(parts) + + @classmethod + def _output_destination(cls, root: Path, remote_path: str) -> Path: + parts = cls._output_parts(remote_path) + target = root.joinpath(*PurePosixPath(*parts).parts) + for component in reversed((target, *target.parents)): + if component.is_symlink() or component.is_junction(): + raise ValueError("Symlinked output destination") + target.parent.mkdir(parents=True, exist_ok=True) + if target.exists() and not stat.S_ISREG(target.stat().st_mode): + raise ValueError("Output destination is not a regular file") + return target + + def _sync_outputs_to_host(self, sandbox: AioSandbox, *, thread_id: str, user_id: str) -> None: + from deerflow.config.paths import get_paths + + root = get_paths().sandbox_outputs_dir(thread_id, user_id=user_id) + quoted_out = shlex.quote(OUTPUTS_ROOT) + listing = sandbox.execute_command(f"[ -d {quoted_out} ] && [ ! -L {quoted_out} ] && find {quoted_out} -type f 2>/dev/null | head -c {_MAX_SYNC_LISTING_BYTES + 1} || true") + if not listing or len(listing.encode("utf-8", errors="ignore")) > _MAX_SYNC_LISTING_BYTES: + return + remote_paths = [line.strip() for line in listing.splitlines() if line.strip().startswith(f"{OUTPUTS_ROOT}/")] + deadline = time.monotonic() + _SYNC_DEADLINE_SECONDS + total = 0 + for index, remote_path in enumerate(remote_paths): + if index >= _MAX_SYNC_FILES or total >= _MAX_SYNC_TOTAL_BYTES or time.monotonic() >= deadline: + break + staged: Path | None = None + try: + target = self._output_destination(root, remote_path) + data = sandbox.download_file(remote_path, max_bytes=min(DEFAULT_DOWNLOAD_LIMIT, _MAX_SYNC_TOTAL_BYTES - total)) + total += len(data) + with tempfile.NamedTemporaryFile(prefix=".vefaas-sync-", dir=target.parent, delete=False) as tmp: + staged = Path(tmp.name) + tmp.write(data) + self._output_destination(root, remote_path) + staged.replace(target) + except (OSError, ValueError): + logger.warning("Could not synchronize veFaaS output %r", remote_path, exc_info=True) + finally: + if staged is not None: + staged.unlink(missing_ok=True) + + # ── Reset & Shutdown ───────────────────────────────────────────────── + + def reset(self) -> None: + """Retire admission and park tracked sandboxes in this instance's warm pool.""" + with self._lock: + self._accepting = False + now = time.monotonic() + for sandbox_id, tracked in self._sandboxes.items(): + self._warm_pool.setdefault(sandbox_id, (tracked, now)) + self._sandboxes.clear() + self._thread_sandboxes.clear() + self._acquire_serializer.close() + + def _shutdown_at_exit(self) -> None: + try: + self.shutdown() + except _VeFaaSShutdownIncompleteError as exc: + logger.warning("%s", exc) + + def shutdown(self) -> None: + """Close admission, stop maintenance threads, and tear down owned remote sandboxes.""" + with self._shutdown_lock: + with self._lock: + if self._shutdown_complete: + return + self._shutdown_called = True + self._accepting = False + if self._mirroring_output_ids: + # Keep clients and lease renewal alive until release finishes copying. + raise _VeFaaSShutdownIncompleteError(f"veFaaS shutdown incomplete: {len(self._mirroring_output_ids)} output mirror(s) active, retry shutdown") + + self._acquire_serializer.close() + + threads_stopped = True + try: + self._stop_idle_checker() + except RuntimeError: + threads_stopped = False + try: + self._stop_renewal_thread() + except RuntimeError: + threads_stopped = False + + with self._lock: + active = list(self._sandboxes.values()) + warm = [entry for entry, _ in self._warm_pool.values()] + pending = list(self._pending_destroys.values()) + pending_rollbacks = list(self._pending_rollbacks.values()) + self._sandboxes.clear() + self._warm_pool.clear() + self._thread_sandboxes.clear() + + unique = {entry.remote_sandbox_id: entry for entry in active + warm + pending} + for tracked in unique.values(): + self._destroy_tracked(tracked, reason="shutdown") + for rollback in pending_rollbacks: + self._cleanup_rollback(rollback, reason="shutdown", require_pending=True) + + with self._lock: + still_pending = len(self._pending_destroys) + len(self._pending_rollbacks) + in_flight_acquires = self._acquires + if in_flight_acquires or still_pending or not threads_stopped: + raise _VeFaaSShutdownIncompleteError(f"veFaaS shutdown incomplete: {in_flight_acquires} acquire(s) active, {still_pending} teardown(s) pending, threads_stopped={threads_stopped}; retry shutdown") + self._shutdown_complete = True + + if self._client is not None and self._client_override is None: + self._client.close() + self._ownership.close() + + +__all__ = ["VeFaaSSandboxProvider"] diff --git a/backend/packages/harness/deerflow/config/sandbox_config.py b/backend/packages/harness/deerflow/config/sandbox_config.py index ab65a1400d..8d44826a68 100644 --- a/backend/packages/harness/deerflow/config/sandbox_config.py +++ b/backend/packages/harness/deerflow/config/sandbox_config.py @@ -289,6 +289,14 @@ class SandboxConfig(BaseModel): (``BOXD_API_KEY`` is the fallback for ``boxd_api_key``). vcpu, memory, from_snapshot, auto_suspend_timeout, ready_timeout, name_prefix, labels: machine shape, readiness deadline and naming. + + VeFaaSSandboxProvider specific options: + vefaas: Optional nested mapping (or flat fields on ``sandbox``) holding + ``region``, ``endpoint``, ``function_id``, ``sandbox_base_url``, + ``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``. """ use: str = Field( diff --git a/backend/tests/blocking_io/test_vefaas_sandbox.py b/backend/tests/blocking_io/test_vefaas_sandbox.py new file mode 100644 index 0000000000..c503496507 --- /dev/null +++ b/backend/tests/blocking_io/test_vefaas_sandbox.py @@ -0,0 +1,125 @@ +"""Blocking-I/O anchors for ``VeFaaSSandboxProvider``. + +1. ``get()`` and ``get_scoped()`` run directly on the LangGraph event loop for + every tool call; they must never touch the ownership store or network. +2. Contended ``acquire_async()`` calls serialize on ``AcquireSerializer`` and + must execute control-plane HTTP and ownership store I/O strictly off the + event loop. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import httpx +import pytest +from blockbuster import BlockingError +from test_vefaas_sandbox_provider import _FakeVeFaaSServer, _install_provider + +from deerflow.community.aio_sandbox.ownership import RenewOutcome +from deerflow.community.vefaas_sandbox import VeFaaSClient + +pytestmark = pytest.mark.asyncio + + +class _BlockingProbeOwnershipStore: + """Ownership store whose every method executes real blocking file I/O.""" + + supports_cross_process = True + + def __init__(self, probe_path: Path) -> None: + self._probe_path = probe_path + self._probe_path.write_text("owner", encoding="utf-8") + self.calls: list[str] = [] + + @property + def owner_id(self) -> str: + return "worker-vefaas-blockingio" + + def _touch(self, op: str) -> str: + self.calls.append(op) + return self._probe_path.read_text(encoding="utf-8") + + def take(self, sandbox_id: str) -> bool: + self._touch("take") + return True + + def claim(self, sandbox_id: str, *, for_destroy: bool = False) -> bool: + self._touch("claim") + return True + + def renew(self, sandbox_id: str) -> RenewOutcome: + self._touch("renew") + return RenewOutcome.RENEWED + + def release(self, sandbox_id: str) -> None: + self._touch("release") + + def owner(self, sandbox_id: str) -> str | None: + return self._touch("owner") + + def close(self) -> None: + pass + + +class _FileIOProbingVeFaaSServer(_FakeVeFaaSServer): + """Fake veFaaS control plane that performs real blocking file I/O on every request.""" + + def __init__(self, probe_dir: Path) -> None: + super().__init__() + self._probe_dir = probe_dir + + def handler(self, request: httpx.Request) -> httpx.Response: + probe = self._probe_dir / f"req-{len(self.requests) + 1}.probe" + probe.write_text("x" * 2048, encoding="utf-8") + return super().handler(request) + + +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) + probe_store = await asyncio.to_thread(_BlockingProbeOwnershipStore, tmp_path / "ownership-probe") + provider._ownership = probe_store + try: + sandbox_id = await provider.acquire_async("t-get", user_id="u-get") + probe_store.calls.clear() + assert provider.get(sandbox_id) is not None + assert provider.get_scoped(sandbox_id, thread_id="t-get", user_id="u-get") is not None + assert provider.get_scoped(sandbox_id, thread_id="t-get", user_id="other") is None + assert probe_store.calls == [] + + # Meta-check (teeth): hitting the probe store via provider code on the loop trips Blockbuster. + with pytest.raises(BlockingError): + provider._renew_leases_once() + finally: + await asyncio.to_thread(provider.shutdown) + + +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._ownership = await asyncio.to_thread(_BlockingProbeOwnershipStore, tmp_path / "ownership-probe-2") + try: + first, second = await asyncio.gather( + provider.acquire_async("t-contend", user_id="u-contend"), + provider.acquire_async("t-contend", user_id="u-contend"), + ) + assert first == second + + # Meta-check (teeth): calling sync acquire directly on the event loop trips Blockbuster. + with pytest.raises(BlockingError): + provider.acquire("t-sync-fail", user_id="u-contend") + finally: + await asyncio.to_thread(provider.shutdown) + + +async def test_client_construction_is_non_blocking_on_event_loop() -> None: + """Constructing VeFaaSClient must defer httpx.Client TLS setup off the event loop.""" + client = VeFaaSClient( + endpoint="https://vefaas.ap-southeast-1.byteplusapi.com", + region="ap-southeast-1", + access_key="ak", + secret_key="sk", + ) + assert client._client is None + client.close() diff --git a/backend/tests/test_agent_guidance_check.py b/backend/tests/test_agent_guidance_check.py index c5f5f78364..a5bca5ed4e 100644 --- a/backend/tests/test_agent_guidance_check.py +++ b/backend/tests/test_agent_guidance_check.py @@ -36,6 +36,7 @@ EXPECTED_GUIDANCE_PATHS = { "backend/packages/harness/deerflow/community/browser_automation/AGENTS.md", "backend/packages/harness/deerflow/community/opensandbox/AGENTS.md", "backend/packages/harness/deerflow/community/boxd_sandbox/AGENTS.md", + "backend/packages/harness/deerflow/community/vefaas_sandbox/AGENTS.md", "backend/packages/harness/deerflow/config/AGENTS.md", "backend/packages/harness/deerflow/extensions/AGENTS.md", "backend/packages/harness/deerflow/runtime/AGENTS.md", diff --git a/backend/tests/test_vefaas_sandbox_provider.py b/backend/tests/test_vefaas_sandbox_provider.py new file mode 100644 index 0000000000..2e4e162fbd --- /dev/null +++ b/backend/tests/test_vefaas_sandbox_provider.py @@ -0,0 +1,1651 @@ +"""Offline unit tests for the BytePlus veFaaS Cloud Sandbox community provider. + +All control-plane tests drive ``VeFaaSClient`` through ``httpx.MockTransport`` +(no live network calls, no cloud credentials required). +""" + +from __future__ import annotations + +import datetime +import io +import json +import os +import signal +import subprocess +import tarfile +import threading +import time +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from types import SimpleNamespace +from typing import Any +from unittest.mock import MagicMock + +import httpx +import pytest + +from deerflow.community.aio_sandbox.ownership import OwnershipBackendError, RenewOutcome +from deerflow.community.provider_credentials import REDACTION_MARKER +from deerflow.community.vefaas_sandbox import ( + VeFaaSApiError, + VeFaaSClient, + VeFaaSSandboxProvider, + sign_v4_headers, +) +from deerflow.community.vefaas_sandbox import provider as provider_mod +from deerflow.config.sandbox_config import SandboxConfig +from deerflow.sandbox.identity import derive_sandbox_scope_token +from deerflow.sandbox.sandbox_provider import hold_sandbox_shutdown_ownership + +# ── Helpers & Fakes ────────────────────────────────────────────────────── + + +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 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.requests: list[tuple[str, dict[str, Any], dict[str, str]]] = [] + self.next_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.ignore_list_metadata_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": + 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"), + } + 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) + return httpx.Response( + 200, + json={ + "ResponseMetadata": {"RequestId": "req-desc"}, + "Result": { + "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 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()): + items.append( + { + "Id": record["Id"], + "FunctionId": record["FunctionId"], + "Status": record["Status"], + "Pending": record["Pending"], + "Metadata": dict(record["Metadata"]), + } + ) + 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": {}}) + + return httpx.Response(400, json={"ResponseMetadata": {"Error": {"Code": "InvalidAction", "Message": action}}}) + + +def _make_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_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_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 + + +# ── 1. SigV4 Signing ───────────────────────────────────────────────────── + + +class TestSigV4Signing: + def test_deterministic_sigv4_golden_vector(self) -> None: + fixed_now = datetime.datetime(2026, 11, 20, 10, 30, 45, tzinfo=datetime.UTC) + ours = sign_v4_headers( + method="POST", + path="/", + query={"Version": "2024-06-06", "Action": "CreateSandbox"}, + host="vefaas.ap-southeast-1.byteplusapi.com:443", + body='{"FunctionId":"fn-123","Timeout":60}', + access_key="AK-SAMPLE", + secret_key="SK-SAMPLE-SECRET", + region="ap-southeast-1", + service="vefaas", + session_token="STS-TOKEN-123", + now=fixed_now, + ) + assert ours["X-Date"] == "20261120T103045Z" + assert ours["X-Content-Sha256"] == "1690c1caa5853a6576bd4d2b6620c64da66231c64c663ce86f5693a30cdc2db7" + assert ours["X-Security-Token"] == "STS-TOKEN-123" + assert ours["Authorization"] == ( + "HMAC-SHA256 Credential=AK-SAMPLE/20261120/ap-southeast-1/vefaas/request, SignedHeaders=content-type;host;x-content-sha256;x-date;x-security-token, Signature=cd6d3ce28d1342fd6569a5fc7b59b3c40b4fa4a2a4f12ca8208c39216a29538d" + ) + + def test_matches_volcengine_sdk_signer_byte_for_byte(self) -> None: + pytest.importorskip("volcenginesdkcore.signv4") + from volcenginesdkcore.signv4 import SignerV4 + + fixed_now = datetime.datetime(2026, 11, 20, 10, 30, 45, tzinfo=datetime.UTC) + query = {"Action": "CreateSandbox", "Version": "2024-06-06"} + body = '{"FunctionId":"fn-123","Timeout":60}' + host = "vefaas.ap-southeast-1.byteplusapi.com:443" + + ours = sign_v4_headers( + method="POST", + path="/", + query=query, + host=host, + body=body, + access_key="AK-SAMPLE", + secret_key="SK-SAMPLE-SECRET", + region="ap-southeast-1", + service="vefaas", + session_token="STS-TOKEN-123", + now=fixed_now, + ) + + # Reproduce SDK signer with the exact same UTC timestamp. + sdk_headers = {"Host": host, "Content-Type": "application/json; charset=utf-8"} + + class _FrozenDateTime(datetime.datetime): + @classmethod + def utcnow(cls) -> datetime.datetime: + return fixed_now.replace(tzinfo=None) + + orig_dt = SignerV4.sign.__globals__["datetime"].datetime + SignerV4.sign.__globals__["datetime"].datetime = _FrozenDateTime + try: + SignerV4.sign( + path="/", + method="POST", + headers=sdk_headers, + body=body, + post_params=None, + query=query, + ak="AK-SAMPLE", + sk="SK-SAMPLE-SECRET", + region="ap-southeast-1", + service="vefaas", + session_token="STS-TOKEN-123", + ) + finally: + SignerV4.sign.__globals__["datetime"].datetime = orig_dt + + assert ours["X-Date"] == sdk_headers["X-Date"] + assert ours["X-Content-Sha256"] == sdk_headers["X-Content-Sha256"] + assert ours["X-Security-Token"] == "STS-TOKEN-123" + assert ours["Authorization"] == sdk_headers["Authorization"] + + +# ── 2. VeFaaSClient OpenAPI & Security ─────────────────────────────────── + + +class TestVeFaaSClient: + def test_enforces_https_and_rejects_userinfo(self) -> None: + with pytest.raises(ValueError, match="HTTPS"): + VeFaaSClient( + endpoint="http://vefaas.ap-southeast-1.byteplusapi.com", + region="ap-southeast-1", + access_key="ak", + secret_key="sk", + ) + with pytest.raises(ValueError, match="username or password"): + VeFaaSClient( + endpoint="https://user:pass@vefaas.ap-southeast-1.byteplusapi.com", + region="ap-southeast-1", + access_key="ak", + secret_key="sk", + ) + + def test_redacts_secrets_from_transport_and_api_errors(self) -> None: + secret = "SUPER-SECRET-SK-999" + + def failing_handler(_req: httpx.Request) -> httpx.Response: + return httpx.Response( + 500, + json={"ResponseMetadata": {"RequestId": "req-err", "Error": {"Code": "InternalError", "Message": f"upstream leaked {secret}"}}}, + ) + + client = VeFaaSClient( + endpoint="https://vefaas.ap-southeast-1.byteplusapi.com", + region="ap-southeast-1", + access_key="AK-1", + secret_key=secret, + httpx_client=httpx.Client(transport=httpx.MockTransport(failing_handler)), + ) + with pytest.raises(VeFaaSApiError) as exc_info: + client.describe_sandbox("fn-1", "sb-1") + assert secret not in str(exc_info.value) + assert REDACTION_MARKER in str(exc_info.value) + + def test_describe_returns_none_only_on_not_found_and_raises_on_500(self) -> None: + server = _FakeVeFaaSServer() + client = VeFaaSClient( + endpoint="https://vefaas.ap-southeast-1.byteplusapi.com", + region="ap-southeast-1", + access_key="ak", + secret_key="sk", + httpx_client=httpx.Client(transport=httpx.MockTransport(server.handler)), + ) + assert client.describe_sandbox("fn-1", "missing-id") is None + + server.describe_error = (503, "ServiceUnavailable", "temporary outage") + with pytest.raises(VeFaaSApiError): + client.describe_sandbox("fn-1", "missing-id") + + # Non-sandbox *NotFound errors and empty-code 404s must fail closed rather than proving absence. + for status_code, err_code, err_msg in ( + (404, "FunctionNotFound", "function does not exist"), + (404, "ActionNotFound", "unknown action"), + (404, "AccountNotFound", "unknown account"), + (404, "RouteNotFound", "unknown route"), + (404, "", "gateway route not found"), + ): + server.describe_error = (status_code, err_code, err_msg) + with pytest.raises(VeFaaSApiError): + client.describe_sandbox("fn-1", "missing-id") + + # Bare JSON HTTP 404 responses (no ResponseMetadata.Error) must also fail closed. + for bare_404 in ({}, {"message": "no Route matched"}): + bare_client = VeFaaSClient( + endpoint="https://vefaas.ap-southeast-1.byteplusapi.com", + region="ap-southeast-1", + access_key="ak", + secret_key="sk", + httpx_client=httpx.Client(transport=httpx.MockTransport(lambda _r, body=bare_404: httpx.Response(404, json=body))), + ) + with pytest.raises(VeFaaSApiError): + bare_client.describe_sandbox("fn-1", "sb-1") + + # Malformed/empty 2xx DescribeSandbox responses must fail closed rather than proving absence. + for bad_body in ( + {"ResponseMetadata": {"RequestId": "req-empty"}, "Result": {}}, + {"ResponseMetadata": {"RequestId": "req-no-id"}, "Result": {"Status": "Running"}}, + ): + bad_client = VeFaaSClient( + endpoint="https://vefaas.ap-southeast-1.byteplusapi.com", + region="ap-southeast-1", + access_key="ak", + secret_key="sk", + httpx_client=httpx.Client(transport=httpx.MockTransport(lambda _r, body=bad_body: httpx.Response(200, json=body))), + ) + with pytest.raises(VeFaaSApiError, match="valid sandbox record"): + bad_client.describe_sandbox("fn-1", "sb-1") + + +# ── 3. Config Validation ───────────────────────────────────────────────── + + +class TestVeFaaSConfigValidation: + def test_rejects_boolean_and_out_of_range_numeric_fields(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + with pytest.raises(ValueError, match="cpu_milli"): + _install_provider(monkeypatch, tmp_path, sandbox_overrides={"vefaas": {"cpu_milli": True}}) + with pytest.raises(ValueError, match="memory_mb"): + _install_provider(monkeypatch, tmp_path, sandbox_overrides={"vefaas": {"memory_mb": 128}}) + with pytest.raises(ValueError, match="timeout_minutes"): + _install_provider(monkeypatch, tmp_path, sandbox_overrides={"vefaas": {"timeout_minutes": 2}}) + + def test_rejects_tos_mount_without_bucket_or_traversal_prefix(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + with pytest.raises(ValueError, match="bucket"): + _install_provider(monkeypatch, tmp_path, sandbox_overrides={"vefaas": {"tos_mount": {"enabled": True}}}) + with pytest.raises(ValueError, match="invalid path segments"): + _install_provider( + monkeypatch, + tmp_path, + sandbox_overrides={"vefaas": {"tos_mount": {"enabled": True, "bucket": "bkt", "prefix": "../escape"}}}, + ) + + def test_rejects_unsafe_skills_roots(self) -> None: + assert provider_mod._validate_skills_root("/mnt/skills") == "/mnt/skills" + for bad in ("/", "/etc", "/mnt/user-data", "/mnt/user-data/skills", "/mnt/skills/../etc"): + with pytest.raises(ValueError): + provider_mod._validate_skills_root(bad) + + +# ── 4. Provider Lifecycle, Skills Sync, TOS Mount & Ownership ──────────── + + +class TestVeFaaSSandboxProviderLifecycle: + def test_acquire_get_scoped_release_reclaim_and_shutdown(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, server, aio_instances = _install_provider( + monkeypatch, + tmp_path, + sandbox_overrides={"vefaas": {"sandbox_access_token": "apig-secret-tok"}}, + ) + try: + assert provider.supports_agent_skill_isolation is True + assert provider.supports_lazy_agent_skill_isolation is False + assert provider.uses_thread_data_mounts is False + + sandbox_id = provider.acquire("thread-1", user_id="user-a") + expected_id = derive_sandbox_scope_token(user_id="user-a", thread_id="thread-1") + assert sandbox_id == expected_id + assert len(aio_instances) == 1 + + # Verify AioSandbox reused with unified domain + instance routing header + bearer token. + aio = aio_instances[0] + assert aio.base_url == "https://sandbox.ap-southeast-1.byteplus.example" + assert aio.request_headers[provider_mod.INSTANCE_ROUTING_HEADER] == "vefaas-sb-1" + assert aio.request_headers["Authorization"] == "Bearer apig-secret-tok" + assert aio.lark_cli_broker is False + + # Identity-scoped lookup fails closed for another user or thread. + assert provider.get(sandbox_id) is aio + assert provider.get_scoped(sandbox_id, thread_id="thread-1", user_id="user-a") is aio + assert provider.get_scoped(sandbox_id, thread_id="thread-1", user_id="user-b") is None + assert provider.get_scoped(sandbox_id, thread_id="thread-2", user_id="user-a") is None + + # Seed an output artifact inside the sandbox and verify release mirrors it to host. + aio.remote_outputs["/mnt/user-data/outputs/report.txt"] = b"hello-vefaas" + provider.release(sandbox_id) + assert provider.get(sandbox_id) is None + + from deerflow.config.paths import get_paths + + mirrored = get_paths().sandbox_outputs_dir("thread-1", user_id="user-a") / "report.txt" + assert mirrored.read_bytes() == b"hello-vefaas" + + # Reclaim from warm pool extends timeout and avoids CreateSandbox. + reclaimed_id = provider.acquire("thread-1", user_id="user-a") + assert reclaimed_id == sandbox_id + actions = [a for a, _, _ in server.requests] + assert actions.count("CreateSandbox") == 1 + assert "SetSandboxTimeout" in actions + finally: + provider.shutdown() + + # Shutdown kills remote sandbox and confirms absence. + actions = [a for a, _, _ in server.requests] + assert "KillSandbox" in actions + assert server.sandboxes == {} + assert aio_instances[0].closed is True + + # Admission stays closed after shutdown. + with pytest.raises(RuntimeError, match="shut down"): + provider.acquire("thread-2", user_id="user-a") + + def test_url_template_mode_omits_instance_routing_header(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, _server, aio_instances = _install_provider( + monkeypatch, + tmp_path, + sandbox_overrides={"vefaas": {"sandbox_base_url": "https://{sandbox_id}.sandbox.example.com"}}, + ) + try: + provider.acquire("t-tpl", user_id="u-1") + assert aio_instances[0].base_url == "https://vefaas-sb-1.sandbox.example.com" + assert provider_mod.INSTANCE_ROUTING_HEADER not in aio_instances[0].request_headers + finally: + provider.shutdown() + + def test_tos_mount_uses_scope_token_and_skips_host_mirroring(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, server, aio_instances = _install_provider( + monkeypatch, + tmp_path, + sandbox_overrides={ + "vefaas": { + "tos_mount": { + "enabled": True, + "bucket": "deerflow-prod-bucket", + "prefix": "user-data", + "local_mount_path": "/mnt/user-data", + } + } + }, + ) + try: + sandbox_id = provider.acquire("t-tos", user_id="alice@example.com") + create_payload = next(p for a, p, _ in server.requests if a == "CreateSandbox") + tos = create_payload["InstanceTosMountConfig"] + assert tos["Enable"] is True + mount = tos["TosMountPoints"][0] + assert mount["BucketName"] == "deerflow-prod-bucket" + assert mount["BucketPath"] == f"/user-data/{sandbox_id}" + assert "alice" not in mount["BucketPath"] + assert mount["LocalMountPath"] == "/mnt/user-data" + + # Output mirroring is skipped because /mnt/user-data is backed directly by TOS. + aio_instances[0].remote_outputs["/mnt/user-data/outputs/a.txt"] = b"skip-me" + provider.release(sandbox_id) + assert not any("find /mnt/user-data/outputs" in cmd for cmd in aio_instances[0].commands) + finally: + provider.shutdown() + + def test_cross_process_discovery_adopts_running_sandbox(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + server = _FakeVeFaaSServer() + sandbox_id = derive_sandbox_scope_token(user_id="u1", thread_id="t-discover") + server.sandboxes["vefaas-existing-9"] = { + "Id": "vefaas-existing-9", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sandbox_id, + }, + } + provider, _, aio_instances = _install_provider(monkeypatch, tmp_path, server=server) + try: + acquired = provider.acquire("t-discover", user_id="u1") + assert acquired == sandbox_id + assert aio_instances[0].request_headers[provider_mod.INSTANCE_ROUTING_HEADER] == "vefaas-existing-9" + assert not any(a == "CreateSandbox" for a, _, _ in server.requests) + finally: + provider.shutdown() + + def test_sync_agent_skills_uploads_tar_and_rejects_symlinks_and_mismatch(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, _server, aio_instances = _install_provider(monkeypatch, tmp_path) + try: + sandbox_id = provider.acquire("t-skills", user_id="u-skills") + aio = aio_instances[0] + # Initial acquire uploads the shared skills projection and writes the init marker. + tar_uploads = [k for k in aio.uploaded_files if k.endswith(".tar.gz")] + assert len(tar_uploads) == 1 + assert provider_mod._INIT_MARKER_PATH in aio.uploaded_files + aio.uploaded_files.clear() + aio.commands.clear() + + proj_root = tmp_path / "proj" + for cat in ("public", "custom", "legacy", "integrations"): + (proj_root / cat).mkdir(parents=True) + (proj_root / "public" / "demo-skill").mkdir() + (proj_root / "public" / "demo-skill" / "SKILL.md").write_text("---\nname: demo\n---\n", encoding="utf-8") + host_secret = tmp_path / "host-secret.txt" + host_secret.write_text("do-not-smuggle", encoding="utf-8") + (proj_root / "public" / "demo-skill" / "escape.txt").symlink_to(host_secret) + + projection = SimpleNamespace( + public=proj_root / "public", + custom=proj_root / "custom", + legacy=proj_root / "legacy", + integrations=proj_root / "integrations", + ) + provider.sync_agent_skills(sandbox_id, thread_id="t-skills", user_id="u-skills", projection=projection) + + assert len(aio.uploaded_files) == 1 + tar_bytes = next(iter(aio.uploaded_files.values())) + with tarfile.open(fileobj=io.BytesIO(tar_bytes), mode="r:gz") as tf: + names = tf.getnames() + assert "public/demo-skill/SKILL.md" in names + assert "public/demo-skill/escape.txt" not in names + assert any("rm -rf --" in cmd and "UPLOAD_OK" in cmd for cmd in aio.commands) + + # Symlinked projection root is refused. + symlink_root = tmp_path / "symlink-public" + symlink_root.symlink_to(proj_root / "public") + bad_projection = SimpleNamespace( + public=symlink_root, + custom=proj_root / "custom", + legacy=proj_root / "legacy", + integrations=proj_root / "integrations", + ) + with pytest.raises(ValueError, match="symlinked upload root"): + provider.sync_agent_skills(sandbox_id, thread_id="t-skills", user_id="u-skills", projection=bad_projection) + + # Identity mismatch fails closed. + with pytest.raises(RuntimeError, match="does not match"): + provider.sync_agent_skills(sandbox_id, thread_id="t-skills", user_id="other-user", projection=projection) + finally: + provider.shutdown() + + def test_lost_ownership_lease_forgets_locally_without_killing_peer_sandbox(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, server, aio_instances = _install_provider(monkeypatch, tmp_path) + try: + sandbox_id = provider.acquire("t-lost", user_id="u1") + mock_store = MagicMock() + mock_store.supports_cross_process = True + mock_store.renew.return_value = RenewOutcome.LOST + provider._ownership = mock_store + + provider._renew_leases_once() + + assert provider.get(sandbox_id) is None + assert aio_instances[0].closed is True + assert not any(a == "KillSandbox" for a, _, _ in server.requests) + assert "vefaas-sb-1" in server.sandboxes + finally: + provider.shutdown() + + def test_quarantine_and_retryable_shutdown_when_absence_unconfirmed(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + server = _FakeVeFaaSServer() + server.describe_after_kill_keeps_running = True + provider, _, _ = _install_provider(monkeypatch, tmp_path, server=server) + + sandbox_id = provider.acquire("t-quar", user_id="u1") + with pytest.raises(provider_mod._VeFaaSShutdownIncompleteError): + provider.shutdown() + + # Remote still alive -> quarantined and shutdown remains retryable. + assert "vefaas-sb-1" in provider._quarantined_remote_ids.get(sandbox_id, set()) + + # Once backend confirms deletion, retry shutdown succeeds cleanly. + server.describe_after_kill_keeps_running = False + provider.shutdown() + assert provider._shutdown_complete is True + assert server.sandboxes == {} + + def test_failed_provisioning_rollback_blocks_shutdown_until_confirmed_absent(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + server = _FakeVeFaaSServer() + server.describe_after_kill_keeps_running = True + provider, _, _ = _install_provider(monkeypatch, tmp_path, server=server, ready_result=False) + + expected_id = derive_sandbox_scope_token(user_id="u1", thread_id="t-rb-shutdown") + with pytest.raises(TimeoutError, match="did not become HTTP-ready"): + provider.acquire("t-rb-shutdown", user_id="u1") + + # Rollback could not confirm absence -> retained for both quarantine and shutdown cleanup. + assert "vefaas-sb-1" in provider._quarantined_remote_ids.get(expected_id, set()) + assert "vefaas-sb-1" in provider._pending_rollbacks + + # First shutdown retries the rollback generation and stays incomplete while still running. + with pytest.raises(provider_mod._VeFaaSShutdownIncompleteError): + provider.shutdown() + assert provider._shutdown_complete is False + + # Once deletion is confirmed, retry shutdown clears rollback state and completes cleanly. + server.describe_after_kill_keeps_running = False + provider.shutdown() + assert provider._shutdown_complete is True + assert provider._pending_rollbacks == {} + assert provider._quarantined_remote_ids == {} + assert server.sandboxes == {} + + def test_ownership_backend_error_rolls_back_fresh_sandbox(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, server, _ = _install_provider(monkeypatch, tmp_path) + mock_store = MagicMock() + mock_store.supports_cross_process = True + mock_store.take.side_effect = OwnershipBackendError("redis down") + provider._ownership = mock_store + try: + with pytest.raises(OwnershipBackendError, match="redis down"): + provider.acquire("t-rb", user_id="u1") + assert any(a == "KillSandbox" for a, _, _ in server.requests) + assert server.sandboxes == {} + finally: + provider.shutdown() + + def test_host_shutdown_ownership_skips_signal_handlers(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + installed_signals: list[int] = [] + monkeypatch.setattr(provider_mod.signal, "signal", lambda sig, _h: installed_signals.append(sig)) + provider, _, _ = _install_provider(monkeypatch, tmp_path) + try: + assert installed_signals == [] + finally: + provider.shutdown() + + def test_signal_handler_restores_and_reraises_sig_dfl_outside_host_ownership(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + installed: dict[int, Any] = {} + raised: list[int] = [] + + monkeypatch.setattr(provider_mod, "host_owns_sandbox_shutdown", lambda: False) + monkeypatch.setattr(provider_mod.signal, "getsignal", lambda _sig: signal.SIG_DFL) + monkeypatch.setattr(provider_mod.signal, "signal", lambda sig, handler: installed.__setitem__(sig, handler)) + monkeypatch.setattr(provider_mod.signal, "raise_signal", lambda sig: raised.append(sig)) + + provider, _, _ = _install_provider(monkeypatch, tmp_path) + try: + assert signal.SIGTERM in installed + handler = installed[signal.SIGTERM] + # Even if shutdown() raises an unexpected exception, SIG_DFL is restored and re-raised. + monkeypatch.setattr(provider, "shutdown", lambda: (_ for _ in ()).throw(RuntimeError("boom"))) + handler(signal.SIGTERM, None) + assert installed[signal.SIGTERM] == signal.SIG_DFL + assert raised == [signal.SIGTERM] + finally: + monkeypatch.undo() + provider.shutdown() + + def test_sandbox_id_normalizes_none_user_id_and_differs_from_literal_none(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, _, _ = _install_provider(monkeypatch, tmp_path) + try: + sid_none = provider.acquire("t-none") + expected_empty = derive_sandbox_scope_token(user_id="", thread_id="t-none") + assert sid_none == expected_empty + assert provider.get_scoped(sid_none, thread_id="t-none", user_id="") is not None + + sid_literal_none = provider.acquire("t-none", user_id="None") + assert sid_literal_none != sid_none + assert provider.get_scoped(sid_literal_none, thread_id="t-none", user_id="None") is not None + finally: + provider.shutdown() + + def test_list_sandboxes_paginates_and_discovery_verifies_metadata_client_side(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + server = _FakeVeFaaSServer() + server.ignore_list_metadata_filter = True + sandbox_id = derive_sandbox_scope_token(user_id="u1", thread_id="t-page2") + + # Fill page 1 (50 entries) with unrelated running sandboxes that do not match metadata. + for idx in range(52): + server.sandboxes[f"vefaas-other-{idx}"] = { + "Id": f"vefaas-other-{idx}", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: f"other-scope-{idx}", + }, + } + # Place the matching sandbox on page 2. + server.sandboxes["vefaas-target-page2"] = { + "Id": "vefaas-target-page2", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sandbox_id, + }, + } + provider, _, aio_instances = _install_provider(monkeypatch, tmp_path, server=server) + try: + acquired = provider.acquire("t-page2", user_id="u1") + assert acquired == sandbox_id + assert aio_instances[0].request_headers[provider_mod.INSTANCE_ROUTING_HEADER] == "vefaas-target-page2" + list_pages = [p["PageNumber"] for a, p, _ in server.requests if a == "ListSandboxes"] + assert list_pages == [1, 2] + assert not any(a == "CreateSandbox" for a, _, _ in server.requests) + finally: + provider.shutdown() + + def test_incomplete_skills_upload_refuses_destructive_replace(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, _, aio_instances = _install_provider(monkeypatch, tmp_path) + try: + sandbox_id = provider.acquire("t-budget", user_id="u-budget") + aio = aio_instances[0] + aio.uploaded_files.clear() + aio.commands.clear() + + proj_root = tmp_path / "proj-budget" + for cat in ("public", "custom", "legacy", "integrations"): + (proj_root / cat).mkdir(parents=True) + (proj_root / "public" / "a.txt").write_text("one", encoding="utf-8") + (proj_root / "public" / "b.txt").write_text("two", encoding="utf-8") + projection = SimpleNamespace( + public=proj_root / "public", + custom=proj_root / "custom", + legacy=proj_root / "legacy", + integrations=proj_root / "integrations", + ) + monkeypatch.setattr(provider_mod, "_MAX_UPLOAD_FILES", 1) + with pytest.raises(RuntimeError, match="exceeds the veFaaS upload limit"): + provider.sync_agent_skills(sandbox_id, thread_id="t-budget", user_id="u-budget", projection=projection) + assert aio.uploaded_files == {} + assert aio.commands == [] + finally: + provider.shutdown() + + @pytest.mark.skipif(os.name == "nt", reason="POSIX persistent shell test") + def test_upload_script_preserves_persistent_shell_and_cleans_up_temp_files(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, _, _ = _install_provider(monkeypatch, tmp_path) + dest_root = tmp_path / "remote-skills" + dest_root.mkdir() + (dest_root / "public").mkdir() + (dest_root / "public" / "existing.txt").write_text("keep-me", encoding="utf-8") + + proj_root = tmp_path / "src-skills" + for cat in ("public", "custom", "legacy", "integrations"): + (proj_root / cat).mkdir(parents=True) + (proj_root / "public" / "new.txt").write_text("fresh-skill", encoding="utf-8") + + proc = subprocess.Popen( + ["/bin/sh"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + ) + assert proc.stdin is not None and proc.stdout is not None + recorded_tars: list[Path] = [] + + def run_in_persistent_shell(cmd: str) -> str: + marker = f"__DONE_{len(recorded_tars)}__" + proc.stdin.write(f"{cmd}\nprintf '%s\\n' '{marker}'\n") + proc.stdin.flush() + lines: list[str] = [] + while True: + line = proc.stdout.readline() + assert line != "", "persistent shell terminated unexpectedly" + if line.strip() == marker: + break + lines.append(line) + return "".join(lines) + + class _ShellSandbox: + def update_file(self, path: str, content: bytes) -> None: + p = Path(path) + recorded_tars.append(p) + p.write_bytes(content) + + def execute_command(self, command: str) -> str: + return run_in_persistent_shell(command) + + try: + shell_sandbox = _ShellSandbox() + sources = [(proj_root / cat, cat) for cat in ("public", "custom", "legacy", "integrations")] + assert provider._upload_trees(shell_sandbox, sources, dest_root=str(dest_root), replace=("public", "custom", "legacy", "integrations")) is True + + # New skill replaced old one, temp tar & staging dir cleaned up, parent shell has no errexit. + assert (dest_root / "public" / "new.txt").read_text(encoding="utf-8") == "fresh-skill" + assert not (dest_root / "public" / "existing.txt").exists() + assert not recorded_tars[-1].exists() + assert not list(dest_root.glob(".vefaas-stage-*")) + flags_out = run_in_persistent_shell("printf '%s\\n' \"$-:\" ; false; echo STILL_ALIVE") + assert "STILL_ALIVE" in flags_out + assert "e" not in flags_out.splitlines()[0].rstrip(":") + + # Failing upload (symlinked dest_root hitting exit 2) keeps parent shell alive & cleans temp tar. + symlink_dest = tmp_path / "symlink-skills" + symlink_dest.symlink_to(dest_root) + with pytest.raises(RuntimeError, match="upload into"): + provider._upload_trees(shell_sandbox, sources, dest_root=str(symlink_dest), replace=("public", "custom", "legacy", "integrations")) + assert not recorded_tars[-1].exists() + assert "STILL_ALIVE" in run_in_persistent_shell("echo STILL_ALIVE") + assert (dest_root / "public" / "new.txt").read_text(encoding="utf-8") == "fresh-skill" + + # Failing tar extraction keeps parent shell alive and leaves existing skills intact. + class _CorruptTarShellSandbox(_ShellSandbox): + def update_file(self, path: str, content: bytes) -> None: + del content + p = Path(path) + recorded_tars.append(p) + p.write_bytes(b"not-a-valid-gzip-archive") + + with pytest.raises(RuntimeError, match="upload into"): + provider._upload_trees(_CorruptTarShellSandbox(), sources, dest_root=str(dest_root), replace=("public", "custom", "legacy", "integrations")) + assert not recorded_tars[-1].exists() + assert not list(dest_root.glob(".vefaas-stage-*")) + assert "STILL_ALIVE" in run_in_persistent_shell("echo STILL_ALIVE") + assert (dest_root / "public" / "new.txt").read_text(encoding="utf-8") == "fresh-skill" + finally: + if proc.stdin: + proc.stdin.close() + proc.wait(timeout=5) + provider.shutdown() + + def test_shutdown_waits_for_inflight_acquire_without_closing_client(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + entered_ready = threading.Event() + release_ready = threading.Event() + acquire_errors: list[Exception] = [] + + provider, server, _ = _install_provider(monkeypatch, tmp_path) + # Allow shutdown() to manage client lifecycle so we verify client stays open while acquire is in-flight. + provider._client_override = None + + def blocking_ready(_url: str, timeout: int = 30, headers: dict[str, str] | None = None) -> bool: + del timeout, headers + entered_ready.set() + release_ready.wait(timeout=5) + return True + + monkeypatch.setattr(provider_mod, "wait_for_sandbox_ready", blocking_ready) + + def run_acquire() -> None: + try: + provider.acquire("t-inflight", user_id="u1") + except Exception as exc: + acquire_errors.append(exc) + + worker = threading.Thread(target=run_acquire) + worker.start() + assert entered_ready.wait(timeout=5) + + # shutdown() sees in-flight acquire -> fails incomplete without closing client or ownership store. + with pytest.raises(provider_mod._VeFaaSShutdownIncompleteError, match="acquire"): + provider.shutdown() + assert provider._shutdown_complete is False + assert provider._client is not None and provider._client._closed is False + + # Unblock acquire -> rolls back using the still-open client, then retry shutdown completes cleanly. + release_ready.set() + worker.join(timeout=5) + assert not worker.is_alive() + assert len(acquire_errors) == 1 + assert isinstance(acquire_errors[0], RuntimeError) + + provider.shutdown() + assert provider._shutdown_complete is True + assert server.sandboxes == {} + + def test_warm_pool_reap_race_does_not_kill_reacquired_sandbox_or_drop_lease(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, server, aio_instances = _install_provider(monkeypatch, tmp_path, sandbox_overrides={"idle_timeout": 1}) + try: + sandbox_id = provider.acquire("t-race", user_id="u1") + provider.release(sandbox_id) + assert sandbox_id in provider._warm_pool + + # Expire warm timestamp so _reap_expired_warm considers it eligible. + entry, _ = provider._warm_pool[sandbox_id] + provider._warm_pool[sandbox_id] = (entry, time.monotonic() - 10.0) + + # Case 1: acquire() reclaims the sandbox while _reap_expired_warm is about to destroy it. + reap_entered = threading.Event() + release_reap = threading.Event() + orig_destroy_warm = provider._destroy_warm_entry + + def paused_destroy_warm(sid: str, warm_entry: Any, *, reason: str) -> bool: + reap_entered.set() + release_reap.wait(timeout=5) + return orig_destroy_warm(sid, warm_entry, reason=reason) + + monkeypatch.setattr(provider, "_destroy_warm_entry", paused_destroy_warm) + reaper = threading.Thread(target=provider._reap_expired_warm, args=(1.0,)) + reaper.start() + assert reap_entered.wait(timeout=5) + + # Concurrent acquire reclaims the sandbox while reaper is paused before reservation. + reacquired = provider.acquire("t-race", user_id="u1") + assert reacquired == sandbox_id + + release_reap.set() + reaper.join(timeout=5) + assert not reaper.is_alive() + + # Active sandbox must remain tracked, open, alive on server, and still owned. + assert provider.get(sandbox_id) is aio_instances[0] + assert aio_instances[0].closed is False + assert "vefaas-sb-1" in server.sandboxes + assert not any(a == "KillSandbox" for a, _, _ in server.requests) + + # Case 2: once teardown reserves _local_teardown, a concurrent acquire refuses to promote it. + provider.release(sandbox_id) + entry2, _ = provider._warm_pool[sandbox_id] + provider._warm_pool[sandbox_id] = (entry2, time.monotonic() - 10.0) + + kill_started = threading.Event() + release_kill = threading.Event() + orig_kill = provider._client.kill_sandbox + + def blocking_kill(fn_id: str, remote_id: str) -> None: + kill_started.set() + release_kill.wait(timeout=5) + orig_kill(fn_id, remote_id) + + monkeypatch.setattr(provider._client, "kill_sandbox", blocking_kill) + monkeypatch.setattr(provider, "_destroy_warm_entry", orig_destroy_warm) + + reaper2 = threading.Thread(target=provider._reap_expired_warm, args=(1.0,)) + reaper2.start() + assert kill_started.wait(timeout=5) + + with pytest.raises(RuntimeError, match="currently being torn down"): + provider.acquire("t-race", user_id="u1") + + release_kill.set() + reaper2.join(timeout=5) + assert not reaper2.is_alive() + assert server.sandboxes == {} + finally: + provider.shutdown() + + def test_stale_renew_lost_does_not_forget_reacquired_sandbox(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, _, aio_instances = _install_provider(monkeypatch, tmp_path) + try: + sandbox_id = provider.acquire("t-epoch", user_id="u1") + + # Simulate a renew() that observes a concurrent re-acquire (bumping epoch) before returning LOST. + mock_store = MagicMock() + mock_store.supports_cross_process = True + + def stale_renew(sid: str) -> RenewOutcome: + with provider._lock: + provider._bump_acquire_epoch_locked(sid) + return RenewOutcome.LOST + + mock_store.renew.side_effect = stale_renew + provider._ownership = mock_store + + provider._renew_leases_once() + assert provider.get(sandbox_id) is aio_instances[0] + assert aio_instances[0].closed is False + + # Also verify _forget_lost_sandbox skips entries currently reserved for local teardown. + with provider._lock: + provider._local_teardown[sandbox_id] = 1 + try: + provider._forget_lost_sandbox(sandbox_id) + assert provider.get(sandbox_id) is aio_instances[0] + assert aio_instances[0].closed is False + finally: + with provider._lock: + provider._local_teardown.pop(sandbox_id, None) + finally: + provider.shutdown() + + def test_release_recycles_dirty_or_pending_sandbox_instead_of_warm_pool(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, server, aio_instances = _install_provider(monkeypatch, tmp_path) + try: + sid1 = provider.acquire("t-dirty", user_id="u1") + aio_instances[0].requires_container_recycle = True + provider.release(sid1) + assert sid1 not in provider._warm_pool + assert sid1 not in provider._sandboxes + assert "vefaas-sb-1" not in server.sandboxes + + sid2 = provider.acquire("t-pending", user_id="u1") + aio_instances[1].has_pending_session_creates = True + provider.release(sid2) + assert sid2 not in provider._warm_pool + assert sid2 not in provider._sandboxes + assert "vefaas-sb-2" not in server.sandboxes + finally: + provider.shutdown() + + @pytest.mark.parametrize("retire_first", [False, True], ids=["active", "retired"]) + def test_shutdown_leaves_an_in_progress_output_mirror_retryable(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, retire_first: bool) -> None: + from deerflow.config.paths import get_paths + + provider, server, aio_instances = _install_provider(monkeypatch, tmp_path) + provider._client_override = None + sandbox_id = provider.acquire("mirror-thread", user_id="mirror-user") + remote = aio_instances[0] + remote.remote_outputs["/mnt/user-data/outputs/report.txt"] = b"completed report" + original_download = remote.download_file + download_started = threading.Event() + finish_download = threading.Event() + + def paused_download(path: str, *, max_bytes: int | None = None) -> bytes: + download_started.set() + assert finish_download.wait(timeout=5) + if remote.closed or not server.sandboxes: + raise OSError("Sandbox was torn down before download completed") + return original_download(path, max_bytes=max_bytes) + + monkeypatch.setattr(remote, "download_file", paused_download) + try: + with ThreadPoolExecutor(max_workers=1) as executor: + release = executor.submit(provider.release, sandbox_id) + try: + assert download_started.wait(timeout=5) + if retire_first: + provider.reset() + assert provider._evict_oldest_warm() is None + with pytest.raises(provider_mod._VeFaaSShutdownIncompleteError, match="output mirror"): + provider.shutdown() + assert not remote.closed + assert len(server.sandboxes) == 1 + assert provider._client is not None and not provider._client._closed + finally: + finish_download.set() + release.result(timeout=5) + + mirrored = get_paths().sandbox_outputs_dir("mirror-thread", user_id="mirror-user") / "report.txt" + assert mirrored.read_bytes() == b"completed report" + provider.shutdown() + assert provider._shutdown_complete + assert remote.closed + assert not server.sandboxes + finally: + provider.shutdown() + + def test_recycling_release_remains_visible_to_concurrent_shutdown(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + provider, server, aio_instances = _install_provider(monkeypatch, tmp_path) + provider._client_override = None + sandbox_id = provider.acquire("t-recycle-race", user_id="u1") + aio_instances[0].requires_container_recycle = True + + # Pause release right after _release_scope_locked unlocks and before _destroy_tracked runs. + destroy_called = threading.Event() + release_destroy = threading.Event() + orig_destroy = provider._destroy_tracked + + def paused_destroy(tracked: Any, *, reason: str, **kwargs: Any) -> bool: + if reason == "recycle_corrupted": + destroy_called.set() + release_destroy.wait(timeout=5) + return orig_destroy(tracked, reason=reason, **kwargs) + + monkeypatch.setattr(provider, "_destroy_tracked", paused_destroy) + releaser = threading.Thread(target=provider.release, args=(sandbox_id,)) + releaser.start() + assert destroy_called.wait(timeout=5) + + # Pending destroy is already registered atomically under _lock, so shutdown() sees and kills it. + assert "vefaas-sb-1" in provider._pending_destroys + claim_calls_before_resume: list[tuple[str, bool]] = [] + orig_claim = provider._ownership.claim + + def spy_claim(sid: str, *, for_destroy: bool = False) -> bool: + claim_calls_before_resume.append((sid, for_destroy)) + return orig_claim(sid, for_destroy=for_destroy) + + monkeypatch.setattr(provider._ownership, "claim", spy_claim) + provider.shutdown() + assert provider._shutdown_complete is True + assert sum(1 for a, p, _ in server.requests if a == "KillSandbox" and p["SandboxId"] == "vefaas-sb-1") == 1 + assert server.sandboxes == {} + assert provider._pending_destroys == {} + claims_during_shutdown = len(claim_calls_before_resume) + + # Resume paused release after shutdown already completed the teardown and closed the client. + release_destroy.set() + releaser.join(timeout=5) + assert not releaser.is_alive() + + # Deferred release teardown must be a no-op once shutdown has already completed the registration. + assert provider._pending_destroys == {} + assert provider._quarantined_remote_ids == {} + assert len(claim_calls_before_resume) == claims_during_shutdown + assert sum(1 for a, p, _ in server.requests if a == "KillSandbox" and p["SandboxId"] == "vefaas-sb-1") == 1 + assert provider._ownership.owner(sandbox_id) is None + provider.shutdown() + assert provider._pending_destroys == {} + + def test_adoption_verifies_initialization_and_restores_uploads_when_uninitialized(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + from deerflow.config.paths import get_paths + + # Case A: uninitialized Running sandbox (worker crashed after CreateSandbox) restores host uploads & writes init marker. + server_a = _FakeVeFaaSServer() + sid_a = derive_sandbox_scope_token(user_id="u1", thread_id="t-uninit") + server_a.sandboxes["vefaas-uninit-1"] = { + "Id": "vefaas-uninit-1", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sid_a, + }, + } + provider_a, _, aio_a = _install_provider(monkeypatch, tmp_path / "case-a", server=server_a) + try: + uploads_dir = get_paths().sandbox_uploads_dir("t-uninit", user_id="u1") + uploads_dir.mkdir(parents=True, exist_ok=True) + (uploads_dir / "report.txt").write_text("from-host", encoding="utf-8") + + acquired = provider_a.acquire("t-uninit", user_id="u1") + assert acquired == sid_a + assert not any(a == "CreateSandbox" for a, _, _ in server_a.requests) + aio = aio_a[0] + assert provider_mod._BOOTSTRAP_COMMAND in aio.commands + assert provider_mod._INIT_MARKER_PATH in aio.uploaded_files + assert aio.uploaded_files[provider_mod._INIT_MARKER_PATH].decode("utf-8").strip() == sid_a + # Verify the existing host upload was packaged and uploaded into /mnt/user-data. + restored_names: set[str] = set() + for path, raw in aio.uploaded_files.items(): + if path.endswith(".tar.gz"): + with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tf: + restored_names.update(tf.getnames()) + assert "uploads/report.txt" in restored_names + finally: + provider_a.shutdown() + + # Case B: already-initialized Running sandbox is adopted without re-running bootstrap or clobbering files. + server_b = _FakeVeFaaSServer() + sid_b = derive_sandbox_scope_token(user_id="u1", thread_id="t-inited") + server_b.sandboxes["vefaas-inited-2"] = { + "Id": "vefaas-inited-2", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sid_b, + }, + } + provider_b, _, aio_b = _install_provider(monkeypatch, tmp_path / "case-b", server=server_b) + orig_ctor = provider_mod.AioSandbox + + def initialized_aio_ctor(**kwargs: Any) -> Any: + inst = orig_ctor(**kwargs) + inst.init_marker_override = f"INIT_MARKER:{sid_b}\n" + return inst + + monkeypatch.setattr(provider_mod, "AioSandbox", initialized_aio_ctor) + try: + acquired_b = provider_b.acquire("t-inited", user_id="u1") + assert acquired_b == sid_b + assert not any(a == "CreateSandbox" for a, _, _ in server_b.requests) + assert provider_mod._BOOTSTRAP_COMMAND not in aio_b[0].commands + assert aio_b[0].uploaded_files == {} + finally: + provider_b.shutdown() + + # Case C: running sandbox with mismatched/invalid init marker is refused; fresh sandbox is provisioned. + server_c = _FakeVeFaaSServer() + sid_c = derive_sandbox_scope_token(user_id="u1", thread_id="t-mismatch") + server_c.sandboxes["vefaas-bad-marker"] = { + "Id": "vefaas-bad-marker", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sid_c, + }, + } + provider_c, _, aio_c = _install_provider(monkeypatch, tmp_path / "case-c", server=server_c) + orig_ctor_c = provider_mod.AioSandbox + + def mismatch_first_ctor(**kwargs: Any) -> Any: + inst = orig_ctor_c(**kwargs) + if kwargs.get("request_headers", {}).get(provider_mod.INSTANCE_ROUTING_HEADER) == "vefaas-bad-marker": + inst.init_marker_override = "INIT_MARKER:wrong-sandbox-id\n" + return inst + + monkeypatch.setattr(provider_mod, "AioSandbox", mismatch_first_ctor) + try: + acquired_c = provider_c.acquire("t-mismatch", user_id="u1") + assert acquired_c == sid_c + assert any(a == "CreateSandbox" for a, _, _ in server_c.requests) + assert aio_c[0].closed is True + assert aio_c[1].request_headers[provider_mod.INSTANCE_ROUTING_HEADER] == "vefaas-sb-1" + finally: + provider_c.shutdown() + + def test_bootstrap_failure_blocks_init_marker_and_rolls_back(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + # Case A: fresh sandbox creation fails bootstrap (including PTY command-echo output without standalone marker). + provider_a, server_a, aio_a = _install_provider(monkeypatch, tmp_path / "fresh") + orig_ctor_a = provider_mod.AioSandbox + + def fail_bootstrap_fresh(**kwargs: Any) -> Any: + inst = orig_ctor_a(**kwargs) + inst.bootstrap_output_override = f"{provider_mod._BOOTSTRAP_COMMAND}\nmkdir: Permission denied\n" + return inst + + monkeypatch.setattr(provider_mod, "AioSandbox", fail_bootstrap_fresh) + try: + with pytest.raises(RuntimeError, match="bootstrap failed"): + provider_a.acquire("t-boot-fresh", user_id="u1") + assert len(aio_a) == 1 + assert provider_mod._INIT_MARKER_PATH not in aio_a[0].uploaded_files + assert any(a == "KillSandbox" for a, _, _ in server_a.requests) + assert server_a.sandboxes == {} + finally: + provider_a.shutdown() + + # Case B: adoption of an uninitialized running sandbox fails bootstrap -> no marker, rolled back. + server_b = _FakeVeFaaSServer() + sid_b = derive_sandbox_scope_token(user_id="u1", thread_id="t-boot-adopt") + server_b.sandboxes["vefaas-uninit-boot"] = { + "Id": "vefaas-uninit-boot", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sid_b, + }, + } + provider_b, _, aio_b = _install_provider(monkeypatch, tmp_path / "adopt", server=server_b) + orig_ctor_b = provider_mod.AioSandbox + + def fail_bootstrap_adopt(**kwargs: Any) -> Any: + inst = orig_ctor_b(**kwargs) + inst.fail_bootstrap = True + return inst + + monkeypatch.setattr(provider_mod, "AioSandbox", fail_bootstrap_adopt) + try: + with pytest.raises(RuntimeError, match="bootstrap failed"): + provider_b.acquire("t-boot-adopt", user_id="u1") + assert len(aio_b) == 1 + assert provider_mod._INIT_MARKER_PATH not in aio_b[0].uploaded_files + assert any(a == "KillSandbox" and p["SandboxId"] == "vefaas-uninit-boot" for a, p, _ in server_b.requests) + assert server_b.sandboxes == {} + finally: + provider_b.shutdown() + + def test_concurrent_second_worker_does_not_restore_over_live_files(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + from deerflow.community.aio_sandbox.ownership import MemoryOwnershipStore + from deerflow.config.paths import get_paths + + def _make_shared_remote_ctor(remote_files: dict[str, bytes], marker_holder: dict[str, bytes | None]) -> Callable[..., Any]: + class _SharedRemoteAioSandbox(_FakeAioSandbox): + def update_file(self, path: str, content: bytes) -> None: + super().update_file(path, content) + if path == provider_mod._INIT_MARKER_PATH: + marker_holder["marker"] = content + + def execute_command(self, command: str) -> str: + self.commands.append(command) + if command == provider_mod._BOOTSTRAP_COMMAND: + return f"{provider_mod._BOOTSTRAP_OK_MARKER}\n" + if "INIT_MARKER:" in command: + marker = marker_holder["marker"] + 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: + # Extract uploaded tar archive into shared remote_files to observe overwrites. + for path, raw in list(self.uploaded_files.items()): + if path.endswith(".tar.gz") and path in command: + with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as tf: + for member in tf.getmembers(): + if member.isfile(): + extracted = tf.extractfile(member) + if extracted is not None: + remote_files[member.name] = extracted.read() + return "UPLOAD_OK\n" + return "" + + return _SharedRemoteAioSandbox + + # Case A (cross-process style): shared ownership store + distinct in-process lock keys. + # Worker A holds an exclusive claim while initializing; Worker B probes missing, sees claim() == False, + # waits until Worker A finishes and writes a live file, then adopts without restoring stale host files. + server_a = _FakeVeFaaSServer() + sid_a = derive_sandbox_scope_token(user_id="u1", thread_id="t-peer-race") + server_a.sandboxes["vefaas-shared-1"] = { + "Id": "vefaas-shared-1", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sid_a, + }, + } + provider_1, _, _ = _install_provider(monkeypatch, tmp_path / "peer-a", server=server_a) + provider_2, _, _ = _install_provider(monkeypatch, tmp_path / "peer-a", server=server_a) + + # Share one underlying ownership table across two distinct owner IDs (simulating two workers on Redis). + shared_leases: dict[str, tuple[str, float]] = {} + store_1 = MemoryOwnershipStore(owner_id="worker-1", ttl_seconds=60.0) + store_2 = MemoryOwnershipStore(owner_id="worker-2", ttl_seconds=60.0) + store_1._leases = shared_leases + store_2._leases = shared_leases + store_1._lock = store_2._lock + provider_1._ownership = store_1 + provider_2._ownership = store_2 + + # Simulate separate OS processes where in-process locks do not collide. + provider_1._config["endpoint"] = "https://worker-1.vefaas.example" + provider_2._config["endpoint"] = "https://worker-2.vefaas.example" + + remote_files_a: dict[str, bytes] = {} + marker_a: dict[str, bytes | None] = {"marker": None} + monkeypatch.setattr(provider_mod, "AioSandbox", _make_shared_remote_ctor(remote_files_a, marker_a)) + + uploads_dir = get_paths().sandbox_uploads_dir("t-peer-race", user_id="u1") + uploads_dir.mkdir(parents=True, exist_ok=True) + (uploads_dir / "report.txt").write_text("stale-host-copy", encoding="utf-8") + + worker1_in_init = threading.Event() + worker2_blocked_on_claim = threading.Event() + orig_init_1 = provider_1._initialize_remote_sandbox + orig_claim_2 = store_2.claim + + def paused_init_1(sandbox: Any, **kwargs: Any) -> None: + worker1_in_init.set() + assert worker2_blocked_on_claim.wait(timeout=5) + orig_init_1(sandbox, **kwargs) + # Simulate live agent write immediately after initialization completes. + remote_files_a["uploads/report.txt"] = b"live-peer-write" + + def spy_claim_2(sid: str, *, for_destroy: bool = False) -> bool: + res = orig_claim_2(sid, for_destroy=for_destroy) + if not res: + worker2_blocked_on_claim.set() + return res + + monkeypatch.setattr(provider_1, "_initialize_remote_sandbox", paused_init_1) + monkeypatch.setattr(store_2, "claim", spy_claim_2) + + errors: list[Exception] = [] + results: dict[str, str] = {} + + def run_worker(name: str, prov: VeFaaSSandboxProvider) -> None: + try: + results[name] = prov.acquire("t-peer-race", user_id="u1") + except Exception as exc: # pragma: no cover - surfaced via assertion + errors.append(exc) + + try: + t1 = threading.Thread(target=run_worker, args=("w1", provider_1)) + t2 = threading.Thread(target=run_worker, args=("w2", provider_2)) + t1.start() + assert worker1_in_init.wait(timeout=5) + t2.start() + t1.join(timeout=5) + t2.join(timeout=5) + assert not errors, f"Unexpected errors: {errors}" + assert results == {"w1": sid_a, "w2": sid_a} + assert remote_files_a["uploads/report.txt"] == b"live-peer-write" + finally: + provider_1.shutdown() + provider_2.shutdown() + + # Case B (stale observation before claim): Worker B's first probe sees missing, then Worker A finishes + # initialization, writes a live file, and releases ownership before Worker B claims. Worker B's post-claim + # re-probe observes the marker and skips restoration. + server_b = _FakeVeFaaSServer() + sid_b = derive_sandbox_scope_token(user_id="u1", thread_id="t-stale-probe") + server_b.sandboxes["vefaas-shared-2"] = { + "Id": "vefaas-shared-2", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sid_b, + }, + } + provider_b, _, _ = _install_provider(monkeypatch, tmp_path / "peer-b", server=server_b) + remote_files_b: dict[str, bytes] = {} + marker_b: dict[str, bytes | None] = {"marker": None} + monkeypatch.setattr(provider_mod, "AioSandbox", _make_shared_remote_ctor(remote_files_b, marker_b)) + + uploads_dir_b = get_paths().sandbox_uploads_dir("t-stale-probe", user_id="u1") + uploads_dir_b.mkdir(parents=True, exist_ok=True) + (uploads_dir_b / "report.txt").write_text("stale-host-copy", encoding="utf-8") + + orig_claim_b = provider_b._ownership.claim + + def peer_finishes_before_claim(sid: str, *, for_destroy: bool = False) -> bool: + # Peer finishes initialization and writes a live file just before this worker's claim succeeds. + marker_b["marker"] = f"{sid_b}\n".encode() + remote_files_b["uploads/report.txt"] = b"live-after-first-probe" + return orig_claim_b(sid, for_destroy=for_destroy) + + monkeypatch.setattr(provider_b._ownership, "claim", peer_finishes_before_claim) + try: + acquired_b = provider_b.acquire("t-stale-probe", user_id="u1") + assert acquired_b == sid_b + assert remote_files_b["uploads/report.txt"] == b"live-after-first-probe" + finally: + provider_b.shutdown() + + # Case C (same-process separate stores): two providers with separate MemoryOwnershipStores + # sharing the same remote endpoint/function/sandbox_id serialize via _remote_init_lock. + server_c = _FakeVeFaaSServer() + sid_c = derive_sandbox_scope_token(user_id="u1", thread_id="t-inproc-lock") + server_c.sandboxes["vefaas-shared-3"] = { + "Id": "vefaas-shared-3", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sid_c, + }, + } + provider_c1, _, _ = _install_provider(monkeypatch, tmp_path / "peer-c", server=server_c) + provider_c2, _, _ = _install_provider(monkeypatch, tmp_path / "peer-c", server=server_c) + remote_files_c: dict[str, bytes] = {} + marker_c: dict[str, bytes | None] = {"marker": None} + monkeypatch.setattr(provider_mod, "AioSandbox", _make_shared_remote_ctor(remote_files_c, marker_c)) + + uploads_dir_c = get_paths().sandbox_uploads_dir("t-inproc-lock", user_id="u1") + uploads_dir_c.mkdir(parents=True, exist_ok=True) + (uploads_dir_c / "report.txt").write_text("stale-host-copy", encoding="utf-8") + + c1_in_init = threading.Event() + release_c1 = threading.Event() + orig_init_c1 = provider_c1._initialize_remote_sandbox + + def paused_init_c1(sandbox: Any, **kwargs: Any) -> None: + c1_in_init.set() + assert release_c1.wait(timeout=5) + orig_init_c1(sandbox, **kwargs) + remote_files_c["uploads/report.txt"] = b"live-inproc-write" + + monkeypatch.setattr(provider_c1, "_initialize_remote_sandbox", paused_init_c1) + + c_errors: list[Exception] = [] + c_results: dict[str, str] = {} + + def run_c(name: str, prov: VeFaaSSandboxProvider) -> None: + try: + c_results[name] = prov.acquire("t-inproc-lock", user_id="u1") + except Exception as exc: # pragma: no cover - surfaced via assertion + c_errors.append(exc) + + try: + tc1 = threading.Thread(target=run_c, args=("c1", provider_c1)) + tc2 = threading.Thread(target=run_c, args=("c2", provider_c2)) + tc1.start() + assert c1_in_init.wait(timeout=5) + tc2.start() + # Give c2 a moment to contend on _remote_init_lock while c1 is initializing. + time.sleep(0.05) + release_c1.set() + tc1.join(timeout=5) + tc2.join(timeout=5) + assert not c_errors, f"Unexpected errors: {c_errors}" + assert c_results == {"c1": sid_c, "c2": sid_c} + assert remote_files_c["uploads/report.txt"] == b"live-inproc-write" + finally: + provider_c1.shutdown() + provider_c2.shutdown() + + # Case D (peer holds lease indefinitely without publishing marker): fail closed on timeout + # rather than stealing ownership and restoring stale files over a live peer. + server_d = _FakeVeFaaSServer() + sid_d = derive_sandbox_scope_token(user_id="u1", thread_id="t-peer-timeout") + server_d.sandboxes["vefaas-shared-4"] = { + "Id": "vefaas-shared-4", + "FunctionId": "fn-demo-app", + "Status": "Running", + "Pending": False, + "Metadata": { + provider_mod.META_KEY_PROVIDER: provider_mod.META_VAL_PROVIDER, + provider_mod.META_KEY_SANDBOX_ID: sid_d, + }, + } + provider_d, _, _ = _install_provider( + monkeypatch, + tmp_path / "peer-d", + server=server_d, + sandbox_overrides={"vefaas": {"ready_timeout": 0.05}}, + ) + remote_files_d: dict[str, bytes] = {"uploads/report.txt": b"untouched"} + marker_d: dict[str, bytes | None] = {"marker": None} + monkeypatch.setattr(provider_mod, "AioSandbox", _make_shared_remote_ctor(remote_files_d, marker_d)) + monkeypatch.setattr(provider_d._ownership, "claim", lambda _sid, *, for_destroy=False: False) + try: + with pytest.raises(RuntimeError, match="Timed out waiting for peer to initialize"): + provider_d.acquire("t-peer-timeout", user_id="u1") + assert remote_files_d["uploads/report.txt"] == b"untouched" + finally: + provider_d.shutdown() diff --git a/config.example.yaml b/config.example.yaml index d61900b8f7..2b857f2497 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -2068,6 +2068,37 @@ sandbox: # # environment: # merged into every command's environment # # PYTHONUNBUFFERED: "1" +# Option 8: BytePlus veFaaS Cloud Sandbox +# Provisions managed All-in-One Sandbox instances via BytePlus Function Service +# (veFaaS) OpenAPI (Version=2024-06-06) and reuses AioSandbox for the data plane. +# Requires no extra cloud SDK dependency (uses httpx + SigV4 directly). +# sandbox: +# use: deerflow.community.vefaas_sandbox:VeFaaSSandboxProvider +# vefaas: +# region: ap-southeast-1 +# endpoint: https://vefaas.ap-southeast-1.byteplusapi.com +# function_id: $BYTEPLUS_VEFAAS_SANDBOX_APP_ID +# sandbox_base_url: $BYTEPLUS_VEFAAS_SANDBOX_BASE_URL # unified domain or https://{sandbox_id}.example.com +# access_key_env: BYTEPLUS_ACCESS_KEY_ID +# secret_key_env: BYTEPLUS_SECRET_ACCESS_KEY +# # session_token_env: BYTEPLUS_SESSION_TOKEN # optional STS temporary credentials +# # sandbox_access_token: $BYTEPLUS_VEFAAS_SANDBOX_ACCESS_TOKEN # optional APIG data-plane token +# # cpu_milli: 1000 # 250..16000 +# # memory_mb: 2048 # 512..131072 +# # timeout_minutes: 60 # 3..1440 +# # ready_timeout: 60 # seconds to wait for Running + HTTP readiness +# # 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 +# # bash_command_timeout: 600 # default remote command timeout seconds +# # ownership: +# # type: redis # required for multi-worker gateways sharing one veFaaS app +# # environment: +# # PYTHONUNBUFFERED: "1" + # ============================================================================ # Subagents Configuration # ============================================================================