phigrade
The PhiGrade client library. Instructors use it to publish an answer key by running their reference solution; students use it to check their own code against that answer key and get immediate, per-checkpoint feedback.
The defining property is that student code never leaves the machine it runs on. Tests execute locally; what travels to the server is the value a function produced at a checkpoint, which the server compares against the value the instructor's solution produced at the same checkpoint. See the top-level README for the full rationale and the platform's data model.
This package works against a hosted PhiGrade backend or entirely offline against a local file, using the same test code either way.
A word on vocabulary. This document says test for the pytest function you write, and unit check for the record the server stores about it — the
UnitCheckrow that carries its point value and aggregation policy. The web application displays that same record to students as a "Unit Test", and aSubUnitCheckas a "Comparison". The code avoids the nameUnitTestbecause pytest collects classes matchingTest*, and these models are imported into test modules.
Installation
pip install phigrade
Running from a Google Colab notebook instead? Install phigrade[notebook], which pulls
in ipytest — see Colab notebooks
below.
For development inside this repository, the Python components form a single uv
workspace rooted at the repo:
uv sync --all-packages # from the repository root
Requires Python 3.12+.
Quick Start
1. Write tests. A PhiGrade test is an ordinary function decorated with @weight,
which declares its point value. Inside it, call a comparison helper at each point you
want checked.
import numpy as np
import phigrade
from phigrade import weight
from mysolution import my_add, my_normalize
@weight(1.0)
def test_my_add():
phigrade.is_equal(my_add(2, 3))
@weight(3.0)
def test_my_normalize():
result = my_normalize(np.array([3.0, 4.0]))
phigrade.all_close(result, rtol=1e-5, atol=1e-8)
Note what is absent: no expected values. The instructor's reference run supplies them. The same file is the assignment's test suite and its answer key generator.
2. Add a phigrade.yaml next to the test file:
course_id: "your-course-uuid"
assessment_id: "your-assessment-uuid"
use_local_server: false
server_url: "https://phigrade.example.org"
teacher_mode: false
timeout_seconds: 5
submission_files:
- mysolution.py
Your API key is never written to phigrade.yaml. It is read from the
PHIGRADE_API_KEY environment variable, so a config file can be committed and shared
without leaking a credential:
export PHIGRADE_API_KEY="your-api-key" # mint this on the Account Settings page
An api_key key in phigrade.yaml is a hard error pointing you at the environment
variable. Local mode needs no key at all.
3. Run the tests. They are named test_*, so pytest collects them normally:
pytest test_mysolution.py
Passing checkpoints print a confirmation; a failing checkpoint raises AssertionError
naming the checkpoint and showing what your code produced.
4. Publish the answer key (instructors). Run the same tests with
PHIGRADE_TEACHER_MODE=true, from a directory holding your reference solution. Each
checkpoint's value is recorded as the expected value, and the whole run publishes as
one definitive answer key when it finishes clean — see
Teacher mode for what that means. The committed
phigrade.yaml stays teacher_mode: false, so there is nothing to set back:
PHIGRADE_TEACHER_MODE=true pytest test_mysolution.py
Authoring API
Everything students and instructors need is exported at the package top level.
import phigrade
from phigrade import weight, load_phigrade_config
The comparison helpers (all_close, close_on_average, is_equal, sequence_match,
mapping_match, row_match, key_value, always_pass) are called
qualified — phigrade.all_close(...) — so the module they come from is visible at the
call site. weight and load_phigrade_config are not comparison functions and are
imported bare.
@weight(w: float, aggregation: str = "even_weight_fail_fast")
Marks a function as a graded test and declares its point value. Attaches
is_utest, autograder_function, autograder_module, weight, and call_count to
the wrapped function, and installs the output-capture and Gradescope-finalization
wrappers.
aggregation decides how the test's checkpoints combine into its score, and is
validated at decoration time against even_weight_fail_fast (the default),
weighted_fail_fast, even_weight, weighted, and the deprecated fail_fast alias.
See Multiple checkpoints per test.
The decorated function must be a module-level global. The comparison helpers locate their calling test by walking the stack and looking each frame's function name up in that frame's module globals. Nested functions, methods, functions built by a factory whose
__name__diverges from the name they are bound to, and calls made outside any test are all not found, and raisePhiGradeUsageError:row_match() must be called from inside a module-level function decorated with @weight— the message names all four cases.
phigrade.is_equal(system_output: Any, weight: float = 1.0, name: str | None = None) -> None
Records system_output as a checkpoint, compared by exact equality (==). The value
must be JSON-serializable.
Publishing refuses any NaN in an
is_equalreference, because==never matches NaN; useall_close, orsequence_match/mapping_matchwhen each NaN is a top-level unit, withequal_nan=True. Infinity is never refused, and neither is a student run.
phigrade.all_close(system_output: np.ndarray, *, rtol=1e-05, atol=1e-08, equal_nan=False, partial=False, grace=0.0, weight=1.0, name=None) -> None
Records a NumPy array checkpoint, compared element by element with np.isclose at the
given tolerances, which are stored alongside the reference so the student run uses the
same ones. rtol, atol and equal_nan are keyword-only as of 3.6.0. The accepted band
is atol + rtol * abs(reference) — anchored on the published reference, not on the
student's own value; see rtol and atol below.
Shapes must match. np.allclose broadcasts, so before 3.6.0 a (4, 1) array
compared against a (4, 2) reference — or a scalar against anything — could compare
equal and score full marks. As of 3.6.0 a shape mismatch scores 0 in both modes.
All-or-nothing by default. With partial=True, the score is the fraction of elements
that are np.isclose, then grace; the AssertionError reports "K of N elements
were within tolerance." grace is accepted only with partial=True — passing it on
an all-or-nothing comparison raises ValueError, since it would have no effect.
Same-shaped empty arrays score full credit.
Raises TypeError — all_close() expects a numpy ndarray, got list — if
system_output is not an ndarray.
all_close compares a bool array numerically (True == 1) — unlike close_on_average,
which rejects a non-numeric dtype, including bool, outright. See its section below.
NaN and infinity are encoded for the request and decoded by the server. A reference that contains NaN must be published with
equal_nan=True; a reference with infinity needs no flag, and-infmatches only-inf. A NaN in the student's output is graded (and the failure names how many positions held NaN) rather than raising.Changed in 3.7.0. Before 3.7.0, a NaN or infinity anywhere in an output could not be sent at all:
requestsrefused it, and the client reportedPhiGradeConnectionError: … could not reach …, so the run was never recorded. 3.7.0 needs a backend from 2026-11-04 or later, which decodes the encoding.
tolist()on a(0, n)array.system_output.tolist()on an empty array whose first dimension is 0 collapses to[], and a freshnp.array([])has shape(0,)— so a(0, 5)reference and a(0, 5)student array both round-trip through JSON as shape(0,). Harmless forall_closeandclose_on_averagetoday, since same-shaped empty arrays already score full credit regardless of the collapsed shape, but worth knowing before relying on the reported shape of an empty array.
phigrade.close_on_average(system_output: np.ndarray, *, tolerance, rtol=1e-05, atol=1e-08, equal_nan=False, grace=0.0, weight=1.0, name=None) -> None
all_close asks whether every element is within tolerance; close_on_average asks
whether the mean relative error is, and grades linearly down to zero. Use it for a
matrix or vector, not a scalar — see the caveat below.
Each element's error is
err_i = min(1.0, abs(ref_i - produced_i) / max(abs(ref_i), 1e-12))
error = mean(err_i)
score = max(0.0, 1.0 - error / tolerance) # then grace
with two snaps: an element that is np.isclose(produced_i, ref_i, rtol=rtol, atol=atol)
counts as exactly 0 error — round-off is free only within rtol/atol, defaulting to
numpy's own defaults (1e-05/1e-08). The accepted band for that snap is
atol + rtol * abs(ref_i), anchored on the reference element, not on the student's own
value; see rtol and atol below. A reference printed to fewer decimals than that
is not automatically forgiven: printing to 6 decimals leaves up to 5e-7 of absolute
error, which the default atol=1e-8 does not snap, so a correct student can score just
under 1.0. Pass atol of about 10**-N for a reference printed to N decimals, or
normalize both sides in the test instead. The second snap: a non-finite per-element
error (a NaN, or an unmatched infinity) counts as fully wrong (err_i = 1) rather than
propagating a NaN into the mean, unless equal_nan=True, in which case a NaN in the
reference matches a NaN in the student's output (and nothing else). 1e-12 is the floor on the
denominator for a reference entry near zero — a reference entry smaller than that in
magnitude accepts anything within atol of it, including zero — and is not exposed as
a parameter.
rtol and atol are keyword-only, published with the reference like tolerance, so
the student run uses the same ones.
tolerance is required and must be a fraction in (0, 1] — 0.05 means 5%, not
a percentage. There is no default: the right value differs by orders of magnitude
between assignments. Because each element's error is capped at 1.0, a tolerance
above 1 would put a floor under every wrong answer's score, so it is rejected. It
accepts any numbers.Real that is not a bool, including a numpy scalar such as
np.float32(0.0035), and is published as a plain float so the JSON body can
serialize it.
A shape mismatch scores 0. Same-shaped empty arrays score full credit. Non-numeric
array dtypes (strings, bools, complex) score 0, with feedback: "close_on_average
compares numbers only; this array is not numeric (bools, strings and complex values are
not accepted)." Unlike all_close, which compares a bool array numerically, this
rejects bool outright — a checkpoint that scores 0 with only that feedback line is a
dtype mismatch, not a value mismatch.
NaN and infinity are encoded for the request and decoded by the server. A reference that contains NaN must be published with
equal_nan=True; a reference with infinity needs no flag, and-infmatches only-inf. A NaN in the student's output is graded (and the failure names how many positions held NaN) rather than raising.
The AssertionError reads "Your values are on average X% off." (X to 3 significant
figures), "less than 0.001% off" for a tiny nonzero error, or "off by 100% or more."
Never names the reference.
On a small array, that percentage narrows down the reference. A single mean relative error over 3 elements lets a student work backward toward the individual values much more easily than over 300. Use
close_on_averageon matrices, not scalars — for a scalar,all_closealready says everythingclose_on_averagewould, without the leak.
phigrade.always_pass(weight: float = 1.0, name: str | None = None) -> None
A checkpoint that simply records True, equivalent to phigrade.is_equal(True). Useful
when reaching a line of code is itself the thing being graded — for example, after an
in-test assertion that would have raised.
phigrade.row_match(system_output: str, weight: float = 1.0, name: str | None = None) -> None
A partial-credit checkpoint for multi-line string output. Both sides are split into
lines and compared position by position, ignoring trailing whitespace; the fraction
awarded is matched / max(len(reference_lines), len(produced_lines)), so missing and
extra lines are both penalized. Raises TypeError — row_match() expects a str, got list — if system_output is not a str.
A partial score still fails the unit test: like every other helper, this one raises
AssertionErrorunless the checkpoint earns full credit. The partial points are recorded on the server and appear in the student's score, and theAssertionErrorreports the score as a percentage of the checkpoint so partial credit is not mistaken for zero.
phigrade.key_value(system_output: str, threshold=1e-3, pattern=r"^(\S+)\s+(\S+)$", weight=1.0, name=None) -> None
A partial-credit checkpoint for a file of key value lines — a metrics file, say.
Each non-blank line is parsed with pattern into a key and a numeric value, and a key
matches when it is present on both sides and the two values differ by less than
threshold, an absolute tolerance. The fraction awarded is
matched / max(reference_keys, produced_keys), so a missing key, an extra key and a
malformed line each cost one key rather than the whole checkpoint. threshold and
pattern are recorded with the reference, so the student run reuses the instructor's
settings. Raises TypeError — key_value() expects a str, got dict — if
system_output is not a str.
Unlike row_match, keys are matched by name, not by position, and the
AssertionError names the keys that cost the points along with the values your code
produced for them:
1 of 2 keys matched. Values differed for: error(test) (yours: 0.55).
It never names the reference value or the size of the difference. Either would hand back the answer key, which is the one thing that must stay on the server.
phigrade.sequence_match(system_output, *, rtol=1e-05, atol=1e-08, equal_nan=False, grace=0.0, weight=1.0, name=None) -> None
Compares a sequence position by position, scoring
matched / max(len(reference), len(yours)), so extra and missing elements are
both penalized. Two elements match numerically when both are numbers — bool
does not count, so True never matches 1.0 — and by == otherwise. A
numeric match is np.isclose(produced, reference, rtol=rtol, atol=atol), so
the accepted band is atol + rtol * abs(reference) — anchored on the
reference, not on the student's own value; see
rtol and atol below.
Raises TypeError for a str or bytes: a string is a sequence of
characters, and grading one character at a time is never what you meant. Split
the text in your test — sequence_match(text.splitlines()) — because parsing
is a one-sided transform and belongs where the author can see it.
Publishing refuses a NaN unit unless
equal_nan=True, and a NaN nested inside a list or dict unit even then (nested units compare with==); useall_close(..., equal_nan=True)for those. Infinity is never refused, and neither is a student run.
phigrade.mapping_match(system_output, *, rtol=1e-05, atol=1e-08, equal_nan=False, grace=0.0, weight=1.0, name=None) -> None
Compares a mapping key by key, scoring
matched / max(reference_keys, your_keys), so a missing key and an extra key
each cost one key. Unlike sequence_match, keys are matched by name rather
than by position. Parse the file into a dict in your test. A numeric value
matches via np.isclose(produced, reference, rtol=rtol, atol=atol), so the
accepted band is atol + rtol * abs(reference) — anchored on the reference,
not on the student's own value; see rtol and atol below.
Keys should be strings. JSON object keys are strings, so {1: 0.5} arrives as
{"1": 0.5} — consistent on both sides, but the feedback shows quoted keys,
and tuple keys do not serialize at all.
Publishing refuses a NaN value unless
equal_nan=True, and a NaN nested inside a list or dict unit even then (nested units compare with==); useall_close(..., equal_nan=True)for those. Infinity is never refused, and neither is a student run.
rtol and atol
all_close, close_on_average's exact-match snap, sequence_match, and mapping_match
all decide whether two numeric values match with
np.isclose(produced, reference, rtol=rtol, atol=atol). The accepted band is
atol + rtol * abs(reference) — anchored on the published reference value, not on the
student's own answer. rtol must satisfy 0 <= rtol < 1 and atol must be finite and
>= 0; both are validated client-side, in each of the four helpers above (raising
TypeError for the wrong type or ValueError for an out-of-range value, before anything
is published) and server-side, in compare.py's _validate_tolerances (an HTTP 400).
Changed in 3.6.1. Before 3.6.1, the call was
np.isclose(reference, produced, ...)— the arguments in the opposite order — and numpy scales the relative term by its second argument, so the accepted band scaled with the student's own answer instead of the reference. With a reference of1.0andrtol=0.2, a student's1.24scored full credit while the closer0.82scored zero, because the band was anchored on the student's own value rather than the reference.rtolandatolwere also unvalidated: a malformed value madenp.iscloseraise, which a broadexceptturned into a silent 0 for every submission, including one identical to the reference. A 2026-09-22 sweep of production references (row_match/key_valueexcluded — neither readsrtol/atol) found no stored key rejected by the new validation: every storedrtolis well below 1 and every tolerance numeric. Scores are unchanged for the 24mapping_matchreferences, published withrtol=0.0; for the 182all_closereferences atrtol=1e-4and 42sequence_matchreferences at the1e-5default, the band edge moves by aboutrtol**2in relative terms — roughly 1e-8 and 1e-10 — so a verdict flips only within that distance of the old boundary, and the flipped verdict is the correct one. Query:SELECT comparison_info->>'comparison_type', comparison_info->>'rtol', comparison_info->>'atol', count(*) FROM sub_unit_check_references WHERE comparison_info::text LIKE '%tol%' GROUP BY 1, 2, 3;
grace
grace is the fraction of a fractional score a student may miss and still earn full
credit; below that the score scales proportionally:
score = min(1.0, fraction / (1.0 - grace)). A grace of 0.05
means 95% matched earns 1.0, 90% earns 0.947, and 0% still earns 0.0. A result within
floating-point tolerance of 1.0 is snapped to exactly 1.0, since a fractional
grace (e.g. 1/3) cannot otherwise land there exactly.
grace is a keyword-only argument of sequence_match, mapping_match,
all_close (with partial=True only — passing it on an all-or-nothing all_close
raises ValueError), and close_on_average — where the fraction it adjusts is
1.0 - error / tolerance, already floored at 0. row_match and key_value also
score fractionally but do not accept it. Validated as 0 <= grace < 1.
grace is published with the answer key, like rtol and atol, so changing
it requires re-publishing.
name
Every comparison takes an optional name, which replaces its position in the
checkpoint identifier: is_equal(x, name="n=4") records
test_returns@n=4 rather than test_returns@2. Use it whenever a comparison
runs inside a loop — positional identifiers desynchronize the moment a
student's code takes a different number of iterations than the publish run
did, and the checkpoint is then graded against the wrong reference. Names must
be unique within a test.
A named checkpoint is also stable across repeated invocation, where the positional
counter is not: the counter lives on the function object and keeps climbing, so a
test run twice in one interpreter produces @0, @1 and then @2, @3 (see
Multiple checkpoints per test), while a named
checkpoint records the same @n=4 both times. The uniqueness check is per
invocation — its _checkpoint_names set is cleared before every run of the test —
so the second run does not see the first run's names as duplicates. Stable identity
is the whole point of name, so this is the desirable behavior, but it is not the
behavior the counter has.
The weight argument on every helper is that checkpoint's relative weight, used only
by the weighted aggregation. It is recorded when the instructor publishes the answer
key, so students do not need to pass it.
All helpers set __tracebackhide__, so pytest hides the phigrade frames and the
failure points at your test.
What a failed checkpoint looks like
AssertionError: Comparison 'test_education2_metrics@0' failed (scored 50% of this checkpoint).
1 of 2 keys matched. Values differed for: error(test) (yours: 999.0).
--- your output ---
error(train): 0.375000
error(test): 999.000000
--- end of your output ---
Three parts, in order:
- The headline names the checkpoint and the score. The score is a percentage
of that checkpoint, not of the test: checkpoints are always published with a
maximum of
1.0and the server scales the combined fraction to the test's@weight, so a checkpoint's share of the test's own points depends on the aggregation and on the other checkpoints — neither of which the client knows. Rounding never reports100%or0%for a score that was neither. - The server's feedback, when the comparison has any.
key_value,sequence_matchandmapping_matchexplain what cost the points;row_matchand the all-or-nothing comparisons say nothing, and the message reads correctly without this line. - Your output, in a delimited block. It is whatever the checkpoint was given — a string is shown raw, a number, list or dict is rendered readably, and anything long is truncated in the middle. The block is closed and the message has no trailing newline, so a runner that appends the student program's own stdout and stderr underneath composes cleanly.
Nothing in any of it comes from the answer key. That is the rule the whole design turns on: a student knows their own value, so even a difference would hand back the reference.
Under even_weight or weighted, a failed checkpoint does not stop the test:
every checkpoint runs, and the AssertionError raised at the end of the test
lists all of them. Under the two _fail_fast policies the first failure
raises immediately, and the checkpoints that never ran score zero.
The client halts under the policy published on the answer key, which the server reports with every graded checkpoint — not under the one in the student's copy of the test file. A handout that has fallen behind a republished key therefore still grades correctly.
Multiple checkpoints per test
A test may call the helpers as many times as it likes. Each call becomes a separate
checkpoint named <function>@<n> — test_my_concat@0, test_my_concat@1, and so on —
so a single test can award partial credit.
How the checkpoints combine into the test's score is chosen with @weight(..., aggregation=...) and recorded on the unit check when the answer key is published:
Each checkpoint scores a fraction between 0 and 1; the combined fraction is then
scaled to the test's declared point value, so a @weight(3.0) test with every
checkpoint correct earns 3.0.
aggregation |
score | client behavior |
|---|---|---|
even_weight_fail_fast (default) |
w × the mean checkpoint fraction |
stops at the first checkpoint below full credit |
weighted_fail_fast |
w × the weight-weighted mean |
stops at the first checkpoint below full credit |
even_weight |
w × the mean checkpoint fraction |
runs every checkpoint, then reports all failures at once |
weighted |
w × the weight-weighted mean |
runs every checkpoint, then reports all failures at once |
The two axes are independent: the formula is read by the server when it scores the test, the halt by the client while the test runs.
The denominator is the number of checkpoints the answer key publishes, not the number the run reached. A test that stops at its second of five checkpoints scores over five, with the three it never reached counted as zero — which is the whole point of a fail-fast policy, and why a partial score earned before the halt is still kept.
fail_fast is accepted as a deprecated alias for even_weight_fail_fast. It
was the default through HW1 and is stored on its published key; nothing new
should use it.
The counter lives on the function object and increments across calls within a process. Invoking the same test twice in one interpreter produces
@0, @1on the first run and@2, @3on the second, which will not match the reference. Let pytest run each test once.
load_phigrade_config(test_func) -> PhiGradeConfig
Returns the resolved configuration, letting a test branch on mode — useful when the reference run and the student run should exercise different code:
config = load_phigrade_config(test_my_add)
@weight(3.0)
def test_handles_edge_case():
if config.teacher_mode:
phigrade.is_equal(reference_impl(...))
else:
phigrade.is_equal(student_impl(...))
Deprecated comparisons
row_match and key_value are deprecated. Both accept a str and parse it
inside the comparison, which puts a parsing decision on the server where the
test cannot see, change, or explain it. Use sequence_match(text.splitlines())
and mapping_match(parse_metrics(text)) instead. Calling either in teacher
mode emits a PhiGradeDeprecationWarning; student runs stay silent, because a
student cannot change the handout they were given.
They are removed on two separate clocks, and both are conditions rather than
dates. The client helpers can go once no test file calls them. The
rowmatch and keyvalue branches in compare.py must live as long as any
published answer key stores references of that type, because a regrade
re-runs the comparison against the stored reference — and since the backend
imports compare.py, that clock is governed by a backend deploy, not by a
client release.
Migrate between assignments, not mid-assignment. Swapping a checkpoint from
row_match to sequence_match at the same position and republishing leaves every
already-graded attempt holding a str where the new comparison wants a list, and a
regrade cannot convert it — the regrade aborts on the first such attempt, naming
the code assessment attempt id, the module.function, and the checkpoint name (not
the student — an instructor has to look the attempt up), and telling you to re-run
those students' tests instead. That abort is deliberate: a stored output of the wrong
shape does not mean the student's work was wrong, so scoring it zero to keep going
would corrupt grades. See the entry in docs/TODO.md.
The Two Modes
The mode comes from teacher_mode in phigrade.yaml, or from the
PHIGRADE_TEACHER_MODE environment variable, which overrides it. There is no CLI flag.
The override is what lets the committed config stay teacher_mode: false forever:
publishing is then a property of the command, not an edit-and-revert dance on a file
that is easy to commit in the wrong state. It announces itself on stdout — see
Environment overrides.
Teacher mode (teacher_mode: true)
- Creates a staged reference attempt.
submission_filesare sent as paths with empty contents, so the reference solution's source is never uploaded. The attempt is not the answer key yet — the previous key stays in force until the run completes. - Registers each
@weighttest as a unit check — an identity row keyed on the test's module and function name. Re-running is safe; an already-existing unit check is tolerated, not updated. - Declares this run's point value and aggregation for the test, staged with the reference attempt, and records each checkpoint's value and comparison settings as the expected answer.
- Publishes at the end of a clean run, and only then. A publish is definitive: the answer key in force becomes exactly the tests and checkpoints that run recorded. A test you deleted stops being graded; a test whose module you renamed is a new test, and the old one retires. Earlier references are kept for the record and never graded against.
- Never asserts. A reference run cannot fail a comparison.
- Writes no Gradescope output and does not capture stdout.
A publish is definitive about which tests are in the key, but never retroactive about what already-graded work was scored out of. Step 2 tolerates an already-existing unit check rather than updating it — a unit check's identity is first-publish-wins, so renaming a test (or its module) is still the only way to give it a fresh identity — but its point value is not stored on that identity row at all:
@weightis recorded fresh with this reference attempt every time it publishes, so editing@weight(2)to@weight(5)and republishing does take effect, the moment the new run activates. What does not happen automatically is retroactive: an attempt already graded keeps the denominator it was actually scored out of, even after a later publish changes what new submissions are scored against. To bring existing submissions onto the key now in force — because a@weightchanged, or a reference output was wrong — callphigrade.regrade_assessment()after publishing. It re-runs the autograder over every stored submission's output, so it repairs a bad reference output the same way it repairs a bad@weight, and leaves any manual grading untouched.if phigrade.finalize_reference_run(): phigrade.regrade_assessment()
regrade_assessment()authenticates the same way every other call in this module does — withPHIGRADE_API_KEY— and the server route accepts it, so this runs from the same teacher-mode run that just published. It is staff only: a key whose owner is a student is refused. Against local mode the call succeeds too — the local server has no auth at all — but it typically has nothing to regrade, for an unrelated reason; see the note on local-mode regrade a few paragraphs down.
A run that dies partway publishes nothing. A collection error, a raise in the reference solution or a
^Cleaves the staged attempt unpublished and the previous answer key in force, and the run says so at exit. Fix the problem and run it again — there is no half-published state to undo.Publishing happens through a pytest plugin that ships with the package (the
pytest11entry point inpyproject.toml), so a plainPHIGRADE_TEACHER_MODE=true pytestneeds nothing extra — as long as the installed package knows about the entry point. An environment set up before this shipped needsuv sync --all-packages(or a plain reinstall) once, so pytest actually discovers the plugin; run it before the plugin is installed and the exit warning above still catches you — every test recorded cleanly, but you get "this teacher-mode run did not complete" anyway, because nothing ever called the publish. If you drive the tests yourself rather than through pytest — a custom runner, a notebook — callphigrade.finalize_reference_run()yourself once they have all run; it is the same idempotent publish the plugin calls, safe to call again on a run that already published.
Teacher mode refuses to run under
pytest-xdistat all. Each-nworker is a separate process running only part of the suite, so no single process ever holds the whole answer key; publishing from one would drop every test the others ran.PHIGRADE_TEACHER_MODE=true pytest -n autofails immediately, on the first test, before anything is staged.-n autois still fine — and, for a large class, wanted — for grading student runs and for thepytest -n autocase mentioned under Submission Slots; it is only a teacher-mode publish that must run single-process. Drop-n(or add-p no:xdist) to publish.
In local mode, a teacher run rebuilds the assessment it is publishing from
scratch: every row belonging to that assessment_id is dropped when the
reference attempt arrives, so a checkpoint or a test you deleted cannot
survive in the file. Rows belonging to other assessments are untouched,
which is what lets one answer-key file hold several
submission slots. This is deliberately unlike the
server, which supersedes rather than deletes: offline there is no gradebook,
and nothing to keep history for. Offline still follows the same grading rule
— a key that was never published does not grade — so a local run that dies
partway leaves a file that reports a missing reference rather than one that
grades against half a key. An answer-key file written by an older phigrade
has no record of which reference attempt wrote each reference and will not
grade at all; the 404 it produces says so and points at republishing, since
there is deliberately no legacy fallback.
Local-mode regrade is inert in the normal split-process workflow. Student
mode always runs against a throwaway temp copy of the shared answer-key file
(local_server_db_file, see _setup_db) and never writes back to it, so
that file never accumulates the student attempts a regrade would act on —
regrade_assessment() against local mode will typically report zero attempts
regraded even right after a student run that should need one. The local
server's /regrade route exists for contract parity with the real backend
and is exercised by tests that drive one teacher-mode server directly; it is
not reachable end to end through the ordinary "teacher publishes, student
runs, instructor regrades" sequence offline.
Student mode (teacher_mode: false)
- Creates a normal attempt, uploading the actual contents of every path in
submission_files. A missing file raisesFileNotFoundError, naming the directory that was searched —submission_filesresolve against the current working directory, so running pytest from the wrong place is the usual cause. - Submits each checkpoint's produced value and reads back the verdict.
- Prints a line per checkpoint; raises
AssertionErroron the first failure within a test. - Writes Gradescope output if configured.
Students cannot define unit checks. A checkpoint with no published reference raises, which is the expected signal that the instructor has not published the answer key yet.
What a run prints. At the end of every session, whatever the exit status, the client prints a receipt in the machine's local time zone:
PhiGrade: recorded attempt #3 for HW1 — 7.1 / 11 · on time · this attempt counts
https://<server>/courses/<id>/assessments/<aid>
A late run says LATE by 2h (and replaces on-time attempt #2 (11 / 11) when it
displaces one), a code run with rubric grading pending says rubric graded by staff after the deadline, and a group run appends for you, Alex Kim and Sam Lee. A run that was
not recorded prints PhiGrade: NOT recorded — <reason>, one of: past the deadline
(closed Oct 14); your released grade belongs to attempt #3 (set PHIGRADE_REPLACE_GRADED=1);
API key missing or invalid; you are not enrolled in this course; could not reach the
server. Local mode prints PhiGrade (local server only, nothing submitted) with no
link, and teacher mode prints no receipt.
Colab notebooks
Coding labs can run entirely inside a Google Colab notebook — tests, solution, and
submission all in cells, with no local Python install. phigrade does not stop using
pytest to do this: ipytest runs pytest inside the
notebook kernel, driving phigrade exactly as a plain pytest invocation would.
1. Install and configure ipytest, once per notebook session:
!pip install 'phigrade[notebook]'
import ipytest
import phigrade
from phigrade import weight
ipytest.autoconfig()
2. Write phigrade.yaml. A Colab session starts with an empty disk, so write it
from a cell instead of uploading it:
%%writefile phigrade.yaml
course_id: "your-course-uuid"
assessment_id: "your-assessment-uuid"
use_local_server: false
server_url: "https://phigrade.example.org"
submit_colab_notebook: true
phigrade.yaml and submission_files both resolve against the working directory in a
notebook — /content — so the two can never land in different directories the way they
can on a laptop, and the "Required file not found" message's usual cause (pytest
started from the wrong place) cannot arise here.
3. Write and run tests. %%ipytest must be the first line of the cell:
%%ipytest
@weight(1.0)
def test_my_add():
phigrade.is_equal(my_add(2, 3))
Calling test_my_add() directly, without %%ipytest, does not work — phigrade looks
for phigrade.yaml next to the test's file, and a cell has no file until ipytest gives
it one for the duration of the run. Calling the test directly raises
PhiGradeUsageError saying so and pointing back at this section, rather than the
confusing TypeError a bare notebook cell would otherwise produce.
If the assessment uses submission slots or group_members, use
%%ipytest -s instead. Submitting to a slot prints Submitting to: <slot name>, and
a group submission prints Submitting as a group: <emails>, both from inside the test —
and both are academic-integrity matters: which slot a submission landed in, and who it
was submitted for, should be visible, not swallowed. Plain %%ipytest captures that
output, so a passing test shows only 1 passed with no confirmation of which slot was
used or who the group was; -s disables the capture.
Authentication
Add a Colab secret named PHIGRADE_API_KEY: open the key icon in the left sidebar,
add a secret with that name, paste in a key minted from the web app's Account Settings
page, and turn on Notebook access for this notebook.
Use the secret rather than pasting the key into a cell. A Colab secret is
per-Google-account and granted per-notebook, so it is not shared when the notebook
is shared. A key typed into a cell travels with the notebook to everyone it is shared
with — and, with submit_colab_notebook on, would be uploaded to the server inside the
submission along with everything else in the notebook.
phigrade resolves the API key in this order: the PHIGRADE_API_KEY environment
variable, then the Colab secret of the same name, then the credentials file from
phigrade auth login. The environment variable stays first so nothing outside a
notebook changes.
submit_colab_notebook
Set submit_colab_notebook: true in phigrade.yaml and a student's run attaches the
running notebook to the submission, keyed by its file name and stored as a plain
.ipynb file.
Outputs are stripped before upload. Cell outputs are the only part of a notebook that gets large — a single embedded matplotlib plot is 50-200 KB of base64 — and the default per-assessment attempt-file budget is 512000 bytes for everything a submission carries. A notebook with a handful of plots could blow that budget and be rejected at the worst possible moment, so only code and markdown are uploaded.
Teacher mode never attaches the notebook. Teacher mode already uploads
submission_files as names with empty contents, because the reference solution must
never reach the database — and the instructor's notebook is the reference solution,
so it is never captured at all.
It is an error outside Colab. Running with submit_colab_notebook: true anywhere
but a Colab notebook raises PhiGradeUsageError, naming the config key and saying to
set it false for local runs, rather than silently submitting without the notebook the
student believes they sent.
Each
%%ipytestrun starts fresh, even without restarting the kernel — with one caveat for the notebook itself. phigrade caches the notebook it attaches, the submission it creates, andphigrade.yamlat module level — a plainpytestprocess is fresh every time, but a notebook kernel is not, and this used to mean a second%%ipytestrun reused the first run's submission and never noticed later edits. Apytest_sessionstarthook now clears that cache at the start of every pytest session, so editing code orphigrade.yamland re-running%%ipytestsubmits your latest edits, not the first run's. What this guarantees for the notebook itself is narrower: each run re-asks Colab for it (google.colab._message'sget_ipynb) rather than replaying a cached copy, but not that Colab answers with unsaved editor state. Save the notebook (Ctrl/Cmd+S) before the run you want graded.Exception: switching between teacher and student mode against the local server needs a restart.
use_local_server: truestarts one server process for the life of the kernel, and that process is locked to whichever mode — andlocal_server_db_file— it first saw:app._setup_dbusesteacher_modeat that moment to decide between the real reference file and a throwaway temp copy, so a later, disagreeing config could otherwise read or write the wrong one. phigrade refuses instead of doing that silently. If you flipPHIGRADE_TEACHER_MODEorteacher_modemid-kernel and hit that error, use Runtime → Restart session and run all.
Publish the answer key from the notebook, not from a
.pyfile. A test defined in a cell belongs to module__main__, and the server identifies a unit check by its module and function name. A key published fromtest_lab1.pyrecords the moduletest_lab1, so a student's notebook run looks up__main__, finds nothing, and is told the answer key is missing. Publish from the same notebook instead — a shell prefix like!PHIGRADE_TEACHER_MODE=true ...does nothing here, since a notebook cell has no shell to prefix and that would only set the variable for a subprocess. Set it on the kernel itself, in a cell above the%%ipytestcell:import os os.environ["PHIGRADE_TEACHER_MODE"] = "true"or set
teacher_mode: truein the%%writefile phigrade.yamlcell. Either way, re-run the%%ipytestcell after setting it — the next pytest session reloads the environment andphigrade.yamlfresh (see above). If you are running against the local server and this switches modes from an earlier run in the same kernel, restart the session first (see the exception above), or the run raises rather than publishing.
Configuration
The only configuration source is a YAML file named phigrade.yaml, located in the
directory containing the test module that defines the @weight function — not the
current working directory. It is loaded once per pytest session and cached for
the rest of that session — one session per pytest process outside a notebook,
and, since the Colab notebooks section above, one session per
%%ipytest run in a single kernel.
Five keys can be overridden from the environment — see Environment overrides below. No other key can.
| Key | Type | Default | Notes |
|---|---|---|---|
course_id |
str | required | Required in both local and remote mode |
assessment_id |
str or mapping | required | The assessment's UUID, or a submission-slot block — see Submission Slots |
use_local_server |
bool | false |
Run against a local file instead of a server; PHIGRADE_USE_LOCAL_SERVER overrides |
server_url |
str | — | Required when remote; overwritten in local mode |
teacher_mode |
bool | false |
Reference run vs. student run; PHIGRADE_TEACHER_MODE overrides |
timeout_seconds |
int | 2 |
Per-request HTTP timeout |
local_server_db_file |
str | phigrade_db.json beside the config |
The local answer key; PHIGRADE_LOCAL_DB_FILE overrides |
gradescope_json_file |
str | — | Enables Gradescope output (student mode only) |
submission_files |
list[str] | — | Paths relative to the working directory |
group_members |
list[str] | — | Every student the submission is for, including you; requires the assessment's group size to allow it |
submit_colab_notebook |
bool | false |
Attach the running notebook to the submission — see Colab notebooks; error outside Colab |
The API key is deliberately absent from this table: it is read from the
PHIGRADE_API_KEY environment variable, and an api_key key in the file is rejected.
Remote mode requires server_url, course_id, assessment_id, and a non-empty
PHIGRADE_API_KEY; local mode requires course_id and assessment_id. Note that
submission_files resolve
against the CWD while phigrade.yaml resolves against the test module's directory —
the usual cause of a FileNotFoundError is running pytest from the wrong directory.
Environment overrides
| Variable | Overrides | Values |
|---|---|---|
PHIGRADE_TEACHER_MODE |
teacher_mode |
1/true/yes, 0/false/no |
PHIGRADE_USE_LOCAL_SERVER |
use_local_server |
the same |
PHIGRADE_LOCAL_DB_FILE |
local_server_db_file |
a path |
PHIGRADE_SLOT |
which slot assessment_id resolves to |
a slot_name |
PHIGRADE_GROUP_MEMBERS |
group_members |
comma-separated email addresses |
PHIGRADE_REPLACE_GRADED |
sends replace_graded for this run only (never a phigrade.yaml key) |
1/true/yes |
Set PHIGRADE_REPLACE_GRADED to replace an attempt whose rubric grade has been
released: PHIGRADE_REPLACE_GRADED=1 pytest. Without it the server refuses the run and
the receipt says so.
Between them, one committed phigrade.yaml serves online publishing, offline
development, and a separate offline answer key per slot.
The two booleans are matched case-insensitively and ignore surrounding whitespace. Any
other value is an error naming the variable, rather than a silent default: quietly
reading a misspelt ture as false would fail to publish an answer key with no
indication of why. An unset or blank variable is simply not an override.
PHIGRADE_LOCAL_DB_FILE is used exactly as given, so a relative path resolves against
the working directory — unlike the config key it overrides, which defaults to a path
beside phigrade.yaml.
Every override announces itself on stdout when the config loads:
Teacher mode: enabled (PHIGRADE_TEACHER_MODE)
Local answer key: slot_a_key.json (PHIGRADE_LOCAL_DB_FILE)
That line is the whole point of announcing: a variable exported once in a shell profile must not silently republish an answer key, or redirect a submission, weeks later. The config is loaded once per pytest session, so each line appears at most once per session (see Configuration above).
Submission Slots
assessment_id can be a mapping instead of a single UUID string, to offer several
assessments as named submission slots the student picks between — for example a
"human work only" slot beside a "human or AI work" slot, both backed by their own
assessment on the server:
course_id: "your-course-uuid"
assessment_id:
message: "Select the appropriate submission slot."
slots:
- slot_name: "Human only"
slot_description: "This submission contains human work only."
slot_assessment_id: "human-only-assessment-uuid"
- slot_name: "Human or AI"
slot_description: "This submission may contain AI-assisted work."
slot_assessment_id: "human-or-ai-assessment-uuid"
message is optional and defaults to "Select the appropriate submission slot.".
Each entry of slots requires all three keys: slot_name, slot_description, and
slot_assessment_id (the assessment UUID that slot resolves to).
The slot is resolved once, at config-load time, in this order:
- The
PHIGRADE_SLOTenvironment variable, if set to a non-empty value. The match againstslot_nameignores surrounding whitespace and case. - Otherwise, an interactive prompt listing each slot's name and description, numbered.
- Otherwise, a
ValueErrornaming the valid slot names.
Either way the resolved slot is announced — Submitting to: Human only — so a
PHIGRADE_SLOT exported once in a shell profile cannot silently redirect later
submissions. On the environment-variable path that line goes to stdout, which
pytest captures and prints on failure (or always, under -s).
The prompt reads and writes the terminal device directly rather than stdin/stdout
— /dev/tty on macOS and Linux, and CONIN$/CONOUT$ on Windows, which has no
single duplex device — so it works under a plain pytest run with no -s
flag: pytest's output capture never sees it.
Some runs have no terminal that can be prompted on, and they must set
PHIGRADE_SLOT to one of the slot names:
export PHIGRADE_SLOT="Human only"
That covers non-interactive environments — a Gradescope autograder, CI, or a
Windows process with no console at all (a pythonw run, or native Windows
Python under Git Bash/mintty) — and three cases that would otherwise hang:
pytest -n auto (each xdist worker is its own process, so N workers would
interleave N prompts on one terminal), any background job (nohup pytest &
under a job-control shell, where reading the terminal raises SIGTTIN and
suspends the process — POSIX only), and a notebook kernel, which on Windows
can inherit the console of whatever launched it and would prompt into a window
the student is not looking at. Each is detected and turned into the same error
naming the valid slot names.
Because the config is loaded once and cached for the rest of the session (see
above), a pytest run resolves the slot — and therefore prompts, if it prompts at
all — at most once, no matter how many tests run.
Teacher mode publishes to one slot only
A reference run (teacher_mode: true) resolves the slot exactly as a student run
does, and then publishes the answer key to that one slot's assessment —
references are per-assessment on the server. A student who picks any other slot
gets a Sub-unit-check reference not found error on every checkpoint, naming the
assessment, module, function and checkpoint it looked for.
So an instructor must publish once per slot. Because the config is cached per
session, that means one pytest process (or one %%ipytest run) per slot:
PHIGRADE_TEACHER_MODE=true PHIGRADE_SLOT="Human only" pytest test_mysolution.py
PHIGRADE_TEACHER_MODE=true PHIGRADE_SLOT="Human or AI" pytest test_mysolution.py
Run those before releasing the assignment, and re-run both whenever the reference solution changes.
In local mode both publishes can share one answer-key file: a reference run clears only
the rows of the assessment it is publishing. Giving each slot its own file with
PHIGRADE_LOCAL_DB_FILE also works, and is what you want when the two keys are
distributed separately.
Errors
Everything phigrade raises deliberately is a PhiGradeError, so a runner can tell
"phigrade could not do its job" from "the student's code is wrong" — the latter
arrives as an AssertionError and nothing else.
| Exception | Raised when |
|---|---|
PhiGradeUsageError |
A comparison helper is called where no @weight test can be found |
PhiGradeConnectionError |
The server could not be reached: DNS, refused connection, or timeout_seconds |
PhiGradeSendError |
A request could not be built or sent, e.g. an output that is not JSON-serializable; nothing reached the server |
PhiGradeAuthError |
401 or 403 — the API key is missing, wrong, expired, or not enrolled |
PhiGradeNotFoundError |
404 — the assessment, unit check, checkpoint or answer key is not there |
PhiGradeServerError |
5xx — the server failed |
PhiGradeResponseError |
Any other unexpected status; the base of the three above, and it carries status_code |
They are classified by status code, never by the server's message text. The two "not found" 404s — a unit check and a reference — differ only in their prose, and that prose is rewritten whenever it can be made clearer; code matching on it would break every time a message improved. What each 404 actually was is in the message, which is written to be read rather than parsed.
A submission past an assessment's cutoff (its late due date, or its due date when none is set) is a 409, not a 403. It falls
through to PhiGradeResponseError, carrying the server's own message naming the
cutoff — deliberately not PhiGradeAuthError, whose "the API key is missing, wrong,
expired, or not enrolled" would send a student who submitted an hour late looking at
the wrong problem. An assessment the caller cannot see at all — before its release
date — is still a 403, since that really is a permission the caller lacks.
A structured 409 detail reads as its message; PhiGradeResponseError.detail and
.headers carry the parsed detail and the response headers.
Older releases raised a bare Exception for all of these.
Authenticating
Remote mode needs an API key. There are two ways to provide one:
PHIGRADE_API_KEY — set it in the shell before running tests, as shown above.
Good for CI and for one-off overrides.
phigrade auth login — a saved credential, so you don't need the environment
variable in every shell:
phigrade auth login --server https://phigrade.example.org
It prompts for an API key (mint one in the web app's Account Settings page),
validates it against the server, and on success saves it to
$XDG_CONFIG_HOME/phigrade/credentials.json (~/.config/phigrade/credentials.json
if XDG_CONFIG_HOME is unset), created with file mode 0600 so it is never
world-readable. phigrade auth whoami --server <url> reports which account a saved
(or --api-key-supplied) credential belongs to. --token is still accepted as an
alias for --api-key, for scripts written before the terminology settled.
A remote-mode phigrade.yaml run resolves its key in this order: PHIGRADE_API_KEY
first, then the credentials file for that phigrade.yaml's server_url. The
environment variable always wins, so it can still override a saved credential without
disturbing it.
Local Mode
Set use_local_server: true and no backend is needed. The client starts a local server
in a daemon subprocess on an automatically chosen port, backed by a TinyDB JSON file.
This is not a mock: the local server implements the same HTTP API as the hosted
backend, and both use the same comparison code (phigrade/compare.py, which the
backend imports directly). A suite developed locally behaves identically against a real
course. Local mode has no authentication, so PHIGRADE_API_KEY need not be set.
Two distinct uses:
- Drafting an assignment before a course exists on the server.
- Distributing a self-contained assignment — ship the tests plus the answer-key JSON, and students get immediate feedback with no account, network, or credentials.
The invariant that makes distribution safe: a student-mode run never writes to the
answer-key file. It requires the file to exist, copies it to a temporary file, and
serves from the copy. Running the tests cannot corrupt or reveal the key, accidentally
or otherwise. (tests/test_student_mode_no_persistence.py exists to enforce this.)
Gradescope Integration
Set gradescope_json_file in student mode and the client writes a Gradescope
results.json:
gradescope_json_file: "results.json"
Behavior worth knowing:
- The file is rewritten after every test, so it is valid even if the run is killed partway through.
stdoutandstderrinside a test body are tee-captured — still shown live — and included in that test's output. Python streams only; subprocess output is not caught.- A test that raises before making any comparison is still reported, with an
explanatory message and a score of zero. This recording is not Gradescope-specific
— it happens in every non-teacher mode, so an instructor can tell "the student's
code crashed" from "this test was never attempted"; only the JSON file itself is
gated on
gradescope_json_file. - A
@weighttest that callspytest.skip()records a zero attempt, with the messageNo phigrade comparison calls were made for this test.rather than a crash message._pytest.outcomes.Skippedderives fromBaseException, notException, so the finalize wrapper'sexcept Exceptionnever sees it: the test looks to phigrade like one that simply made no comparisons. In hosted mode this also creates a submission. It is documented rather than fixed — a skipped test scoring zero is the same outcome as an unattempted one, which is defensible — but do not reach forpytest.skip()inside a@weighttest expecting it to leave no trace. Before crash recording ran in every mode, this happened only whengradescope_json_filewas configured. - Unit checks the student never attempted appear with score zero, since the test list comes from the published unit-check set rather than from what ran.
- A test is
passedonly if it made all its expected comparisons and all passed — skipping comparisons cannot yield a pass. - Individual outputs longer than 500 characters are truncated in the middle.
No run_autograder / setup.sh scaffolding ships with this package; wire it into your
own Gradescope container.
Package Layout
phigrade/
├── phigrade/
│ ├── __init__.py Public exports: weight, is_equal,
│ │ all_close, close_on_average, always_pass,
│ │ sequence_match, mapping_match, row_match,
│ │ key_value, PhiGradeConfig,
│ │ load_phigrade_config, the PhiGradeError
│ │ hierarchy, __version__
│ ├── phigrade.py The client: config loading, the @weight decorator and
│ │ its wrappers, comparison helpers, submission creation,
│ │ HTTP calls, Gradescope finalization, finalize_reference_run
│ ├── pytest_plugin.py The pytest11 plugin: publishes a staged reference
│ │ attempt from pytest_sessionfinish on a clean run
│ ├── app.py create_app() — the TinyDB-backed local server, mirroring
│ │ the backend's REST API
│ ├── server.py Server lifecycle: port discovery, subprocess spawn,
│ │ readiness polling
│ ├── compare.py Scoring and aggregation — shared with the backend;
│ │ `weighted_comparison_points` (each comparison's share
│ │ of its unit test's points, beside
│ │ `aggregate_unit_check_points`)
│ ├── messages.py The not-found messages — shared with the backend, so
│ │ local mode and the hosted server cannot diverge
│ ├── errors.py The exception hierarchy raised by the client
│ ├── gradescope_output.py results.json writer
│ ├── cli.py The `phigrade` console script: `auth login`, `auth whoami`
│ ├── credentials.py The CLI's credentials file (server-keyed API keys)
│ └── colab.py Everything that only works inside Google Colab: fetching
│ and stripping the running notebook, the secrets-based API
│ key lookup
├── examples/ A runnable end-to-end example (see below)
└── tests/ The suite (see below)
Examples
examples/ is both documentation and a regression test — its tests run as part of the
default suite.
| File | What it shows |
|---|---|
simplefns.py |
The code under test, including a deliberately wrong variant |
test_simplefns.py |
The canonical autograder file: single and multiple comparisons per test, branching on teacher_mode, and the missing-reference error |
phigrade.yaml |
A local, student-mode configuration |
phigrade_db.json |
A checked-in answer key from a teacher run — this is what makes the example runnable out of the box |
run_teacher_mode.py |
The reference workflow, including the global-state reset ritual |
Run them from the phigrade/ directory (not from examples/, since paths resolve
against the CWD):
uv run --all-packages pytest examples/test_simplefns.py
Contributing
Tests
cd phigrade
uv run --all-packages pytest
uv run --all-packages pytest tests/test_local_server.py
There is no conftest.py and no pytest configuration — discovery is the default from
the phigrade/ directory.
| Test file | Covers |
|---|---|
test_local_server.py |
The local server's HTTP endpoints directly |
test_is_equal_local.py |
The largest suite: end-to-end runs against generated test modules, call-count tracking, Gradescope output, error paths |
test_all_close_local.py |
Tolerances, non-array inputs, mixed comparison types |
test_all_close_partial_local.py |
all_close's shape check, partial=True and grace, end to end |
test_close_on_average_local.py |
close_on_average end to end against the local server |
test_compare_rowmatch.py |
rowmatch partial-credit fractions and aggregation validation, at the unit level |
test_compare_keyvalue.py |
keyvalue partial-credit fractions and its per-key feedback, at the unit level |
test_compare_aggregation.py |
The four aggregation policies, the fail_fast alias, and their formulas, at the unit level |
test_compare_sequence_mapping.py |
sequencematch and mappingmatch scoring and grace, at the unit level |
test_compare_allclose.py |
allclose scoring: the shape check, partial=True and grace, at the unit level |
test_compare_close_on_average.py |
closeonaverage scoring by mean relative error, at the unit level |
test_phigrade_aggregation_local.py |
Each aggregation type end-to-end, plus always_pass, rowmatch and keyvalue |
test_soft_checkpoints_local.py |
even_weight/weighted run every checkpoint and report all failures; the two _fail_fast policies halt on the first |
test_reference_count_denominator_local.py |
A halted or crashed test is scored over the answer key's published checkpoint count, not the number reached |
test_named_checkpoints_local.py |
name= replaces a checkpoint's positional identifier |
test_crash_recording_local.py |
A test that raises before its first comparison still leaves a record |
test_deprecation_warnings.py |
row_match/key_value warn with PhiGradeDeprecationWarning in teacher mode only, never for a student |
test_sequence_mapping_local.py |
sequence_match and mapping_match end-to-end against the local server |
test_phigrade_config.py |
Config loading and the environment overrides (the invalid-config paths are not covered) |
test_student_mode_no_persistence.py |
The answer-key isolation invariant, and the per-assessment reset |
test_teacher_mode_endpoints.py |
Which endpoints each mode calls, with requests.post mocked |
test_notebook_config_errors.py |
The error a notebook user gets when tests are not run under %%ipytest |
test_notebook_ipytest.py |
Every phigrade feature exercised from notebook cells through ipytest — the Colab support guarantee, in executable form |
test_colab.py |
colab.py exercised without Colab, by injecting a fake google.colab module |
test_colab_api_key.py |
The API key resolution order in a notebook: environment, then Colab secret, then credentials file |
test_submit_colab_notebook.py |
submit_colab_notebook: config parsing, output stripping, the outside-Colab error, and that teacher mode never attaches the notebook |
test_real_backend_integration.py |
Full stack against a real backend instance |
The last of these boots the actual backend, which works because the uv workspace puts
both packages in one environment. notebook_harness.py is not itself a test file — it
runs notebook cells in a real IPython shell, in a subprocess, and is what
test_notebook_ipytest.py uses to drive them.
local_run_harness.py is likewise not a suite of its own: it is the shared
"write a test module, run it as teacher then as student against the local
server, read the scores back" harness that test_soft_checkpoints_local.py,
test_reference_count_denominator_local.py, test_named_checkpoints_local.py,
test_crash_recording_local.py, test_deprecation_warnings.py,
test_sequence_mapping_local.py, test_all_close_partial_local.py and
test_close_on_average_local.py all import rather than duplicate.
Global state
The client keeps process-global mutable state: _config, _local_server,
_submission_id, _unit_check_attempt_ids, _unit_check_definition_cache,
_gradescope_test_output, _reference_attempt_pending, _deferred_failures,
_checkpoint_names, and _run_error (the error that stopped the run being recorded,
which the end-of-session receipt reports). (_local_server_mode is likewise global, but it is only a
mode-tracking companion to _local_server — the pair it was spawned with — and
isn't listed separately here.) There is no public reset API, so anything that
runs more than one logical session in a single interpreter must clear these by
hand — see the clear_phigrade_state autouse fixture in
test_real_backend_integration.py, the reset in examples/run_teacher_mode.py,
and the fuller reset pytest_sessionstart performs in pytest_plugin.py.
Removing this global state in favor of an explicit session object would be a
welcome improvement.
The last two are the exception: _deferred_failures and _checkpoint_names are
both keyed by (module, function) and both popped at the start of every test
invocation by _wrap_with_test_finalize, so a stale entry cannot survive into the
next run of a test and neither needs a manual reset — unlike the other seven.
They are listed here because they are global, not because they leak.
Lint, format, and types
make python-tools-phigrade # from the repo root: ruff check, ruff format, mypy
Ruff handles both linting and formatting (it replaced black). Line length 88, target
py312, rules E,F,I,B,UP. Type hints on everything; docstrings on public functions.
Releasing
make upload from the repository root — it refuses to run with a dirty working tree,
then builds and uploads to PyPI:
make upload # uv build --package phigrade && twine upload dist/*
Bump version in pyproject.toml first; phigrade.__version__ reads it from package
metadata at runtime.
Known Limitations
- The CLI is auth-only.
phigrade auth loginandphigrade auth whoamiare the onlyphigradeconsole-script commands; there is nophigrade runor similar, and tests are still run withpytest. - Only five keys have environment-variable overrides — see Environment overrides. Everything else is YAML only.
- Checkpoint maximums are always
1.0when references are published. That is by design — a checkpoint scores a fraction, and the fraction is scaled to the test's@weight— but it does mean a checkpoint cannot carry its own point value. Relative weighting between checkpoints is settable, via each helper'sweightargument underweightedaggregation. - A local-mode receipt is always "on time" and solo: the local server has no due date and no roster.
Serverhas nostop(). The subprocess is a daemon and dies with its parent.- Student-mode temporary answer-key copies are never cleaned up.
- The comparison set is small — exact equality,
all_close(np.isclose, all-or-nothing orpartial),close_on_average(mean relative error),sequence_match,mapping_match, and the deprecatedrow_matchandkey_value. Adding a comparison type — or an aggregation policy — means changingcompare.py, which the backend imports, so the backend must be deployed before the client release reaches anyone. The backend validates what the client sends against its own copy ofcompare.py. A backend whose bundledcompare.pypredates 3.5.0 knows onlyfail_fast,even_weightandweighted, so itsvalidate_aggregationrejects botheven_weight_fail_fastandweighted_fail_fast— and sinceeven_weight_fail_fastis now the default the@weightdecorator publishes, every teacher run of a 3.5.0 client against an older backend fails, not just the ones that name a new policy explicitly. Itscalculate_comparison_resultlikewise rejects thesequencematchandmappingmatchdispatch strings, and — before 3.6.0 — thecloseonaveragedispatch string: a client that publishes acloseonaveragereference against an older backend gets a 400Unsupported comparison type.allclosefails differently, and more quietly: a backend whosecompare.pypredates 3.6.0 still recognizes theallclosedispatch string, and its older_allclose_resultsimply ignores keys it does not understand, sopartialandgraceare silently dropped from a published reference — no error, no warning. Grading then falls back to the old all-or-nothing verdict, withnp.allclose's broadcasting still in effect (the shape check is new in 3.6.0 too). Apartial=Truecheckpoint behaves as thoughpartialwere never set. Deploy the backend before releasing a client that publishespartial/graceonallclose, orclose_on_average. The reverse order is safe: a newer backend still understands everything an older client sends, which is what the deprecatedfail_fastalias exists for. 3.6.1's reference-anchoring fix breaks that safety net in the quietest way yet: a backend whose bundledcompare.pypredates 3.6.1 still recognizes every key a 3.6.1 client publishes —rtol/atolare not new — and grades it, silently, with the old student-anchored band. There is no dispatch- string change and no unknown key to raise on, so the divergence is invisible: the same submission scores differently depending on which backend happens to answer the request. Going the other way, a 3.6.1 backend rejects anrtol >= 1that an older, pre-validation client published and that grading had silently accepted (as a 0 for every submission) ever since. Deploy the backend before releasing the client. The same holds for NaN/infinity encoding: an older server scores the tagged outputs as 0 and, in teacher mode, would store tagged references that every student then fails. Deploy the backend before releasing a client that encodes NaN or infinity.
License
MIT. See LICENSE.
Metadata
Release files for phigrade 3.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| phigrade-3.7.0.tar.gz | 230.6 kB | Without provenance | Details for phigrade-3.7.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| phigrade-3.7.0-py3-none-any.whl | Python 3 | none | any | Details for phigrade-3.7.0-py3-none-any.whl |
Total release size: 339.7 kB
Release files / phigrade-3.7.0.tar.gz
| Download URL | phigrade-3.7.0.tar.gz |
|---|---|
| Size | 230.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
29ebf32c453ee826a4c8e32aeba7ff5d17abc885b0cc8e056f7f4c0b524896f1
|
|
BLAKE2b-256 checksum How to use checksums |
0b10060caca38c0a04f321a0df50b6ce772f8a6e4cdcd3391442d0060adc5d39
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Release files / phigrade-3.7.0-py3-none-any.whl
| Download URL | phigrade-3.7.0-py3-none-any.whl |
|---|---|
| Size | 109.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
11581ae4c0f449325dc96c388ec90bc2ce456693a8750d36f4fbb9d7fc6589f2
|
|
BLAKE2b-256 checksum How to use checksums |
f54b25958fdbeb220f5ee8f32c9eb09baf4088577f391bc8f05bbb2f74b7f524
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Security for phigrade 3.7.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.