fix(sandbox): forward operator environment to provisioned pods (#8370)

* fix(sandbox): forward operator environment to provisioned pods

* docs(sandbox): record the Kubernetes idle baseline

* test(sandbox): fold operator environment cases into the provisioner suite

* fix(provisioner): keep the operator environment budget and values intact

Generated capacity settings no longer travel in the forwarded map, so all 32
entries belong to the operator. Pod values are escaped before they reach the
API server, and a key with a trailing newline is rejected at validation.

* fix(provisioner): fail an unusable environment map when the backend is built

The provisioner rejects a forwarded map it cannot apply, which used to surface
only as a bare 422 on the first sandbox create. The backend now applies the same
limits while it is constructed and names the setting and key that offend, so the
failure lands before any Pod is attempted.
The provisioner README and the memory guide also record that the profile needs
the newer provisioner, and that existing Pods keep their environment.

* fix(provisioner): reject an unusable environment map at Gateway start-up

* fix(provisioner): tighten the start-up refusal wording

* fix(provisioner): skip the start-up check when the map is empty

---------

Co-authored-by: gcl-coder <gcl-coder@users.noreply.github.com>
This commit is contained in:
ChengLong GU 2026-11-24 21:14:34 +08:00 committed by GitHub
parent b5e19e03a0
commit 6f5e24b500
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 537 additions and 4 deletions

View File

@ -411,6 +411,33 @@ def _validate_agent_storage(config: AppConfig) -> None:
)
def _validate_provisioner_environment(config: AppConfig) -> None:
"""Refuse a ``sandbox.environment`` map the provisioner would reject.
The sandbox provider is built lazily, so the map used to pass startup and
fail on the first sandbox create instead: no Pod appeared, the upload path
turned the resulting ``ValueError`` into a 400 against a request that was
fine, and ``/health/ready`` still reported ready. The limits checked here
are the provisioner's own, applied to the same filtered map the backend
forwards, and sandbox allocation itself stays lazy.
"""
from app.gateway.health import resolve_provisioner_url
sandbox = getattr(config, "sandbox", None)
if resolve_provisioner_url(config) is None or not str(getattr(sandbox, "use", "")).endswith(":AioSandboxProvider"):
return
environment = dict(getattr(sandbox, "environment", None) or {})
if not environment:
return
from deerflow.community.aio_sandbox.remote_backend import check_provisioner_environment, operator_provisioner_environment
try:
check_provisioner_environment(operator_provisioner_environment(environment))
except ValueError as exc:
raise SystemExit(f"{exc}. Correct sandbox.environment in config.yaml, or remove it to use the image defaults.") from None
def _probe_managed_subagent_file_storage() -> None:
"""Warn early if this volume cannot support create-only publication."""
from deerflow.config.paths import get_paths
@ -868,6 +895,10 @@ async def langgraph_runtime(app: FastAPI, startup_config: AppConfig) -> AsyncGen
# Reject agent_storage.backend='db' on a non-durable database, and warn on
# node-divergent file storage under multi-worker Postgres.
_validate_agent_storage(startup_config)
# Reject a sandbox.environment map the provisioner cannot accept while the
# provider is still unbuilt, so the failure lands on the setting upstream of
# the first sandbox create instead of on a request that did nothing wrong.
_validate_provisioner_environment(startup_config)
if getattr(getattr(startup_config, "agent_storage", None), "backend", None) == "file":
await asyncio.to_thread(_probe_managed_subagent_file_storage)
# Warn when login lockouts stay per-process under several Gateway processes.

View File

@ -70,6 +70,59 @@ the same workload and record:
| Cleanup | Release, idle timeout, process restart, and orphan cleanup free resources |
| Operations | Deployment prerequisites, privileged components, networking, storage, and upgrade path |
## AIO idle baseline and the lean profile
Measured on `all-in-one-sandbox:1.11.0` with a local Docker run, no workload,
and `/v1/sandbox` answering 200 in every configuration:
| Configuration | Idle memory |
| --- | --- |
| Image defaults | 725 MiB |
| `DISABLE_JUPYTER=true`, `DISABLE_CODE_SERVER=true` | 281 MiB |
| The two above plus `DISABLE_BROWSER`, `DISABLE_MCP_BROWSER`, `DISABLE_VNC`, `DISABLE_NODEJS_REPL` | 165 MiB |
The image also reads `DISABLE_BROWSER`, `DISABLE_MCP_BROWSER`, `DISABLE_VNC` and
`DISABLE_NODEJS_REPL`. Turning those off removes browser screenshots, the
browser MCP server, the desktop view and Node REPL execution, so decide per
deployment whether the agent stack needs them.
The same image was measured in a temporary Kubernetes 1.31.5 cluster (k3d,
one node) with no workload. Every Pod answered `/v1/sandbox` with 200 after
90 seconds of idle time, and memory came from the Pod's cgroup
`memory.current`:
| Configuration | Kubernetes idle memory |
| --- | --- |
| Image defaults | 544 MiB |
| `DISABLE_JUPYTER=true`, `DISABLE_CODE_SERVER=true` | 317 MiB |
| The two above plus `DISABLE_BROWSER`, `DISABLE_MCP_BROWSER`, `DISABLE_VNC`, `DISABLE_NODEJS_REPL` | 191 MiB |
Kubernetes adds kubelet and container-runtime overhead and can report different
values from `docker stats`. Compare profiles in the same cluster; the relative
reduction is what decides whether the lean profile fits the deployment.
Deployments set these through `sandbox.environment`, which reaches local Docker
containers and, through the provisioner, Kubernetes sandbox Pods. The Kubernetes
path needs a provisioner that forwards that map: older provisioners ignore it
and start the Pod with image defaults, so upgrade them first. Pods that already
exist keep the environment they were created with until they are recreated. The
provisioner accepts at most 32 operator entries, names matching
`[A-Za-z_][A-Za-z0-9_]*` within 64 characters, and values of up to 1024
characters; the Gateway checks the same limits at startup, so a map it cannot
deliver stops the process with `sandbox.environment` named.
```yaml
sandbox:
use: deerflow.community.aio_sandbox:AioSandboxProvider
environment:
DISABLE_JUPYTER: "true"
DISABLE_CODE_SERVER: "true"
```
Keep a measured record of any other combination before recommending it. The
numbers above are idle figures; the workload samples in the first section decide
whether a lean profile still serves the tools an agent uses.
## PR Guidance
Do not claim that a new provider fixes high-concurrency memory usage until the

View File

@ -367,6 +367,7 @@ class AioSandboxProvider(WarmPoolLifecycleMixin[SandboxInfo], SandboxProvider):
max_shell_sessions=self._config.get("max_shell_sessions"),
max_bash_sessions=self._config.get("max_bash_sessions", 50),
required_shell_sessions=self._config.get("required_shell_sessions", 0),
environment=self._config.get("environment"),
)
logger.info("Using local container sandbox backend")

View File

@ -19,6 +19,8 @@ from __future__ import annotations
import logging
import posixpath
import re
from collections.abc import Mapping
from pathlib import PurePosixPath
import requests
@ -58,6 +60,45 @@ _RESERVED_SANDBOX_MOUNT_PATHS = (
)
_AIO_DEFAULT_MAX_SHELL_SESSIONS = 10
# ``sandbox.environment`` keys the provider composes itself and forwards through
# dedicated request fields. Sending them in the operator map as well would spend
# the provisioner's entry budget on values it already owns, so the map trimmed
# here leaves the published 32-entry limit entirely to the operator.
PROVISIONER_OWNED_ENVIRONMENT_KEYS = frozenset({"AIO_BASH_MAX_SESSIONS", "MAX_SHELL_SESSIONS", "DEERFLOW_LARK_BROKER_URL"})
# The provisioner's own limits for the forwarded map. Checked here so a config
# that cannot be delivered fails at Gateway start-up with the setting named,
# instead of surfacing later as a bare 422 on every sandbox create.
_PROVISIONER_ENVIRONMENT_KEY = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,63}")
_PROVISIONER_MAX_ENVIRONMENT_ENTRIES = 32
_PROVISIONER_MAX_ENVIRONMENT_VALUE_CHARS = 1024
def operator_provisioner_environment(environment: Mapping[str, str] | None) -> dict[str, str]:
"""Return the ``sandbox.environment`` entries that actually reach the provisioner.
Keys the provider fills from dedicated request fields are dropped here, so
the published entry limit counts operator entries only. Gateway start-up
and ``RemoteSandboxBackend`` both go through this function; a map that one
of them publishes and the other trims would drift.
"""
return {name: value for name, value in (environment or {}).items() if name not in PROVISIONER_OWNED_ENVIRONMENT_KEYS}
def check_provisioner_environment(environment: dict[str, str]) -> None:
"""Raise ``ValueError`` when the provisioner would reject ``sandbox.environment``.
Messages name the setting and the offending key but never echo a value,
because these entries commonly carry credentials.
"""
if len(environment) > _PROVISIONER_MAX_ENVIRONMENT_ENTRIES:
raise ValueError(f"sandbox.environment carries {len(environment)} entries; the provisioner applies at most {_PROVISIONER_MAX_ENVIRONMENT_ENTRIES}")
for name, value in environment.items():
if not _PROVISIONER_ENVIRONMENT_KEY.fullmatch(name):
raise ValueError(f"sandbox.environment key {name!r} must match [A-Za-z_][A-Za-z0-9_]* and be at most 64 characters")
if "\x00" in value:
raise ValueError(f"sandbox.environment value for {name!r} contains a NUL byte")
if len(value) > _PROVISIONER_MAX_ENVIRONMENT_VALUE_CHARS:
raise ValueError(f"sandbox.environment value for {name!r} exceeds {_PROVISIONER_MAX_ENVIRONMENT_VALUE_CHARS} characters")
def _normalize_skills_container_path(container_path: str) -> str:
@ -153,6 +194,7 @@ class RemoteSandboxBackend(SandboxBackend):
*,
required_shell_sessions: int = 0,
max_bash_sessions: int | None = None,
environment: dict[str, str] | None = None,
):
"""Initialize with the provisioner service URL and optional API key.
@ -165,12 +207,19 @@ class RemoteSandboxBackend(SandboxBackend):
to each provisioned sandbox Pod.
required_shell_sessions: Minimum usable capacity, even when new Pods use the image default.
max_bash_sessions: Bash capacity to provision and attest before admission.
environment: Operator ``sandbox.environment`` forwarded to the
sandbox Pod so optional AIO services can be disabled per
deployment (for example ``DISABLE_JUPYTER``). Keys the
provider sets from dedicated fields are dropped before the
request is sent.
"""
self._provisioner_url = provisioner_url.rstrip("/")
self._api_key = api_key
self._max_shell_sessions = max_shell_sessions
self._max_bash_sessions = max_bash_sessions
self._required_shell_sessions = max(required_shell_sessions, max_shell_sessions or 0)
self._environment = operator_provisioner_environment(environment)
check_provisioner_environment(self._environment)
@property
def provisioner_url(self) -> str:
@ -354,6 +403,8 @@ class RemoteSandboxBackend(SandboxBackend):
payload["max_shell_sessions"] = self._max_shell_sessions
if self._max_bash_sessions is not None:
payload["max_bash_sessions"] = self._max_bash_sessions
if self._environment:
payload["environment"] = dict(self._environment)
provisioner_extra_mounts = _provisioner_extra_mounts_payload(
extra_mounts,
skills_container_path=normalized_skills_container_path,

View File

@ -208,6 +208,57 @@ def test_backend_checks_runtime_minimum_without_overriding_image_default(monkeyp
assert listed[0].requires_replacement is (persisted_capacity < 9)
@pytest.mark.parametrize("remote", [False, True], ids=["docker", "provisioner"])
def test_backend_generated_capacity_stays_out_of_the_forwarded_map(monkeypatch, remote):
"""The provisioner scores its entry budget against operator keys, so owned keys stop at the provider."""
aio_mod = importlib.import_module("deerflow.community.aio_sandbox.aio_sandbox_provider")
app_config = SimpleNamespace(
sandbox=SandboxConfig(
use="deerflow.community.aio_sandbox:AioSandboxProvider",
container_prefix="sandbox",
provisioner_url="http://provisioner:8002" if remote else None,
environment={"DISABLE_JUPYTER": "true"},
),
stream_bridge=None,
subagent_runtime=SimpleNamespace(max_running=12),
)
monkeypatch.setattr(aio_mod, "get_app_config", lambda: app_config)
provider = aio_mod.AioSandboxProvider.__new__(aio_mod.AioSandboxProvider)
provider._config = provider._load_config()
assert provider._config["environment"]["AIO_BASH_MAX_SESSIONS"] == "50"
assert provider._config["environment"]["MAX_SHELL_SESSIONS"] == "13"
backend = provider._create_backend()
if remote:
assert backend._environment == {"DISABLE_JUPYTER": "true"}
assert backend._max_shell_sessions == 13
else:
assert backend._environment["MAX_SHELL_SESSIONS"] == "13"
assert backend._environment["AIO_BASH_MAX_SESSIONS"] == "50"
def test_provisioner_backend_rejects_an_unusable_environment_at_startup(monkeypatch):
"""A map the provisioner would refuse must fail where the operator can see the setting name."""
aio_mod = importlib.import_module("deerflow.community.aio_sandbox.aio_sandbox_provider")
app_config = SimpleNamespace(
sandbox=SandboxConfig(
use="deerflow.community.aio_sandbox:AioSandboxProvider",
container_prefix="sandbox",
provisioner_url="http://provisioner:8002",
environment={f"OPERATOR_{index}": "true" for index in range(33)},
),
stream_bridge=None,
subagent_runtime=SimpleNamespace(max_running=3),
)
monkeypatch.setattr(aio_mod, "get_app_config", lambda: app_config)
provider = aio_mod.AioSandboxProvider.__new__(aio_mod.AioSandboxProvider)
provider._config = provider._load_config()
with pytest.raises(ValueError, match=r"sandbox\.environment carries 33 entries; the provisioner applies at most 32"):
provider._create_backend()
def test_load_config_rejects_shell_capacity_below_subagent_runtime(monkeypatch):
aio_mod = importlib.import_module("deerflow.community.aio_sandbox.aio_sandbox_provider")
sandbox_config = SandboxConfig(

View File

@ -24,6 +24,7 @@ from app.gateway.deps import (
_validate_agent_storage,
_validate_login_throttle_storage,
_validate_memory_retrieval_index,
_validate_provisioner_environment,
credentials_key_consumers,
langgraph_runtime,
)
@ -982,6 +983,83 @@ async def test_langgraph_runtime_enforces_the_credentials_key_before_persistence
make_stream_bridge.assert_not_called()
# ---------------------------------------------------------------------------
# sandbox.environment for provisioner sandboxes
# ---------------------------------------------------------------------------
def _provisioner_config(environment: dict[str, str] | None, *, use: str = "deerflow.community.aio_sandbox:AioSandboxProvider", provisioner_url: str | None = "http://provisioner:8002"):
config = _cluster_ready()
config.sandbox = SimpleNamespace(use=use, environment=environment or {}, provisioner_url=provisioner_url)
return config
def test_provisioner_environment_is_rejected_while_startup_config_is_validated():
"""The provider is built lazily, so a config the provisioner refuses must fail before /health/ready.
It used to pass startup and only break the first sandbox create, which the
upload handler reported as a 400 against a request that was fine.
"""
with pytest.raises(SystemExit) as exc_info:
_validate_provisioner_environment(_provisioner_config({f"OPERATOR_{index}": "true" for index in range(33)}))
msg = str(exc_info.value)
assert "sandbox.environment carries 33 entries; the provisioner applies at most 32" in msg
assert "config.yaml" in msg, "must point at the file an operator edits"
@pytest.mark.parametrize(
("environment", "message"),
[
({"DISABLE JUPYTER": "true"}, "must match"),
({"DISABLE_VNC": "x" * 1025}, "exceeds 1024 characters"),
({"DISABLE_VNC": "true\x00"}, "NUL byte"),
],
)
def test_provisioner_environment_rejects_the_names_and_values_the_provisioner_refuses(environment, message):
with pytest.raises(SystemExit, match=message):
_validate_provisioner_environment(_provisioner_config(environment))
def test_provisioner_environment_counts_only_entries_the_operator_sends():
"""The provider's own capacity keys travel in dedicated fields and never spend the 32 entries."""
operator = {f"OPERATOR_{index}": "true" for index in range(32)}
_validate_provisioner_environment(_provisioner_config({**operator, "AIO_BASH_MAX_SESSIONS": "50", "MAX_SHELL_SESSIONS": "13"}))
@pytest.mark.parametrize(
("use", "provisioner_url"),
[
("deerflow.community.aio_sandbox:AioSandboxProvider", None),
("deerflow.sandbox.local:LocalSandboxProvider", "http://provisioner:8002"),
],
ids=["no-provisioner", "local-backend"],
)
def test_provisioner_environment_is_not_checked_without_a_provisioner_backend(use, provisioner_url):
"""Nothing forwards this map to a provisioner, so its limits do not apply."""
_validate_provisioner_environment(_provisioner_config({f"OPERATOR_{index}": "true" for index in range(33)}, use=use, provisioner_url=provisioner_url))
@pytest.mark.asyncio
async def test_langgraph_runtime_validates_the_provisioner_environment_before_persistence_setup():
init_engine_from_config = AsyncMock(name="init_engine_from_config")
@asynccontextmanager
async def _noop_stream_bridge(_config):
yield MagicMock()
with (
patch("deerflow.persistence.engine.init_engine_from_config", init_engine_from_config),
patch("deerflow.runtime.make_stream_bridge", side_effect=_noop_stream_bridge) as make_stream_bridge,
):
startup_config = _provisioner_config({f"OPERATOR_{index}": "true" for index in range(33)})
with pytest.raises(SystemExit, match="sandbox.environment carries 33 entries"):
async with langgraph_runtime(FastAPI(), startup_config):
pass
init_engine_from_config.assert_not_called()
make_stream_bridge.assert_not_called()
# ---------------------------------------------------------------------------
# IM channel leader lease clause (channels.leader_lease)
# ---------------------------------------------------------------------------

View File

@ -103,6 +103,108 @@ def test_provisioner_threads_shell_capacity_into_sandbox_pod(
assert env["MAX_SHELL_SESSIONS"] == "13"
@pytest.mark.parametrize(
"name",
["DISABLE JUPYTER", "1DISABLE", "DISABLE-YUP", "D" * 65, "DISABLE_JUPYTER\n"],
)
def test_provisioner_rejects_malformed_environment_keys(provisioner_module, name: str) -> None:
from pydantic import ValidationError
with pytest.raises(ValidationError):
provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-env", environment={name: "true"})
def test_provisioner_rejects_unusable_environment_entries(provisioner_module) -> None:
from pydantic import ValidationError
requests = [
{f"KEY_{index}": "true" for index in range(33)},
{"DISABLE_VNC": "x" * 1025},
{"DISABLE_VNC": "true\x00"},
]
for environment in requests:
with pytest.raises(ValidationError):
provisioner_module.CreateSandboxRequest(sandbox_id="sandbox-env", environment=environment)
@pytest.mark.parametrize(
("written", "expected"),
[
("example$$suffix", "example$$$$suffix"),
("$(POD_NAME)", "$$(POD_NAME)"),
("plain", "plain"),
],
)
def test_provisioner_keeps_pod_environment_values_literal(monkeypatch, provisioner_module, written, expected) -> None:
"""Kubelet expands $(NAME) and collapses $$, so every value is escaped before it is written."""
core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-escape": 1})
monkeypatch.setattr(provisioner_module, "core_v1", core)
provisioner_module.create_sandbox(
provisioner_module.CreateSandboxRequest(
sandbox_id="sandbox-escape",
thread_id="thread-1",
environment={"DISABLE_VNC": written},
)
)
pod = core.created_pod_specs["sandbox-escape"]
env = {item.name: item.value for item in (pod.spec.containers[0].env or [])}
assert env["DISABLE_VNC"] == expected
def test_provisioner_threads_operator_environment_into_sandbox_pod(
monkeypatch: pytest.MonkeyPatch,
provisioner_module,
) -> None:
fake_core_v1 = _RecordingCoreV1(
event_loop_thread_id=-1,
ready_after_service_reads={"sandbox-env": 1},
)
monkeypatch.setattr(provisioner_module, "core_v1", fake_core_v1)
response = provisioner_module.create_sandbox(
provisioner_module.CreateSandboxRequest(
sandbox_id="sandbox-env",
thread_id="thread-1",
environment={"DISABLE_JUPYTER": "true", "DISABLE_CODE_SERVER": "true"},
)
)
assert response.status == "Running"
pod = fake_core_v1.created_pod_specs["sandbox-env"]
env = {item.name: item.value for item in (pod.spec.containers[0].env or [])}
assert env["DISABLE_JUPYTER"] == "true"
assert env["DISABLE_CODE_SERVER"] == "true"
def test_provisioner_keeps_its_own_environment_keys(monkeypatch, provisioner_module) -> None:
core = _RecordingCoreV1(event_loop_thread_id=-1, ready_after_service_reads={"sandbox-owned": 1})
monkeypatch.setattr(provisioner_module, "core_v1", core)
reserved = {
"AIO_BASH_MAX_SESSIONS": "9999",
"MAX_SHELL_SESSIONS": "13",
"DEERFLOW_LARK_BROKER_URL": "http://spoofed",
}
provisioner_module.create_sandbox(
provisioner_module.CreateSandboxRequest(
sandbox_id="sandbox-owned",
thread_id="thread-1",
max_bash_sessions=10,
environment={**reserved, "DISABLE_VNC": "true"},
)
)
pod = core.created_pod_specs["sandbox-owned"]
env = {item.name: item.value for item in (pod.spec.containers[0].env or [])}
assert env["AIO_BASH_MAX_SESSIONS"] == "10"
# The provisioner only sets the shell limit when the request carries one.
assert "MAX_SHELL_SESSIONS" not in env
assert "DEERFLOW_LARK_BROKER_URL" not in env
assert env["DISABLE_VNC"] == "true"
@pytest.mark.parametrize("capacity", [1, 50, 72])
def test_provisioner_attests_bash_capacity_from_created_and_reused_pod(monkeypatch, provisioner_module, capacity):
core = _RecordingCoreV1(event_loop_thread_id=-1)

View File

@ -824,3 +824,99 @@ def test_provisioner_discover_returns_none_on_request_exception(monkeypatch):
monkeypatch.setattr(requests, "get", mock_get)
assert backend._provisioner_discover("abc123") is None
def test_provisioner_create_forwards_sandbox_environment(monkeypatch):
backend = RemoteSandboxBackend(
"http://provisioner:8002",
environment={"DISABLE_JUPYTER": "true", "DISABLE_CODE_SERVER": "true"},
)
monkeypatch.setattr(remote_backend_mod, "user_should_see_legacy_skills", lambda _user_id: False)
seen = {}
def mock_post(url, json, timeout, headers=None):
seen.update(json)
return _StubResponse(payload={"sandbox_id": "abc123", "sandbox_url": "http://k3s:31001"})
monkeypatch.setattr(requests, "post", mock_post)
backend._provisioner_create("thread-1", "abc123")
assert seen["environment"] == {"DISABLE_JUPYTER": "true", "DISABLE_CODE_SERVER": "true"}
def test_provisioner_create_leaves_owned_settings_to_dedicated_fields(monkeypatch):
"""Dropped capacity keys must not eat the operator's entry budget."""
operator = {f"OPERATOR_{index}": "true" for index in range(32)}
backend = RemoteSandboxBackend(
"http://provisioner:8002",
max_shell_sessions=13,
max_bash_sessions=50,
environment={
**operator,
"AIO_BASH_MAX_SESSIONS": "50",
"MAX_SHELL_SESSIONS": "13",
"DEERFLOW_LARK_BROKER_URL": "http://spoofed",
},
)
monkeypatch.setattr(remote_backend_mod, "user_should_see_legacy_skills", lambda _user_id: False)
seen = {}
def mock_post(url, json, timeout, headers=None):
seen.update(json)
return _StubResponse(payload={"sandbox_id": "abc123", "sandbox_url": "http://k3s:31001", "max_shell_sessions": 13, "max_bash_sessions": 50})
monkeypatch.setattr(requests, "post", mock_post)
backend._provisioner_create("thread-1", "abc123")
assert seen["environment"] == operator
assert (seen["max_shell_sessions"], seen["max_bash_sessions"]) == (13, 50)
@pytest.mark.parametrize(
("environment", "message"),
[
({f"OPERATOR_{index}": "true" for index in range(33)}, "carries 33 entries"),
({"DISABLE JUPYTER": "true"}, "must match"),
({"DISABLE_VNC": "x" * 1025}, "exceeds 1024 characters"),
({"DISABLE_VNC": "true\x00"}, "NUL byte"),
],
)
def test_provisioner_backend_rejects_a_map_the_provisioner_would_refuse(environment, message):
"""A config the provisioner rejects must fail where the operator set it, not on first create."""
with pytest.raises(ValueError, match=message):
RemoteSandboxBackend("http://provisioner:8002", environment=environment)
def test_provisioner_backend_counts_entries_the_provisioner_owns_out(monkeypatch):
"""Owned keys never reach the provisioner, so they cannot push a valid map over its limit."""
operator = {f"OPERATOR_{index}": "true" for index in range(32)}
backend = RemoteSandboxBackend(
"http://provisioner:8002",
environment={**operator, "AIO_BASH_MAX_SESSIONS": "50", "MAX_SHELL_SESSIONS": "13"},
)
monkeypatch.setattr(remote_backend_mod, "user_should_see_legacy_skills", lambda _user_id: False)
seen = {}
def mock_post(url, json, timeout, headers=None):
seen.update(json)
return _StubResponse(payload={"sandbox_id": "abc123", "sandbox_url": "http://k3s:31001", "max_shell_sessions": 13, "max_bash_sessions": 50})
monkeypatch.setattr(requests, "post", mock_post)
backend._provisioner_create("thread-1", "abc123")
assert seen["environment"] == operator
def test_provisioner_create_omits_environment_when_unconfigured(monkeypatch):
backend = RemoteSandboxBackend("http://provisioner:8002")
monkeypatch.setattr(remote_backend_mod, "user_should_see_legacy_skills", lambda _user_id: False)
seen = {}
def mock_post(url, json, timeout, headers=None):
seen.update(json)
return _StubResponse(payload={"sandbox_id": "abc123", "sandbox_url": "http://k3s:31001"})
monkeypatch.setattr(requests, "post", mock_post)
backend._provisioner_create("thread-1", "abc123")
assert "environment" not in seen

View File

@ -186,6 +186,32 @@ provisioner does not delete an existing Pod to upgrade its capacity, including
after a transient Gateway discovery failure. If the old Pod has already gone
but its Service remains, create can safely provision the missing Pod.
The Gateway also forwards the operator's `sandbox.environment` map, and the
provisioner writes those entries to the sandbox container so image-level knobs
such as `DISABLE_JUPYTER=true` or `DISABLE_CODE_SERVER=true` reach Kubernetes
sandboxes the same way they reach local Docker ones. A Gateway that provisions
through this service leaves `AIO_BASH_MAX_SESSIONS`, `MAX_SHELL_SESSIONS` and
`DEERFLOW_LARK_BROKER_URL` out of that map, because it already sends them
through the dedicated fields above; the provisioner ignores those names in the
map if another client sends them anyway, so one Pod keeps a single source per
setting. All 32 entries a request may carry are therefore the operator's own,
keys must match `[A-Za-z_][A-Za-z0-9_]*` within 64 characters, and a value is
limited to 1024 characters. Values are written literally: a `$` is escaped so
Kubernetes does not expand `$(NAME)` or collapse `$$` before the container reads
the value.
The Gateway applies those limits to the filtered map while it starts, so a map
this service would refuse stops the Gateway with `sandbox.environment` named
instead of failing the first sandbox create. Sandbox allocation itself stays
lazy.
Both directions of a version skew drop the profile silently, so upgrade the
provisioner before you rely on it. A request from a Gateway older than this
change carries no map and produces the same Pods as before; a new Gateway
talking to a provisioner from before this change gets a successful create whose
Pod ignores the map. Existing Pods also keep the environment they were created
with until they are recreated.
### Custom sandbox image
Provisioner-created sandbox Pods use the provisioner's `SANDBOX_IMAGE` environment variable. This is separate from `sandbox.image` in `config.yaml`, which applies to local Docker or Apple Container mode.

View File

@ -45,7 +45,7 @@ from fastapi import FastAPI, HTTPException, Request, Response
from kubernetes import client as k8s_client
from kubernetes import config as k8s_config
from kubernetes.client.rest import ApiException
from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, field_validator
# Suppress only the InsecureRequestWarning from urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
@ -77,6 +77,14 @@ LARK_CLI_RUNTIME_VOLUME_NAME = "lark-cli-runtime"
# broker off (Pattern A / legacy behavior). Broker supersedes Pattern A when both
# are set.
LARK_CLI_BROKER_IMAGE = os.environ.get("LARK_CLI_BROKER_IMAGE", "")
# Sandbox Pod environment the Gateway forwards from ``sandbox.environment``.
# Entries whose names the provisioner already sets from dedicated request fields
# are dropped so one Pod never carries two sources for the same setting.
RESERVED_SANDBOX_ENVIRONMENT_KEYS = frozenset({"AIO_BASH_MAX_SESSIONS", "MAX_SHELL_SESSIONS", "DEERFLOW_LARK_BROKER_URL"})
MAX_SANDBOX_ENVIRONMENT_ENTRIES = 32
MAX_SANDBOX_ENVIRONMENT_VALUE_CHARS = 1024
SANDBOX_ENVIRONMENT_KEY_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,63}")
# Machine-readable marker attached to lark provisioning-config conflict
# responses (409/503) telling the Gateway to drop its cached broker
# capability observation for this endpoint. Keep in sync with
@ -569,6 +577,25 @@ class CreateSandboxRequest(BaseModel):
# keeps requests from older Gateways and custom provisioner callers working.
max_shell_sessions: int | None = Field(default=None, gt=0)
max_bash_sessions: int | None = Field(default=None, gt=0)
# Operator ``sandbox.environment`` forwarded by the Gateway. The AIO image
# reads these to disable optional services (DISABLE_JUPYTER, ...), which is
# how a deployment lowers idle per-sandbox memory (#3213). Keys the
# provisioner owns are dropped in ``_build_pod``.
environment: dict[str, str] = Field(default_factory=dict)
@field_validator("environment")
@classmethod
def _validate_environment(cls, value: dict[str, str]) -> dict[str, str]:
if len(value) > MAX_SANDBOX_ENVIRONMENT_ENTRIES:
raise ValueError(f"environment accepts at most {MAX_SANDBOX_ENVIRONMENT_ENTRIES} entries")
for name, entry in value.items():
if not SANDBOX_ENVIRONMENT_KEY_PATTERN.fullmatch(name):
raise ValueError(f"environment key {name!r} must match [A-Za-z_][A-Za-z0-9_]* and be at most 64 characters")
if "\x00" in entry:
raise ValueError(f"environment value for {name!r} contains a NUL byte")
if len(entry) > MAX_SANDBOX_ENVIRONMENT_VALUE_CHARS:
raise ValueError(f"environment value for {name!r} exceeds {MAX_SANDBOX_ENVIRONMENT_VALUE_CHARS} characters")
return value
class SandboxResponse(BaseModel):
@ -1031,6 +1058,17 @@ def _build_lark_cli_broker_sidecars(
]
def _pod_environment_value(value: str) -> str:
"""Escape a container value so Kubernetes stores it literally.
Kubelet treats ``$(NAME)`` in a plain ``env.value`` as a reference to an
earlier variable and collapses ``$$`` to ``$``. Doubling every dollar sign
cancels both rewrites, so the container reads the value the operator wrote
instead of one the API server derived from it.
"""
return value.replace("$", "$$")
def _build_pod(
sandbox_id: str,
thread_id: str,
@ -1042,6 +1080,7 @@ def _build_pod(
provision_lark_cli_broker: bool = False,
max_shell_sessions: int | None = None,
max_bash_sessions: int | None = None,
environment: dict[str, str] | None = None,
) -> k8s_client.V1Pod:
"""Construct a Pod manifest for a single sandbox."""
_validate_lark_provisioning_request(provision_lark_cli_runtime, provision_lark_cli_broker)
@ -1050,21 +1089,25 @@ def _build_pod(
)
sandbox_env: list[k8s_client.V1EnvVar] = []
if max_bash_sessions is not None:
sandbox_env.append(k8s_client.V1EnvVar(name="AIO_BASH_MAX_SESSIONS", value=str(max_bash_sessions)))
sandbox_env.append(k8s_client.V1EnvVar(name="AIO_BASH_MAX_SESSIONS", value=_pod_environment_value(str(max_bash_sessions))))
if max_shell_sessions is not None:
sandbox_env.append(
k8s_client.V1EnvVar(
name="MAX_SHELL_SESSIONS",
value=str(max_shell_sessions),
value=_pod_environment_value(str(max_shell_sessions)),
)
)
if _lark_cli_broker_enabled(provision_lark_cli_broker):
sandbox_env.append(
k8s_client.V1EnvVar(
name="DEERFLOW_LARK_BROKER_URL",
value=LARK_BROKER_URL,
value=_pod_environment_value(LARK_BROKER_URL),
)
)
for name, value in sorted((environment or {}).items()):
if name in RESERVED_SANDBOX_ENVIRONMENT_KEYS:
continue
sandbox_env.append(k8s_client.V1EnvVar(name=name, value=_pod_environment_value(value)))
return k8s_client.V1Pod(
metadata=k8s_client.V1ObjectMeta(
name=_pod_name(sandbox_id),
@ -1391,6 +1434,7 @@ def create_sandbox(req: CreateSandboxRequest):
provision_lark_cli_broker=provision_lark_cli_broker,
max_shell_sessions=max_shell_sessions,
max_bash_sessions=max_bash_sessions,
environment=req.environment,
),
)
logger.info(f"Created Pod {_pod_name(sandbox_id)}")