Commits
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
2026-09-11
🧹 chore: split exam_answer/exam_result/answer_image/question_image into domain/db/service layersAhmet Kaan Gümüş · 61990deBrowse files
🧹 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.2026-08-05
🖼️ fix: stop image slots orphaning rows and blobsAhmet Kaan Gümüş · 2eab9e2
🖼️ fix: stop image slots orphaning rows and blobs bank_question_image was the only child in its domain whose write moved nothing on its parent, and BankQuestion::delete was two round trips rather than one transaction. An upload whose body was still streaming when the template was deleted left a metadata row and a blob that no route could read or remove. Three more of one shape: store_image read the slot's current row to learn which blob to retire and then upserted, so two concurrent uploads both retired the same old blob and stranded the loser's new one. Fixed on the bank, exam-question and answer-image paths alike by reading the replaced name inside the write's own transaction — the shape PoolQuestion::set_image already used. delete_question no longer unlinks blobs from a pre-read snapshot; the delete returns the rows it actually swept, as Note::delete does. BankQuestion::update_if_unchanged moves to write_with_retry: the image upsert now writes the template row, so a raced PATCH would otherwise have started answering 500.
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-07-31
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-27
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-19
✨ 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)