ADR-125 — Paper copies: the hand-out and its answer zones, PDF through Typst, the paper attempt entered by the teacher¶
Status¶
Accepted (2026-11-03, the product owner's decisions on issue #551, palier A;
points 2, 5, 8, 14 and 16 arbitrated by the orchestrator after review).
Delivery progress lives in changes/.
Amended 2026-11-04 by ADR-126,
scope: §5 and §20 (diagram, circuit, logic and blocks become
printable; ADR-126 §8) and §6 (a free zone may be a ruled frame with a
starter, pattern and underlay, and stays free; ADR-126 §3–§4).
Amended 2026-11-04 (product owner, 2026-11-04, after the first look at the PDF), scope: §6 (a choice question's choices are its paper zone; the page) and §7 (every document in the requester's language); see the amendment at the end.
Amended 2026-11-26 by ADR-148, scope: §5 (a
parameterized question prints: the parameterized refusal is gone), §8 (the
paper seed becomes variant 1 of paper_variants, with the values it draws
stored; the statement with key of a printed evaluation follows the paper's
order), §9 (a paper attempt is entered on the variant and carries its
values) and §17 (those values tell a paper copy apart on the anonymised
table: an accepted limit); then, the same day, §6 (a zone's manifest entry
names its booklet, the variant) and §9, §11 (a paper copy names the variant
printed on it, 422 paper_variant).
Scope: the printed hand-out of an exam and the PDF of every export; the
paper attempt a staff member enters, its scan, and every reader of
attempts that counts; the student's documents of ADR-112's amendment.
Relations: amends ADR-121 §1, §2, §4, §7 and §8 steps 2, 3, 6; ADR-112 (open question 62 settled); ADR-122 §4; N-I18N-01 (a scoped exception). Depends on invariants 1, 4–7, 9, ADR-056, ADR-097, ADR-044. F-EXP-04..06, F-PAPER-01..05, F-GRADE-01, F-GRADE-03 (02); N-DATA-02/03/07, N-I18N-01 (03); 05 §5.7–§5.9.
Context¶
An evaluation can only be taken on a screen. Issue #551 names two real situations with no answer: a student's computer dies during an exam, and the teacher cannot bring a paper copy back into the platform; and Safe Exam Browser can be recompiled (ADR-027) while kiosk stations (ADR-051) are a limited fallback — a paper exam is the one confinement that cannot be defeated technically.
The issue proposes a full pipeline: print one identical copy, scan the stack, read the zones by machine, import each copy as an attempt. Its riskiest part is image robustness. The owner cut it in three paliers: A (this record) prints the hand-out and lets a staff member type a paper copy by hand, scan attached; B adds fiducials, a page QR code, the zone manifest and bubbles read without a model; C adds vision OCR of the written zones through the LLM gateway. Palier A is also ADR-121 steps 2, 3 and 6; it reserves zone ids, the manifest and the margins, and builds nothing of B or C.
Decision¶
-
Engine: Typst on the server. Every PDF is rendered from the ADR-121 document tree by a pinned static
typstbinary in the Docker image; no Chromium, no browser print view. Markdown becomes Typst source inpackages/docexport(pure, unit tested) onmarked's lexer, the grammar of the web app and docrender; LaTeX becomes Typst math throughtex2typst, with the LaTeX source in a visible raw box when a formula does not convert. The API runs the binary from an adapter directory,apps/api/src/typst/. -
The compile sandbox. An
execFilewith an argv array, never a shell:typst compile --root <mkdtemp> --ignore-system-fonts …. - A closed environment built from scratch, never inherited from
process.env(no database URL, OIDC, LLM or GitHub secret):PATH;HOME,XDG_*,TYPST_PACKAGE_PATH,TYPST_PACKAGE_CACHE_PATHinside the temporary directory;HTTPS_PROXY,https_proxy,HTTP_PROXY,http_proxy=http://127.0.0.1:9. Moving the package paths alone does not stop a download (verified on Typst 0.15.1); the dead proxy does. A test asserts the list, like the runner's. - Bounds:
SIGKILLafterPDF_TIMEOUT_MS(20 s); an address-space cap throughprlimit --aswhere available (util-linux in the image);maxBuffer1 MB; output ≤ 25 MB; one compile at a time behind a bounded queue (503 pdf_busy,Retry-After); the directory removed infinally. - Input: user text escaped (
typstText); a code fence is#raw(block: true, lang: …, "<string literal>"); images only fromasset:<id>, copied intoassets/<id>of the root. A test compiles a statement holding#import "@preview/x:0.1.0"and proves nothing was fetched.
The child shares the API container, with no namespace isolation; the
escape, the closed environment and --root are the defence.
-
Availability. A probe (one real compile in the sandbox of point 2, memoized) feeds
pdf: booleanin the public configuration the web app already fetches at boot (/app/api/config, every session kind); the web app hides every PDF button when it is false, a PDF route answers503 pdf_unavailable(503 pdf_busywithRetry-Afterbehind a full queue), and the system status gains apdfentry (ADR-055). CI installstypstandpoppler-utils; the PDF tests fail underCI=1without the binary and skip on a workstation without it. -
Formats. PDF and JSON (the ADR-121 record) wherever an export is offered; Markdown where ADR-121 already gives it (staff documents).
-
Printability is a declaration of the type. A type prints on the hand-out if and only if it implements the optional hook
answerZone?(student), on the student view;coreand the API hold no list of type names. One pureprintRefusal(items)refuses withreason: "parameterized"(ADR-056: a copy has no draw) orreason: "type"(a type without the hook, listed) (amended by ADR-148 §5: noparameterizedreason, a paper variant has its draw); it feedsEvaluationDetail.exports, the hand-out routes andPOST /paper, all answering409 not_printablewithPrintRefusal = { reason, types }. The staff "statement with key" accepts every type withstatementDoc. In palier A,mcq,short,cloze,richandmathimplement it.diagramandcircuitdo not (see Alternatives). A student's answer renders through a second hook,studentAnswerDoc?(student, answer, details)(amends ADR-121 §2), fed only the student view, the answer as handed back andstudentDetailsunder the policy; the staff copy and the student copy use it. (Amended by ADR-126 §8:diagram,circuit,logicandblocksprint; andcode, alinesframe, by its amendment of 2026-11-04.) -
The
answerZoneblock (amends ADR-121 §1):{ kind: "answerZone"; id: string; part?: string; zone: "bubbles" | "lines" | "free" | "name"; labels?: readonly string[]; multiple?: boolean; lines?: number; heightMm?: number }. A type's hook sees no item id: it writes onlypart(b<n>for a cloze blank); the document builder scopes every zone withscopeZones(itemId, blocks), soidis<itemId>or<itemId>:<part>, andnamefor the name frame of page -
linescounts the ruled lines of a written answer;heightMmsizes afreezone, the generic shape (an essay's). The Markdown renderer draws a zone as a plain preview (bubbles, underscores, blank lines), for thehandout.mda teacher downloads. In Typst a zone is#zone(id, kind)[…], which emits#metadata((id, kind, page, x, y, w, h)) <answer-zone>for palier B'stypst query. No fiducial, no QR code; a margin of at least 10 mm stays free for them. (Amended by ADR-126 §3: a ruledfreeframe; amended 2026-11-04, see the end: achoicesblock is a zone too; amended by ADR-148 §10: the entry is(id, kind, booklet, page, x, y, w, h), the booklet the variant's letter, none outside one.) -
Fixed words of a student-facing document (a scoped exception to invariant 1 / N-I18N-01 and to ADR-121 §4). Three documents only — the hand-out, the student's copy, the blank print of a series — take their fixed words in the requester's language (
readerLang(req)) from a typed dictionary inpackages/docexport:EN_LABELS, andFR_LABELS: Record<keyof typeof EN_LABELS, string>. The copy-lint rules run over both; the precedent isnotifications/templates.ts. Staff documents stay English; question content is printed as written. (Amended 2026-11-04: every document, staff ones included.) -
One secret order per evaluation, never the base order. A printed paper follows a random seed stored on the evaluation, the nullable column
evaluations.paper_seed(the type of an attempt's seed), drawn like a digital attempt's seed (drawSeed) on the first print or paper entry by one function,paperSeedOf(db, evaluation), of the evaluation module's service. It is never sent to a client, never in a record, never in the zone manifest; a reprint is identical. The migration lands with ADR-121 step 3, its first consumer. The order honoursshuffleItemsandshuffleChoicesas a digital attempt's seed does. The hand-out, the blank print and the paper attempt use it, so copies are identical and the paper attempt takes the ordinary ADR-097 path, with no special case initemView.ts. The staff "statement with key" keeps the base order. (Amended by ADR-148 §2–§3, §6: the seed is variant 1's, inpaper_variants, beside the values it draws, stored; the key of an evaluation whose hand-out prints follows the paper's order.) -
The paper attempt: one staff submission. It does not exist before the teacher hands in the whole copy:
POST /app/api/evaluations/:id/paperwithPaperAttemptBody = { userId, examDate, answers: Record<itemId, unknown> }. - Target (invariant 6):
userIdis loaded as a claimed, non-staff enrollment of the evaluation's classroom, else422 paper_no_seat. - Validation (invariants 4, 7): each answer goes through the
student save's path —
answerFromStudent,answerSchema,fromStudentAnswer— on the view of the paper seed; one malformed answer refuses the copy (422). No grade, verdict or key comes from the client. (Amended by ADR-148 §4: on the view of the paper variant, its values included; the attempt copies its seed and its values,fallbackincluded.) - One transaction: end the replaced unfinished attempt (point 12),
then insert the attempt —
origin: "paper",state: "submitted",closedBy: "teacher",submittedAt= now,startedAtanddeadlineAtnull,afterDue: false,displayTracked: false, the paper seed,attemptNumber= the student's highest + 1 (unique indexattempts_evaluation_user_number_uq) and its answers, then thepaper_sheetsrow. - Grading: evaluation
runningorpaused→ nothing now, graded at the close like any handed-in attempt;closedorgrading→enqueueEvaluationGrading({ evaluationId, attemptIds: [id] }). - Boundary: the transaction runs in
paper/service.ts. It calls the attempt insert oflive/paperAttempt.ts, exported throughlive/service.ts, which writes onlyattempts(originincluded) and its answers; then it inserts its ownpaper_sheetsrow. -
No
in_progressstate, ticker or autosave. The entry page keeps its draft insessionStorageand rendersPlayerViewwith a local session, as the preview does. -
state: submittedwithclosedBy: teacher. A new pair: until now a teacher's close meantexpired. It is the truth — the student answered, a teacher handed the copy in. The paper attempt emits noattempt.closed: it reaches the dashboard through the existingdashboard.attemptevent, which carriesstate. No reader changes; the student of a replaced attempt sees "evaluation_closed" (useAttempt.ts), as for any attempt a teacher ends. -
When, for whom, by whom. Exams only (
409 paper_mode); from the evaluation's first run (startedAtset) until its release —running,paused,closed,grading;draft,scheduled,lobby→409 paper_not_started;released→409 paper_released. Any staff member of the course (staffAccess); a stranger gets a 404. (Amended by ADR-148 §12: where the paper has several variants, the copy names the one printed on it, else422 paper_variant.) -
Superseding. A paper attempt may replace the student's attempts, digital or paper; nothing is merged.
attempts.superseded_by(uuid, null, referencesattempts,on delete no action, checked at the end of the statement so a cascade deleting both attempts of a pair succeeds) marks each replaced one, andofficialAttemptgainssuperseded_by is null(amends ADR-122 §4);isLatestAttemptandattemptOfkeep working, the paper attempt being the latest. A replaced attempt stillnot_startedorin_progressis ended first,expiredwithclosedBy: teacher, freeing the open-attempt index; the student's player learns it through the existing attempt-closed event. The replaced attempt stays readable by the staff, marked; it is never served to the student (404 on the attempt view, the feedback and the copy; the student's lists readofficialAttempt). Neither a paper attempt nor a replaced one is ever reopened (409 not_reopenable): a reopening would hand a student a screen for a copy that was never theirs to type, or for one that no longer counts. The entry dialog says an attempt will be replaced. -
The exam date and the clock (invariant 5). A paper sitting is supervised by a person; the platform enforces no deadline on it.
submittedAtis the server's time of entry;paper_sheets.exam_daterecords the day written (default: the evaluation's opening date, editable). Nothing but the scan is written after creation.startedAtis null, and the duration statistics already skip such attempts. -
Untyped free zones. On a paper attempt, an item whose zones are all
freeand that has no answer row — in palier A an essay the teacher did not transcribe — gets aproposedgrading at 0 points with reasonpaper_free_zone, asrunner_unavailableandllm_not_configureddo (grading/jobs.ts): nograde()call, no model job. Validating it needs no override comment; until then it holds the attempt back like any proposal. An exception to F-GRADE-01's validated 0. -
Scan. Optional, attached right after the submission or later; a second upload rewrites the
paper_sheetsrow throughpaper/service.ts(the old file swept). PDF, PNG or JPEG by magic bytes, at mostPAPER_SCAN_MAX_BYTES(25 MB), else415or413. Stored underASSETS_DIR/paper/<attemptId>/<sha256>.<ext>throughwriteAssetandsafeJoin, with noassetsrow, never reachable through/app/api/assets/:id. Served to the course's staff only (staffAccess, 404 otherwise), as an attachment withnosniff, each read audited. Deleted with its attempt (cascade, then a file sweep); retention is the attempt's (N-DATA-03). A student never sees it in palier A. -
Data, contracts, audit. A new module
paper(routes.ts,service.ts) ownspaper_sheets(apps/api/src/db/paper.ts) and is its only writer:attempt_id(primary key, cascade),exam_date,entered_by, and the scan's hash, type, size, upload time and uploader; the scan's path is rebuilt from the attempt id, hash and type.attempts.origin(not null default 'digital', orpaper) stays on the row, so readers get it cheaply. A*.db.test.tsdeletes an evaluation holding a replaced attempt and its replacement (N-DATA-03). Contracts inpackages/contracts:PaperAttemptBody,PaperSheet,PrintRefusal,Capabilities, the scan upload's reply. The audit union gainspaper.enter(withsupersededAttemptId?),paper.scan_uploadandpaper.scan_read. -
Where the teacher finds it. Each entry point is a secondary action of a screen with its own purpose (invariant 2). Never on the grading table: it is anonymised (F-GRADE-03, ADR-044), and a "Paper" badge there would name the one student whose computer died. The badge lives on the dashboard row, the results row, the staff copy and the inspect view. (Amended by ADR-148, Consequences: on a parameterized item the variant's values, shown in the cell, tell a paper copy apart — an accepted limit.)
-
The student's documents — their own copy and the blank print of a past series — follow the ADR-112 amendment, which settles open question 62. No solution document for a student (invariant 4, ADR-124 §3).
-
Leak test. Every student-facing document is searched in three forms — tree, rendered source, PDF text — as 05 §5.7 states.
-
Not in palier A. Fiducials, QR codes, machine reading, a model call on a scan; merging a partial digital attempt; per-student copies; detecting pages out of order (palier B flags them); printing
diagramandcircuit. (Amended by ADR-126 §8: they print.)
Consequences¶
- A student whose computer dies, or a class sat without computers, gets a normal attempt — graded, in the results, the release and the gradebook — at the cost of teacher time per copy.
- One renderer more to keep in step with the web's Markdown and KaTeX; the conversion is pure and tested, and an unconverted formula prints as LaTeX.
- The image grows by one static binary; one compile at a time bounds
memory and may answer
pdf_busy; the compile is not namespace-isolated. - A new type is printable by implementing
answerZone; nothing else moves. - Every reader of
attemptsthat counts keeps usingofficialAttempt, which now also hides a replaced attempt. - Handwriting scans are personal data of a new kind (N-DATA-02/03/07); their retention horizon is open question 64.
Alternatives considered¶
- Headless Chromium printing the web app's pages (the issue's recommendation, ADR-121 §7's first version): a browser in the image for a print layout; Typst paginates, measures zones and is one static binary.
cmarkerandmitexvendored inside Typst: the conversion would escape the Node unit and leak tests, with WASM pinned in the repository.mitexstays the fallback iftex2typstproves short.- The base order (seed 0) on paper: the editor creates an
mcqwith its first choice ticked, so the base order puts the key at A in most single-answer questions — a leak through the print. - A seed derived from the evaluation's id: the id is in every student
route and the hash is public code (
packages/core/src/rng.ts), so a student could recompute the base order and the key. - A keyed hash of the id (an HMAC under a server secret): a rotation of the secret would change the order of a reprint and of every paper attempt already entered; a stored random seed survives it.
- A paper attempt
in_progress, typed through the student's routes in a staff mode: it widens the student loader to a staff caller, needs refusals on check, events and submit, exposes an open attempt to the close pass and adds a dashboard state. One validated submission gives the same guarantee. - Refuse a paper copy when the student has an attempt (the issue's scope): rejected by the owner; the computer that died is that case.
- A free zone for
diagramandcircuitnow (the owner's first decision): deferred. Their figure, the canvas a student completes, has no server-side renderer (packages/diagramandpackages/qt-circuitrender through React only), so a hand-out would print a question without its statement. A later record may add them once a server-side SVG exists. (Done by ADR-126.) - A list of printable type names:
corenames no type; the hook is the declaration. - Merge a partial digital attempt with the paper copy: two sources for one answer, and no rule for which wins.
Amendment 2026-11-04: the printed look and the language of every document¶
Decided by the product owner, 2026-11-04, after the first look at the PDF. The rest of the record stands.
- A choice question's choices are its paper zone (amends §6 and
ADR-121 §1). A
choicesblock of the document tree lists every choice beside its box: a square when several may be ticked, a round one for one answer, drawn empty or ticked (by position, like a stored answer).mcqdraws it on the statement (none ticked), on the key (the right ones) and on an answer (the ticked ones), every choice listed each time. ItsanswerZonehook returns no block:scopeZoneskeys the statement'schoicesblock to the item like an answer zone, and the Typst renderer wraps a keyed block inzone(id, "choices", …), so the<answer-zone>manifest lists it with its position. The type stays printable: the hook is present.bubblesstays a zone kind, for a cloze dropdown's options (round, one to pick). Markdown writes the block as a task list,- [ ] **A.** textor- [x]. The leak tests assert that no box is ticked on a statement or a hand-out, nor on a copy whose key is hidden. - Every document follows the requester's language (amends §7 and,
through it, ADR-121 §4). The hand-out,
the student's copy, the blank print of a series and the staff documents
— the statement with key, an item's answers, the staff copy — all take
their fixed words from
LABELS[readerLang(req)]; every hook of a type,answerDocincluded, receives the labels. "Staff documents stay English" no longer holds. A value the platform stores as a code (a policy's name, a matcher's kind, a math problem's code) is printed as stored. - The page (§6). The body font is New Computer Modern, the Latin
Modern look of a LaTeX paper, embedded in the Typst binary like the
others (
--ignore-system-fontsstays); formulas keep New Computer Modern Math, code and a drawing's text (ADR-126) DejaVu Sans Mono. A question's points sit at the right end of its heading line, lighter (1 pt, never plural), outside the heading itself so a PDF bookmark holds the heading alone (aheadingblock'saside, ADR-121 §1). No rule separates two questions: a level-2 heading opens each with space above; a light rule remains between two students of an item's answers. - The JSON record is indented (two spaces), so a person can read it; it parses as before.