> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 세션

> 샌드박스 라이프사이클을 관리하고 함수 실행을 제공합니다.

Source: [src/cwsandbox/\_session.py:49](https://github.com/coreweave/cwsandbox-client/blob/v1.14.2/src/cwsandbox/_session.py#L49)

```python theme={"system"}
class Session(defaults: SandboxDefaults | Mapping[str, Any] | None = None, report_to: list[str] | None = None, *, auth: AuthConfig | None = None)
```

샌드박스 라이프사이클을 관리하고 함수 실행을 제공합니다.

세션을 사용하는 경우:

* 공유 설정으로 여러 샌드박스를 생성할 때
* 샌드박스에서 Python 함수를 실행할 때
* 고아 샌드박스의 자동 정리를 원할 때

이 세션과 연결된 샌드박스에서 exec()이 완료되면
메트릭이 자동으로 추적됩니다. 특정 트레이닝 step에서 메트릭을 로깅하려면
log\_metrics(step=N)을 사용하세요.

<h2 id="properties">
  속성
</h2>

<h3 id="sandbox_count">
  sandbox\_count
</h3>

```python theme={"system"}
@property
def sandbox_count(self) -> int
```

이 세션에서 현재 추적 중인 샌드박스 수입니다.

<h2 id="methods">
  메서드
</h2>

<h3 id="log_metrics">
  log\_metrics
</h3>

```python theme={"system"}
log_metrics(step: int | None = None, *, reset: bool = True) -> bool
```

샌드박스에 누적된 메트릭을 wandb에 로깅합니다.

트레이닝 중에 이 메서드를 호출하면 샌드박스 사용량을 트레이닝 step과 연관 지을 수 있습니다.
exec()가 완료되면 메트릭이 자동으로 추적되므로, 사용자는 step과 연관 짓기 위해
log\_metrics()만 호출하면 됩니다.

메트릭은 세션 종료 시에도 자동으로 로깅됩니다.
**매개변수**

* `step` (`int | None`): 메트릭과 연결할 트레이닝 step입니다. 지정하면 메트릭이 wandb에서 이 step 번호로 로깅됩니다.
* `reset` (`bool`): True(기본값)이면 로깅에 성공한 후 누적된 메트릭을 재설정합니다. log()가 실패하면(활성 wandb run이 없는 경우) 메트릭이 유지됩니다. 로깅 여부와 관계없이 계속 누적하려면 False로 설정하세요.

**반환값**

* `bool`: 메트릭이 로깅된 경우 True, reporter가 설정되지 않았거나
* `bool`: 활성 wandb run이 없는 경우 False입니다.

**예시**

```python theme={"system"}
with Session(defaults, report_to=["wandb"]) as session:
    for step in range(100):
        sb = session.sandbox(...)
        result = sb.exec(...).result()  # 메트릭이 자동으로 추적됩니다
        session.log_metrics(step=step)  # 각 step마다 로깅합니다
```

<h3 id="get_metrics">
  get\_metrics
</h3>

```python theme={"system"}
get_metrics() -> dict[str, Any]
```

현재 누적된 메트릭을 조회합니다.
**반환값**

* `dict[str, Any]`: cwsandbox/\* 접두사가 붙은 메트릭 이름과 값이 포함된 딕셔너리입니다.
* `dict[str, Any]`: reporter가 설정되지 않은 경우 빈 딕셔너리입니다.

<h3 id="close">
  close
</h3>

```python theme={"system"}
close() -> OperationRef[None]
```

관리되는 모든 샌드박스를 중지하고 OperationRef를 즉시 반환합니다.
**반환값**

* `OperationRef[None]`: OperationRef\[None]: 모든 샌드박스가 중단될 때까지 대기하려면 .result()를 사용하세요.

**예외**

* `SandboxError`: 실행 중인 샌드박스 중 하나 이상을 중지하지 못한 경우 발생합니다.

**예시**

```python theme={"system"}
session.close().result()  # 모든 샌드박스가 중단될 때까지 대기
```

<h3 id="sandbox">
  sandbox
</h3>

```python theme={"system"}
sandbox(*, command: str | None = None, args: list[str] | None = None, container_image: str | None = None, tags: list[str] | None = None, runner_ids: list[str] | None = None, resources: ResourceOptions | dict[str, Any] | None = None, mounted_files: list[dict[str, Any]] | None = None, network: NetworkOptions | dict[str, Any] | None = None, services: list[Service] | tuple[Service, ...] | None = None, volumes: list[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any]] | tuple[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any], ...] | None = None, file_system_snapshot: FileSystemSnapshotOptions | dict[str, Any] | None = None, placement_mode: PlacementMode | str | None = None, placement_spillover: PlacementSpillover | str | None = None, template_id: str | None = None, image_pull_credentials: ImagePullCredentials | dict[str, Any] | None = None, runtime_class: str | None = None, security_context: SecurityContext | dict[str, Any] | None = None, working_dir: str | None = None, object_storage_access: ObjectStorageAccess | dict[str, Any] | None = None, environment_variables: dict[str, str] | None = None, annotations: dict[str, str] | None = None, secrets: Sequence[Secret | dict[str, Any]] | None = None, request_timeout_seconds: float | None = None, data_plane_mode: DataPlaneMode | str | None = None, auth: AuthConfig | None = None, containers: Sequence[Container | Mapping[str, Any]] | None = None, **kwargs: Any = {}) -> Sandbox
```

세션 기본값으로 시작되지 않은 샌드박스를 생성합니다.

네트워크 호출 없이 즉시 반환됩니다. 샌드박스는
첫 번째 오퍼레이션(exec, read\_file, write\_file,
wait) 시 자동으로 시작되며, start().result()로 명시적으로 시작할 수도 있습니다.
**매개변수**

* `command` (`str | None`): 샌드박스에서 실행할 명령
* `args` (`list[str] | None`): 명령의 인수
* `container_image` (`str | None`): 사용할 컨테이너 이미지
* `tags` (`list[str] | None`): 샌드박스의 태그(세션 기본값과 병합되며, `template_id`가 설정된 경우에도 병합되므로 `list()`/`adopt`로 샌드박스를 찾을 수 있음). 환경 변수와 어노테이션은 템플릿 경로에서 병합되지 않음(template-owned spec).
* `profile_ids`: 1.x에서 제거됨. 값을 전달하면 `TypeError`가 발생합니다.
* `profile_names`: 1.x에서 제거됨. 값을 전달하면 `TypeError`가 발생합니다.
* `runner_ids` (`list[str] | None`): 선택적 CKS 러너 고정(serverless 및 `placement_spillover='serverless_then_cks'`와 호환되지 않음)
* `resources` (`ResourceOptions | dict[str, Any] | None`): 리소스 설정. 요청/제한을 분리하려면 ResourceOptions를, 하위 호환되는 Guaranteed QoS를 사용하려면 평면 dict를 전달합니다.
* `mounted_files` (`list[dict[str, Any]] | None`): 시작 시 샌드박스에 마운트할 파일. 각 dict에는 `mount_path`(str)와 `file_content`(bytes)가 있어야 합니다. 참고: 마운트된 파일은 런타임에 읽기 전용입니다. 파일을 수정하려면 샌드박스가 실행된 후 `sandbox.write_file()`을 사용하세요.
* `s3_mount`: 1.x에서 제거됨. 값을 전달하면 `TypeError`가 발생합니다.
* `ports`: 1.x에서 제거됨. 대신 `services=[Service(...)]`를 사용하세요.
* `network` (`NetworkOptions | dict[str, Any] | None`): 거부 플래그와 생성 시점의 선택적 호스트 이름 허용 설정을 포함하는 `NetworkOptions`(또는 dict). 포트 노출에는 `services=`를 사용합니다.
* `file_system_snapshot` (`FileSystemSnapshotOptions | dict[str, Any] | None`): 단일 마운트용 간편 FSS 옵션(`FileSystemSnapshotOptions` 또는 dict). 다중 볼륨 구성에는 `volumes=`를 사용하는 것이 좋습니다.
* `max_timeout_seconds`: 1.x에서 제거됨. `request_timeout_seconds`를 사용하세요.
* `request_timeout_seconds` (`float | None`): 샌드박스 RPC에 대한 클라이언트 측 HTTP timeout. 기본값은 세션의 `SandboxDefaults.request_timeout_seconds`입니다.
* `data_plane_mode` (`DataPlaneMode | str | None`): 세션의 데이터 플레인 전송 정책을 재정의합니다.
* `auth` (`AuthConfig | None`): 인증 전략, 확인된 헤더 또는 공급자. 이 샌드박스에 한해 세션 기본값을 재정의합니다.
* `environment_variables` (`dict[str, str] | None`): 샌드박스에 주입할 환경 변수. 세션 기본값과 병합되며, 키가 겹치면 이 값이 우선합니다. 민감하지 않은 설정에만 사용하세요.
* `annotations` (`dict[str, str] | None`): 샌드박스의 Kubernetes 파드 어노테이션. 세션 기본값과 병합되며, 키가 겹치면 이 값이 우선합니다. 민감하지 않은 메타데이터에만 사용하세요.
* `secrets` (`Sequence[Secret | dict[str, Any]] | None`): 환경 변수로 주입할 시크릿. 세션 기본값과 병합됩니다(기본값이 먼저, 그다음 이 목록).
* `containers` (`Sequence[Container | Mapping[str, Any]] | None`): 다중 컨테이너 사양. 단일 컨테이너용 kwargs와 함께 사용할 수 없습니다. 세션의 `defaults.secrets`, `environment_variables`, `security_context`, `working_dir`을 대체하므로 이러한 값은 각 `Container`에 지정하세요. `@session.function()`에서는 사용되지 않습니다.

**반환값**

* `Sandbox`: 세션에 등록된, 아직 시작되지 않은 Sandbox.

**예외**

* `SandboxError`: 세션이 이미 닫힌 경우.

**예시**

```python theme={"system"}
with Session(defaults) as session:
    # 자동 시작: 첫 exec() 호출 시 샌드박스가 시작됩니다
    sb = session.sandbox(command="sleep", args=["infinity"])
    result = sb.exec(["echo", "hello"]).result()

    # 명시적 시작: 시작 시점을 직접 제어합니다
    sb2 = session.sandbox(command="sleep", args=["infinity"])
    sb2.start().result()
    sb2.wait()
    result = sb2.exec(["echo", "hello"]).result()
```

<h3 id="list">
  목록
</h3>

```python theme={"system"}
list(*, tags: list[str] | None = None, status: str | None = None, profile_ids: list[str] | None = None, profile_names: list[str] | None = None, runner_ids: list[str] | None = None, show_terminated: bool = False, adopt: bool = False, volume_ids: list[str] | tuple[str, ...] | None = None) -> OperationRef[list[Sandbox]]
```

샌드박스 목록을 조회하고, 선택적으로 이 세션에 adopt합니다.

세션의 기본 태그가 필터에 자동으로 포함됩니다.
따라서 이 세션 또는 동일한 기본값을 사용한 이전 run에서 생성된 샌드박스를 쉽게 찾을 수 있습니다.

기본적으로 active(종료되지 않은) 샌드박스만 반환됩니다.
`show_terminated=True`로 설정하면 검색 범위가 넓어져 종료 상태의
샌드박스(completed, failed, terminated)도 포함됩니다.
종료 상태 필터(예: `status="completed"`)를 지정해도 검색 범위가
자동으로 넓어집니다.
**매개변수**

* `tags` (`list[str] | None`): 필터링에 사용할 추가 태그(세션의 기본 태그와 병합됨)
* `status` (`str | None`): 상태로 필터링
* `profile_ids` (`list[str] | None`): 1.x에서 제거되었습니다. 값을 전달하면 `TypeError`가 발생합니다.
* `profile_names` (`list[str] | None`): 1.x에서 제거되었습니다. 값을 전달하면 `TypeError`가 발생합니다.
* `runner_ids` (`list[str] | None`): 러너 ID로 필터링(설정된 경우 세션의 runner\_ids가 기본값)
* `volume_ids` (`list[str] | tuple[str, ...] | None`): 지정한 registered Volume ID에 연결된 샌드박스로 필터링
* `show_terminated` (`bool`): True이면 종료 상태의 샌드박스(completed, failed, terminated)를 포함합니다. 기본값은 False입니다.
* `adopt` (`bool`): True이면 검색된 샌드박스를 이 세션에 등록하여 세션이 닫힐 때 함께 중단되도록 합니다.

**반환값**

* `OperationRef[list[Sandbox]]`: OperationRef\[list\[Sandbox]]: .result()를 사용하여 결과가 나올 때까지 블로킹하거나,
* `OperationRef[list[Sandbox]]`: async 컨텍스트에서는 직접 await하세요.

**예시**

```python theme={"system"}
# 세션 기본값에는 이 애플리케이션/run에 대한 태그가 포함됩니다
defaults = SandboxDefaults(tags=("my-app", "run-abc123"))

with Session(defaults) as session:
    # 동기 사용 - 자동으로 ["my-app", "run-abc123"]로 필터링합니다
    orphans = session.list(adopt=True).result()

    # 추가 필터를 적용할 수 있습니다
    running = session.list(status="running").result()

    # 정리 또는 감사를 위해 중단된 샌드박스를 포함합니다
    all_sandboxes = session.list(show_terminated=True).result()

# 비동기 사용
async with Session(defaults) as session:
    orphans = await session.list(adopt=True)
```

<h3 id="from_id">
  from\_id
</h3>

```python theme={"system"}
from_id(sandbox_id: str, *, adopt: bool = True) -> OperationRef[Sandbox]
```

기존 샌드박스에 연결하며, 선택적으로 이 세션에 adopt합니다.
**매개변수**

* `sandbox_id` (`str`): 기존 샌드박스의 ID
* `adopt` (`bool`): True(기본값)이면 샌드박스를 이 세션에 등록합니다

**반환값**

* `OperationRef[Sandbox]`: OperationRef\[Sandbox]: .result()를 사용해 Sandbox 인스턴스가 반환될 때까지 block하거나,
* `OperationRef[Sandbox]`: 비동기 컨텍스트에서는 직접 await하세요.

**예시**

```python theme={"system"}
with Session(defaults) as session:
    # Sync 사용 - 샌드박스에 재연결
    sb = session.from_id("sandbox-abc123").result()
    result = sb.exec(["echo", "hello"]).result()
# 세션 종료 시 sb는 중단됨

# Async 사용
async with Session(defaults) as session:
    sb = await session.from_id("sandbox-abc123")
    result = await sb.exec(["echo", "hello"])
```

<h3 id="adopt">
  adopt
</h3>

```python theme={"system"}
adopt(sandbox: Sandbox) -> None
```

기존 샌드박스 인스턴스를 이 세션에 adopt하여 정리 추적을 수행합니다.

Sandbox.list() 또는 Sandbox.from\_id()에서 가져온 샌드박스를 세션이 닫힐 때 자동으로 중단되도록 하려는 경우에 사용하세요.
**매개변수**

* `sandbox` (`Sandbox`): 추적할 샌드박스 인스턴스

**예외**

* `SandboxError`: 세션이 닫힌 경우
* `ValueError`: 샌드박스에 sandbox\_id가 없는 경우

**예시**

```python theme={"system"}
with Session(defaults) as session:
    # 클래스 메서드로 샌드박스 조회
    sandboxes = Sandbox.list(tags=["my-job"]).result()

    # 샌드박스를 세션에 편입
    for sb in sandboxes:
        session.adopt(sb)

    # 이제 세션이 닫힐 때 샌드박스도 함께 중단됩니다
```

<h3 id="function">
  function
</h3>

```python theme={"system"}
function(*, container_image: str | None = None, temp_dir: str | None = None, runner_ids: list[str] | None = None, resources: ResourceOptions | dict[str, Any] | None = None, mounted_files: Sequence[dict[str, Any]] | None = None, network: NetworkOptions | dict[str, Any] | None = None, services: Sequence[Service] | None = None, volumes: Sequence[ScratchVolumeOptions | RegisteredVolumeOptions | dict[str, Any]] | None = None, file_system_snapshot: FileSystemSnapshotOptions | dict[str, Any] | None = None, placement_mode: PlacementMode | str | None = None, placement_spillover: PlacementSpillover | str | None = None, runtime_class: str | None = None, security_context: SecurityContext | dict[str, Any] | None = None, working_dir: str | None = None, object_storage_access: ObjectStorageAccess | dict[str, Any] | None = None, environment_variables: dict[str, str] | None = None, annotations: dict[str, str] | None = None, request_timeout_seconds: float | None = None, data_plane_mode: DataPlaneMode | str | None = None, **kwargs: Any = {}) -> Callable[[Callable[P, R]], RemoteFunction[P, R]]
```

샌드박스에서 Python 함수를 실행하는 데코레이터입니다.

함수를 호출할 때마다 임시 샌드박스가 생성되고, 함수를 실행한 뒤
결과를 반환합니다. 샌드박스는 자동으로 정리됩니다.

데코레이트된 함수는 동기 함수여야 합니다. Async 함수는 지원되지 않습니다.
**매개변수**

* `container_image` (`str | None`): 이 함수에 사용할 이미지로 세션의 기본 이미지를 재정의합니다
* `temp_dir` (`str | None`): 샌드박스 내 페이로드/결과 파일용 임시 디렉터리를 재정의합니다. 기본값은 세션 기본값입니다. 디렉터리가 없으면 생성됩니다.
* `profile_ids`: 1.x에서 제거되었습니다. 값을 전달하면 `TypeError`가 발생합니다.
* `profile_names`: 1.x에서 제거되었습니다. 값을 전달하면 `TypeError`가 발생합니다.
* `runner_ids` (`list[str] | None`): 특정 CKS 러너에 고정합니다(선택). serverless 및 `placement_spillover='serverless_then_cks'`와 함께 사용할 수 없습니다.
* `resources` (`ResourceOptions | dict[str, Any] | None`): 리소스 설정입니다. 요청/제한을 따로 지정하려면 ResourceOptions를, 하위 호환되는 Guaranteed QoS를 사용하려면 평면 dict를 전달하세요.
* `mounted_files` (`Sequence[dict[str, Any]] | None`): 시작 시 샌드박스에 마운트할 파일입니다. 각 dict에는 `mount_path`(str)와 `file_content`(bytes)가 있어야 합니다. 참고: 마운트된 파일은 런타임에 읽기 전용입니다. 파일을 수정하려면 샌드박스가 실행된 후 `sandbox.write_file()`을 사용하세요.
* `s3_mount`: 1.x에서 제거되었습니다. 값을 전달하면 `TypeError`가 발생합니다.
* `ports`: 1.x에서 제거되었습니다. 대신 `services=[Service(...)]`를 사용하세요.
* `network` (`NetworkOptions | dict[str, Any] | None`): 거부 플래그와 생성 시점 호스트 이름 grants(선택)를 포함하는 `NetworkOptions`(또는 dict)입니다. 포트 노출에는 `services=`를 사용하세요.
* `file_system_snapshot` (`FileSystemSnapshotOptions | dict[str, Any] | None`): 단일 마운트용 간편 FSS 옵션(`FileSystemSnapshotOptions` 또는 dict)입니다. 다중 볼륨 구성에는 `volumes=`를 사용하는 것이 좋습니다.
* `max_timeout_seconds`: 1.x에서 제거되었습니다. `request_timeout_seconds`를 사용하세요.
* `request_timeout_seconds` (`float | None`): 샌드박스 RPC에 대한 클라이언트 측 HTTP timeout입니다. 기본값은 세션의 `SandboxDefaults.request_timeout_seconds`입니다.
* `data_plane_mode` (`DataPlaneMode | str | None`): 세션의 데이터 플레인 전송 정책을 재정의합니다.
* `environment_variables` (`dict[str, str] | None`): 샌드박스에 주입할 환경 변수입니다. 세션 기본값과 병합되며, 키가 겹치면 이 값이 우선합니다. 민감하지 않은 설정에만 사용하세요.
* `annotations` (`dict[str, str] | None`): 샌드박스의 Kubernetes 파드 어노테이션입니다. 세션 기본값과 병합되며, 키가 겹치면 이 값이 우선합니다. 민감하지 않은 메타데이터에만 사용하세요.

**반환값**

* `Callable[[Callable[P, R]], RemoteFunction[P, R]]`: 함수를 RemoteFunction으로 래핑하는 데코레이터

**예시**

```python theme={"system"}
with Session(defaults) as session:
    @session.function()
    def compute(x: int, y: int) -> int:
        return x + y

    # .remote()를 호출하여 샌드박스에서 실행하세요
    ref = compute.remote(2, 3)  # OperationRef를 즉시 반환합니다
    result = ref.result()       # 결과를 기다립니다
    print(result)  # 5

    # 또는 async 컨텍스트에서 await를 사용하세요
    result = await compute.remote(2, 3)

    # 테스트를 위해 로컬에서 실행하세요
    result = compute.local(2, 3)

    # 여러 입력을 병렬로 매핑하세요
    refs = compute.map([(1, 2), (3, 4), (5, 6)])
    results = [ref.result() for ref in refs]
```
