> ## 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.

# Troubleshooting

> Common errors and solutions for the CoreWeave sandbox Python client.

This guide helps you diagnose and resolve common problems when you use the CoreWeave sandbox Python client. Use it to identify the cause of an error and apply a fix. It also explains which conditions trigger each error so you can avoid them later.

## Authentication issues

This section covers errors that occur when the SDK can't find or validate your credentials.

**Symptom**: `CWSandboxAuthenticationError` or `WandbAuthError` raised on sandbox operations.

The SDK resolves authentication in this order:

1. `CWSANDBOX_API_KEY` env var (takes priority), a [CoreWeave API Access Token](/security/authn-authz/manage-api-access-tokens)
2. `WANDB_API_KEY` + `WANDB_ENTITY_NAME` env vars
3. `~/.netrc` (api.wandb.ai) + `WANDB_ENTITY_NAME`

You need one of these configured. Check which method you're using:

```bash theme={"system"}
# Option 1: CoreWeave API Access Token (recommended)
echo $CWSANDBOX_API_KEY

# Option 2: W&B credentials
echo $WANDB_API_KEY
echo $WANDB_ENTITY_NAME
```

### Common issues

| Issue                               | Solution                                                                                               |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------ |
| No credentials configured           | Set `CWSANDBOX_API_KEY` or W\&B credentials                                                            |
| Invalid or expired token            | [Create a new API Access Token](/security/authn-authz/manage-api-access-tokens) from the Cloud Console |
| W\&B API key set but entity missing | Set `WANDB_ENTITY_NAME` to your W\&B entity/team                                                       |
| Using netrc but entity missing      | Set `WANDB_ENTITY_NAME`. It's always required for W\&B                                                 |
| Netrc parse errors                  | Check `~/.netrc` file syntax and permissions                                                           |

## Command execution issues

This section covers problems related to running commands inside a sandbox, including timeouts, long-running processes, and how to interpret exit codes.

### Timeout tuning

The difference between client-side and server-side timeouts helps you choose the right setting when a command takes longer than expected. The SDK has two types of timeouts:

| Timeout                | Scope            | Default            | Where set          |
| ---------------------- | ---------------- | ------------------ | ------------------ |
| `timeout_seconds`      | Per-exec         | None               | `exec()` parameter |
| `max_lifetime_seconds` | Sandbox lifetime | Backend-controlled | `SandboxDefaults`  |

**Client-side timeout** (`timeout_seconds`):

```python theme={"system"}
from cwsandbox import SandboxTimeoutError

try:
    result = sandbox.exec(
        ["python", "slow_script.py"],
        timeout_seconds=60.0,  # 60 second timeout
    ).result()
except SandboxTimeoutError:
    print("Command timed out")
```

**Server-side lifetime** (`max_lifetime_seconds`):

```python theme={"system"}
from cwsandbox import SandboxDefaults

defaults = SandboxDefaults(
    container_image="python:3.11",
    max_lifetime_seconds=3600,  # Sandbox terminates after 1 hour
)
```

### Long-running commands

**Issue**: Command takes longer than expected.

**Solutions**:

1. Set an appropriate timeout:

```python theme={"system"}
process = sandbox.exec(
    ["pip", "install", "tensorflow"],
    timeout_seconds=300.0,  # 5 minutes for large packages
)
result = process.result()
```

1. Use streaming to monitor progress:

```python theme={"system"}
process = sandbox.exec(["pip", "install", "tensorflow"])

for line in process.stdout:
    print(line, end="")

result = process.result()
```

### Exit code interpretation

**Issue**: You need to understand command failures.

Exit codes follow Unix conventions:

| Code  | Meaning                |
| ----- | ---------------------- |
| 0     | Success                |
| 1     | General error          |
| 2     | Misuse of command      |
| 126   | Command not executable |
| 127   | Command not found      |
| 128+N | Killed by signal N     |

Use `check=True` to raise on non-zero exit:

```python theme={"system"}
from cwsandbox import SandboxExecutionError

try:
    result = sandbox.exec(
        ["python", "-c", "import nonexistent"],
        check=True,
    ).result()
except SandboxExecutionError as e:
    print(f"Exit code: {e.exec_result.returncode}")
    print(f"stderr: {e.exec_result.stderr}")
```

## Streaming output issues

This section covers issues that affect how output from a sandbox command appears in your client.

### Line buffering behavior

**Issue**: Output appears delayed or all at once when streaming.

Python buffers stdout when not connected to a TTY. Force unbuffered output:

```python theme={"system"}
# Option 1: Use -u flag
process = sandbox.exec(["python", "-u", "script.py"])
for line in process.stdout:
    print(line, end="")
result = process.result()

# Option 2: Set PYTHONUNBUFFERED
process = sandbox.exec(["sh", "-c", "PYTHONUNBUFFERED=1 python script.py"])
for line in process.stdout:
    print(line, end="")
result = process.result()
```

For your own scripts, flush explicitly:

```python theme={"system"}
print("Progress...", flush=True)
```

## Cleanup problems

This section covers situations where sandboxes aren't released as expected. These situations can lead to unnecessary cost and resource consumption.

### Orphaned sandboxes

**Issue**: Sandboxes remain running after script exits or crashes.

**Prevention**: Use context managers:

```python theme={"system"}
# Recommended: automatic cleanup
with Sandbox.run() as sandbox:
    result = sandbox.exec(["echo", "hello"]).result()
# Sandbox stopped automatically
```

See [Cleanup patterns: orphan management](/products/sandboxes/client/guides/cleanup-patterns#orphan-management) for how to find and clean up orphaned sandboxes by tag.

## Common error messages

The following table summarizes the most common exceptions that the SDK raises, along with their typical causes and recommended fixes.

| Error                                          | Cause                                          | Solution                                              |
| ---------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------- |
| `CWSandboxAuthenticationError`                 | Missing or invalid credentials                 | Check `CWSANDBOX_API_KEY` is set                      |
| `WandbAuthError: WANDB_ENTITY_NAME is not set` | W\&B API key found but entity missing          | Set `WANDB_ENTITY_NAME` env var                       |
| `SandboxNotRunningError`                       | Operation on stopped sandbox                   | Check `sandbox.status` before operations              |
| `SandboxTimeoutError`                          | Operation exceeded timeout                     | Increase `timeout_seconds` or optimize command        |
| `SandboxTerminatedError`                       | Sandbox ended externally                       | Check `max_lifetime_seconds` or external termination  |
| `SandboxFailedError`                           | Sandbox failed to start                        | Check container image and resources                   |
| `SandboxNotFoundError`                         | Sandbox deleted or never existed               | Verify sandbox ID is correct                          |
| `SandboxExecutionError`                        | Command returned non-zero (with `check=True`)  | Check `e.exec_result.stderr` for details              |
| `SandboxFileError`                             | File operation failed                          | Check file path and permissions                       |
| `FunctionSerializationError`                   | Can't serialize function args                  | Use JSON-serializable types or `Serialization.PICKLE` |
| `AsyncFunctionError`                           | Async function passed to `@session.function()` | Use sync functions only                               |
