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.
- mogs/__init__.py +17 -0
- mogs/_assertrewrite.py +44 -0
- mogs/_env.py +26 -0
- mogs/_run.py +111 -0
- mogs/_typst/preview/cmarker/0.1.10/LICENSE +7 -0
- mogs/_typst/preview/cmarker/0.1.10/lib.typ +462 -0
- mogs/_typst/preview/cmarker/0.1.10/plugin.wasm +0 -0
- mogs/_typst/preview/cmarker/0.1.10/typst.toml +11 -0
- mogs/_typst/preview/mitex/0.2.7/LICENSE +176 -0
- mogs/_typst/preview/mitex/0.2.7/lib.typ +1 -0
- mogs/_typst/preview/mitex/0.2.7/mitex.typ +45 -0
- mogs/_typst/preview/mitex/0.2.7/mitex.wasm +0 -0
- mogs/_typst/preview/mitex/0.2.7/specs/latex/standard.typ +1187 -0
- mogs/_typst/preview/mitex/0.2.7/specs/mod.typ +12 -0
- mogs/_typst/preview/mitex/0.2.7/specs/prelude.typ +230 -0
- mogs/_typst/preview/mitex/0.2.7/typst.toml +12 -0
- mogs/assignment.py +172 -0
- mogs/build.py +605 -0
- mogs/check.py +410 -0
- mogs/cli.py +272 -0
- mogs/config.py +619 -0
- mogs/environment.py +118 -0
- mogs/export.py +556 -0
- mogs/grader/__init__.py +1 -0
- mogs/grader/_process.py +383 -0
- mogs/grader/_user.py +7 -0
- mogs/grader/bundle.py +320 -0
- mogs/grader/child.py +317 -0
- mogs/grader/datafiles.py +54 -0
- mogs/grader/main.py +132 -0
- mogs/grader/protocol.py +175 -0
- mogs/grader/results.py +337 -0
- mogs/grader/sandbox.py +462 -0
- mogs/grader/templates/__init__.py +38 -0
- mogs/grader/templates/run_autograder +3 -0
- mogs/grader/templates/setup.sh +28 -0
- mogs/loader.py +260 -0
- mogs/pdf.py +676 -0
- mogs/regrade.py +223 -0
- mogs/requirements.py +232 -0
- mogs/runner.py +281 -0
- mogs/scaffold.py +155 -0
- mogs/selfcheck.py +173 -0
- mogs/source.py +1438 -0
- mogs/transform.py +769 -0
- mogs-0.7.0.dist-info/METADATA +17 -0
- mogs-0.7.0.dist-info/RECORD +49 -0
- mogs-0.7.0.dist-info/WHEEL +4 -0
- mogs-0.7.0.dist-info/entry_points.txt +3 -0
mogs/grader/child.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""Grading child: runs one phase's tests on a submission and reports events.
|
|
2
|
+
|
|
3
|
+
Usage: `python -m mogs.grader.child EVENT_FD`. The parent passes a writable file
|
|
4
|
+
descriptor `EVENT_FD` (e.g. with `pass_fds`) and writes a `Job` to stdin; the child writes
|
|
5
|
+
events to `EVENT_FD`, as `grader.protocol` describes. Stdout and stderr belong to the
|
|
6
|
+
student's code.
|
|
7
|
+
|
|
8
|
+
Linux and macOS: each test runs under a `SIGALRM` timer of `config.timeout` seconds.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import signal
|
|
13
|
+
import sys
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from types import FrameType
|
|
17
|
+
|
|
18
|
+
from mogs._assertrewrite import compile_tests
|
|
19
|
+
from mogs.grader.bundle import HiddenHelper, TestCell
|
|
20
|
+
from mogs.grader.protocol import Event, Job, Loaded, Loading, Result, Start, encode
|
|
21
|
+
from mogs.loader import bind, load
|
|
22
|
+
from mogs.runner import (
|
|
23
|
+
FailureReason,
|
|
24
|
+
Outcome,
|
|
25
|
+
cap,
|
|
26
|
+
exception_summary,
|
|
27
|
+
run_test,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
type Emit = Callable[[Event], None]
|
|
31
|
+
type Namespace = dict[str, object]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _Timeout(BaseException):
|
|
35
|
+
"""Raised by the timer inside the running test."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Alarm:
|
|
39
|
+
"""One-shot `SIGALRM` timer that raises `_Timeout` and remembers that it fired.
|
|
40
|
+
|
|
41
|
+
It fires at most once, so code that catches `_Timeout` around the `with` block sees every
|
|
42
|
+
expiry, even one that lands while the block exits.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(self, seconds: float) -> None:
|
|
46
|
+
self.seconds = seconds
|
|
47
|
+
self.fired = False
|
|
48
|
+
|
|
49
|
+
def __enter__(self) -> None:
|
|
50
|
+
signal.signal(signal.SIGALRM, self._expire)
|
|
51
|
+
signal.setitimer(signal.ITIMER_REAL, self.seconds)
|
|
52
|
+
|
|
53
|
+
def __exit__(self, *exc: object) -> None:
|
|
54
|
+
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
55
|
+
signal.signal(signal.SIGALRM, signal.SIG_DFL)
|
|
56
|
+
|
|
57
|
+
def _expire(self, signum: int, frame: FrameType | None) -> None:
|
|
58
|
+
self.fired = True
|
|
59
|
+
raise _Timeout
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def main(argv: list[str] | None = None) -> int:
|
|
63
|
+
"""Read the job from stdin, run it, and write events to the descriptor in `argv`."""
|
|
64
|
+
|
|
65
|
+
[fd] = sys.argv[1:] if argv is None else argv
|
|
66
|
+
events = int(fd)
|
|
67
|
+
|
|
68
|
+
if events <= 2:
|
|
69
|
+
raise SystemExit(f"EVENT_FD must not be stdin, stdout or stderr (0-2); got {events}.")
|
|
70
|
+
|
|
71
|
+
# Student code may start processes; they must not inherit the event channel.
|
|
72
|
+
os.set_inheritable(events, False)
|
|
73
|
+
|
|
74
|
+
job = Job.from_json(sys.stdin.read())
|
|
75
|
+
_close_stdin()
|
|
76
|
+
|
|
77
|
+
with os.fdopen(events, "w", encoding="utf-8") as stream:
|
|
78
|
+
|
|
79
|
+
def emit(event: Event) -> None:
|
|
80
|
+
stream.write(encode(event))
|
|
81
|
+
stream.flush()
|
|
82
|
+
|
|
83
|
+
run(job, emit)
|
|
84
|
+
|
|
85
|
+
return 0
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def run(job: Job, emit: Emit) -> None:
|
|
89
|
+
"""Set up the namespace, then run every test not in `job.skip`, emitting events.
|
|
90
|
+
|
|
91
|
+
The base namespace holds the setup code's names and the bound student names. Each test
|
|
92
|
+
cell runs in its own copy of it, plus the names of the hidden helpers it needs. If the
|
|
93
|
+
setup code fails or the notebook does not import, every test fails with `LOAD_FAILED`.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
bundle = job.bundle
|
|
97
|
+
timeout = bundle.config.timeout
|
|
98
|
+
base: Namespace = {"__name__": "__mogs_tests__"}
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
exec(compile(bundle.setup_code, "<mogs-setup>", "exec", dont_inherit=True), base)
|
|
102
|
+
except BaseException as exc:
|
|
103
|
+
error = cap(f"the grader's setup code failed ({exception_summary(exc)})")
|
|
104
|
+
emit(Loaded(error))
|
|
105
|
+
|
|
106
|
+
for cell in bundle.cells:
|
|
107
|
+
_fail_cell(cell, job.skip, error, FailureReason.LOAD_FAILED, emit)
|
|
108
|
+
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
_, import_error = load(job.submission)
|
|
112
|
+
|
|
113
|
+
if import_error is not None:
|
|
114
|
+
emit(Loaded(import_error))
|
|
115
|
+
|
|
116
|
+
for cell in bundle.cells:
|
|
117
|
+
_fail_cell(cell, job.skip, import_error, FailureReason.LOAD_FAILED, emit)
|
|
118
|
+
|
|
119
|
+
return
|
|
120
|
+
|
|
121
|
+
# One call: a second `bind` could give different objects after an `app.run()` fallback.
|
|
122
|
+
parts = [*bundle.helpers, *bundle.cells]
|
|
123
|
+
uses = sorted({name for part in parts for name in part.uses})
|
|
124
|
+
base.update(bind(job.submission, uses, run_failed=job.run_failed))
|
|
125
|
+
emit(Loaded(None))
|
|
126
|
+
|
|
127
|
+
helpers = _Helpers(bundle.helpers, base, timeout)
|
|
128
|
+
|
|
129
|
+
for cell in bundle.cells:
|
|
130
|
+
_run_cell(cell, base, helpers, job.skip, timeout, emit)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@dataclass(frozen=True, slots=True)
|
|
134
|
+
class _Failure:
|
|
135
|
+
"""Why a hidden helper, or one it needs, did not load."""
|
|
136
|
+
|
|
137
|
+
message: str
|
|
138
|
+
reason: FailureReason
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class _Helpers:
|
|
142
|
+
"""Runs hidden helpers on first need, each at most once, and keeps what they define.
|
|
143
|
+
|
|
144
|
+
A helper runs in a copy of the base namespace plus the names of the helpers it needs, which
|
|
145
|
+
run first. A failure is kept too, so it reaches every cell that needs the helper and no
|
|
146
|
+
other cell.
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
def __init__(self, helpers: tuple[HiddenHelper, ...], base: Namespace, timeout: float) -> None:
|
|
150
|
+
self._helpers = helpers
|
|
151
|
+
self._base = base
|
|
152
|
+
self._timeout = timeout
|
|
153
|
+
self._done: dict[int, Namespace | _Failure] = {}
|
|
154
|
+
self._running: set[int] = set()
|
|
155
|
+
|
|
156
|
+
def provide(self, needs: tuple[str, ...]) -> Namespace | _Failure:
|
|
157
|
+
"""The values of `needs`, or the failure of a helper that defines one of them."""
|
|
158
|
+
|
|
159
|
+
names: Namespace = {}
|
|
160
|
+
|
|
161
|
+
for index, helper in enumerate(self._helpers):
|
|
162
|
+
if not set(helper.defines) & set(needs):
|
|
163
|
+
continue
|
|
164
|
+
|
|
165
|
+
match self._run(index):
|
|
166
|
+
case _Failure() as failure:
|
|
167
|
+
return failure
|
|
168
|
+
case defined:
|
|
169
|
+
names.update(defined)
|
|
170
|
+
|
|
171
|
+
return names
|
|
172
|
+
|
|
173
|
+
def _run(self, index: int) -> Namespace | _Failure:
|
|
174
|
+
if index in self._done:
|
|
175
|
+
return self._done[index]
|
|
176
|
+
|
|
177
|
+
helper = self._helpers[index]
|
|
178
|
+
label = ", ".join(f"`{name}`" for name in helper.defines)
|
|
179
|
+
|
|
180
|
+
if index in self._running:
|
|
181
|
+
message = f"the hidden helper cell defining {label} needs itself through other cells"
|
|
182
|
+
return _Failure(message, FailureReason.LOAD_FAILED)
|
|
183
|
+
|
|
184
|
+
self._running.add(index)
|
|
185
|
+
|
|
186
|
+
match self.provide(helper.needs):
|
|
187
|
+
case _Failure() as failure:
|
|
188
|
+
result: Namespace | _Failure = failure
|
|
189
|
+
case names:
|
|
190
|
+
namespace = {**self._base, **names}
|
|
191
|
+
match _load(helper.source, "hidden-helper", namespace, self._timeout):
|
|
192
|
+
case (message, reason):
|
|
193
|
+
result = _Failure(
|
|
194
|
+
f"the hidden helper cell defining {label} {message}", reason
|
|
195
|
+
)
|
|
196
|
+
case None:
|
|
197
|
+
result = {
|
|
198
|
+
name: namespace[name] for name in helper.defines if name in namespace
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
self._running.discard(index)
|
|
202
|
+
self._done[index] = result
|
|
203
|
+
|
|
204
|
+
return result
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _load(
|
|
208
|
+
source: str, label: str, namespace: Namespace, timeout: float
|
|
209
|
+
) -> tuple[str, FailureReason] | None:
|
|
210
|
+
"""Run cell source into `namespace` under the timer.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
`None` on success, else the end of a message (after "the cell") and the reason.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
alarm = _Alarm(timeout)
|
|
217
|
+
error = None
|
|
218
|
+
|
|
219
|
+
try:
|
|
220
|
+
with alarm:
|
|
221
|
+
exec(compile_tests(source, label), namespace)
|
|
222
|
+
except BaseException as exc:
|
|
223
|
+
error = exc
|
|
224
|
+
|
|
225
|
+
if alarm.fired:
|
|
226
|
+
return f"took longer than {timeout:g} s to load", FailureReason.TIMEOUT
|
|
227
|
+
|
|
228
|
+
if error is not None:
|
|
229
|
+
return f"failed to load ({exception_summary(error)})", FailureReason.LOAD_FAILED
|
|
230
|
+
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _run_cell(
|
|
235
|
+
cell: TestCell,
|
|
236
|
+
base: Namespace,
|
|
237
|
+
helpers: _Helpers,
|
|
238
|
+
skip: tuple[str, ...],
|
|
239
|
+
timeout: float,
|
|
240
|
+
emit: Emit,
|
|
241
|
+
) -> None:
|
|
242
|
+
"""Run one cell's body in a copy of `base` and its helpers' names, then its tests."""
|
|
243
|
+
|
|
244
|
+
tests = tuple(name for name in cell.tests if name not in skip)
|
|
245
|
+
|
|
246
|
+
if not tests:
|
|
247
|
+
return
|
|
248
|
+
|
|
249
|
+
# The parent blames these tests if the process dies or hangs while the cell loads.
|
|
250
|
+
emit(Loading(tests))
|
|
251
|
+
|
|
252
|
+
match helpers.provide(cell.needs):
|
|
253
|
+
case _Failure(message, reason):
|
|
254
|
+
_fail_cell(cell, skip, message, reason, emit)
|
|
255
|
+
return
|
|
256
|
+
case provided:
|
|
257
|
+
pass
|
|
258
|
+
|
|
259
|
+
namespace = {**base, **provided}
|
|
260
|
+
|
|
261
|
+
match _load(cell.source, f"{cell.qid}-tests", namespace, timeout):
|
|
262
|
+
case (message, reason):
|
|
263
|
+
_fail_cell(cell, skip, f"the test cell {message}", reason, emit)
|
|
264
|
+
return
|
|
265
|
+
|
|
266
|
+
for name in tests:
|
|
267
|
+
emit(Start(name))
|
|
268
|
+
emit(Result(_run_one(name, namespace.get(name), timeout)))
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _run_one(name: str, test: object, timeout: float) -> Outcome:
|
|
272
|
+
"""Run one test under the timer."""
|
|
273
|
+
|
|
274
|
+
if not callable(test):
|
|
275
|
+
return Outcome(
|
|
276
|
+
name, False, f"`{name}` is not defined by its test cell", FailureReason.ERROR
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
alarm = _Alarm(timeout)
|
|
280
|
+
outcome = None
|
|
281
|
+
|
|
282
|
+
try:
|
|
283
|
+
with alarm:
|
|
284
|
+
outcome = run_test(name, test)
|
|
285
|
+
except _Timeout:
|
|
286
|
+
pass
|
|
287
|
+
|
|
288
|
+
if alarm.fired or outcome is None:
|
|
289
|
+
message = f"the test took longer than {timeout:g} s"
|
|
290
|
+
return Outcome(name, False, message, FailureReason.TIMEOUT, timeout)
|
|
291
|
+
|
|
292
|
+
return outcome
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _fail_cell(
|
|
296
|
+
cell: TestCell, skip: tuple[str, ...], message: str, reason: FailureReason, emit: Emit
|
|
297
|
+
) -> None:
|
|
298
|
+
"""Fail every test of `cell` not in `skip` with the same message."""
|
|
299
|
+
|
|
300
|
+
for name in cell.tests:
|
|
301
|
+
if name in skip:
|
|
302
|
+
continue
|
|
303
|
+
|
|
304
|
+
emit(Start(name))
|
|
305
|
+
emit(Result(Outcome(name, False, cap(message), reason)))
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _close_stdin() -> None:
|
|
309
|
+
"""Point fd 0 at `/dev/null`, closing the parent's pipe; student reads see end of file."""
|
|
310
|
+
|
|
311
|
+
null = os.open(os.devnull, os.O_RDONLY)
|
|
312
|
+
os.dup2(null, 0)
|
|
313
|
+
os.close(null)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
if __name__ == "__main__":
|
|
317
|
+
sys.exit(main())
|
mogs/grader/datafiles.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Data files shipped with a notebook: path checks and folder expansion.
|
|
2
|
+
|
|
3
|
+
Shared by the build and the sandbox. Stdlib only, so the build can use it on any platform.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from pathlib import Path, PurePosixPath
|
|
8
|
+
|
|
9
|
+
# The name the sandbox gives the submission in each phase folder.
|
|
10
|
+
SUBMISSION = "submission.py"
|
|
11
|
+
# Folders and files that tools leave behind; never shipped.
|
|
12
|
+
JUNK = frozenset({"__pycache__", "__marimo__", "__MACOSX", ".ipynb_checkpoints", ".DS_Store"})
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def data_files(root: Path, files: Sequence[str]) -> dict[PurePosixPath, Path]:
|
|
16
|
+
"""The data files to ship, by path relative to `root`, with folders expanded.
|
|
17
|
+
|
|
18
|
+
Files in `JUNK` folders, and `JUNK` files, are left out.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
root: Folder the paths are relative to.
|
|
22
|
+
files: Relative paths of files or folders.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Source path by relative destination, in the order of `files`, folders sorted.
|
|
26
|
+
|
|
27
|
+
Raises:
|
|
28
|
+
ValueError: If a path is absolute, has a `..` part, is empty, starts with
|
|
29
|
+
`submission.py`, or does not exist. The message names the path.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
out: dict[PurePosixPath, Path] = {}
|
|
33
|
+
|
|
34
|
+
for name in files:
|
|
35
|
+
rel = PurePosixPath(name)
|
|
36
|
+
|
|
37
|
+
if rel.is_absolute() or ".." in rel.parts or not rel.parts:
|
|
38
|
+
raise ValueError(f"a data file must be a relative path inside its folder: {name!r}")
|
|
39
|
+
|
|
40
|
+
if rel.parts[0] == SUBMISSION:
|
|
41
|
+
raise ValueError(f"a data file must not be named {SUBMISSION}: {name!r}")
|
|
42
|
+
|
|
43
|
+
source = root / rel
|
|
44
|
+
if source.is_file():
|
|
45
|
+
out[rel] = source
|
|
46
|
+
elif source.is_dir():
|
|
47
|
+
for path in sorted(source.rglob("*")):
|
|
48
|
+
inner = PurePosixPath(path.relative_to(root).as_posix())
|
|
49
|
+
if path.is_file() and not JUNK & set(inner.parts):
|
|
50
|
+
out[inner] = path
|
|
51
|
+
else:
|
|
52
|
+
raise ValueError(f"data file {name!r} not found in {root}")
|
|
53
|
+
|
|
54
|
+
return out
|
mogs/grader/main.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Gradescope entry point: grade `/autograder/submission` and write `results.json`.
|
|
2
|
+
|
|
3
|
+
`run_autograder` calls `python -m mogs.grader.main`. It always writes
|
|
4
|
+
`results.json` and exits with code 0, since Gradescope treats any other code as a crash and
|
|
5
|
+
shows no results. Logs go to stderr, which students do not see.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from mogs.grader._user import STUDENT_USER
|
|
17
|
+
from mogs.grader.bundle import GradingBundle
|
|
18
|
+
from mogs.grader.results import (
|
|
19
|
+
Results,
|
|
20
|
+
build_results,
|
|
21
|
+
failure_results,
|
|
22
|
+
find_submission,
|
|
23
|
+
inline_code,
|
|
24
|
+
)
|
|
25
|
+
from mogs.grader.sandbox import grade
|
|
26
|
+
from mogs.runner import FailureReason, Outcome
|
|
27
|
+
|
|
28
|
+
AUTOGRADER = Path("/autograder")
|
|
29
|
+
WORKDIR = Path("/tmp/mogs")
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def main(argv: list[str] | None = None) -> None:
|
|
35
|
+
"""Grade the submission and write `results.json`, whatever happens.
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
argv: Command-line arguments; `sys.argv[1:]` when `None`. The defaults are
|
|
39
|
+
Gradescope's paths.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
args = _parser().parse_args(argv)
|
|
43
|
+
logging.basicConfig(level=logging.INFO, stream=sys.stderr)
|
|
44
|
+
bundle = None
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
bundle = GradingBundle.from_json((args.source / "bundle.json").read_text(encoding="utf-8"))
|
|
48
|
+
results = run(bundle, args.source, args.submission, args.workdir)
|
|
49
|
+
except Exception as error:
|
|
50
|
+
logger.exception("the autograder failed")
|
|
51
|
+
results = failure_results(bundle, error)
|
|
52
|
+
|
|
53
|
+
args.results.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
args.results.write_text(json.dumps(results, indent=2), encoding="utf-8")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def run(bundle: GradingBundle, source: Path, submission: Path, workdir: Path) -> Results:
|
|
58
|
+
"""Find the upload, grade it in the sandbox and build the results.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
bundle: The grading bundle.
|
|
62
|
+
source: Folder with the data files, at their paths relative to the notebook.
|
|
63
|
+
submission: The unpacked upload.
|
|
64
|
+
workdir: Folder for the sandbox's phase folders; replaced if it exists.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
The results.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
config = bundle.config
|
|
71
|
+
found = find_submission(submission, config.notebook, config.name)
|
|
72
|
+
notices = [] if found.error is None else [found.error]
|
|
73
|
+
|
|
74
|
+
if any(question.manual for question in config.questions.values()):
|
|
75
|
+
notices += _answers_notices(found.answers)
|
|
76
|
+
|
|
77
|
+
if found.py is None:
|
|
78
|
+
tests = [name for cell in bundle.cells for name in cell.tests]
|
|
79
|
+
outcomes = {
|
|
80
|
+
name: Outcome(name, False, "not run: no notebook", FailureReason.NOT_RUN)
|
|
81
|
+
for name in tests
|
|
82
|
+
}
|
|
83
|
+
else:
|
|
84
|
+
_fresh_workdir(workdir)
|
|
85
|
+
user = STUDENT_USER if os.geteuid() == 0 else None
|
|
86
|
+
outcomes = grade(
|
|
87
|
+
bundle, found.py, workdir, user=user, files_root=source, files=config.files
|
|
88
|
+
).outcomes
|
|
89
|
+
|
|
90
|
+
return build_results(bundle, outcomes, notices)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _answers_notices(answers: Path | None) -> list[str]:
|
|
94
|
+
"""Warnings about the written answers for manual questions."""
|
|
95
|
+
|
|
96
|
+
if answers is None:
|
|
97
|
+
return [
|
|
98
|
+
"No PDF of your written answers found. Questions graded by hand need it: upload "
|
|
99
|
+
"the zip from the notebook's export button."
|
|
100
|
+
]
|
|
101
|
+
|
|
102
|
+
if answers.suffix.lower() == ".md":
|
|
103
|
+
return [
|
|
104
|
+
f"No PDF of your written answers found; graders will read {inline_code(answers.name)}"
|
|
105
|
+
" instead."
|
|
106
|
+
]
|
|
107
|
+
|
|
108
|
+
return []
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _fresh_workdir(workdir: Path) -> None:
|
|
112
|
+
"""Create an empty `workdir` that others can enter but not write to."""
|
|
113
|
+
|
|
114
|
+
if workdir.exists():
|
|
115
|
+
shutil.rmtree(workdir)
|
|
116
|
+
|
|
117
|
+
workdir.mkdir(parents=True)
|
|
118
|
+
workdir.chmod(0o755)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _parser() -> argparse.ArgumentParser:
|
|
122
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
123
|
+
parser.add_argument("--source", type=Path, default=AUTOGRADER / "source")
|
|
124
|
+
parser.add_argument("--submission", type=Path, default=AUTOGRADER / "submission")
|
|
125
|
+
parser.add_argument("--results", type=Path, default=AUTOGRADER / "results" / "results.json")
|
|
126
|
+
parser.add_argument("--workdir", type=Path, default=WORKDIR)
|
|
127
|
+
|
|
128
|
+
return parser
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == "__main__":
|
|
132
|
+
main()
|
mogs/grader/protocol.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Messages between the grader parent and a grading child.
|
|
2
|
+
|
|
3
|
+
The parent writes one `Job` as JSON to the child's stdin. The child writes events, one JSON
|
|
4
|
+
object per line, to a separate file descriptor whose number is its first argument:
|
|
5
|
+
|
|
6
|
+
- `{"event": "loaded", "error": str | None}` once, after setup and binding;
|
|
7
|
+
- `{"event": "loading", "tests": [name, ...]}` before loading each test cell (and the hidden
|
|
8
|
+
helpers it needs), naming the cell's tests that will run;
|
|
9
|
+
- `{"event": "start", "test": name}` before each test;
|
|
10
|
+
- `{"event": "result", **outcome}` after each test, with the fields of `Outcome.to_dict`.
|
|
11
|
+
|
|
12
|
+
Student code writes to stdout and stderr freely; neither carries events.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Self
|
|
19
|
+
|
|
20
|
+
from mogs.grader.bundle import GradingBundle
|
|
21
|
+
from mogs.runner import Outcome
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ProtocolError(Exception):
|
|
25
|
+
"""A line or job that does not follow the protocol."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True, slots=True)
|
|
29
|
+
class Job:
|
|
30
|
+
"""What one child runs.
|
|
31
|
+
|
|
32
|
+
Attributes:
|
|
33
|
+
bundle: The bundle of one phase.
|
|
34
|
+
submission: The student's notebook.
|
|
35
|
+
skip: Tests already done, e.g. by an earlier child that died.
|
|
36
|
+
run_failed: Why an earlier child died while running the whole notebook. When set,
|
|
37
|
+
the child does not run it again; see `loader.bind`.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
bundle: GradingBundle
|
|
41
|
+
submission: Path
|
|
42
|
+
skip: tuple[str, ...] = ()
|
|
43
|
+
run_failed: str | None = None
|
|
44
|
+
|
|
45
|
+
def to_json(self) -> str:
|
|
46
|
+
"""The job as JSON text."""
|
|
47
|
+
|
|
48
|
+
return json.dumps(
|
|
49
|
+
{
|
|
50
|
+
"bundle": self.bundle.to_dict(),
|
|
51
|
+
"submission": str(self.submission),
|
|
52
|
+
"skip": list(self.skip),
|
|
53
|
+
"run_failed": self.run_failed,
|
|
54
|
+
}
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_json(cls, text: str) -> Self:
|
|
59
|
+
"""Inverse of `to_json`.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
ProtocolError: If the text is not a job.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
match json.loads(text):
|
|
67
|
+
case {
|
|
68
|
+
"bundle": bundle,
|
|
69
|
+
"submission": str() as submission,
|
|
70
|
+
"skip": list() as skip,
|
|
71
|
+
"run_failed": None | str() as run_failed,
|
|
72
|
+
} if all(isinstance(name, str) for name in skip):
|
|
73
|
+
return cls(
|
|
74
|
+
GradingBundle.from_dict(bundle), Path(submission), tuple(skip), run_failed
|
|
75
|
+
)
|
|
76
|
+
except ValueError as e:
|
|
77
|
+
raise ProtocolError(f"bad job: {e}") from e
|
|
78
|
+
|
|
79
|
+
raise ProtocolError("bad job: expected bundle, submission, skip and run_failed")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True, slots=True)
|
|
83
|
+
class Loaded:
|
|
84
|
+
"""The child is ready to run tests, or failed to set up (`error`)."""
|
|
85
|
+
|
|
86
|
+
error: str | None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True, slots=True)
|
|
90
|
+
class Loading:
|
|
91
|
+
"""The child is about to load the test cell of `tests`."""
|
|
92
|
+
|
|
93
|
+
tests: tuple[str, ...]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True, slots=True)
|
|
97
|
+
class Start:
|
|
98
|
+
"""The child is about to run `test`."""
|
|
99
|
+
|
|
100
|
+
test: str
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True, slots=True)
|
|
104
|
+
class Result:
|
|
105
|
+
"""A test finished."""
|
|
106
|
+
|
|
107
|
+
outcome: Outcome
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
type Event = Loaded | Loading | Start | Result
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def encode(event: Event) -> str:
|
|
114
|
+
"""One event as a JSON line, ending in a newline."""
|
|
115
|
+
|
|
116
|
+
match event:
|
|
117
|
+
case Loaded(error):
|
|
118
|
+
data: dict[str, object] = {"event": "loaded", "error": error}
|
|
119
|
+
case Loading(tests):
|
|
120
|
+
data = {"event": "loading", "tests": list(tests)}
|
|
121
|
+
case Start(test):
|
|
122
|
+
data = {"event": "start", "test": test}
|
|
123
|
+
case Result(outcome):
|
|
124
|
+
data = {"event": "result", **outcome.to_dict()}
|
|
125
|
+
|
|
126
|
+
# `json.dumps` escapes newlines inside strings, so the line stays one line.
|
|
127
|
+
return json.dumps(data) + "\n"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def decode(line: str) -> Event:
|
|
131
|
+
"""Parse one event line.
|
|
132
|
+
|
|
133
|
+
The line may come from hostile code, so any failure to parse or validate it, such as a
|
|
134
|
+
`RecursionError` from deeply nested JSON, becomes a `ProtocolError`.
|
|
135
|
+
|
|
136
|
+
Raises:
|
|
137
|
+
ProtocolError: If the line is not an event.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
try:
|
|
141
|
+
return _decode(line)
|
|
142
|
+
except ProtocolError:
|
|
143
|
+
raise
|
|
144
|
+
except Exception as e:
|
|
145
|
+
raise ProtocolError(f"bad event ({type(e).__name__}): {_excerpt(line)}") from e
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _decode(line: str) -> Event:
|
|
149
|
+
try:
|
|
150
|
+
data = json.loads(line)
|
|
151
|
+
except ValueError as e:
|
|
152
|
+
raise ProtocolError(f"not JSON: {_excerpt(line)}") from e
|
|
153
|
+
|
|
154
|
+
match data:
|
|
155
|
+
case {"event": "loaded", "error": None | str() as error}:
|
|
156
|
+
return Loaded(error)
|
|
157
|
+
case {"event": "loading", "tests": list() as tests} if all(
|
|
158
|
+
isinstance(test, str) for test in tests
|
|
159
|
+
):
|
|
160
|
+
return Loading(tuple(tests))
|
|
161
|
+
case {"event": "start", "test": str() as test}:
|
|
162
|
+
return Start(test)
|
|
163
|
+
case {"event": "result", **fields}:
|
|
164
|
+
try:
|
|
165
|
+
return Result(Outcome.from_dict(fields))
|
|
166
|
+
except ValueError as e:
|
|
167
|
+
raise ProtocolError(str(e)[:200]) from e
|
|
168
|
+
|
|
169
|
+
raise ProtocolError(f"not an event: {_excerpt(line)}")
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _excerpt(line: str) -> str:
|
|
173
|
+
"""The start of `line`, short enough for an error message."""
|
|
174
|
+
|
|
175
|
+
return repr(line[:200]) + ("..." if len(line) > 200 else "")
|