# 샌드박스

> [!NOTE]
> Sandbox API는 실험적입니다. API 및 동작이 사전 통보 없이 변경될 수 있습니다. 공유 샌드박스는 동일한 신뢰 경계 내 워크로드를 위해 설계되었습니다. 서로를 신뢰하지 않는 워크로드의 경우 전용 샌드박스를 사용하세요.

사용 방법을 배우려면 [Sandboxes 가이드](../guides/sandbox)를 확인하세요.

## Sandbox[[huggingface_hub.Sandbox]]

#### huggingface_hub.Sandbox[[huggingface_hub.Sandbox]]

```python
huggingface_hub.Sandbox(id: str, server: _SandboxServer, local_id: str | None, owns_sandbox: bool, owns_server: bool, sandbox_token: str | None = None)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L809)

Hugging Face Jobs에서 실행되는 격리된 클라우드 머신입니다.

> [!NOTE]
> Sandbox API는 실험적입니다. API 및 동작이 사전 통보 없이 변경될 수 있습니다.

[Sandbox.create()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.create)를 사용하여 전용 샌드박스를 하나 생성하거나(샌드박스당 하나의 작업), [SandboxPool](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxPool)에서 저렴하게 공유되는 샌드박스를 여러 개 가져올 수 있습니다.

어디서든 [Sandbox.connect()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.connect)를 사용하여 실행 중인 샌드박스에 다시 연결할 수 있습니다. 컨텍스트 매니저로 사용하여 종료 시 샌드박스를 종료합니다:

```python
>>> from huggingface_hub import Sandbox
>>> with Sandbox.create(image="python:3.12") as sbx:
...     print(sbx.run("python --version").stdout)
```

#### 닫기[[huggingface_hub.Sandbox.close]]

```python
close()
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1069)

샌드박스를 종료하지 않고 로컬 HTTP 클라이언트를 해제합니다. 멱등적입니다.

풀 샌드박스에 대해서는 아무 동작도 수행하지 않습니다(클라이언트가 풀의 호스트에 속해 있음).

#### 연결[[huggingface_hub.Sandbox.connect]]

```python
connect(sandbox_id: str, namespace: str | None = None, token: str | None = None)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L993)

id만 사용하여 어디서든 실행 중인 샌드박스에 다시 연결합니다.

#### 생성[[huggingface_hub.Sandbox.create]]

```python
create(image: str = 'python:3.12', flavor: str = 'cpu-basic', idle_timeout: int | float | str | None = 600, env: dict[str, typing.Any] | None = None, secrets: dict[str, typing.Any] | None = None, volumes: typing.Optional[typing.List[huggingface_hub._space_api.Volume]] = None, namespace: str | None = None, forward_hf_token: bool = False, labels: dict[str, str] | None = None, network: typing.Union[typing.Literal['none'], dict[str, typing.List[str]], NoneType] = None, start_timeout: float = 120.0, token: str | None = None)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L861)

**매개변수:**

image (`str`, *선택 사항*, 기본값 `"python --3.12"`): `/bin/sh`가 포함된 Docker 이미지(Docker Hub 또는 `hf.co/spaces/...`).

flavor (`str`, *선택 사항*, 기본값 `"cpu-basic"`) : 하드웨어 유형, 예: `"cpu-basic"`, `"a10g-small"`. `hf jobs hardware`를 참조하세요.

idle_timeout (`int` 또는 `float` 또는 `str`, *선택 사항*, 기본값 `600`) : 이 시간만큼 비활성 상태(API 호출 없음, 실행 중인 프로세스 없음)가 지속되면 자동으로 종료됩니다. 기본값은 10분이며, `None`을 전달하면 비활성화됩니다. *foreground* 명령은 현재 활동으로 계산되지 않으므로, 다른 API 트래픽 없이 이 시간보다 오래 걸리는 단일 `run()`은 샌드박스가 아래에서 종료될 수 있습니다. 긴 단일 명령의 경우 타임아웃을 늘리거나(`None`을 전달) 처리하세요.

env (`dict[str, Any]`, *선택 사항*) : 샌드박스에서 사용할 수 있는 환경 변수입니다.

secrets (`dict[str, Any]`, *선택 사항*) : Secret 환경 변수(서버 측에서 암호화됨).

volumes (`List[Volume]`, *선택 사항*) : 마운트할 HF 리포지토리/버킷, [Volume](/docs/huggingface_hub/v2.5.0/ko/package_reference/jobs#huggingface_hub.Volume) 참고.

namespace (`str`, *선택 사항*) : 실행할 사용자 또는 조직 네임스페이스(기본값은 현재 사용자).

forward_hf_token (`bool`, *선택 사항*, 기본값 `False`) : True인 경우, HF 토큰이 `HF_TOKEN`으로 주입됩니다(선택적).

labels (`dict[str, str]`, *선택 사항*) : 기본 HF Job에 연결할 라벨입니다.

network (`"none"` 또는 `dict`, *선택*) : 샌드박스에서 실행되는 명령어의 네트워크 액세스를 제한합니다. 모든 아웃바운드 연결을 차단하려면 `"none"`을 전달하고, 일부 대상만 허용하려면 `{"allow": [...]}`를 전달합니다. 허용 대상에는 IP 범위(`"10.0.0.0/8"`), 선택적 포트가 포함된 단일 IP(`"203.0.113.10:443"`) 또는 호스트 이름(`"huggingface.co"`)을 지정할 수 있습니다. 허용 목록이 있어도 TCP만 허용됩니다. 기본값은 `None`(제한 없음)입니다. [인터넷 액세스가 없는 샌드박스](../guides/sandbox#sandboxes-without-internet-access)를 참조하세요.

start_timeout (`float`, *선택 사항*, 기본값 `120.0`) : 샌드박스가 준비될 때까지 대기할 최대 초(second) 수.

token (`str`, *선택 사항*) : HF 토큰 오버라이드.

전용 샌드박스(하나의 HF Job)를 생성하고 준비가 될 때까지 차단합니다(cpu-basic에서 약 7초 소요).

각 샌드박스는 완전히 격리된 VM이므로, GPU 워크로드나 신뢰할 수 없는 코드를 실행하는 데 적합한 선택입니다. 대신 저렴한 CPU 샌드박스를 대량으로 배포하려면 [SandboxPool](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxPool)을 사용하세요.

작업은 최대 24시간의 고정 수명 제한으로 실행되며, `idle_timeout`이 실제 핵심입니다. 유휴 상태의 샌드박스는 그보다 훨씬 일찍 스스로 종료됩니다.

이미지에는 `/bin/sh`만 필요합니다. 샌드박스 서버는 사용 가능한 경우 시작 시 `wget`/`curl`로 다운로드되고, 그렇지 않으면 항상 마운트된 서버 버킷에서 읽힙니다(이 경우 콜드 스타트에 약 2~3초가 추가되므로 `wget`/`curl`를 포함하면 빠릅니다).

#### 프로세스[[huggingface_hub.Sandbox.processes]]

```python
processes()
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1243)

이 샌드박스의 백그라운드 프로세스를 나열합니다.

[Sandbox.run()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.run)`(..., background=True)`로 시작된 프로세스를 반환합니다. [SandboxProcess.kill()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxProcess.kill)을(를) 사용하여 하나를 중지할 수 있습니다. 최근 완료된 프로세스는 목록에 유지되며(`running=False` 및 해당 `exit_code` 포함), 서버는 이러한 프로세스의 수를 제한하므로 수천 개의 짧은 명령을 실행한 샌드박스의 모든 프로세스가 목록에 표시되지 않습니다.

#### proxy_url_for[[huggingface_hub.Sandbox.proxy_url_for]]

```python
proxy_url_for(port: int | str, path: str = '/', scheme: str = 'https://')
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1279)

**매개변수:**

port (`int` 또는 `str`) : 내부 서버가 수신하는 포트(풀: unix 소켓의 `<port>`).

path (`str`, *선택 사항*, 기본값 `"/"`) : 내부 서버에서 가리킬 경로, 예: `"/ws"`.

scheme (`str`, *선택 사항*, 기본값 `"https --//"`): 링크를 구성할 URL 스킴입니다. 기본값은 `"https://"`이며, WebSocket 클라이언트의 경우 `"wss://"`를 전달합니다(프록시는 프로토콜에 무관하므로 클라이언트 측 스킴만 변경됩니다).

**반환값:** `str`

`https://<job_id>--49983.hf.jobs/v1/.../proxy/8000/ws`와 같은 URL(또는 `scheme="wss://"`를 사용한 `wss://...`).

이 샌드박스 *내부*에서 실행 중인 서버로 프록시하는 공개 URL입니다.

반환된 URL에 대한 요청은 작업 내 샌드박스 서버에 의해 샌드박스에서 시작하신 서버의 `port`로 전달되며, WebSocket(`ws(s)://`) 업그레이드 및 스트림된 응답도 포함됩니다. 인증을 위해 `proxy_headers`와 함께 사용하세요.

샌드박스가 `port`에서 리스닝해야 하는 방법:

- **Pool / 공유 샌드박스**: TCP 포트 바인딩이 불가능합니다(Landlock). 따라서 `$SBX_PROXY_DIR/<port>.sock` 위치에 **unix socket**을 바인딩해야 합니다(`SBX_PROXY_DIR` 환경 변수는 모든 샌드박스에 설정되어 있습니다). 예: `uvicorn app:app --uds $SBX_PROXY_DIR/8000.sock`.
- **전용 샌드박스**: `127.0.0.1:<port>`에 일반 TCP 포트를 바인딩합니다. (여기를 거치지 않고 job proxy를 통해 포트를 직접 노출할 수도 있습니다.)

예:
```python
>>> url = sandbox.proxy_url_for(8000, "/ws", scheme="wss://")
>>> import websockets
>>> async with websockets.connect(url, additional_headers=sandbox.proxy_headers) as ws:
...     await ws.send("hello")
```

#### 실행[[huggingface_hub.Sandbox.run]]

```python
run(cmd: typing.Union[str, typing.List[str]], shell: bool | None = None, env: dict[str, typing.Any] | None = None, cwd: str | None = None, timeout: float | None = None, stdin: str | None = None, on_stdout: typing.Optional[typing.Callable[[str], NoneType]] = None, on_stderr: typing.Optional[typing.Callable[[str], NoneType]] = None, check: bool = True, capture_output: bool = True, background: bool = False)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1116)

**매개변수:**

cmd (`str` 또는 `List[str]`) : 셸 명령 문자열(`/bin/sh -c`로 실행) 또는 argv 목록(직접 exec됨).

shell (`bool`, *선택 사항*) : `cmd`의 타입에서 추론하는 대신 실행 모드를 강제합니다. `True`는 `/bin/sh -c`를 통해 실행되며 `cmd`가 문자열이어야 합니다. `False`는 `cmd`를 직접 exec하며 argv 리스트여야 합니다. `None`(기본값)은 타입에서 추론합니다. 타입 기반의 함정(예: `["echo hi"]`이 `"echo hi"`라는 단일 프로그램으로 exec되는 경우)을 피하려면 명시적으로 설정하세요.

env (`dict[str, Any]`, *선택 사항*) : 이 명령에 대한 추가 환경 변수입니다.

cwd (`str`, *선택 사항*) : 작업 디렉터리.

timeout (`float`, *선택 사항*) : 이 초 수 이후에 명령(전체 프로세스 그룹)을 종료합니다.

stdin (`str`, *선택 사항*) : 명령의 stdin에 쓸 데이터.

on_stdout (`Callable[[str], None]`, *선택 사항*) : 표준 출력(stdout) 청크가 도착할 때마다 호출되는 콜백입니다.

on_stderr (`Callable[[str], None]`, *선택 사항*) : stderr 청크가 도착할 때마다 호출되는 콜백입니다.

check (`bool`, *선택 사항*, 기본값 `True`) : True인 경우, 종료 코드가 0이 아니면 `SandboxCommandError`를 발생시킵니다.

capture_output (`bool`, *선택 사항*, 기본값 `True`) : True인 경우, 반환되는 결과에 stdout/stderr를 누적합니다. `on_stdout`/`on_stderr`만 사용하려면 `False`를 전달하세요. 이 경우 출력은 콜백에 전달된 후 폐기되므로, 기가바이트 단위의 출력을 생성하는 명령어도 메모리에 모두 담기지 않아도 됩니다. 이때 `result.stdout`/`result.stderr`는 비어 있습니다.

background (`bool`, *선택 사항*, 기본값 `False`) : True인 경우, 명령을 분리(detached) 상태로 시작하고 대기하지 않고 즉시 [SandboxProcess](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxProcess)를 반환하며 [SandboxCommandResult](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxCommandResult)를 반환하지 않습니다.

샌드박스에서 명령을 실행하고 완료까지 대기하며, 출력을 실시간으로 스트리밍합니다.

`background=True`를 사용하면 명령이 분리(detached) 상태로 시작되며, `run`은 완료 대기 없이 즉시 [SandboxProcess](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxProcess)를 반환합니다. 서버와 같은 장기 실행 프로세스에 유용합니다. 이후 [Sandbox.processes()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.processes)로 목록을 확인하고, [SandboxProcess.kill()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxProcess.kill)로 특정 프로세스를 종료할 수 있습니다. 스트리밍/대기 전용 옵션(`timeout`, `stdin`, `on_stdout`, `on_stderr`, `check`)은 해당 모드에서는 적용되지 않습니다.

[SandboxCommandResult](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxCommandResult)(`exit_code`, `stdout`, `stderr`, `duration_ms` 포함)를 반환하거나, `background=True`인 경우 [SandboxProcess](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxProcess)를 반환합니다.

## SandboxPool[[huggingface_hub.SandboxPool]]

#### huggingface_hub.SandboxPool[[huggingface_hub.SandboxPool]]

```python
huggingface_hub.SandboxPool(image: str = 'python:3.12', flavor: str = 'cpu-basic', sandboxes_per_host: int = 50, warm_up: int = 1, max_hosts: int | None = None, name: str | None = None, idle_timeout: int | float | str | None = 600, namespace: str | None = None, start_timeout: float = 120.0, adopt_hosts: str = 'own', token: str | None = None, _connect_mode: bool = False)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1354)

각각 여러 개의 landlock 격리 샌드박스를 포함하는 공유 "host" 작업의 플릿(fleet).

> [!WARNING]
> Sandbox API는 실험적입니다. API 및 동작이 사전 통보 없이 변경될 수 있습니다.
>
> **Pooled sandboxes는 하나의 신뢰 경계(trust boundary) 내부 워크로드에 사용됩니다.** Pooled sandbox는 공유 VM 내부의 uid와 Landlock ruleset으로 구성되며, 자체 VM을 가지지 않습니다. 호스트의 모든 sandbox는 해당 호스트의 인증 토큰과 권한 있는 제어 평면을 공유합니다. 풀을 사용하면 *자신의* 코드를 저렴하게 확장하여 실행할 수 있습니다. 상호 신뢰하지 않는 워크로드의 경우, 각 워크로드에 자체 VM을 제공하는 [Sandbox.create()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.create)를 사용하세요. 구체적인 한계 사항은 샌드박스 개념 가이드의 "Known limitations" 섹션에 나열되어 있습니다.

호스트 1개는 과금 대상 HF Job(VM) 1개에 해당하며, 샌드박스 서버를 실행하고 uid + Landlock LSM으로 서로 격리된 `sandboxes_per_host`개의 경량 샌드박스를 다중화합니다. 이를 통해 대규모 fan-out이 저렴해집니다(VM 비용이 해당 호스트의 모든 샌드박스에 걸쳐 공유됨) 그리고 빠릅니다(호스트가 워밍업된 후 샌드박스 생성은 프록시 왕복 1회 수준). RL rollout과 같은 병렬 CPU 샌드박스가 많은 경우에 적합하며, GPU 또는 상호 신뢰하지 않는 워크로드 간의 강력한 VM 수준 격리가 필요한 경우 [Sandbox.create()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.create)를 사용하세요.

생성자는 `warm_up` 호스트(기본값 1)를 사전에 프로비저닝하고 준비가 될 때까지 차단합니다. 이후 샌드박스가 요청되면 추가 호스트가 필요에 따라 프로비저닝되며, 모든

`close()` 시(또는 `idle_timeout`를 통해 유휴 상태일 때) 해제됩니다. 사용자는 작업을 관리하지 않습니다:

```python
>>> from huggingface_hub import SandboxPool
>>> with SandboxPool(image="python:3.12", flavor="cpu-basic", warm_up=2) as pool:
...     boxes = [pool.create() for _ in range(100)]   # packed across the warm hosts
...     print(boxes[0].run("echo hi").stdout)
hi
```

`create()`는 한 번에 **하나**의 샌드박스를 생성합니다. 새 호스트를 부팅하기 전에 아직 여유 용량이 있는 호스트를 재사용하므로, 워크로드가 도착할 때按需 확장됩니다. 처음 몇 번의 호출에서 콜드 스타트를 피하려면 `warm_up`(또는 `warm`)로 호스트를 사전 프로비저닝하세요. 워밍된 호스트는 잡 라벨을 통해 발견되므로, 재사용은 **프로세스 간**에도 작동합니다(같은 `image`/`flavor`/`name`을 가진 새 풀은

이전에 실행된 것이 남긴

```python
>>> pool = SandboxPool(image="python:3.12")
>>> sbx = pool.create()    # finds a warm host (here or in another process), else boots one
```

#### 닫기[[huggingface_hub.SandboxPool.close]]

```python
close()
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1780)

풀을 해제합니다. 멱등적입니다.

생성된 풀의 경우, 이 작업은 모든 호스트 작업(따라서 모든 샌드박스)을 종료합니다. `connect()`된 핸들의 경우, 로컬 HTTP 클라이언트만 해제합니다. 공유 호스트는 다른 클라이언트를 서비스 중일 수 있으므로, [Sandbox.connect()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.connect)와 마찬가지로 `with` 블록을 벗어나도 호스트를 종료하지 않아야 합니다. 연결된 풀의 호스트는 `hf sandbox pool delete <id>`를 사용하여 명시적으로 종료하십시오.

*이 핸들에서 시작*된 호스트만 취소됩니다. 레이블을 통해 발견된 호스트는 다른 프로세스의 샌드박스를 서비스 중일 수 있으므로 종료되지 않고 해제됩니다.

호스트 작업을 취소할 수 없는 경우 `SandboxError`를 발생시키며, 여전히 실행 중인 작업 이름을 명시합니다. 해당 작업은 계속 과금되며, 캐시 항목이 유지되어 검색 가능 상태로 남습니다. 예외가 이미 발생 중인 상태에서 `__exit__`를 통해 `close()`에 도달하면, 원래 오류를 가리지 않도록 실패가 기록됩니다.

#### 연결[[huggingface_hub.SandboxPool.connect]]

```python
connect(pool_id: str, namespace: str | None = None, adopt_hosts: str = 'own', token: str | None = None)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1535)

**매개변수:**

pool_id (`str`) : 풀이 처음 생성될 때 반환된 id입니다.

namespace (`str`, *선택 사항*) : 풀의 호스트를 검색할 네임스페이스(기본값은 사용자의 네임스페이스).

adopt_hosts (`str`, *선택 사항*, 기본값 `"own"`) : 연결할 수 있는 호스트를 지정합니다. [SandboxPool](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxPool)을 참조하세요. 네임스페이스의 다른 멤버가 시작한 호스트가 포함된 풀에 다시 연결하려면 `"namespace"`가 필요합니다.

token (`str`, *선택 사항*) : HF 토큰 오버라이드.

id를 사용하여 로컬 상태 없이 어떤 머신에서든 실행 중인 풀에 다시 연결합니다.

`pool_id` 레이블이 지정된 실행 중인 호스트를 찾아 해당 호스트 작업의 spec 및 환경 변수를 기반으로 풀의 구성(이미지/플래버/밀도/호스트-유휴)을 재구성하고, 더 많은 샌드박스를 `create()`할 준비가 된 [SandboxPool](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxPool)을 반환합니다. 실행 중인 호스트에 패킹하거나, 호스트가 가득 차면 동일한 구성으로 복제본을 부팅합니다.

실행 중인 호스트를 찾을 수 없으면 `SandboxError`를 발생시킵니다. (호스트가 모두 사라지면 풀이 더 이상 존재하지 않습니다 — 유휴 타임아웃 또는 종료된 경우).

#### 생성[[huggingface_hub.SandboxPool.create]]

```python
create(env: dict[str, typing.Any] | None = None, idle_timeout: int | float | str | None = 600, forward_hf_token: bool = False, network: typing.Union[typing.Literal['none'], dict[str, typing.List[str]], NoneType] = None)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1632)

**매개변수:**

env (`dict[str, Any]`, *선택 사항*) : 이 샌드박스에 사용할 환경 변수입니다(각 샌드박스는 자체 환경 변수를 가집니다).

idle_timeout (`int` 또는 `float` 또는 `str`, *선택 사항*, 기본값 `600`) : 샌드박스별 유휴 타임아웃 — 이 시간만큼 비활성 상태(호출된 API 없음, 실행 중인 프로세스 없음)가 지속되면 샌드박스가 해당 호스트에서 제거됩니다. 호스트 유휴 타임아웃과는 다릅니다. 비활성화하려면 `None`을 전달하세요.

forward_hf_token (`bool`, *선택 사항*, 기본값 `False`) : True인 경우, 샌드박스에 HF 토큰을 `HF_TOKEN`으로 주입합니다(선택적). 전용 샌드박스의 `secrets`와 달리, 풀링된 샌드박스의 env는 생성 시 호스트 서버에 전달되며(호스트 작업에 저장되지 않음), 어떤 작업의 메타데이터에도 표시되지 않습니다.

network (`"none"` 또는 `dict`, *선택*) : 이 샌드박스에서 실행되는 명령어의 네트워크 액세스를 제한합니다. 모든 아웃바운드 연결을 차단하려면 `"none"`을 전달하고, 일부 대상만 허용하려면 `{"allow": [...]}`를 전달합니다. 허용 대상에는 IP 범위(`"10.0.0.0/8"`), 선택적 포트가 포함된 단일 IP(`"203.0.113.10:443"`) 또는 호스트 이름(`"huggingface.co"`)을 지정할 수 있습니다. 허용 목록이 있어도 TCP만 허용됩니다. 기본값은 `None`(제한 없음)입니다. [인터넷 액세스가 없는 샌드박스](../guides/sandbox#sandboxes-without-internet-access)를 참조하세요. 정책을 적용한 샌드박스와 적용하지 않은 샌드박스가 동일한 호스트를 공유할 수 있습니다.

필요한 경우 호스트를 프로비저닝하여 샌드박스를 하나 생성합니다.

여유 용량이 있는 호스트(해당 풀의 호스트 또는 job labels/로컬 캐시를 통해 찾은 warm host)를 재사용한 후 새 호스트를 부팅하므로, warm host에 대한 `create()` 호출 비용은 약 1회 왕복 통신 수준입니다. 여러 작업으로 분산 처리하려면 반복적으로 호출하고, `warm_up`(또는 `warm`)을 호출하여 호스트를 사전 프로비저닝하면 첫 호출 시 콜드 스타트를 방지할 수 있습니다. 호스트가 다른 프로세스에 의해 가득 차거나 캐시된 호스트가 사라진 경우, 샌드박스는 다른 호스트(또는 새 호스트)에 다시 배치됩니다.

#### warm[[huggingface_hub.SandboxPool.warm]]

```python
warm(num_hosts: int = 1)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L1605)

`num_hosts`개의 빈 호스트가 실행 중인지 확인하고 실행 상태를 유지합니다. 풀의 호스트 작업 ID를 반환합니다.

풀을 사전에 "생성"하는 데 사용됩니다. 호스트는 풀 라벨과 구성(환경 변수에 포함)을 보유하므로, 이후 `SandboxPool.connect(pool_id)` 호출(다른 머신에서 실행하더라도) 시 해당 호스트를 찾아 콜드 스타트 없이 샌드박스를 생성합니다. 호스트는 종료되거나 유휴 상태가 될 때까지 계속 과금됩니다.

이 풀에서 이미 실행 중인 호스트를(잡 라벨을 통해 발견) 부팅 전에 채택하므로, `connect()` 이후의 `warm()` — 또는 반복된 `warm()` — 은 실행 중인 호스트를 중복하여 `max_hosts`를 초과하는 대신 `num_hosts`까지 채웁니다.

## 데이터 구조

### SandboxCommandResult[[huggingface_hub.SandboxCommandResult]]

#### huggingface_hub.SandboxCommandResult[[huggingface_hub.SandboxCommandResult]]

```python
huggingface_hub.SandboxCommandResult(exit_code: int | None, stdout: str, stderr: str, signal: int | None = None, timed_out: bool = False, duration_ms: int = 0)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L217)

[Sandbox.run()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.run)를 사용하여 샌드박스에서 실행된 명령의 결과입니다.

### SandboxProcess[[huggingface_hub.SandboxProcess]]

#### huggingface_hub.SandboxProcess[[huggingface_hub.SandboxProcess]]

```python
huggingface_hub.SandboxProcess(id: str | None, pid: int, cmd: typing.Union[str, typing.List[str]], _sandbox: Sandbox, tag: str | None = None, started_at_ms: int | None = None, running: bool = True, exit_code: int | None = None)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L237)

`(..., background=True)`로 [Sandbox.run()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.run)을 사용하여 샌드박스에서 시작된 백그라운드 프로세스입니다.

[Sandbox.processes()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.Sandbox.processes)로 샌드박스의 프로세스 목록을 조회하고, [SandboxProcess.kill()](/docs/huggingface_hub/v2.5.0/ko/package_reference/sandbox#huggingface_hub.SandboxProcess.kill)로 프로세스를 종료할 수 있습니다. 최근 완료된 프로세스는 목록에 유지됩니다(서버는 유한한 수의 프로세스만 유지하므로), 따라서 `running`와 `exit_code`를 통해 프로세스가 여전히 실행 중인지 이미 종료되었는지(목록에 표시된 시점 기준)를 확인할 수 있습니다.

#### kill[[huggingface_hub.SandboxProcess.kill]]

```python
kill()
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L261)

백그라운드 프로세스를 종료합니다. 멱등적입니다.

이 호출이 프로세스를 중단했는지 여부를 반환합니다: `False`는 프로세스가 이미 종료되었거나 종료 명령을 받았음을 의미하며, 이는 오류가 아닙니다.

`setsid()`을 호출하여 분리되는 자손 프로세스는 시그널이 전송된 프로세스 그룹을 떠나 이 호출보다 오래 유지됩니다. 샌드박스가 시작한 모든 프로세스가 종료되었는지 확인하려면 샌드박스를 삭제하십시오.

### FileEntry[[huggingface_hub._sandbox.FileEntry]]

#### huggingface_hub._sandbox.FileEntry[[huggingface_hub._sandbox.FileEntry]]

```python
huggingface_hub._sandbox.FileEntry(name: str, path: str, type: typing.Literal['file', 'dir', 'symlink'], size: int, mtime_ms: int | None = None, mode: str = '')
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/_sandbox.py#L282)

샌드박스 내부의 파일 또는 디렉터리.

## 오류

### SandboxError[[huggingface_hub.errors.SandboxError]]

#### huggingface_hub.errors.SandboxError[[huggingface_hub.errors.SandboxError]]

```python
huggingface_hub.errors.SandboxError(message: str, status_code: int | None = None)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L621)

**매개변수:**

status_code : 샌드박스 내 서버에서 반환된 HTTP 상태입니다. 오류가 API 응답에서 발생했을 때 적용됩니다(예: 파일이 없는 경우 `404`). 그렇지 않으면 `None`입니다.

샌드박스 작업의 기본 예외 (자세한 내용은 `huggingface_hub.Sandbox`를 참조하세요).

### SandboxCommandError[[huggingface_hub.errors.SandboxCommandError]]

#### huggingface_hub.errors.SandboxCommandError[[huggingface_hub.errors.SandboxCommandError]]

```python
huggingface_hub.errors.SandboxCommandError(cmd, result)
```

[소스](https://github.com/huggingface/huggingface_hub/blob/v2.5.0/src/huggingface_hub/errors.py#L634)

**매개변수:**

cmd : 실패한 명령입니다.

result : 전체 `SandboxCommandResult`(exit_code, stdout, stderr, ...).

샌드박스에서 실행된 명령이 0이 아닌 코드로 종료될 때 발생됩니다.

