Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/pytest_prairielearn_grader/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,14 @@ def test_student_code(sandbox):
```
"""

sandbox_timeout: float = 1.0
sandbox_timeout: float | None = None
"""Timeout in seconds for sandbox initialization and operations.

Must be a positive number. Default is 1.0 second.
Must be a positive number when set. When None (the default), the timeout falls back to the
grader image's default, which an image can set with the ``PL_GRADER_SANDBOX_TIMEOUT``
environment variable (e.g. the torch image raises it to accommodate model work), and
otherwise to 1.0 second. Setting an explicit value here always overrides the image default.

This timeout applies to both sandbox initialization and individual student code operations.
"""

Expand Down Expand Up @@ -271,7 +275,7 @@ def test_student_code(sandbox):
def __post_init__(self) -> None:
"""Validate configuration values after initialization."""
# Validate sandbox_timeout
if self.sandbox_timeout <= 0:
if self.sandbox_timeout is not None and self.sandbox_timeout <= 0:
raise ValueError(f"sandbox_timeout must be positive, got {self.sandbox_timeout}")

# Validate import_whitelist contains non-empty strings
Expand Down
34 changes: 31 additions & 3 deletions src/pytest_prairielearn_grader/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,32 @@
# Default configuration constants
DEFAULT_SANDBOX_TIMEOUT = 1.0
DEFAULT_IMPORT_BLACKLIST = ["os", "sys", "subprocess", "pathlib", "shutil"]
# A grader image can raise the default sandbox timeout through this environment variable. Per-question
# configuration always overrides it, so questions can still set a lower (or higher) value.
ENV_DEFAULT_SANDBOX_TIMEOUT = "PL_GRADER_SANDBOX_TIMEOUT"


def _default_sandbox_timeout() -> float:
"""The sandbox timeout used when a question doesn't set one.

Reads ``PL_GRADER_SANDBOX_TIMEOUT`` so an image (such as the torch image, where importing the
framework and running a model easily exceeds a second) can bake in a more sensible default.
Falls back to ``DEFAULT_SANDBOX_TIMEOUT`` when the variable is unset or invalid.
"""
raw = os.environ.get(ENV_DEFAULT_SANDBOX_TIMEOUT)
if raw is None:
return DEFAULT_SANDBOX_TIMEOUT
try:
value = float(raw)
except ValueError:
logger.warning("Ignoring invalid %s=%r; using %s", ENV_DEFAULT_SANDBOX_TIMEOUT, raw, DEFAULT_SANDBOX_TIMEOUT)
return DEFAULT_SANDBOX_TIMEOUT
if value <= 0:
logger.warning("Ignoring non-positive %s=%r; using %s", ENV_DEFAULT_SANDBOX_TIMEOUT, raw, DEFAULT_SANDBOX_TIMEOUT)
return DEFAULT_SANDBOX_TIMEOUT
return value


# Failing subtests shown in a test's message. The rest are only counted, to keep the message readable.
MAX_SHOWN_SUBTEST_FAILURES = 5

Expand Down Expand Up @@ -321,7 +347,7 @@ def _resolve_sandbox_config(
when there's no ConfigObject), merges them with the ConfigObject taking precedence, and injects
the names_for_user values into starting_vars.
"""
initialization_timeout: float = DEFAULT_SANDBOX_TIMEOUT
initialization_timeout: float = _default_sandbox_timeout()

if data_json is None:
params_dict = {}
Expand All @@ -341,8 +367,10 @@ def _resolve_sandbox_config(
pytest.fail(f"autograder_config must be a ConfigObject instance, got {type(config_object).__name__}")
logger.debug("Using module-level autograder_config - overriding all other configuration sources")
config_dict = config_object.to_dict()
# Handle timeout and starting_vars separately as they're not in to_dict()
initialization_timeout = config_object.sandbox_timeout
# Handle timeout and starting_vars separately as they're not in to_dict().
# A None timeout means "use the image/global default" computed above.
if config_object.sandbox_timeout is not None:
initialization_timeout = config_object.sandbox_timeout
config_starting_vars = config_object.starting_vars
helper_module_names = config_object.helper_modules
data_file_names = config_object.data_files
Expand Down
21 changes: 20 additions & 1 deletion tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import pytest

from pytest_prairielearn_grader import ConfigObject
from pytest_prairielearn_grader.plugin import DEFAULT_SANDBOX_TIMEOUT
from pytest_prairielearn_grader.plugin import _calculate_summary_scores
from pytest_prairielearn_grader.plugin import _default_sandbox_timeout

# ---------------------------------------------------------------------------
# Valid configurations
Expand All @@ -13,10 +15,27 @@
def test_default_config() -> None:
config = ConfigObject()
assert config.workspace_mode is False
assert config.sandbox_timeout == 1.0
# None means "defer to the image/global default"; it is resolved at grading time.
assert config.sandbox_timeout is None
assert config.student_code_pattern == "student_code*.py"


def test_default_sandbox_timeout_without_env(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("PL_GRADER_SANDBOX_TIMEOUT", raising=False)
assert _default_sandbox_timeout() == DEFAULT_SANDBOX_TIMEOUT


def test_default_sandbox_timeout_from_env(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("PL_GRADER_SANDBOX_TIMEOUT", "12.5")
assert _default_sandbox_timeout() == 12.5


@pytest.mark.parametrize("bad_value", ["not-a-number", "0", "-3"])
def test_default_sandbox_timeout_ignores_invalid_env(monkeypatch: pytest.MonkeyPatch, bad_value: str) -> None:
monkeypatch.setenv("PL_GRADER_SANDBOX_TIMEOUT", bad_value)
assert _default_sandbox_timeout() == DEFAULT_SANDBOX_TIMEOUT


def test_single_file_mode_full() -> None:
config = ConfigObject(
sandbox_timeout=5.0,
Expand Down