Commits
2026-09-17
📝 docs: rewrite the Turkish comments and doc comments in EnglishAhmet Kaan Gümüş · 7fec874
📝 docs: rewrite the Turkish comments and doc comments in English The Rust repo's own language is English; Turkish had leaked in from the sibling AI services. Translate every comment and doc comment to English using the code's own vocabulary (şube -> class section, dönem -> term, sınıf öğretmeni -> homeroom teacher, ortak sınav -> shared exam, karne -> report card, …). Quoted Turkish letters/words that are themselves the data under test (the text-fold examples in `text_fold`/`settings`, the non-ASCII filename sample) are kept. The README endpoint table is generated from those doc comments, so it is regenerated. AGENTS.md records the convention going forward: Turkish survives only where it is the data under test or user-visible content.
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 courses, subjects, terms, enrollments, sessions, attendance to sqlx/PostgresAhmet Kaan Gümüş · f734c6aBrowse files
🗃️ feat: pub fn uuid(&self) accessor on all 34 Uuid id newtypesAhmet Kaan Gümüş · b3ab76fBrowse files
🗃️ fix: appointment.slot nullable ON DELETE SET NULL (dangling-ref booking contract)Ahmet Kaan Gümüş · d9b4e8eBrowse files
2026-09-11
🧹 chore: split subject and term into domain/db/service layersAhmet Kaan Gümüş · 6533a0a
🧹 chore: split subject and term into domain/db/service layers
domain/subject.rs keeps SubjectId/SubjectName/SubjectDescription/Subject + getters
and the pure validation tests; domain/term.rs keeps TermId/TermName/gone_error/
archived_error/ref_move/Term + getters.
db/subject.rs: create (cap::touch_and_create), read, list_by_ids, list_for_course,
update (FieldUpdate), delete (guarded transaction). db/term.rs: create, read,
list_all, update (ordered range guard), delete (refcount-guarded), archive,
unarchive, stamp. Persistence race tests ride along byte-identical.
service/subject.rs: pass-throughs + the moved id resolvers in_course/must_exist
(was web::subjects helpers). service/term.rs: pass-throughs + require_open
(was Term::require_open), resolve (was web::terms::resolve_term), require_writable
(the archived-refusal gate update/delete handlers inlined), delete's linked-409
mapping (was web::terms).
Web: subjects.rs/terms.rs handlers call service only; the archived gate stays
ordered before the range pre-flight by calling service::term::require_writable
between read and write. Callers re-pointed crate-wide: web/courses.rs,
web/classes.rs, web/homework.rs, web/exams/{mod,questions}.rs, web/bank_questions.rs,
db/{course,exam,exam_attempt,exam_question}.rs (tests + doc links),
service/{course,exam_attempt}.rs, domain/{class_group,bank_question,homework,
homework_file,homework_result,homework_submission}.rs (tests + doc links),
tests/regress_course_{child_orphans,delete}.rs.
Purity verdicts: domain/{timestamp,monotonic_id,text_fold,role}.rs have zero
production query execution (text_fold's only .query( is inside a #[cfg(test)]
folding test) — they stay domain-only, no db/service modules.
cargo check --all-targets 0 warnings; cargo test --lib 577 passed 0 failed;
integration: 13 subject/term/question/homework route tests green.2026-09-05
🗄️ feat: archive academic terms; an archived year is read-onlyAhmet Kaan Gümüş · c4232e6
🗄️ feat: archive academic terms; an archived year is read-only
`Term.archived_at` (nullable, no backfill) plus `POST /terms/{id}/archive`
and `POST /terms/{id}/unarchive` (manager+, idempotent: a repeat archive
keeps the original stamp). While a term is archived its own PATCH/DELETE,
linking a new course or class to it, and every write to a course or
class on it — enrollment, teacher assignment, class membership and
attach/detach/blueprint apply, sessions and roll call, subjects, exams
with their questions, images, attempts and answers, the exam-room
WebSocket door and `finish` frame, grading, homework and submissions,
course notes and files — answer `409` with `code: "term_archived"`.
Reads stay open. The guard is a pre-flight read of the term row: an
archive landing in the same instant as a write lets that one write
through (documented as the third accepted race).
Out of scope on purpose: personal notes, messages, pomodoro, meals,
payments, boards, appointments, chatbot, question pool/bank, events,
blueprint templates, the staff work log, and the role-demotion and
subject-delete integrity sweeps.
Coverage: 155 write routes classified (59 guarded, 93 out of scope);
e2e over real TCP covers archive → refused writes → open reads → the WS
handshake 409 → unarchive; the class refusal-code pin gains
`term_archived`; README prose, tag text and endpoint table regenerated.
Closes #22.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-08-01
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
fix: 🧩 a PATCH writes only the fields it was givenAhmet Kaan Gümüş · 85b408e
fix: 🧩 a PATCH writes only the fields it was given - every PATCH handler loaded the row and refilled the fields the request omitted from that stale snapshot, so two concurrent partial PATCHes touching different fields lost each other: whoever wrote last silently reverted a field it was never asked to change - field-scoping the write did not fix this — the value bound to the SET still came from a stale read - add domain/field_update.rs: .set(column, Option<T>) skips an absent field entirely, so it is neither written nor bound, and an all-absent PATCH writes nothing at all - convert notes, events, terms, homework, work entries and courses, each with a 20-round concurrent-PATCH regression that fails against the old code on round 0 and passes after - nullable columns stay clearable: an event's schedule, a course's capacity and term, and homework's assigned subset keep the double-option so an explicit null still writes NONE, while an omitted field is left alone - homework's old fallback was worse than a no-op: it could re-narrow the assigned subset over a concurrent widening, behind the guard that exists to stop exactly that - cross-field validation still reads the stored row where it must (event and term ranges need both ends) — read for the check, never written back - HOMEWORK_LOCK was taken after the row read, so it never covered the read-modify-write it looked like it guarded
fix: 🔒 drain the whole-row save backlogAhmet Kaan Gümüş · 19ba18a
fix: 🔒 drain the whole-row save backlog - a whole-row .content(self) reverts any write that landed between the struct's read and its save; the gate flagged 14 sites and this empties it - course.rs was the only genuinely raceable one, in both directions: teachers[] is written by assign, unassign and the demotion sweep while Course::update rewrites the text columns, so staffing a course reverted a concurrent rename and a rename dropped a concurrent assignment. Both reproduced as failing tests first - assign/unassign now use array::distinct(array::append(...)) and teachers -= $usr rather than rewriting the array from a stale read - session, event, note, term, homework and work-entry updates are each their row's only writer and rewrite every mutable field, so no failing interleaving exists today; converted defensively anyway, following Subject::update, and not test-proven - the five create/upsert sites are annotated instead: each builds its struct in place from the request and never reads it back
2026-07-22
✨ feat(deletes): guard course, exam-kind, and term removalAhmet Kaan Gümüş · 9191711
✨ feat(deletes): guard course, exam-kind, and term removal
Three referential-integrity guards, all 409 instead of silently taking
dependent data with them:
- DELETE /courses/{id} refuses while anyone is enrolled. The cascade
used to delete the enrollments along with the course, so a roster
could vanish on a misclick; the check and the delete are held under
ENROLL_LOCK so a concurrent enroll cannot slip in behind it.
- PATCH /settings refuses to drop an exam kind whose exams already
carry marks. Weights resolve live, so removing the kind would
re-weight every one of those marks to 1 without touching a row. The
check is re-run per CAS retry against the snapshot the save is
conditioned on, under an EXAM_LOCK writer lease so grading cannot
land the first mark mid-flight. An unmarked kind still leaves freely.
- DELETE /terms/{id} refuses while any course links it, rather than
unlinking those courses. Guarded by a new TERM_LOCK, taken by the
course writes that assign a term. Lock order: never held together
with ENROLL_LOCK; if a path ever needs both, ENROLL_LOCK first.
No rows change; existing courses with a roster and terms with linked
courses simply need emptying before deletion. Frontend must surface
the new 409 on all three.2026-07-13
✨ 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.