Commits
2026-09-25
✨ feat(api): server-side filters on the list doorsAhmet Kaan Gümüş · d8dad92
✨ feat(api): server-side filters on the list doors A caller no longer has to download a capped collection and narrow it in the client: - events, exams: the WindowParams pair is SQL (no whole-table load) and gains starts_before/ends_before, so a past/completed view is expressible - sessions: starts_after/starts_before, half-open months - homework: due_after/due_before (the open/past tabs), class_course - meals menus: slot (was a post-page JS filter — page counts lied) - users (admin): roles= comma set; courses: kind, q, taught - appointments + slots: teacher (or me), starts_after/starts_before, status - pomodoro log: from/to, with the focus total summed in SQL - messages and boards: q (folded literal substring) - pool questions: ?status= is a WHERE, not a post-filter - bank/course-notes id filters: garbage is a 400 naming the field, not an empty page Absent params return today's response byte-shape; page and count share one WHERE.
2026-09-16
✨ feat: the class×course instance is the academic anchor (K-12 remodel)Ahmet Kaan Gümüş · ae84034
✨ feat: the class×course instance is the academic anchor (K-12 remodel)
`course` was a school-wide singleton: enrollment, exams, sessions,
roll-call and homework all keyed on it, so two class sections teaching the same
course shared one roster, one exam set and one timetable. This moves the
academic anchor to `class_course` — the per-class instance — and rebuilds
the academic model around Turkish K-12.
Schema (migrations/school/20260916000001_k12_remodel.sql): `class_course`
becomes an instance (ders_saati, counts_toward_karne, enrollment_count,
class_course_teacher); enrollment re-keys to (class_course, app_user);
exam carries class_course + term (+ exam_audience for shared exams);
course_session / session_attendance / homework re-key; `class_member` is a
soft-leave history table (uuid PK, joined_at/left_at, partial unique index
on the live stint); `academic_year` sits above `term`; `class_group` links
a year, not a term; new `course_membership` (clubs/study), `karne_snapshot`;
settings gain branches/excuse_kinds/absence limits/timezone; profile gains
branch. Drops/recreates the identity-changing tables (pre-customer; the
migration resets every counter on a kept table that pointed at a dropped
one).
Layers: domain/db/service/web rewritten to the instance seam, with
`ensure_instance_teacher` gating instance writes (D10), the report card computed per
instance and weighted by ders_saati, an absence report, `/instances`
and `/academic-years` nests, and `/classes/{id}/instances`. Capacity and
the seat-claim 409 are gone; detach sweeps the whole instance subtree and
unlinks its blob keys.
Gates: cargo check --all-targets, SQLX_OFFLINE check (cache regenerated),
doc_sync, spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1370/1370.2026-09-12
🗃️ feat!: port exams domain to sqlx/PostgresAhmet Kaan Gümüş · 381e16c
🗃️ feat!: port exams domain to sqlx/Postgres
- db/{exam,exam_question,exam_attempt,exam_answer,exam_result,question_image,answer_image}:
SurrealQL -> static query!/query_as! (PagedList exemption kept for
exam_question listing); composite natural PKs (exam,user,seq) everywhere;
sitting scoping via key.rs wire helpers unchanged.
- Freeze gate: write_unfrozen/IndexedResults/FROZEN_SLOT deleted; freeze is
a shared in-tx freeze_gate() (exam row FOR UPDATE + EXISTS(attempts)) run
inside each question/image write's own tx_with_retry.
- EXAM_LOCK deleted: sitting create re-judges sittable/window gates on the
locked exam row (guard_start) then claims exam_sat_total in one CTE;
exam delete locks the exam row before its ordered cascade and collects
blob keys inside the tx; answer/answer-image saves lock the exam row
ahead of their upserts (bump-and-restore touch tricks deleted).
- PRESENCE_LOCK deleted: join = unconditional left_at clear; last-out =
single conditional stamp_left_if_running (left_at IS NULL AND
finished_at IS NULL AND live-schedule in-progress); ExamPresence map
mutex stays for counts.
- Grade tx: exam row FOR UPDATE, draft gate in-tx, kind_ref claim
(retired=false), 4-counter first-vs-regrade precedence preserved exactly;
remove() refunds via data-modifying CTE.
- THROW markers -> early returns: exam_redraft, questions_frozen, no_exam,
question_subject_gone, question_row_gone, question_stale_move,
exam_missing, exam_draft, kind_retired.
- cfg(test) mods left for wave 3.🗃️ fix: qualify uuid::Uuid in accessor where the import is absentAhmet Kaan Gümüş · 3343a14Browse files
🗃️ feat: pub fn uuid(&self) accessor on all 34 Uuid id newtypesAhmet Kaan Gümüş · b3ab76fBrowse files
2026-09-11
Merge branch 'layer-split/exam_attempt'Ahmet Kaan Gümüş · 7267caa
Merge branch 'layer-split/exam_attempt' # Conflicts: # src/db/mod.rs # src/domain/exam_attempt.rs # src/service/mod.rs # src/web/courses.rs # src/web/exam_ws.rs # src/web/exams/attempts.rs # src/web/exams/mod.rs # tests/regress_course_delete.rs
🧹 chore: split exam_attempt into domain/db/service layersAhmet Kaan Gümüş · c13b51d
🧹 chore: split exam_attempt into domain/db/service layers
src/domain/exam_attempt.rs keeps the pure core (ExamAttemptId, AttemptStatus,
the entity + getters, deadline/status arithmetic); fields went pub(crate) so
the layers can mint and target rows.
src/db/exam_attempt.rs takes every query: finish/set_left (the two
field-scoped writes), the reads (read, read_latest_for_user, list_*,
any_for_exam), and the write_unfrozen[_with] freeze-gate transaction gateway
with FROZEN_SLOT and the THROW markers.
src/service/exam_attempt.rs owns the workflows and the cross-call state:
EXAM_LOCK moves here from web/exams/mod.rs (it spans multi-call workflows —
start's writer lease, saves' reader leases), the sitting gates
(ensure_sittable/ensure_student/ensure_student_now/ensure_enrolled/
check_rejoin/writable_attempt) move out of the handlers, as do course_of
(web may not be imported from service) and question_of_exam (the answer
funnel's lookup). start keeps its name from the domain; start_attempt /
finish_attempt / save_answer_checked are the handler workflows extracted
whole, windows and term gates and all, in the original gate order.
web/exams/attempts.rs keeps authz extractors, DTOs, and response assembly
only; exam_ws.rs, exams/{mod,questions,images,review}.rs and courses.rs
re-point to the service paths; domain/exam_question.rs and
question_image.rs call the db-layer write_unfrozen* directly. Doc links to
moved items re-pointed. Tests ride with their layer: persistence
(field-scoped write) tests in db, workflow (start/retake/race) tests in
service; assertions unchanged, only paths and call shapes.🧹 chore: split note/session/settings into domain/db/service layersAhmet Kaan Gümüş · efea304
🧹 chore: split note/session/settings into domain/db/service layers
Pilot wave of the three-layer split. All query execution for the three
domains now lives in src/db/{note,session,settings}.rs as free fns taking
db first; web handlers call service::<x>::* only; domain keeps pure types.
- service/settings.rs gains the PATCH workflow (apply) and SETTINGS_LOCK —
it spans a multi-call pair (retire names, CAS save, restore), so it is a
service lock, not a db lock. The service takes its own input records
(SettingsPatch/*Input) so wire DTOs stay in web and list validation keeps
its original order, including the try_kept grandfathering that needs the
stored list.
- Note/Session/Settings fields the db layer mints or CAS-binds become
pub(crate); Settings::record_id becomes pub(crate).
- Unit tests rode with their fns: note delete cascade → db/note, session
purge → db/session, settings load/save/CAS → db/settings, the whole
settings edit workflow suite → service/settings.
- Doc links re-pointed (user, class_blueprint, bank_question, exam,
note_file, tests/regress_roles); NoteId::generate's stale
'Note::list_for_user' link now names db::note::list_for.
- Known residual for a later wave: web/notes.rs:411 file.delete() is
note_file-domain persistence (note_file splits in C3).2026-08-05
🔗 fix: stop a course's children outliving the courseAhmet Kaan Gümüş · 0251364
🔗 fix: stop a course's children outliving the course
Exam, CourseSession and Subject creates were bare db.create calls that
wrote no key the delete cascade writes, so a create racing
DELETE /courses/{id} committed alongside it. The orphans were not merely
stray: every exam route funnels through course_of, which answered 500
forever, so the row was undeletable while still listed to manager+.
Sessions and subjects 404'd the same way.
All three now ride cap::touch_and_create against the course row.
Course::delete also skipped the two bank_question cleanups its per-entity
siblings perform, leaving source_exam and subject pointing at deleted
records — contradicting the documented "null once that subject was
deleted".
Real-server measurement: 4/4 rounds orphaned before, 0/4 after.fix: 🎨 stop a drawing from outliving its examAhmet Kaan Gümüş · f8b854c
fix: 🎨 stop a drawing from outliving its exam A drawn answer was still a bare upsert — the exact shape the text answer had before yesterday's fix — so it kept the hole: a drawing landing after an exam delete removed the row but before it committed was swept by nothing, and both sides reported success. 4 of 4 raced rounds against a real server. The blob went with it. The handler collects the names to unlink before it calls the delete, so bytes written after that snapshot sit on disk with no row and no reader forever. It now moves the exam's mark counter and puts it straight back inside its own transaction, like the answer beside it, so the two writes collide on one key and the store refuses a side. Restored by captured value, so the row is byte-identical and no teacher's edit is refused because a student drew.
fix: 📝 stop a question or picture from outliving its examAhmet Kaan Gümüş · 317df96
fix: 📝 stop a question or picture from outliving its exam Adding a question, or a picture on one, only *read* the exam it hung off — the freeze gate reads exam_attempt and nothing else — and an exam delete sweeps its questions in its own transaction. A write landing after that delete removed the exam row but before it committed read a row that was still there, while the cascade ran on a snapshot predating the insert, so both committed and neither caller was told: 4 of 4 raced rounds against a real server. An orphan question is worse than untidy. It keeps the reference it claimed on its subject, because the cascade's per-subject decrement counted only the rows it could see, and a subject delete is gated on that count reading zero — a subject nobody can ever delete again, hanging off an exam nobody can ever see. An orphan picture strands its blob too: the handler collects the names to unlink before it calls the delete. The gate now writes the exam row itself — bumping the mark counter and putting it straight back, by captured value so the row is byte-identical and NONE stays NONE — which is the shape an answer save and a menu child already use. It moves a value on purpose: an update that leaves the document unchanged is elided and never reaches the write set, so it would collide with nothing. One site covers both children, and every future writer through the gate. Tests that wrote a question or a picture against an exam id nothing ever created now create one: that is a 404 today, not a silent orphan.
2026-08-04
fix: 📝 stop an answer from outliving its examAhmet Kaan Gümüş · 02b1ff8
fix: 📝 stop an answer from outliving its exam Saving an answer only read the exam it belonged to, and a delete sweeps answers in its own transaction — so a save landing inside that window wrote a row the sweep had already passed, and both sides reported success. The same shape as the attendance mark, one domain over; measured 4 of 4 raced rounds against a real server. The save now writes the exam row itself, so the two collide and the store refuses one. It has to move a value to do that: SurrealDB drops an update that leaves the document unchanged, so setting the counter to itself never enters the write set and never conflicts — it is bumped and put back inside the one transaction instead. No new column, since a whole-row save would strip one at the next edit. Editing an exam now rides the retry too. The answer touch makes that row hot, and a lost round through the old bare query was a 500.
2026-08-02
fix: 🔩 close the leaks a five-domain hunt turned upAhmet Kaan Gümüş · a3fe8cf
fix: 🔩 close the leaks a five-domain hunt turned up Five hunters swept exams, homework/attendance, identity, money/scheduling and messaging/courses; a three-lens verifier panel then refuted three of the first fixes, and those corrections are folded in here. Leaks and races closed: - exam self-review gated on *any* mark, so a seq-1 grade opened the answer key forever — a student mid-retake read `correct` and `is_correct` off the sheet they were still writing. All four review reads now 409 while the caller's latest sitting is in progress. - roll call could land after its session was deleted, and the orphan was unremovable (its delete route 404s on the vanished session) while the attendance report went on counting it. The write now proves its parent exists in the same transaction, the way ExamResult::grade does. - a teacher could counter-propose and then approve their own proposal, committing the requester to a time only the teacher ever named; and even after that, re-proposing between the requester's read and their accept moved the meeting under them. Approve refuses while a proposal stands, and accept now pins the window it is answering. - two concurrent chatbot posts on one thread cross-attributed their answers — both replied to the second prompt, the first was never answered. The prompt id rides the request instead of being re-derived from write order. - a whiteboard participant demoted to `parent` kept drawing, and kept *reading* the live canvas for up to 15s. Every frame is authorized before delivery now, and a demotion sweeps the account off rosters. - a demotion to `parent` stranded event signups no one could free. Promotions are left alone (staff free their own seats) and closed lists are never rewritten. - the rate-limit bucket map was unbounded past 10k live keys and then scanned O(n) under the global mutex on every request. Eviction is bounded and never frees an exhausted bucket — the first attempt did, which traded a memory bug for an auth-bypass, so it is pinned by a test that floods at the victim's own spend. - session and event cascades ran as loose queries; a concurrent write slipped between them and orphaned rows, and for notes a blob nothing could ever reclaim. All three are one transaction now. - sixteen id generators still used Ulid::new(), whose random low bits scramble same-millisecond rows under the "newest first" the docs promise; five listings had no tie-break at all, so offset paging could skip or duplicate a row. Also: $session is a protected SurrealDB 3 variable — binding it fails the whole query as a bare 500, which is what hid the attendance fix. Accepted, documented, not fixed: one bank template instantiated into two exams copies `correct` into both, and the review gate is per-exam.
2026-07-31
fix: 🧮 refuse a mark on an exam that no longer existsAhmet Kaan Gümüş · bb774eb
fix: 🧮 refuse a mark on an exam that no longer exists
ExamResult::write_mark gated on the exam being a draft, and read that
gate as `IF (SELECT VALUE draft FROM ONLY $exam)`. A deleted exam reads
NONE, NONE is falsy, so the gate passed and the mark landed cleanly on a
row that was already gone. The grade handler's pre-flight read cannot
close that — DELETE /exams/{id} takes no EXAM_LOCK while grading holds a
read lock, so a delete can land in the gap.
A missing exam now throws inside the same transaction and answers 404.
The handler already documented that status, so no doc surface moves.
Exam::delete's race test had to change with it. Its witness that the
delete landed inside the racer burst was "some marks survived" — exactly
the orphan this gate removes, so the witness was structurally
unsatisfiable and the test failed 3 of 3 runs against the real server.
It is #[ignore]d, so a green suite hid that.
The replacement witness is per-round: of six racing grades, a round where
between one and five were refused proves the delete landed between them.
That is stronger than what it replaces, which a clean no-overlap split
would also have satisfied. Measured two to four such rounds per twenty
across five runs, and it goes red when the beat is flattened so the
delete always lands first. What survives as an assertion rather than a
signal is that every round sweeps clean: a mark never outlives its exam.fix: 🔁 retry every guarded transaction that loses a write raceAhmet Kaan Gümüş · 755f4ab
fix: 🔁 retry every guarded transaction that loses a write race 08b1b0f gave the four guarded deletes a retry. It left the rest of the class alone, and the rest of the class is the same defect: a guarded BEGIN..COMMIT that loses a round reports the abort's generic sibling slot as AppError::Db, so an ordinary contended write answers 500 instead of the 409 or 404 it owes. Eight more sites now go through transaction_with_retry: ExamResult's mark and its removal, AppointmentSlot::delete_free, MenuDish::create, PomodoroSession::finish, WorkEntry::check_out, and the exam freeze gate covering ExamQuestion insert/update/delete and QuestionImage upsert/delete. The freeze gate needed restructuring rather than wrapping. unfrozen() built the SQL and frozen_check() inspected an already-sent response, so the five callers owned the send and nothing in that split could re-send. Both are replaced by write_unfrozen(), which owns the send and therefore can retry; frozen_check is gone, so no path skips it. ExamResult::remove additionally dropped its .check()? — that returns the lowest-slot error, so an aborted transaction's "not executed" sibling masked the real retryable conflict. The same masker was deleted from Exam::delete in 08b1b0f. transaction_with_retry's admissibility clause is now a rule instead of a list of callers, which had already gone stale: a statement is admissible iff it cannot legitimately answer "already exists" — UPDATE and DELETE never can, a CREATE cannot when no rival can reach its id, and an UPSERT cannot when its id is bijective with every unique tuple its table indexes. Re-send soundness is measured, not argued: injecting a THROW just before each batch's trailing RETURN makes every statement run and then aborts the whole transaction, and re-sending the real SQL afterwards left the suite green across all twelve sites, with no batch double-applied.
2026-07-30
fix: 🔁 retry a guarded cascade that loses a write raceAhmet Kaan Gümüş · 616a66b
fix: 🔁 retry a guarded cascade that loses a write race A BEGIN/COMMIT delete that lost a write conflict answered 500 instead of the refusal or retry it owed. An aborted transaction errors *every* slot, and all but the failing one say a generic "not executed" — the consequence of the abort, never a reason of its own. Picking one of those out of the unordered HashMap from take_errors, or taking the first via check(), retired a retryable round as a database error. Measured on Course::delete at 1-3 of 20 raced rounds against a real server. transaction_with_retry is write_with_retry's story for the cascades that cannot be one statement: it matches the caller's THROW markers first, since a THROW is a decision and outranks a conflict, then re-sends while any slot reports a lost round. It hands back both the response and the drained errors because take_errors consumes and the caller needs the slots as well as the map. Course, Subject and Exam route through it; Exam also loses the check() that was masking the conflict behind a sibling slot. Term needed none of it — it is a single statement, so the existing write_with_retry was the whole fix. Four ignored race tests come with it. Only the course one discriminates, proven by cutting the retry loop to a single attempt and watching it go red; the other three guard their handlers' status codes and say so on themselves rather than implying a measurement they do not make. They share a lock so the documented invocation works.
2026-07-27
fix: 🧷 close the cross-table races the locks never closedAhmet Kaan Gümüş · 4f7bdaf
fix: 🧷 close the cross-table races the locks never closed
Every remaining check-then-write that spanned tables becomes a
single-record conditional write, so it holds across replicas:
- subject delete: refcounts (exam_question_count/homework_count) claimed
and released by every question/homework write; the triple lock hold
dies, BANK/TERM/ENROLL locks die outright
- exam kinds: kind_ref {count,retired} records; grading claims, removal
retires only at zero — grading a removed kind and re-kinding a graded
exam are now 409 (both previously silently mis-weighted marks)
- homework: the grade stamps the submission row in its own transaction;
student writes are conditional on the stamp being absent
- appointments: slot occupancy is a cap-1 counter; the lock survives
only for the within-replica approved-overlap check
- meals: seat counter + menu version CAS (price can no longer tear mid
booking) + deterministic menu:date_slot id kills duplicate publish
- cap::claim_and_create: member gate, then seat, then child CREATE in
one transaction — a duplicate loser no longer eats a stranger's seat
or gets refused for a row it already owns
- boot: the two unguarded lease statements now retry on transaction
conflict (the escape was ~1-in-15 under full-suite load)
Two races reviewed and accepted, documented in README ## Concurrency
model: the attempt-seq late save (one history row, grade of record
untouched) and cross-replica approved-overlap (visible, cancellable).
Deployment contract (README): counter-adding releases restart all
replicas together — an old binary's writes skip new counters and the
= NONE backfill guard rightly refuses to re-seed.
Every guard is mutation-proven; backfills are one-time, = NONE-guarded,
ordered after the destructive sweeps, and verified against the live
volume.fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process
Two replicas are live; every process-local lock silently stopped
meaning anything. Move the invariants into the writes themselves:
- count caps (enroll/register/files/threads) become a counter column
claimed by UPDATE .. WHERE n < cap (domain/cap.rs), backfilled once,
decremented in the same transaction as every child delete
- exam freeze, re-draft and grade gates ride inside the write's own
transaction (IF .. THROW); SESSION/WORK_ENTRY/EVENT locks die, range
checks fold into the UPDATE's WHERE (FieldUpdate::ordered)
- appointment decisions CAS on status+proposed window+decided_by;
bank/exam updates CAS on their editable columns
- rate limiter syncs local windows to a shared minute row every 2s,
fail-open when the database is down
- paged GETs run LIMIT/START in the database (domain/page.rs); sites
that post-filter in Rust stay web-sliced and say so
- exams.rs (3629 lines) splits into web/exams/{mod,attempts,questions,
images,review}; image uploads single-source in web/image.rs; the
bare-seq key rule lives once in domain/key.rs; migration SQL moves
to migration_sql.rs
Every new guard is mutation-proven (removing it fails a named test).
Migration adds counter columns + rate_limit table; backfill is
one-time, guarded by = NONE, and verified against the live volume.
Traps recorded: SurrealQL 'x ?? 0 > 0' parses as 'x ?? (0 > 0)'; the
embedded mem engine drops one of two concurrent writes yet answers Ok.2026-07-26
chore: 📦 give every constant one homeAhmet Kaan Gümüş · 78b25b5
chore: 📦 give every constant one home Constants were scattered across 18 modules: table names and migration SQL in database.rs, limits in config.rs and rate_limit.rs, magic strings sitting next to the only code that read them. Nobody could answer "what are all the hard values in this service?" without a grep. They all live in constant.rs now — validation bounds, the 37 SurrealDB table names, the PRE_REPAIR/MIGRATION/BACKFILL schema SQL, and the enum value tables that used to hide as associated consts (Role::ALL -> ROLES, Folder::SENDER -> SENDER_FOLDERS, and friends). Values are byte-identical; this changes no behavior. constant.rs now imports crate::domain for the enum types, an intra-crate cycle that compiles fine. Statics stayed where they were. A Mutex or a ULID generator is runtime state, not a constant, and moving them would only blur that line. Two guards keep the consolidation honest. limits_completeness.rs already failed on any pub const in constant.rs that is neither published through /limits nor excluded with a reason; the *_TABLE names are excused by shape rather than by 37 lines of boilerplate, but the excuse now requires the absence of a MAX_/MIN_/DEFAULT_ prefix so a real bound cannot hide behind the naming convention. And the move quietly dropped three rules off the end of the text-fold table, which every existing test still passed — so the circumflexed vowels are pinned, and search_fold_sql must emit one string::replace per rule or the needle and the column drift apart.
2026-07-25
🎨 style: cargo fmt the tree before the audit fixesAhmet Kaan Gümüş · b4a5a00
🎨 style: cargo fmt the tree before the audit fixes Pure reformatting, no behaviour change: rustfmt wrapping plus its alphabetical `use`-list reordering across the files that had drifted. Kept separate so the correctness commits that follow carry only logic.
fix: 🏦 choice identity, bank visibility, and whole-row save racesAhmet Kaan Gümüş · ca93ae9
fix: 🏦 choice identity, bank visibility, and whole-row save races
- choices become {id, text} with stable server-minted ids; correct and
exam_answer.selected name a choice id, and image rows key off it, so
editing a choice list can no longer re-point an answer key, a picture
or a student's recorded answer
- a PATCH carrying choices no longer wipes every option picture: it
drops only rows whose choice id is absent from the new list, and
omitting choices re-submits the stored ids untouched
- bank templates are private by default; list, read, both image routes
and from-bank enforce it, and an invisible template 404s rather than
403s so it cannot be probed for existence
- bank list pages in SQL, newest first, with server-side text and
visibility filters and a count over the same predicate — it used to
return the whole table and window it in memory
- text search folds Turkish casing through one shared table used by
both the Rust needle and the SurrealQL column
- fix: ExamAttempt::finish whole-row-saved a stale struct, so a
walk-out stamp written by the exam-room socket could be reverted;
it now writes only finished_at
- fix: BankQuestion::update and Subject::update had the same shape;
ban it going forward with scripts/check-whole-row-saves.sh and an
explicit whole-row-save-ok opt-out for rows that cannot be raced
- fix: question_to_bank wrote its back-link holding only BANK_LOCK, so
a save racing a question edit lost the link
- ids come from the monotonic ULID generator that already existed for
appointment slots — Ulid::new is not monotonic within a millisecond,
so newest-first ordering was wrong for same-ms rows
- source_bank splits into from_bank and banked_as; deleting a template
clears both, deleting a subject clears the template's subject instead
of blocking the delete
- add refresh-from-bank, frozen once an attempt exists, and a one-query
per-page usage count
- Exam::delete no longer reads a hardcoded statement slot
- proptest over QuestionSpec::try_new: a key matching a stored choice is
that choice, any other key is a new option that cannot steal an
identity2026-07-24
fix: 🏦 link exam questions to their bank template, both waysAhmet Kaan Gümüş · ebbd813
fix: 🏦 link exam questions to their bank template, both ways - question_to_bank now writes source_bank back onto the exam question, mirroring what question_from_bank already did; repeat saves repoint the link at the newest template instead of leaving the client blind - link_source_bank is a field-scoped UPDATE, not a whole-row content save: the caller holds only BANK_LOCK and awaits a bank insert plus the blob-copy loop between reading the row and linking it, so a concurrent PATCH of the question was silently reverted - a failed back-link is logged and swallowed: the template and its copied blobs stand, and the next save re-links it - deleting a template clears source_bank on every question that referenced it; deleting an exam clears source_exam on its templates (both cascades were documented but never written) - tests: the concurrent-edit clobber, the two cascades, and repeat saves repointing the link
✨ feat(exams): let students review their own graded examAhmet Kaan Gümüş · 4db4ff2
✨ feat(exams): let students review their own graded exam
Add a per-exam teacher toggle `allow_review` (default false, opt-in,
mirrors `allow_rejoin`) and three student self-review endpoints:
GET /exams/{id}/review/attempts
GET /exams/{id}/review/attempts/{seq}/answers
GET /exams/{id}/review/attempts/{seq}/answers/{qid}/image
All are CurrentUser-scoped (no {user} param, so a student only ever
sees their own data) and gated by reviewable_exam(): 404 on missing or
draft exam, 403 when allow_review is off, 404 until an ExamResult row
exists for that student (proves the teacher marked them). Readers are
the same ones the teacher history endpoints use.
Schema: DEFINE FIELD allow_review DEFAULT false + a separate backfill
query flipping legacy NONE rows to false — no existing exam auto-exposes
answer sheets. Podman-verified: 9 legacy rows migrated null->false.2026-07-22
🐛 fix(exams): report why sync rejects a durationAhmet Kaan Gümüş · 0c59412
🐛 fix(exams): report why sync rejects a duration The duration-vs-window check ran before the mode match, so a sync exam sent with an over-long duration_ms was told "must fit within the starts_at..ends_at window" — advice that would not have fixed the request, since a sync exam takes no duration at all whatever its size. Moving the check below the match lets the root cause answer first. Only async can reach it with a duration to compare, so nothing else changes: same inclusive bound, same duration_ms field, same reason string, same 400. The sync case in schedule_invariants_hold now pins which message wins instead of only asserting is_err.
🐛 fix(exams): reject a duration over its windowAhmet Kaan Gümüş · ea17828
🐛 fix(exams): reject a duration over its window An `async` exam accepted any `duration_ms` inside the global 1min–24h bounds, even one longer than its own `starts_at`..`ends_at` window. Such a schedule saved happily and was then silently truncated at attempt time: a teacher who set 90 minutes inside a 60-minute window saw a 90-minute exam echoed back, while every student actually got 60. The lie only surfaced once students were already sitting it. `ExamSchedule::try_new` now rejects that up front with a 400 (`duration_ms: must fit within the starts_at..ends_at window`), so the impossible schedule never reaches the database at all. Runtime enforcement was already correct — `ExamAttempt::deadline()` caps the personal deadline at `ends_at` — and is untouched; this only stops the teacher from being told something the exam will not honour. The bound is inclusive on purpose. A duration exactly equal to the window is a legitimate "the whole slot is yours" exam, and because `update_exam` re-validates the entire stored schedule on every PATCH, an exclusive bound would have made an existing row like that unpatchable for completely unrelated edits (title, kind, attempt limit). Only `async` can reach the check: `sync` takes no duration and `open` has no window. The unit test `schedule_invariants_hold` used to assert the buggy behaviour, so it flips to the fix plus the inclusive boundary. Two integration tests happened to be built on now-illegal schedules and were moved onto legal ones without losing what they cover.
2026-07-21
feat: 🎨 student answer-image endpoints mirroring question imagesAhmet Kaan Gümüş · 2c83c6f
feat: 🎨 student answer-image endpoints mirroring question images
- new AnswerImage domain keyed by (exam, user, question), stored as an
image/png blob with upsert-overwrite, mirroring QuestionImage
- routes: POST/DELETE/GET /exams/{id}/attempt/answers/{qid}/image (student
own, gated by the save_answer writable-attempt chain) and GET
/exams/{id}/attempts/{user}/answers/{qid}/image (teacher grading)
- answer_image (Option<ImageMetaResponse>) on the student sitting view and
the teacher grading sheet; live monitor and exam_ws untouched
- a drawing-only answer creates a blank text answer row so the drawing
surfaces in both views; removing the drawing grooms that blank row away
- cascade blobs+rows on exam delete, course delete, and retake wipe (rows
in the wipe transaction, blobs swept in start_attempt)
- integration tests: raster wall, own/teacher auth walls, upsert, retake +
exam-delete cascade, drawing-only surfacing and its cleanup2026-07-19
✨ feat(exams): draft exams hidden until publishedAhmet Kaan Gümüş · d8fdbf0
✨ feat(exams): draft exams hidden until published Exam prep is long work: draft: true keeps an exam private to its course's managers while it's written. Students get 404s (not 403/409 — existence must not leak) on get/attempt/ws and filtered lists; sitting and grading are blocked. Publish via PATCH draft: false; re-drafting is 409 once attempts or results exist. grade now holds an EXAM_LOCK read lease so a mark can't race a re-draft. Modeless exams renamed offline-graded/unscheduled everywhere — "draft" now means only this. Old rows backfill published at boot.
✨ feat(exams): images on questions and choice optionsAhmet Kaan Gümüş · dbeb122
✨ feat(exams): images on questions and choice options Teachers pin one illustration to any question (the map above the prompt) and one picture per option on choice questions — the options themselves can be images. Multipart upload per slot, replace by re-upload, frozen with the question once attempts exist. - rows in question_image (deterministic id per slot, UPSERT = replace); blobs beside note files under FILES_PATH, capped by max_file_bytes - raster allowlist png/jpeg/webp/gif — SVG can script and these bytes render inline to students; served with nosniff + private, no-store - students fetch bytes behind the sitting wall (enrollment + started attempt, no early peek); course managers anytime - replacing a question's choices drops its option pictures (the illustration stays) — old pictures belong to the old options - blob cleanup wired into image replace/delete and question, exam, and course deletes (exam cascade result slot shifted 5 -> 6)
2026-07-18
🐛 fix: six correctness holes from full-code auditAhmet Kaan Gümüş · ecbd550
🐛 fix: six correctness holes from full-code audit
- register response resolved people from {target, caller} only; a
re-register returns the original placer's row, so registered_by
degraded to a bare ULID username — resolve from the row itself
- note-file cap was count-then-write with no lock (SurrealDB does not
conflict-check cross-record counts against inserts): concurrent
uploads pushed a note past 10 files; the cap now lives inside
NoteFile::insert under FILE_CAP_LOCK, web pre-check dropped
- ends_at-only registration events (pure signup deadlines) never closed
signups; the gate read starts_at alone — close at starts_at ?? ends_at
- WorkEntry::check_out deleted the open row and created the closed one
in separate calls — a failure between them silently destroyed the
whole stint; take and re-file share one transaction now
- Exam::delete removed the exam row outside the child-cascade
transaction — a failure left an empty exam shell; folded in
- ExamAttempt::start treated any create failure as a lost double-start
and returned the latest attempt as a resume, passing a finished
sitting off as 200 on a transient error; resume only when the
read-back attempt is still in progress
Regression tests (failing-first) cover the first three; the remaining
three are fault-injection-only windows validated by the existing suites.2026-07-14
✨ feat(exams)!: move weight off exams onto their kindAhmet Kaan Gümüş · 3681441
✨ feat(exams)!: move weight off exams onto their kind
Weighting is school policy, not per-exam data: each settings
exam_kinds entry is now {name, weight} (1-100, defaults all 1) and
mark reports resolve weights at read time, so editing a kind
reweights every exam of that kind at once; an exam keeping a
since-removed kind counts as 1.
BREAKING CHANGE: exams lose `weight` on the wire and in storage,
settings `exam_kinds` become objects. No data migration (pre-customer
clean break) — delete ./data/hezarfen.db and reboot.2026-07-13
✨ feat(exams): open mode, attempt limits, retakes, rejoin doorAhmet Kaan Gümüş · 9835fe7
✨ feat(exams): open mode, attempt limits, retakes, rejoin door
Unscheduled exams were dead ends: attempts answered 409 "nothing to
sit", and every exam was hard-wired to a single sitting.
- mode "open": sittable anytime, no window; duration_ms optional per
attempt (absent = unlimited time). Modeless exams stay offline
drafts — still 409, so a student can't freeze a draft's questions.
- max_attempts (0 = unlimited, default 1): terminal attempts can be
followed by numbered retakes that start from a blank answer sheet;
the previous sitting's answers are wiped on the next start.
- allow_rejoin: live teacher toggle. Leaving the exam room (WS close
mid-attempt) stamps left_at; with the door closed, re-entry and all
saves 409 until reopened. Finish stays allowed either way.
- Attempt deadline generalized to min(ends_at, started_at + duration),
either side optional; none = ends only by submission.
Boot migration backfills max_attempts/allow_rejoin/seq on existing
rows and replaces the single-attempt unique index (exam, user) with
(exam, user, seq) via REMOVE INDEX IF EXISTS. Sitting #1 keeps the
legacy {exam}_{user} record id, so pre-upgrade attempts stay valid.✨ feat(school): editable policy settings + academic termsAhmet Kaan Gümüş · ea8bfeb
✨ feat(school): editable policy settings + academic terms Every school differs; the varying parts become data instead of code: - settings singleton (GET any user, PATCH manager+): exam kinds, attendance statuses, grade-display bands. Absent row = old hardcoded defaults, so existing databases behave unchanged. - core four attendance statuses stay mandatory — the attendance rate is defined over them; school extras tally rate-neutral under a new `custom` bucket in reports. - grade bands are display-only over the canonical 0-100 marks: reports gain grade/average_grade/overall_grade labels, stored marks never change with the display scale. - terms are rows (semester/trimester/quarter all fit); courses link via nullable term_id, term delete unlinks, past dates allowed for mid-year calendar backfill. - settings edits never rewrite stored rows: retired kinds and statuses live on in old records; only new writes validate against the current lists.
2026-07-12
✨ feat(authz): wall course reads behind enrollment and ownershipAhmet Kaan Gümüş · ed007d9
✨ feat(authz): wall course reads behind enrollment and ownership
Students could read any roster, roll call, and event attendance; any
teacher could read any exam's results, statistics, live monitor,
answer sheets, and answer key (correct included), plus full
marks/attendance reports of any user.
- can_view_course = enrolled | creator | manager+; the /courses and
/exams catalogs filter per caller (list_created, list_for_courses)
- course sub-reads (roster, results, statistics, live, questions,
answer sheets) require course-management rights
- roll-call and event rosters become teacher+ views; students keep
/attendance/me and /marks/me
- /marks/{user} and /attendance/{user} narrow to the courses the
caller manages; manager+ still sees the full report✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam roomAhmet Kaan Gümüş · ade4fed
✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam room
- exam scheduling as one validated unit: mode sync|async + window
(+ per-student duration_ms for async); unscheduled stays offline-graded
- exam_attempt: one row per exam+user by composite id; start = attendance
signal, finish = submission; status/deadline recomputed from the current
schedule on every read (mode frozen once attempts exist, times extend live)
- teacher live monitor: GET /exams/{id}/live snapshot + SSE /live/stream
- exam_question: choice|text authored per exam, kind bundle (choices+correct)
validated as a unit, frozen once attempts start, ULID order
- exam_answer: upsert per question+user via composite id, kind-coherent,
server-clock stamped; pure auto_score over choice questions as a grading
suggestion — final mark stays human via /results
- student exam room WebSocket at /exams/{id}/attempt/ws: state ticks,
autosave acks, finish/expire lifecycle, gates rejected pre-upgrade with
proper HTTP statuses; shares the REST write path
- PersonRef embeds (id + username + display name) in people-bearing
responses, plus teacher+ GET /users/search
- cascades: exam/course deletes sweep attempts, questions, answers, results2026-07-11
✨ feat(courses): courses, enrollment, and course-scoped weighted examsAhmet Kaan Gümüş · cd56c5b
✨ feat(courses): courses, enrollment, and course-scoped weighted exams
Courses become the unit exams and enrollments hang off. Teachers create
them; editing, deleting, enrolling, and adding exams require course
management rights (creator, or manager/admin). Enrollment rows use a
deterministic composite (course, user) id, so enrolling is one atomic
idempotent UPSERT with no find-then-insert race. Deleting a course
cascades its exams, their results, and enrollments in one transaction.
Exams move inside a course (POST /courses/{id}/exams) and gain a weight
(1-100) that says how many times they count into the course average;
kinds grow to homework, quiz, midterm, final, project, and oral —
informational only, weight drives the math. Grading now demands course
management rights and an enrolled target; moving an exam between
courses is deliberately impossible so results can't be stranded.
Routes: courses CRUD, GET /courses/me for the caller's enrollments,
roster listing, enroll/unenroll, and per-course exam creation/listing.✨ feat(domain): validated newtypes and entity persistenceAhmet Kaan Gümüş · ba2b9b1
✨ feat(domain): validated newtypes and entity persistence Every value is a newtype constructed only after its validator passes (Username, Password, NoteTitle, Mark, ...), so an invalid value can't be represented. Each type derives SurrealValue, so one typed value flows unchanged from HTTP input into the SCHEMAFULL store, and each entity module owns its own persistence. - user/role: argon2-hashed passwords; four hierarchical roles (student < teacher < manager < admin) with at_least() checks. - session: an opaque random token, 7-day expiry, server-side lookup. - note: per-user notes. - event/attendance: events own attendance rows keyed by event+user; optional unix-millisecond starts_at/ends_at with ends >= starts. - exam/exam_result: homework|quiz exams; one 0-100 mark per exam+user in its own row, never on a note. - timestamp: the unix-millisecond instant shared across entities. Record ids are ULIDs — time-sortable and safe to expose.