feat(sandbox): make AIO sandbox Pod resources configurable (#8575)

* feat(sandbox): configure AIO sandbox Pod resource requests and limits

* fix(helm): reject unknown sandbox resource keys

Validate sandboxResources requests and limits against the three resource names the AIO provisioner reads. Helm now reports misspellings and unsupported extended resources during rendering, before a sandbox can start with the default limit.

Cover a misspelled memory limit and an extended resource request in the Helm render tests.
This commit is contained in:
ZedingZhang 2026-11-25 22:02:46 +08:00 committed by GitHub
parent f56fb962d0
commit f9b7598fdd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 187 additions and 13 deletions

View File

@ -81,7 +81,7 @@ def _render_chart(*settings: str) -> list[dict]:
def _render_failure(*args: str) -> str:
"""Return helm's stderr for a render that must be refused."""
result = _helm(*args)
assert result.returncode != 0, "the render must fail instead of producing a budget that protects nothing"
assert result.returncode != 0, "Helm accepted invalid chart values"
return result.stderr
@ -262,6 +262,30 @@ def test_rendered_default_matches_the_previous_single_replica_deployment() -> No
assert not any(document.get("kind") == "PodDisruptionBudget" for document in documents)
def test_rendered_provisioner_passes_sandbox_resources_as_strings() -> None:
documents = _render_chart("provisioner.sandboxResources.limits.cpu=2", "provisioner.sandboxResources.requests.ephemeral-storage=0")
deployment = _by_kind(documents, "Deployment", "-provisioner")
container = deployment["spec"]["template"]["spec"]["containers"][0]
env = {item["name"]: item.get("value") for item in container["env"]}
assert {key: value for key, value in env.items() if key.endswith(("_REQUEST", "_LIMIT"))} == {
"SANDBOX_CPU_REQUEST": "100m",
"SANDBOX_MEMORY_REQUEST": "256Mi",
"SANDBOX_EPHEMERAL_STORAGE_REQUEST": "0",
"SANDBOX_CPU_LIMIT": "2",
"SANDBOX_MEMORY_LIMIT": "1Gi",
"SANDBOX_EPHEMERAL_STORAGE_LIMIT": "500Mi",
}
assert container["resources"] == _values()["provisioner"]["resources"]
@pytest.mark.parametrize(("group", "resource"), [("limits", "memroy"), ("requests", "nvidia.com/gpu")])
def test_render_rejects_unknown_sandbox_resource(group: str, resource: str, tmp_path: Path) -> None:
values_file = tmp_path / "values.yaml"
values_file.write_text(yaml.safe_dump({"provisioner": {"sandboxResources": {group: {resource: "1"}}}}), encoding="utf-8", newline="\n")
error = _render_failure("--values", str(values_file))
assert group in error and resource in error
def test_gateway_and_provisioner_budgets_render_side_by_side() -> None:
documents = _render_chart("gateway.replicas=2", "provisioner.replicas=2")
names = sorted(document["metadata"]["name"] for document in documents if document.get("kind") == "PodDisruptionBudget")

View File

@ -103,6 +103,42 @@ def test_provisioner_threads_shell_capacity_into_sandbox_pod(
assert env["MAX_SHELL_SESSIONS"] == "13"
def test_sandbox_pod_default_resources(provisioner_module):
resources = provisioner_module._build_pod("sandbox-1", "thread-1").spec.containers[0].resources
assert resources.requests == {"cpu": "100m", "memory": "256Mi", "ephemeral-storage": "500Mi"}
assert resources.limits == {"cpu": "1000m", "memory": "1Gi", "ephemeral-storage": "500Mi"}
def test_sandbox_pod_resource_overrides(monkeypatch, request):
monkeypatch.setenv("SANDBOX_CPU_REQUEST", "500m")
monkeypatch.setenv("SANDBOX_CPU_LIMIT", ".5")
monkeypatch.setenv("SANDBOX_MEMORY_REQUEST", "1024Mi")
monkeypatch.setenv("SANDBOX_EPHEMERAL_STORAGE_REQUEST", "1e9")
monkeypatch.setenv("SANDBOX_EPHEMERAL_STORAGE_LIMIT", "1Gi")
module = request.getfixturevalue("provisioner_module")
resources = module._build_pod("sandbox-1", "thread-1").spec.containers[0].resources
assert resources.requests == {"cpu": "500m", "memory": "1024Mi", "ephemeral-storage": "1e9"}
assert resources.limits == {"cpu": ".5", "memory": "1Gi", "ephemeral-storage": "1Gi"}
@pytest.mark.parametrize(
"variable,value",
[
("SANDBOX_CPU_REQUEST", "1001m"),
("SANDBOX_MEMORY_LIMIT", "250M"),
("SANDBOX_EPHEMERAL_STORAGE_REQUEST", "501Mi"),
("SANDBOX_CPU_LIMIT", "NaN"),
("SANDBOX_MEMORY_LIMIT", "1e3Mi"),
("SANDBOX_MEMORY_REQUEST", "-1"),
("SANDBOX_EPHEMERAL_STORAGE_LIMIT", ""),
],
)
def test_invalid_sandbox_resources_fail_at_startup(monkeypatch, request, variable, value):
monkeypatch.setenv(variable, value)
with pytest.raises(RuntimeError, match=variable):
request.getfixturevalue("provisioner_module")
@pytest.mark.parametrize(
"name",
["DISABLE JUPYTER", "1DISABLE", "DISABLE-YUP", "D" * 65, "DISABLE_JUPYTER\n"],

View File

@ -519,6 +519,8 @@ triggers a rolling restart.
`nginx.resources`, `provisioner.resources`, `postgresql.primary.resources`,
`redis.primary.resources`). The gateway's init containers have their own
`gateway.initContainers.resources` and `gateway.initContainers.image`.
Set `provisioner.sandboxResources` for each new sandbox Pod. See
[Kubernetes sandbox Pod resources](../../../docs/guide/sandbox.md#kubernetes-sandbox-pod-resources).
### Not yet enforced (deferred hardening)

View File

@ -53,6 +53,16 @@ spec:
value: {{ include "deer-flow.namespace" . | quote }}
- name: SANDBOX_IMAGE
value: {{ .Values.provisioner.sandboxImage | quote }}
{{- with .Values.provisioner.sandboxResources }}
{{- range $resource, $quantity := .requests }}
- name: SANDBOX_{{ $resource | replace "-" "_" | upper }}_REQUEST
value: {{ $quantity | quote }}
{{- end }}
{{- range $resource, $quantity := .limits }}
- name: SANDBOX_{{ $resource | replace "-" "_" | upper }}_LIMIT
value: {{ $quantity | quote }}
{{- end }}
{{- end }}
# Shared secret the gateway sends as X-API-Key. verify_api_key in
# docker/provisioner/app.py answers 401 to every /api/* request
# while this is empty or mismatched, so a provisioner without it

View File

@ -0,0 +1,30 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"provisioner": {
"type": "object",
"properties": {
"sandboxResources": {
"type": "object",
"properties": {
"requests": { "$ref": "#/definitions/sandboxResourceQuantities" },
"limits": { "$ref": "#/definitions/sandboxResourceQuantities" }
},
"additionalProperties": false
}
}
}
},
"definitions": {
"sandboxResourceQuantities": {
"type": "object",
"properties": {
"cpu": {},
"memory": {},
"ephemeral-storage": {}
},
"additionalProperties": false
}
}
}

View File

@ -215,6 +215,16 @@ provisioner:
memory: 512Mi
# -- AIO-compatible sandbox container image used for sandbox Pods.
sandboxImage: "enterprise-public-cn-beijing.cr.volces.com/vefaas-public/all-in-one-sandbox:latest"
# -- Resource requests and limits for the sandbox container in each new Pod.
sandboxResources:
requests:
cpu: 100m
memory: 256Mi
ephemeral-storage: 500Mi
limits:
cpu: 1000m
memory: 1Gi
ephemeral-storage: 500Mi
# -- Service type for per-sandbox Services. `ClusterIP` (default) exposes
# sandboxes only inside the cluster via Service DNS - correct for the
# in-cluster gateway and avoids binding the code-execution surface on

View File

@ -175,6 +175,9 @@ The provisioner is configured via environment variables (set in [docker-compose-
| `NODE_HOST` | `host.docker.internal` | Hostname that backend containers use to reach host NodePorts; ignored when `SANDBOX_SERVICE_TYPE=ClusterIP` |
| `K8S_API_SERVER` | (from kubeconfig) | Override K8s API server URL (e.g., `https://host.docker.internal:26443`) |
For the sandbox CPU, memory and ephemeral storage environment variables and their
defaults, see [Kubernetes sandbox Pod resources](../../docs/guide/sandbox.md#kubernetes-sandbox-pod-resources).
For new sandbox requests, the Gateway also sends the effective AIO shell-session
capacity derived from `subagent_runtime.max_running`. The provisioner writes it
to the sandbox Pod as `MAX_SHELL_SESSIONS`; requests from older Gateways omit the

View File

@ -38,6 +38,7 @@ import re
import secrets
import time
from contextlib import asynccontextmanager
from decimal import Decimal, DecimalException, localcontext
from pathlib import PurePosixPath, PureWindowsPath
import urllib3
@ -45,6 +46,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 kubernetes.utils.quantity import parse_quantity
from pydantic import BaseModel, Field, field_validator
# Suppress only the InsecureRequestWarning from urllib3
@ -160,6 +162,46 @@ PROVISIONER_API_KEY = os.environ.get("PROVISIONER_API_KEY", "")
NODE_HOST = os.environ.get("NODE_HOST", "host.docker.internal")
# The client's parse_quantity also accepts Decimal spellings (NaN, underscores,
# exponents combined with SI suffixes) that the Kubernetes API rejects.
_RESOURCE_QUANTITY = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+|[numkMGTPE]|[KMGTPE]i)?")
def _read_resource_quantity(name: str, default: str) -> tuple[str, Decimal]:
value = os.environ.get(name, default)
if not _RESOURCE_QUANTITY.fullmatch(value):
raise RuntimeError(f"Invalid {name}={value!r}: expected a Kubernetes resource quantity")
try:
with localcontext() as context:
# Keep comparisons exact even when multiplying by Ei (2**60).
context.prec = max(context.prec, len(value) + 19)
amount = parse_quantity(value)
except (DecimalException, ValueError) as exc:
raise RuntimeError(f"Invalid {name}={value!r}: {exc}") from exc
if amount < 0:
raise RuntimeError(f"Invalid {name}={value!r}: resource quantities must be nonnegative")
return value, amount
def _load_sandbox_resources() -> k8s_client.V1ResourceRequirements:
requests = {}
limits = {}
for resource, default_request, default_limit in (
("cpu", "100m", "1000m"),
("memory", "256Mi", "1Gi"),
("ephemeral-storage", "500Mi", "500Mi"),
):
prefix = "SANDBOX_" + resource.upper().replace("-", "_")
requests[resource], request = _read_resource_quantity(f"{prefix}_REQUEST", default_request)
limits[resource], limit = _read_resource_quantity(f"{prefix}_LIMIT", default_limit)
if request > limit:
raise RuntimeError(f"{prefix}_REQUEST={requests[resource]!r} exceeds {prefix}_LIMIT={limits[resource]!r}")
return k8s_client.V1ResourceRequirements(requests=requests, limits=limits)
SANDBOX_RESOURCES = _load_sandbox_resources()
def join_host_path(base: str, *parts: str) -> str:
"""Join host filesystem path segments for a Kubernetes hostPath.
@ -1153,18 +1195,7 @@ def _build_pod(
timeout_seconds=3,
failure_threshold=3,
),
resources=k8s_client.V1ResourceRequirements(
requests={
"cpu": "100m",
"memory": "256Mi",
"ephemeral-storage": "500Mi",
},
limits={
"cpu": "1000m",
"memory": "1Gi",
"ephemeral-storage": "500Mi",
},
),
resources=SANDBOX_RESOURCES,
volume_mounts=_build_volume_mounts(
thread_id,
user_id=user_id,

View File

@ -131,6 +131,34 @@ saved API error responses and avoids blocking later reads when the optional
`tool_progress` guard is enabled. Actual read failures and output truncation
still retain their error or partial-result status.
## Kubernetes sandbox Pod resources
With the AIO Kubernetes provisioner, set `provisioner.sandboxResources` in
your Helm values to size the sandbox container in each new Pod. For example,
to raise the memory limit to 4 GiB and the ephemeral storage limit to 2 GiB:
```yaml
provisioner:
sandboxResources:
limits:
memory: 4Gi
ephemeral-storage: 2Gi
```
Each field can be overridden independently. Helm rejects unknown resource names
in `requests` and `limits` when rendering the chart. For a standalone provisioner,
set the corresponding environment variables on the provisioner container.
| Resource | Request variable | Default request | Limit variable | Default limit |
| --- | --- | --- | --- | --- |
| `cpu` | `SANDBOX_CPU_REQUEST` | `100m` | `SANDBOX_CPU_LIMIT` | `1000m` |
| `memory` | `SANDBOX_MEMORY_REQUEST` | `256Mi` | `SANDBOX_MEMORY_LIMIT` | `1Gi` |
| `ephemeral-storage` | `SANDBOX_EPHEMERAL_STORAGE_REQUEST` | `500Mi` | `SANDBOX_EPHEMERAL_STORAGE_LIMIT` | `500Mi` |
The provisioner checks at startup that each value is a nonnegative Kubernetes
quantity and each request is at most its limit. The separate Helm value
`provisioner.resources` sizes the provisioner container itself.
## Redis Cluster for shared sandbox ownership
Gateways sharing AIO containers or E2B VMs can store ownership leases in Redis