mogs 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. mogs/__init__.py +17 -0
  2. mogs/_assertrewrite.py +44 -0
  3. mogs/_env.py +26 -0
  4. mogs/_run.py +111 -0
  5. mogs/_typst/preview/cmarker/0.1.10/LICENSE +7 -0
  6. mogs/_typst/preview/cmarker/0.1.10/lib.typ +462 -0
  7. mogs/_typst/preview/cmarker/0.1.10/plugin.wasm +0 -0
  8. mogs/_typst/preview/cmarker/0.1.10/typst.toml +11 -0
  9. mogs/_typst/preview/mitex/0.2.7/LICENSE +176 -0
  10. mogs/_typst/preview/mitex/0.2.7/lib.typ +1 -0
  11. mogs/_typst/preview/mitex/0.2.7/mitex.typ +45 -0
  12. mogs/_typst/preview/mitex/0.2.7/mitex.wasm +0 -0
  13. mogs/_typst/preview/mitex/0.2.7/specs/latex/standard.typ +1187 -0
  14. mogs/_typst/preview/mitex/0.2.7/specs/mod.typ +12 -0
  15. mogs/_typst/preview/mitex/0.2.7/specs/prelude.typ +230 -0
  16. mogs/_typst/preview/mitex/0.2.7/typst.toml +12 -0
  17. mogs/assignment.py +172 -0
  18. mogs/build.py +605 -0
  19. mogs/check.py +410 -0
  20. mogs/cli.py +272 -0
  21. mogs/config.py +619 -0
  22. mogs/environment.py +118 -0
  23. mogs/export.py +556 -0
  24. mogs/grader/__init__.py +1 -0
  25. mogs/grader/_process.py +383 -0
  26. mogs/grader/_user.py +7 -0
  27. mogs/grader/bundle.py +320 -0
  28. mogs/grader/child.py +317 -0
  29. mogs/grader/datafiles.py +54 -0
  30. mogs/grader/main.py +132 -0
  31. mogs/grader/protocol.py +175 -0
  32. mogs/grader/results.py +337 -0
  33. mogs/grader/sandbox.py +462 -0
  34. mogs/grader/templates/__init__.py +38 -0
  35. mogs/grader/templates/run_autograder +3 -0
  36. mogs/grader/templates/setup.sh +28 -0
  37. mogs/loader.py +260 -0
  38. mogs/pdf.py +676 -0
  39. mogs/regrade.py +223 -0
  40. mogs/requirements.py +232 -0
  41. mogs/runner.py +281 -0
  42. mogs/scaffold.py +155 -0
  43. mogs/selfcheck.py +173 -0
  44. mogs/source.py +1438 -0
  45. mogs/transform.py +769 -0
  46. mogs-0.7.0.dist-info/METADATA +17 -0
  47. mogs-0.7.0.dist-info/RECORD +49 -0
  48. mogs-0.7.0.dist-info/WHEEL +4 -0
  49. mogs-0.7.0.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,383 @@
1
+ """Operating-system side of the sandbox: start, watch and kill one grading child.
2
+
3
+ Linux and macOS. The child runs in its own session, so killing its process group also kills the
4
+ processes it started, unless they left the group; with a dedicated `user`, `pkill -u` gets those
5
+ too. macOS rejects `RLIMIT_AS`, so there the child has no memory cap.
6
+ """
7
+
8
+ import os
9
+ import pwd
10
+ import resource
11
+ import select
12
+ import signal
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ import threading
17
+ import time
18
+ from dataclasses import dataclass
19
+ from functools import partial
20
+ from pathlib import Path
21
+ from typing import IO
22
+
23
+ from mogs._env import grading_env
24
+ from mogs.grader.protocol import Event, ProtocolError, decode
25
+
26
+ OUTPUT_LIMIT = 64 * 1024
27
+ LINE_LIMIT = 1024 * 1024
28
+ NPROC_LIMIT = 512
29
+ POLL = 0.05
30
+ KILL_PASSES = 5
31
+ OOM_MESSAGE = "killed, probably out of memory: raise the Gradescope container memory"
32
+
33
+ type Limit = tuple[int, int]
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class LaunchOptions:
38
+ """How to start a child, apart from what every child shares.
39
+
40
+ Attributes:
41
+ cwd: Working directory.
42
+ env: Environment.
43
+ user: User to run as, or `None` to keep the current one.
44
+ group: Primary group of `user`.
45
+ extra_groups: Supplementary groups; empty drops root's groups.
46
+ limits: Resource limits set before the child starts.
47
+ python: Interpreter to run the child with.
48
+ """
49
+
50
+ cwd: Path
51
+ env: dict[str, str]
52
+ user: str | None
53
+ group: int | None
54
+ extra_groups: list[int] | None
55
+ limits: list[Limit]
56
+ python: str
57
+
58
+
59
+ def child_command(event_fd: int, python: str) -> list[str]:
60
+ """The command line of a grading child that runs on `python` and writes events to `event_fd`."""
61
+
62
+ return [python, "-m", "mogs.grader.child", str(event_fd)]
63
+
64
+
65
+ def child_env(workdir: Path) -> dict[str, str]:
66
+ """The current environment, made fit for student code that runs in `workdir`.
67
+
68
+ It sets `MOGS_GRADING=1`, so `check` and `export` cells do nothing when the notebook runs.
69
+ """
70
+
71
+ env = grading_env() | {
72
+ "MPLBACKEND": "Agg",
73
+ "OMP_NUM_THREADS": "4",
74
+ "HOME": str(workdir),
75
+ "MPLCONFIGDIR": str(workdir),
76
+ "PYTHONDONTWRITEBYTECODE": "1",
77
+ }
78
+
79
+ return env
80
+
81
+
82
+ def limits(memory_mb: int, user: str | None) -> list[Limit]:
83
+ """Resource limits for a child.
84
+
85
+ The process cap counts every process of the real user, so it applies only to a dedicated
86
+ grading `user`; on a developer machine it would count the developer's own processes. The
87
+ memory cap is Linux only: macOS fails `setrlimit(RLIMIT_AS, ...)`, so a self-check on macOS
88
+ runs without one.
89
+ """
90
+
91
+ result: list[Limit] = []
92
+
93
+ if sys.platform == "linux":
94
+ result.append((resource.RLIMIT_AS, memory_mb * 1024 * 1024))
95
+
96
+ if user is not None:
97
+ result.append((resource.RLIMIT_NPROC, NPROC_LIMIT))
98
+
99
+ return result
100
+
101
+
102
+ def check_user(user: str) -> pwd.struct_passwd:
103
+ """The password entry of a grading user.
104
+
105
+ Raises:
106
+ ValueError: If `user` is root or the user running the grader, since `pkill -u` would
107
+ then kill the grader, and student code would get the grader's rights.
108
+ KeyError: If there is no such user.
109
+ """
110
+
111
+ entry = pwd.getpwnam(user)
112
+
113
+ if entry.pw_uid == 0:
114
+ raise ValueError(f"the grading user must not be root: {user!r} has uid 0")
115
+
116
+ if entry.pw_uid == os.getuid():
117
+ raise ValueError(f"the grading user must not be the user running the grader: {user!r}")
118
+
119
+ return entry
120
+
121
+
122
+ def launch_options(workdir: Path, user: str | None, memory_mb: int, python: str) -> LaunchOptions:
123
+ """Options for a child that runs on `python` in `workdir`, as `user` when set.
124
+
125
+ Raises:
126
+ ValueError: If `user` is root or the current user (see `check_user`).
127
+ """
128
+
129
+ group = None if user is None else check_user(user).pw_gid
130
+ extra_groups = None if user is None else []
131
+
132
+ return LaunchOptions(
133
+ workdir, child_env(workdir), user, group, extra_groups, limits(memory_mb, user), python
134
+ )
135
+
136
+
137
+ def describe_exit(returncode: int) -> str:
138
+ """How a child ended, from its exit status, for a failure message."""
139
+
140
+ match returncode:
141
+ case code if code == -signal.SIGKILL:
142
+ return OOM_MESSAGE
143
+ case code if code < 0:
144
+ return f"killed by signal {_signal_name(-code)}"
145
+ case code:
146
+ return f"exited with code {code}"
147
+
148
+
149
+ def kill_user(user: str) -> None:
150
+ """Kill every process of `user`.
151
+
152
+ Repeats, up to `KILL_PASSES` times, while `pgrep` still finds processes, which a fork
153
+ bomb can start between two passes.
154
+ """
155
+
156
+ for _ in range(KILL_PASSES):
157
+ subprocess.run(["pkill", "-KILL", "-u", user], check=False)
158
+
159
+ # `pgrep` exits with 1 when no process matches.
160
+ if subprocess.run(["pgrep", "-u", user], capture_output=True).returncode == 1:
161
+ return
162
+
163
+
164
+ class Child:
165
+ """A running grading child: its process, its event channel and the tail of its output.
166
+
167
+ Events are read with `select` and deadlines, never up to end of file: a process the child
168
+ forks keeps the write end open after the child is gone.
169
+
170
+ Args:
171
+ job: The `Job` as JSON, given to the child as stdin.
172
+ options: How to start it.
173
+ """
174
+
175
+ def __init__(self, job: str, options: LaunchOptions) -> None:
176
+ self._user = options.user
177
+ self._buffer = bytearray()
178
+ self.returncode: int | None = None
179
+ self.error: ProtocolError | None = None
180
+
181
+ read, write = os.pipe()
182
+ os.set_blocking(read, False)
183
+ self._events: int | None = read
184
+
185
+ # Stdin is a file, so the parent never blocks on a job the child does not read.
186
+ with tempfile.TemporaryFile() as stdin:
187
+ stdin.write(job.encode())
188
+ stdin.seek(0)
189
+
190
+ try:
191
+ self._process = subprocess.Popen(
192
+ child_command(write, options.python),
193
+ stdin=stdin,
194
+ stdout=subprocess.PIPE,
195
+ stderr=subprocess.STDOUT,
196
+ pass_fds=(write,),
197
+ start_new_session=True,
198
+ cwd=options.cwd,
199
+ env=options.env,
200
+ user=options.user,
201
+ group=options.group,
202
+ extra_groups=options.extra_groups,
203
+ preexec_fn=partial(_set_limits, options.limits),
204
+ )
205
+ except BaseException:
206
+ os.close(read)
207
+ raise
208
+ finally:
209
+ os.close(write)
210
+
211
+ stdout = self._process.stdout
212
+ assert stdout is not None # `stdout=PIPE` above.
213
+ self._output = _Tail(stdout)
214
+
215
+ def wait(self, until: float) -> list[Event]:
216
+ """Events that arrive within `POLL` seconds, or before the monotonic time `until`.
217
+
218
+ Sets `returncode` once the child has ended. When the child writes a line that is not an
219
+ event, sets `error` and returns the events before that line; later lines are dropped.
220
+ """
221
+
222
+ seconds = min(POLL, max(0.0, until - time.monotonic()))
223
+
224
+ if self._events is None:
225
+ time.sleep(seconds)
226
+ else:
227
+ select.select([self._events], [], [], seconds)
228
+
229
+ events = self._read()
230
+
231
+ if self._ended():
232
+ # Until reaped, the child is a zombie and its process group id stays reserved.
233
+ self._kill_group()
234
+ self.returncode = self._process.wait()
235
+ events += self._read()
236
+
237
+ return events
238
+
239
+ def close(self) -> str:
240
+ """Kill the child and everything it started, and release its resources.
241
+
242
+ Returns:
243
+ The last `OUTPUT_LIMIT` bytes of its stdout and stderr, decoded.
244
+ """
245
+
246
+ # Once the child is reaped, its process group id may belong to someone else.
247
+ if self.returncode is None:
248
+ self._kill_group()
249
+
250
+ if self._user is not None:
251
+ kill_user(self._user)
252
+
253
+ self.returncode = self._process.wait()
254
+
255
+ if self._events is not None:
256
+ os.close(self._events)
257
+ self._events = None
258
+
259
+ return self._output.close()
260
+
261
+ def _read(self) -> list[Event]:
262
+ if self._events is None or self.error is not None:
263
+ return []
264
+
265
+ # Bounded, so a child that writes without end cannot keep the parent from its deadlines.
266
+ for _ in range(LINE_LIMIT // 65536):
267
+ try:
268
+ chunk = os.read(self._events, 65536)
269
+ except BlockingIOError:
270
+ break
271
+
272
+ if not chunk:
273
+ os.close(self._events)
274
+ self._events = None
275
+ break
276
+
277
+ self._buffer += chunk
278
+
279
+ *lines, rest = self._buffer.split(b"\n")
280
+ self._buffer = bytearray(rest)
281
+ events = []
282
+
283
+ # Events before a bad line still count, so blame goes to what the child was doing.
284
+ for line in lines:
285
+ try:
286
+ events.append(decode(line.decode(errors="replace")))
287
+ except ProtocolError as e:
288
+ self.error = e
289
+ return events
290
+
291
+ if len(self._buffer) > LINE_LIMIT:
292
+ self.error = ProtocolError(f"an event line is longer than {LINE_LIMIT} bytes")
293
+
294
+ return events
295
+
296
+ def _ended(self) -> bool:
297
+ """Whether the child has ended, without reaping it."""
298
+
299
+ flags = os.WEXITED | os.WNOHANG | os.WNOWAIT
300
+
301
+ try:
302
+ return os.waitid(os.P_PID, self._process.pid, flags) is not None
303
+ except ChildProcessError:
304
+ return True
305
+
306
+ def _kill_group(self) -> None:
307
+ """Kill the child's process group, if anything is left in it."""
308
+
309
+ try:
310
+ os.killpg(self._process.pid, signal.SIGKILL)
311
+ except ProcessLookupError:
312
+ pass
313
+ except PermissionError:
314
+ # macOS answers EPERM, not ESRCH, when every process left in the group is a zombie,
315
+ # as when the ended child is not reaped yet. While the child runs, EPERM is a real
316
+ # problem: the parent may not signal a process in the group.
317
+ if not self._ended():
318
+ raise
319
+
320
+
321
+ class _Tail:
322
+ """Drains a pipe on a thread and keeps its last `OUTPUT_LIMIT` bytes."""
323
+
324
+ def __init__(self, pipe: IO[bytes]) -> None:
325
+ self._pipe = pipe
326
+ self._fd = pipe.fileno()
327
+ os.set_blocking(self._fd, False)
328
+ self._data = bytearray()
329
+ self._stop = threading.Event()
330
+ self._thread = threading.Thread(target=self._drain, daemon=True)
331
+ self._thread.start()
332
+
333
+ def close(self) -> str:
334
+ """Stop draining, close the pipe and return what was kept."""
335
+
336
+ self._stop.set()
337
+ self._thread.join()
338
+ self._pipe.close()
339
+
340
+ return self._data.decode(errors="replace")
341
+
342
+ def _drain(self) -> None:
343
+ while not self._stop.is_set():
344
+ ready, _, _ = select.select([self._fd], [], [], 0.1)
345
+
346
+ if not ready:
347
+ continue
348
+
349
+ try:
350
+ chunk = os.read(self._fd, 65536)
351
+ except BlockingIOError:
352
+ continue
353
+
354
+ if not chunk:
355
+ return
356
+
357
+ self._data += chunk
358
+ del self._data[:-OUTPUT_LIMIT]
359
+
360
+
361
+ def _set_limits(items: list[Limit]) -> None:
362
+ """Runs in the child between fork and exec. Never raises a limit above its hard limit."""
363
+
364
+ for kind, value in items:
365
+ resource.setrlimit(kind, clamped(kind, value))
366
+
367
+
368
+ def clamped(kind: int, value: int) -> tuple[int, int]:
369
+ """Soft and hard limits of `value` for resource `kind`, at most the current hard limit."""
370
+
371
+ _, hard = resource.getrlimit(kind)
372
+
373
+ if hard != resource.RLIM_INFINITY:
374
+ value = min(value, hard)
375
+
376
+ return value, value
377
+
378
+
379
+ def _signal_name(number: int) -> str:
380
+ try:
381
+ return signal.Signals(number).name
382
+ except ValueError:
383
+ return str(number)
mogs/grader/_user.py ADDED
@@ -0,0 +1,7 @@
1
+ """The user that runs student code on Gradescope.
2
+
3
+ Kept apart from the sandbox, so build-time code can read it without importing Linux-only
4
+ modules.
5
+ """
6
+
7
+ STUDENT_USER = "mogs-student"
mogs/grader/bundle.py ADDED
@@ -0,0 +1,320 @@
1
+ """The tests the grader runs, cut from the source notebook and stored as JSON.
2
+
3
+ A bundle holds the setup cell and every test cell. Each grading phase gets only its own cells,
4
+ so the public phase never sees hidden test source.
5
+ """
6
+
7
+ import copy
8
+ import json
9
+ from dataclasses import dataclass
10
+ from enum import StrEnum
11
+ from typing import Self
12
+
13
+ from mogs.config import AssignmentConfig, Question
14
+ from mogs.source import Notebook, SourceError, cell_names, question_id
15
+
16
+
17
+ class Phase(StrEnum):
18
+ """A grading pass. Each runs in its own child process."""
19
+
20
+ PUBLIC = "public"
21
+ HIDDEN = "hidden"
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class TestCell:
26
+ """One test cell of the source notebook.
27
+
28
+ Attributes:
29
+ qid: Question id of the cell's tests.
30
+ hidden: Whether the cell is marked `# HIDDEN`.
31
+ source: Cell body, run as a module.
32
+ tests: Test function names, in file order.
33
+ uses: Student names the cell refers to, bound from the submission.
34
+ needs: Names the cell reads from hidden helpers. Empty for public cells.
35
+ """
36
+
37
+ __test__ = False
38
+
39
+ qid: str
40
+ hidden: bool
41
+ source: str
42
+ tests: tuple[str, ...]
43
+ uses: tuple[str, ...]
44
+ needs: tuple[str, ...] = ()
45
+
46
+ def to_dict(self) -> dict[str, object]:
47
+ """JSON-ready fields."""
48
+
49
+ return {
50
+ "qid": self.qid,
51
+ "hidden": self.hidden,
52
+ "source": self.source,
53
+ "tests": list(self.tests),
54
+ "uses": list(self.uses),
55
+ "needs": list(self.needs),
56
+ }
57
+
58
+ @classmethod
59
+ def from_dict(cls, data: object) -> Self:
60
+ """Inverse of `to_dict`.
61
+
62
+ Raises:
63
+ ValueError: If a field is missing or has the wrong type.
64
+ """
65
+
66
+ match data:
67
+ case {
68
+ "qid": str() as qid,
69
+ "hidden": bool() as hidden,
70
+ "source": str() as source,
71
+ "tests": list() as tests,
72
+ "uses": list() as uses,
73
+ "needs": list() as needs,
74
+ }:
75
+ return cls(qid, hidden, source, _strings(tests), _strings(uses), _strings(needs))
76
+
77
+ raise ValueError(f"not a test cell: {data!r}")
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class HiddenHelper:
82
+ """A `# HIDDEN` cell without tests, such as data or helpers for hidden tests.
83
+
84
+ The grader runs a helper only when a test cell needs one of the names it defines, and at
85
+ most once.
86
+
87
+ Attributes:
88
+ source: Cell body, run as a module.
89
+ defines: Names the cell binds at top level.
90
+ uses: Student names the cell refers to, bound from the submission.
91
+ needs: Names the cell reads from other hidden helpers.
92
+ """
93
+
94
+ source: str
95
+ defines: tuple[str, ...]
96
+ uses: tuple[str, ...]
97
+ needs: tuple[str, ...]
98
+
99
+ def to_dict(self) -> dict[str, object]:
100
+ """JSON-ready fields."""
101
+
102
+ return {
103
+ "source": self.source,
104
+ "defines": list(self.defines),
105
+ "uses": list(self.uses),
106
+ "needs": list(self.needs),
107
+ }
108
+
109
+ @classmethod
110
+ def from_dict(cls, data: object) -> Self:
111
+ """Inverse of `to_dict`.
112
+
113
+ Raises:
114
+ ValueError: If a field is missing or has the wrong type.
115
+ """
116
+
117
+ match data:
118
+ case {
119
+ "source": str() as source,
120
+ "defines": list() as defines,
121
+ "uses": list() as uses,
122
+ "needs": list() as needs,
123
+ }:
124
+ return cls(source, _strings(defines), _strings(uses), _strings(needs))
125
+
126
+ raise ValueError(f"not a hidden helper: {data!r}")
127
+
128
+
129
+ @dataclass(frozen=True, slots=True)
130
+ class GradingBundle:
131
+ """Everything a grading child needs besides the submission.
132
+
133
+ Attributes:
134
+ config: Assignment config.
135
+ setup_code: Body of the notebook's setup cell, run before the test cells.
136
+ cells: Test cells in file order.
137
+ helpers: Hidden cells without tests, in file order.
138
+ """
139
+
140
+ config: AssignmentConfig
141
+ setup_code: str
142
+ cells: tuple[TestCell, ...]
143
+ helpers: tuple[HiddenHelper, ...] = ()
144
+
145
+ def for_phase(self, phase: Phase) -> "GradingBundle":
146
+ """The bundle with only what `phase` runs.
147
+
148
+ The public phase gets the public test cells. The hidden phase gets the hidden test
149
+ cells and the hidden helpers.
150
+ """
151
+
152
+ hidden = phase is Phase.HIDDEN
153
+ cells = tuple(c for c in self.cells if c.hidden == hidden)
154
+
155
+ return copy.replace(self, cells=cells, helpers=self.helpers if hidden else ())
156
+
157
+ def to_dict(self) -> dict[str, object]:
158
+ """JSON-ready fields."""
159
+
160
+ return {
161
+ "config": _config_to_dict(self.config),
162
+ "setup_code": self.setup_code,
163
+ "cells": [cell.to_dict() for cell in self.cells],
164
+ "helpers": [helper.to_dict() for helper in self.helpers],
165
+ }
166
+
167
+ @classmethod
168
+ def from_dict(cls, data: object) -> Self:
169
+ """Inverse of `to_dict`.
170
+
171
+ Raises:
172
+ ValueError: If a field is missing or has the wrong type.
173
+ """
174
+
175
+ match data:
176
+ case {
177
+ "config": dict() as config,
178
+ "setup_code": str() as setup,
179
+ "cells": list() as cells,
180
+ "helpers": list() as helpers,
181
+ }:
182
+ return cls(
183
+ _config_from_dict(config),
184
+ setup,
185
+ tuple(TestCell.from_dict(cell) for cell in cells),
186
+ tuple(HiddenHelper.from_dict(helper) for helper in helpers),
187
+ )
188
+
189
+ raise ValueError("not a grading bundle")
190
+
191
+ def to_json(self) -> str:
192
+ """The bundle as JSON text."""
193
+
194
+ return json.dumps(self.to_dict())
195
+
196
+ @classmethod
197
+ def from_json(cls, text: str) -> Self:
198
+ """Inverse of `to_json`.
199
+
200
+ Raises:
201
+ ValueError: If the text is not JSON or not a bundle.
202
+ """
203
+
204
+ return cls.from_dict(json.loads(text))
205
+
206
+
207
+ def bundle_from_notebook(nb: Notebook, cfg: AssignmentConfig) -> GradingBundle:
208
+ """Cut the setup cell, the test cells and the hidden helper cells out of a source notebook.
209
+
210
+ Scope analysis of each cell body gives its `uses`, the student names
211
+ (`nb.student_names()`) it reads without defining them, and, for hidden cells, its `needs`,
212
+ the names it reads from other hidden helper cells. A hidden helper is a `# HIDDEN` cell
213
+ without tests.
214
+
215
+ Raises:
216
+ SourceError: If a cell holds tests of more than one question.
217
+ """
218
+
219
+ students = nb.student_names()
220
+ helper_cells = nb.helper_cells()
221
+ names = {cell: cell_names(nb.cell_body_source(cell)) for cell in helper_cells}
222
+ helpers = []
223
+
224
+ for cell in helper_cells:
225
+ bound, free = names[cell]
226
+ others = {name for other in helper_cells if other is not cell for name in names[other][0]}
227
+ helpers.append(
228
+ HiddenHelper(
229
+ nb.cell_body_source(cell),
230
+ defines=tuple(sorted(bound)),
231
+ uses=tuple(sorted(free & students)),
232
+ needs=tuple(sorted(free & others)),
233
+ )
234
+ )
235
+
236
+ provided = {name for helper in helpers for name in helper.defines}
237
+ cells = []
238
+
239
+ for cell in nb.cells:
240
+ if not cell.tests:
241
+ continue
242
+
243
+ qids = {question_id(name) for name in cell.tests}
244
+ if len(qids) > 1:
245
+ raise SourceError(
246
+ f"line {cell.start}: put the tests of each question in their own cell; found "
247
+ f"{', '.join(cell.tests)}."
248
+ )
249
+
250
+ source = nb.cell_body_source(cell)
251
+ _, free = cell_names(source)
252
+ uses = tuple(sorted(free & students))
253
+ needs = tuple(sorted(free & provided)) if cell.hidden else ()
254
+ cells.append(TestCell(qids.pop(), cell.hidden, source, cell.tests, uses, needs))
255
+
256
+ return GradingBundle(cfg, nb.setup_source(), tuple(cells), tuple(helpers))
257
+
258
+
259
+ def _strings(items: list) -> tuple[str, ...]:
260
+ if all(isinstance(item, str) for item in items):
261
+ return tuple(items)
262
+
263
+ raise ValueError(f"expected a list of strings, got {items!r}")
264
+
265
+
266
+ def _config_to_dict(config: AssignmentConfig) -> dict[str, object]:
267
+ """The config fields the grader needs. `requirements` is left out: it is a host path."""
268
+
269
+ return {
270
+ "name": config.name,
271
+ "notebook": config.notebook,
272
+ "questions": [
273
+ {"id": q.id, "title": q.title, "points": q.points, "manual": q.manual}
274
+ for q in config.questions.values()
275
+ ],
276
+ "files": list(config.files),
277
+ "timeout": config.timeout,
278
+ "budget": config.budget,
279
+ "memory_mb": config.memory_mb,
280
+ "python": config.python,
281
+ }
282
+
283
+
284
+ def _config_from_dict(data: dict) -> AssignmentConfig:
285
+ match data:
286
+ case {
287
+ "name": str() as name,
288
+ "notebook": str() as notebook,
289
+ "questions": list() as questions,
290
+ "files": list() as files,
291
+ "timeout": int() | float() as timeout,
292
+ "budget": int() | float() as budget,
293
+ "memory_mb": int() as memory_mb,
294
+ "python": str() as python,
295
+ }:
296
+ return AssignmentConfig(
297
+ name=name,
298
+ notebook=notebook,
299
+ questions={q.id: q for q in map(_question_from_dict, questions)},
300
+ files=_strings(files),
301
+ timeout=float(timeout),
302
+ budget=float(budget),
303
+ memory_mb=memory_mb,
304
+ python=python,
305
+ )
306
+
307
+ raise ValueError(f"not an assignment config: {data!r}")
308
+
309
+
310
+ def _question_from_dict(data: object) -> Question:
311
+ match data:
312
+ case {
313
+ "id": str() as qid,
314
+ "title": str() as title,
315
+ "points": int() | float() as points,
316
+ "manual": bool() as manual,
317
+ }:
318
+ return Question(qid, title, float(points), manual)
319
+
320
+ raise ValueError(f"not a question: {data!r}")