Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
0db9b89
fix(cli): say 1 pt, not 1 pts, in the build report
wiseodd Nov 26, 2026
a3c6bf0
fix(build): skip 0-point questions in the free-points warning
wiseodd Nov 26, 2026
c1bc184
fix(build): warn when # HIDDEN comes after code in its cell
wiseodd Nov 26, 2026
92cd33e
fix(source): report a misnamed test, not a cell mixing questions
wiseodd Nov 26, 2026
b97848c
fix(build): remove the old dist/ output when a build fails
wiseodd Nov 26, 2026
335d90c
fix(grade): skip public test files when looking for the notebook
wiseodd Nov 26, 2026
87dfcdb
fix(config): title question<N> ids Question <N>, like q<N>
wiseodd Nov 26, 2026
0521c0f
fix(check): word the source notebook's grade cells for the instructor
wiseodd Nov 26, 2026
1dcf6d3
fix(export): name the submission files after the assignment
wiseodd Nov 26, 2026
06fa456
fix(pdf): drop a prompt heading that repeats the question title
wiseodd Nov 26, 2026
8445916
fix(source): fail the build when the notebook imports pytest without …
wiseodd Nov 26, 2026
1997516
fix(build): warn when pytest on the notebook would skip a cell's tests
wiseodd Nov 26, 2026
0aaa6ea
test: expect the new submission messages and answers name in grader t…
wiseodd Nov 26, 2026
2bbdb2f
fix(grade): find a notebook named like a public test file
wiseodd Nov 26, 2026
06b6229
fix(source): read the header only when the notebook imports pytest
wiseodd Nov 26, 2026
cadf03f
fix(pdf): keep math symbols when matching a prompt heading to the title
wiseodd Nov 26, 2026
4238d82
fix(grade): skip tests/ files only when they sit next to a notebook
wiseodd Nov 26, 2026
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
6 changes: 3 additions & 3 deletions docs/src/content/docs/instructors.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ The questions appear on Gradescope in the order of these cells.
| ----------- | ----------- | -------------------------- | ----------------------------------------------------------------------------------------- |
| question id | required | `"q1"` | The first argument. |
| `points` | required | `points=25` | Points for the question. A written question can be worth 0. |
| `title` | from the id | `title="Gradient descent"` | Name on Gradescope and in the PDF. `q1` becomes `Question 1`; other ids stay as they are. |
| `title` | from the id | `title="Gradient descent"` | Name on Gradescope and in the PDF. `q1` and `question1` become `Question 1`; other ids stay as they are. |

Question ids are letters and digits, and start with a letter, e.g., `q1` or `bonus`.
They can't contain `_`: test names use `_` to separate the id from the rest of the name.
Expand Down Expand Up @@ -223,7 +223,7 @@ def _():
```

The build removes this cell from the student notebook, and only Gradescope runs it.
A hidden cell can also hold data or helpers that the hidden tests need.
Data or helpers that the hidden tests need go in a hidden cell of their own: `pytest notebook.py` skips the tests in a cell that holds anything else.

The question ends with a grade cell, which also sets its points:

Expand Down Expand Up @@ -341,7 +341,7 @@ examples/demo/
Upload `<name>-autograder-<timestamp>.zip` to Gradescope as the autograder.
The directory also contains the solved notebook, i.e., the student notebook with the solutions, together with its public tests, the data files and `requirements.txt`.

Each build replaces both directories.
Each build replaces both directories, and a failed build removes them.

Before writing them, the build checks the assignment by grading two notebooks with the real grader: the solved notebook and the blank student notebook.
It does this in a fresh environment with the same pinned requirements that Gradescope gets.
Expand Down
38 changes: 33 additions & 5 deletions src/mogs/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,14 @@
from mogs.grader.templates import run_autograder_script, setup_script
from mogs.requirements import gradescope_requirements
from mogs.runner import FailureReason, Outcome
from mogs.source import Notebook, parse_notebook, prompt_previews, question_id, validate
from mogs.source import (
Notebook,
parse_notebook,
prompt_previews,
question_id,
source_warnings,
validate,
)
from mogs.transform import (
TESTS_FOLDER,
pinned_requirement,
Expand Down Expand Up @@ -247,7 +254,8 @@ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildRes
"""Build and self-check the assignment in `assignment_dir`.

The output is written in full to a temporary folder first. Only when every step succeeds
does it replace `dist/student/` and `dist/autograder/`, so only the newest zip is kept.
does it replace `dist/student/` and `dist/autograder/`, so only the newest zip is kept. A
failed build removes them.

Args:
assignment_dir: Folder with the source notebook and its data files.
Expand All @@ -266,6 +274,18 @@ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildRes
RequirementsError: If the dependencies cannot be pinned or installed.
"""

try:
return _build(assignment_dir, tool_requirement)
except Exception:
for part in ("student", "autograder"):
shutil.rmtree(assignment_dir / DIST / part, ignore_errors=True)

raise


def _build(assignment_dir: Path, tool_requirement: str | None) -> BuildResult:
"""`build` without the cleanup of a failed build."""

require_posix()
assignment = read_assignment(assignment_dir)
src, cfg, nb = assignment.src, assignment.cfg, assignment.nb
Expand All @@ -277,6 +297,7 @@ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildRes
tests = public_test_files(nb)
requirement = tool_requirement or f"{TOOL}=={__version__}"
requirements, warnings = gradescope_requirements(src, cfg, requirement)
warnings = source_warnings(nb) + warnings
entries = {
"setup.sh": setup_script(cfg).encode(),
"run_autograder": run_autograder_script().encode(),
Expand Down Expand Up @@ -314,7 +335,7 @@ def build(assignment_dir: Path, tool_requirement: str | None = None) -> BuildRes
)

blank = _self_grade(bundle, student_path, check / "blank", assignment_dir, python)
warnings += _blank_warnings(blank)
warnings += free_points_warnings(blank.outcomes, cfg)

# Output, written in full before it replaces the old one.
out = stage / DIST
Expand Down Expand Up @@ -472,8 +493,15 @@ def _failed_tests(names: list[str], load_failed: bool) -> str:
return f"{tests} of {questions}"


def _blank_warnings(blank: _Graded) -> list[str]:
passing = [outcome.name for outcome in blank.outcomes.values() if outcome.passed]
def free_points_warnings(blank: Mapping[str, Outcome], cfg: AssignmentConfig) -> list[str]:
"""A warning naming the tests that pass on the blank notebook, in questions worth points."""

passing = [
outcome.name
for outcome in blank.values()
if outcome.passed and cfg.questions[question_id(outcome.name)].points > 0
]

if not passing:
return []

Expand Down
29 changes: 22 additions & 7 deletions src/mogs/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,23 @@ def grade(
found = discover(qid, namespace) if tests is None else tests

if not found and tests is None and _written_in_source(qid, namespace):
return mo.Html(written_panel(qid, points, title))
return mo.Html(written_panel(qid, points, title, source=True))

outcomes = [run_test(name_of(test), with_rewritten_asserts(test)) for test in found]

return mo.Html(panel(qid, outcomes, points, hidden, title, problem))
# Tests found in the source notebook include the hidden ones.
public = tests is not None or test_file is not None

return mo.Html(panel(qid, outcomes, points, hidden, title, problem, public=public))

def written_panel(qid: str, points: float | None, title: str | None) -> str:
"""HTML for a written question: its title and points, and where the answer goes."""

def written_panel(
qid: str, points: float | None, title: str | None, *, source: bool = False
) -> str:
"""HTML for a written question: its title and points, and where the answer goes.

In the `source` notebook, which has no export button, it says where the student's answer goes.
"""

title = question_title(qid) if title is None else title

Expand All @@ -140,7 +148,10 @@ def written_panel(qid: str, points: float | None, title: str | None) -> str:
else:
note = "Written answer, not graded."

note += " Write it in the cell above. It goes into the PDF when you export."
if source:
note += " Students write it in the cell above, and it goes into the PDF they export."
else:
note += " Write it in the cell above. It goes into the PDF when you export."

return (
f'<div style="{PANEL_STYLE.format(accent=SHADE, shade=SHADE)}">'
Expand Down Expand Up @@ -333,10 +344,13 @@ def panel(
hidden: int,
title: str | None = None,
problem: str | None = None,
*,
public: bool = True,
) -> str:
"""HTML for the panel, headed by `title`, or by `question_title(qid)` when it is `None`.

`problem` says why there are no outcomes; it defaults to "No tests found".
`problem` says why there are no outcomes; it defaults to "No tests found". `public` says the
outcomes are of public tests only, and the title calls them so.
"""

title = question_title(qid) if title is None else title
Expand All @@ -351,7 +365,8 @@ def panel(
else:
passed = sum(outcome.passed for outcome in outcomes)
accent = PASS if passed == len(outcomes) else FAIL
title += f" · {passed}/{len(outcomes)} public tests passed"
kind = "public tests" if public else "tests"
title += f" · {passed}/{len(outcomes)} {kind} passed"
items = "".join(outcome_item(outcome) for outcome in outcomes)
body = f'<ul style="{LIST_STYLE}">{items}</ul>'

Expand Down
3 changes: 2 additions & 1 deletion src/mogs/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from mogs import __version__
from mogs.build import BuildError, BuildResult, build, failure_report, source_notebook
from mogs.check import format_points
from mogs.config import ConfigError
from mogs.regrade import GradeResult, grade_submission
from mogs.requirements import RequirementsError
Expand Down Expand Up @@ -156,7 +157,7 @@ def report(result: BuildResult) -> str:
for score in result.scores:
if score.solution is None or score.blank is None:
how = (
f"{score.points:g} pts, graded by hand"
f"{format_points(score.points)}, graded by hand"
if score.points
else "collected in the PDF, not graded"
)
Expand Down
6 changes: 4 additions & 2 deletions src/mogs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
TOOL = "mogs"
PACKAGE = "mogs"
ASSIGNMENT = "mogs.assignment()"
# Folder next to the student notebook with its public tests, `tests/<qid>.py`.
TESTS_FOLDER = "tests"
MIN_MEMORY_MB = 2048

# The reference regex from PEP 723, for the `script` block.
Expand Down Expand Up @@ -390,9 +392,9 @@ def _points(where: str, value: object) -> float:


def default_title(qid: str) -> str:
"""`q1` → `Question 1`, `q2b` → `Question 2b`; other ids stay as they are."""
"""`q1` → `Question 1`, `question_2b` → `Question 2b`, any case; other ids stay as they are."""

match = re.fullmatch(r"q(\d\w*)", qid)
match = re.fullmatch(r"(?:q|question)_?(\d\w*)", qid, re.IGNORECASE)
return f"Question {match.group(1)}" if match else qid


Expand Down
2 changes: 1 addition & 1 deletion src/mogs/grader/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def run(bundle: GradingBundle, source: Path, submission: Path, workdir: Path) ->
"""

config = bundle.config
found = find_submission(submission, config.notebook)
found = find_submission(submission, config.notebook, config.name)
notices = [] if found.error is None else [found.error]

if any(question.manual for question in config.questions.values()):
Expand Down
51 changes: 36 additions & 15 deletions src/mogs/grader/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from pathlib import Path
from typing import NotRequired, TypedDict

from mogs.config import TESTS_FOLDER
from mogs.grader.bundle import GradingBundle
from mogs.runner import Outcome, cap

Expand Down Expand Up @@ -61,45 +62,65 @@ class Submission:
error: str | None


def find_submission(sub_dir: Path, notebook: str) -> Submission:
def find_submission(sub_dir: Path, notebook: str, name: str | None = None) -> Submission:
"""Find the notebook and the written answers anywhere under `sub_dir`.

Skips `__MACOSX`, `__pycache__`, dot files and dot folders, and never follows or picks a
symlink. A file named `notebook` wins; otherwise the only `.py` file is taken. Any PDF
counts as the written answers. Of Markdown files, only the export's fallback
`<notebook stem>_answers.md` (any case) does, so a stray `README.md` does not.
symlink. Public tests, the `.py` files in a `tests/` folder next to another `.py` file, are
never the notebook. Of the rest, a file named `notebook` wins; otherwise the only `.py` file
is taken. Any PDF counts as the written answers. Of Markdown files, only the export's
fallback `<name>_answers.md` (any case) does, so a stray `README.md` does not.

Args:
sub_dir: The unpacked upload.
notebook: File name of the student notebook.
name: Assignment name, which the export names its files after. Defaults to the
notebook's stem.

Returns:
The files found, with an error message when the notebook is missing or ambiguous.
"""

files = sorted(_regular_files(sub_dir))
scripts = [path for path in files if path.suffix == ".py"]
exact = [path for path in scripts if path.name == notebook]
# Not the public tests the student copy ships in `tests/`, next to the notebook.
folders = {path.parent for path in scripts}
others = [
path
for path in scripts
if path.parent.name != TESTS_FOLDER or path.parent.parent not in folders
]
exact = [path for path in others if path.name == notebook]
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
pdfs = [path for path in files if path.suffix.lower() == ".pdf"]
fallback = f"{Path(notebook).stem}_answers.md".casefold()
fallback = f"{name or Path(notebook).stem}_answers.md".casefold()
markdown = [path for path in files if path.name.casefold() == fallback]
answers = next(iter(pdfs or markdown), None)
wanted = inline_code(notebook)

match exact or scripts:
case [py]:
match exact, others:
case [py], _:
return Submission(py, answers, None)
case []:
error = f"No `.py` file found in your upload. Upload {inline_code(notebook)}."
case several:
names = ", ".join(inline_code(str(path.relative_to(sub_dir))) for path in several)
error = (
f"Found several notebooks: {names}. Upload only {inline_code(notebook)}, "
"or a single `.py` file."
case [], [py]:
return Submission(py, answers, None)
case [], []:
error = f"No `.py` file found in your upload. Upload {wanted}."
case [], several:
names = _names(several, sub_dir)
error = f"No {wanted} in your upload, and several other `.py` files: {names}. " + (
f"Upload {wanted}, or a single `.py` file."
)
case several, _:
error = f"Found {wanted} more than once: {_names(several, sub_dir)}. Upload one."

return Submission(None, answers, error)


def _names(paths: Sequence[Path], root: Path) -> str:
"""The paths relative to `root`, as inline code, comma separated."""

return ", ".join(inline_code(str(path.relative_to(root))) for path in paths)


def _regular_files(root: Path) -> list[Path]:
"""Regular files under `root`, skipping junk folders, dot names and symlinks."""

Expand Down
29 changes: 29 additions & 0 deletions src/mogs/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,9 +338,38 @@ def part(cell: Cell, role: Role) -> Part:
if not answers:
parts += (Part(f"*No answer cell `answer_{qid}` found.*", Role.ANSWER),)

match parts:
case (Part(role=Role.PROMPT, style=Style.MARKDOWN) as first, *rest):
parts = (replace(first, text=without_title_heading(first.text, title)), *rest)

return Question(title, parts)


def without_title_heading(text: str, title: str) -> str:
"""`text` without a leading Markdown heading whose words `title` already has.

`## Derive the slope` goes under the title `Question 4: Derive the slope`; `## Question 4:
Derive the slope` stays under the title `Question 4`, since it says more.
"""

match = re.match(r"\s*#{1,6}[ \t]+(.+?)[ \t#]*(?:\n|$)", text)

if match is None or _words(match.group(1)) not in _words(title):
return text

return text[match.end() :].lstrip("\n")


def _words(text: str) -> str:
"""The words and symbols of `text` in lower case, spaced: `x + y.` → ` x + y `.

Sentence punctuation is dropped, so `Question 4:` matches `Question 4`; other symbols, such
as `+` and `-` in math, are kept.
"""

return f" {' '.join(re.findall(r'\w+|[^\w\s.,:;!?]', text.casefold()))} "


def cell_markdown(nb: Notebook, cell: Cell) -> str:
"""The Markdown of a cell that is just `mo.md("...")`; else its source as a code block."""

Expand Down
Loading
Loading