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-24
🐛 fix(schedule): code-review findings on the holiday and section surfacesAhmet Kaan Gümüş · ecd544b
🐛 fix(schedule): code-review findings on the holiday and section surfaces A PATCH that moves a lesson onto an instant another lesson of the same section already starts at now answers the coded 409 session_time_taken instead of a 500 — the new UNIQUE (class_course, starts_at) was mapped on the create door only. The materialize route rejects an unrepresentable from/to (i64::MAX and friends) with a 400 naming the field, instead of panicking inside the day math; the guard is checked arithmetic over the largest offset the timezone allow-list can produce, and zoned_day's own contract is untouched. The profile course block withholds class, class_name and grade_level from a viewer who fails the same bar the classes block in the same response applies — a student could read another student's class name and grade through a shared catalogue course. visible_instances resolves the sections a teacher is assigned in with one statement instead of a query per taught course plus one per instance; every new per-section surface pays that read.
✨ feat(courses): per-section course lists behind the catalogue rowAhmet Kaan Gümüş · 6ecaebc
✨ feat(courses): per-section course lists behind the catalogue row `CourseSectionRef` and `CourseResponse.sections`: every catalogue row now carries its sections (instance id, resolved title, class, grade level, hours, teachers, roster size), truncated to `MAX_COURSE_SECTIONS` while `class_course_count` keeps the untruncated total. `list_courses`/`get_course` populate it through one batched builder — seven statements per page, nothing per row — and a non-manager sees only the sections they reach. `GET /courses/me` and the profile course block switch from catalogue rows to one row per section with the section's resolved title. Reach is the union of the class-roster/homeroom/taught set and the user's own instance enrollments, so a hand-placed enrollment keeps appearing exactly as it did before.
✨ feat(courses): grade-ladder course templates with per-class overridesAhmet Kaan Gümüş · 450bc8c
✨ feat(courses): grade-ladder course templates with per-class overrides course_offering per (course x grade_level 0..=12), per-class overrides on class_course (nullable scalars + *_inherited flags), subjects/weights/ weekly-plan axis tables, instance_resolve with batched twin, resolved title/description on instance-scoped reads, six new route groups, integration scenario test, README regenerated. Evolution migrations squashed into the base schema (20260912000002_courses + 20260916000001_k12_remodel). Local-Gate: 246daa3fb3ee7b0ff507a95d6ab346bab1333a37 (1556 passed, 455s)
2026-09-23
✨ feat(profile): add gender, address, and emergency contact to the user row Local-Gate: 1f2b0abcf3798a63b2c5365e0d15c9f708f45833 (1523 passed, 430s)Ahmet Kaan Gümüş · f151345
✨ feat(profile): add gender, address, and emergency contact to the user row Local-Gate: 1f2b0abcf3798a63b2c5365e0d15c9f708f45833 (1523 passed, 430s)
✨ feat: school identity is the uuid; drop the slugAhmet Kaan Gümüş · 2918040
✨ feat: school identity is the uuid; drop the slug
The school slug is gone from every surface: the session cookie prefix,
the /schools/{id} builder routes, FILES_PATH blob dirs, the hab/2 frame
school value, DTOs, and the /limits contract. SchoolId::try_parse is the
one wire parse (hyphenated uuid only); a non-uuid frame school answers
unknown_school. Register gets a public picker via the new unauthenticated
GET /auth/schools returning active [{id, name}]. The control migration
drops school_slug and the slug column, which invalidates every existing
session — old cookie prefixes cannot resolve.
Local-Gate: 3fafffd98aec59c68e2606833b87785d0abf2fee (1510 passed, 425s)2026-09-20
✨ feat(users): give students a school-issued student numberAhmet Kaan Gümüş · 777c7df
✨ feat(users): give students a school-issued student number
Every school numbers its students its own way ("1234", "9-B/17"), and the
account carried no field for it: the office kept the mapping outside the
product. The number is now a first-class optional field on the user row,
unique inside the school (per-school uniqueness is the per-school database)
and held by students only.
- migrations/school/20260920000001_student_number.sql: `app_user
.student_number TEXT NULL`, the partial unique index over its non-NULL
values, and a CHECK (student_number IS NULL OR role = 'student'). The boot
sweep applies the file to already-provisioned schools like every other
school migration.
- domain: `StudentNumber`, a validated newtype (trimmed, non-blank, at most
MAX_STUDENT_NUMBER_LEN = 32) in the shape of `Username`, plus the one
spelling of the non-student refusal both the web gate and the database map
answer; `User` carries `Option<StudentNumber>`.
- db: `create_with_role` binds it into the mint; `set_profile` writes it and
maps the index's 23505 to the coded 409 and the row's 23514 to the same 400
the handler gate answers; `set_role_cascade` clears it in the same statement
that leaves the `student` role. The CHECK is what closes the read-then-write
race the handler-side gate cannot see: a profile save carrying a number from
a `student` snapshot while a promotion commits first is refused by the row
itself, and a test pins exactly that (it writes a teacher holding a number
without the CHECK).
- web: `POST /users` and both profile doors (`PATCH /users/me`,
`PATCH /users/{id}/profile`) accept it under the merge semantics the other
patchable fields have (omitted = keep, blank = clear), with the role gate as
a 400 and a duplicate as a 409 carrying `code: student_number_taken`.
`UserResponse` (admin reads, create/patch echoes, `/auth/me`) and `PersonRef`
(pickers, students lists) carry it; the school-wide public profile
deliberately does not — an office identifier is not broadcast school-wide.
- /limits publishes `max_student_number_len`; spec_bounds pins both new
`max_length` annotations and the README's bound count moves to 224.
- tests: the mint and both patch doors — trimmed storage, 33 chars a 400,
whitespace read as absent, a duplicate a coded 409 on both paths, a
non-student a 400, blank clearing, a promotion clearing with the role change
(and a demotion back not restoring it), and the stale-snapshot race at the
db layer.
Evidence: the partial index refuses a duplicate (23505 naming
app_user_student_number) and admits both rows once dropped inside a
rolled-back transaction; with the 409 mapping removed both write paths answer
500 and the tests fail; with the CHECK removed the race test writes the
forbidden row (role: Teacher, student_number: Some(...)) and fails.
Local-Gate: 2c10aae51c575b7f4207fa310d8938070c0fbb80 (1509 passed, 572s)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.✨ feat: an empty user search lists everyone the caller may seeAhmet Kaan Gümüş · 6cf8640
✨ feat: an empty user search lists everyone the caller may see GET /users/search no longer refuses a blank `q`. Omitted, empty and whitespace-only are the same input now: each returns the caller's visible directory, which is what a receiver picker opens with — staff see the school, while a student or parent still see only the staff they may write to, and naming a role outside that set is still a 403. `role` still narrows, an unknown role is still a 400, and `limit`/`offset` bounds are unchanged. The store already treated a blank needle as "no clause"; this drops the web-layer guard that contradicted it and pins the behavior on both sides (blank == omitted == whitespace-only, and blank still narrowed below staff).
✨ feat: an admin mints a school account directlyAhmet Kaan Gümüş · 57de5b3
✨ feat: an admin mints a school account directly POST /users creates the person plus the school's app_user in one call, born with the role the caller names (student by default) — no self-registration and no register-then-promote two-step. Reuses the register credential rules: a username new everywhere mints the person, an existing person attaches only when the password matches (409 otherwise), a name already taken in the school is a 409, and the reserved staff-reading names are a 400.
2026-09-12
🚧 wip: class-pump/meals/homework production fixes + T5 test-port continuationAhmet Kaan Gümüş · 35683acBrowse files
🗃️ feat!: port identity+auth (user, session, profile, badge, settings, builder) to sqlx/PostgresAhmet Kaan Gümüş · 29cdff2
🗃️ feat!: port identity+auth (user, session, profile, badge, settings, builder) to sqlx/Postgres - db/user: static query_as! row mint (23505 on app_user_username -> 409), PagedList listings, position()-based fold search, role cascade as ONE tx_with_retry(cascade=true) closure (admin floor = guard on the role write itself; class/enrollment counts decrement in the delete CTEs; parent-seat sweep frees unfrozen lists via DELETE..USING; board close CAS + strip with post-image fan-out rows; appointment bookings cancelled then slots deleted under the new SET NULL link); avatar writers return the FOR UPDATE pre-image - service/user: ADMIN_FLOOR_LOCK deleted (floor rides the UPDATE's WHERE), would_orphan_admins deleted; set_role keeps the 404 pre-read - service/settings: SETTINGS_LOCK, Undo/restore deleted; retire/unretire + guarded save ride ONE transaction (stale save aborts via marker and retries); retire switch = cap.rs recipe (FOR UPDATE + ON CONFLICT..WHERE count=0); messages byte-identical - db/settings: load/save/save_if_unchanged as static macros; CAS is ONE guarded upsert (INSERT arm seeds defaults, ON CONFLICT WHERE IS NOT DISTINCT FROM per column) - db/badge: counter projection off app_user *_total columns; sync keeps the runtime N-statement exemption with ON CONFLICT..WHERE earned_at IS NULL - db/profile: one-row pomodoro aggregate (COALESCE sum, negative floor) - db/session, db/builder: static macros; builder_session keys now uuid v7 - domain/badge: fields crate-visible for macro construction - db/page: Param::Texts variant for ANY() text-array binds - web/users: avatar blob name mints via next_uuid; docs de-Surrealized - cfg(test) mods left for wave 3 (service/settings tests reference the deleted lock machinery; db tests reference init_mem) SQL semantics probe-verified on a scratch Postgres: CAS arms (insert/match/ stale/NULL), admin floor (demote/refuse/promote), retire switch (insert/ in-use-refused/unchanged/idempotent unretire), cascade CTEs (counts, frozen list kept, strip post-image, close first-stamp-wins), position() fold, badge stamp idempotency.
2026-09-11
Merge branch 'layer-split/class'Ahmet Kaan Gümüş · dc8a635
Merge branch 'layer-split/class' # Conflicts: # src/db/cap.rs # src/domain/class_group.rs # src/domain/event.rs # src/web/classes.rs # src/web/users.rs # tests/regress_role_sweep.rs
🧹 chore: split class_course/class_group/class_member/class_pump into domain/db/service layersAhmet Kaan Gümüş · b1261c7Browse files
2026-09-05
🔒 fix: exam presence, board hub and chatbot limiter keys are school-scopedAhmet Kaan Gümüş · 4f92fea
🔒 fix: exam presence, board hub and chatbot limiter keys are school-scoped In-process maps were keyed by bare record keys, which two schools' databases can now hand out identically. `state::scoped_key` is the only key constructor; the maps take the slug themselves so no caller can pass an unscoped key.
✨ feat: one database per school behind a control registry; login names the schoolAhmet Kaan Gümüş · b7dfc0c
✨ feat: one database per school behind a control registry; login names the school Namespace `hezarfen` now holds one DATABASE per school (name = slug) plus a `control` database with the school registry, builder accounts and builder sessions. `Tenants` keeps one separately-connected handle per school; the shadow `web::tenant_state::State` resolves the school from the `<slug>.<token>` cookie so every handler's `st.db` is school-scoped by construction. `POST /auth/login` / `register` carry `school`; a suspended school answers 403 everywhere. `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed the vendor account; the boot admin seed is gone. No customers, no compat shims.
✉️ feat: messages go upward only; students and parents can search staffAhmet Kaan Gümüş · 1d423c0
✉️ feat: messages go upward only; students and parents can search staff A student or parent may only write to a teacher, manager or admin (`Role::may_message`); staff still write to anyone. `POST /messages` answers 403 below that bar, and only new sends are gated — stored student↔student rows stay readable and filable. `GET /users/search` opens to every signed-in role: a caller below teacher sees only the staff they may message (the restriction sits in the query, so `total` stays right), and asking for `role=student` or `role=parent` from there is a 403. This is the recipient picker the messaging rule needs. Closes #23, closes #24.
2026-08-12
📝 fix: stop swagger offering the ai role as assignableAhmet Kaan Gümüş · b97b802
📝 fix: stop swagger offering the ai role as assignable
The `SetRole` body pointed at the response-side `Role` schema, which names
`ai` — the QUIC bridge's own service principal. Swagger UI therefore offered
`ai` in the try-it-out form for `PATCH /users/{id}/role`, where the server has
always answered 400: `Role::try_from_str` searches `ROLES`, the five human
roles. The "never assignable" note lived on the variant, and utoipa emits only
type-level doc comments, so nothing of it reached the document.
Request bodies now reference a documentation-only `AssignableRole` enum with
exactly those five; the response schema keeps `ai` (a service principal really
does read back as one) and carries the explanation where utoipa will emit it.
No server behavior changes — the string still funnels through
`Role::try_from_str`.
The user-search `?role=` param and the event role-audience DTO are plain
strings in the spec, so neither advertised `ai`; both are left alone.
`role_ai_is_unreachable_over_http` gains step 6, pinning the emitted enums so
the drift cannot come back.2026-08-05
🖍️ fix: close a whiteboard whose creator was demotedAhmet Kaan Gümüş · 26e7470
🖍️ fix: close a whiteboard whose creator was demoted A board's creator demoted to `parent` left a room nobody could command. The whiteboard is shut to that role outright, so the creator was answered 404 on their own board; clear, lock, close and delete are the creator's alone, so every other participant was answered 403; and `Board::list_for_user` is the crate's only enumeration, so no manager or admin could so much as find the id. Meanwhile the participants kept drawing (the room re-derives membership per frame and they still pass) into a board only the 50 000-stroke lifetime cap could ever retire — and `Board::delete`, the sole releaser of `board_count` and the sole deleter of `board_stroke`, was unreachable forever. The demotion now stamps `closed_at` on every board the account created, in `set_role`'s own transaction and with the same compare-and-set `Board::close` uses, so an already-closed board keeps its first stamp. Written before the roster strip, so the strip's `RETURN AFTER` carries the closed row the caller fans out — as a `closed` frame beside the `participants` one, which is what turns the open sockets read-only. Closed and not deleted: the marks are the other participants' work too, so the board, its history and its epochs stay readable and only writes are refused (`board_closed`, terminal). The cost is accepted — the creator's `board_count` seat stays taken, which is correct while the row it counts still exists, and the strokes stay on disk. The concurrent half needs nothing: `Board::create` claims the creator's own user row (`cap::claim_and_create` on `board_count`), the very record this transaction writes `role` on, so a board opened while the demotion runs collides in the store and one side re-sends — it cannot slip past the sweep.
👤 fix: show a person under the name they chose, everywhereAhmet Kaan Gümüş · 4e4a808
👤 fix: show a person under the name they chose, everywhere
`PersonRef::new` built `display_name` from `name` + `surname` only and never
read the stored `display_name`, so anybody who chose one was still rendered
under their legal name by every route that embeds a person — messages,
`/users/search`, course creator/teachers, rosters, exam results, appointments,
meals, payments, the question pool. Meanwhile `GET /users/{id}/profile` served
the chosen name, and `GET /users/{id}` is admin-only, so the profile was the
one surface telling the truth.
The rule was written twice: `ProfileResponse` did the three documented steps
(stored, else the join, else null) and borrowed only the join half from
`PersonRef`, which had the other half missing. Two hand-kept copies of one
documented rule is how it drifted, so the resolve now lives once, in
`PersonRef::new`; the profile calls it whole. The test that was missing is the
one that fails on drift: a display name differing from the join, asserted on a
`PersonRef` route and against the profile's own answer, at all three steps.
Second, unrelated to the resolve but on the same doc: `profile_of` claimed only
`stats.courses` and `stats.classes` cross a gate the reader would fail. Eight
more do — `pomodoro_focus_ms`, `pomodoro_focus_ms_total`,
`lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`,
`exam_sat_total`, `high_mark_total` mirror data behind `ensure_can_observe`,
and for an exactly-teacher reader they are wider than the reports themselves.
The disclosure stays (motivational counters, no object named); the comment,
the schema description, the tag and the README now say so accurately.📅 fix: withdraw the calendar a demotion used to leave unreachableAhmet Kaan Gümüş · e879fd3
📅 fix: withdraw the calendar a demotion used to leave unreachable `set_role`'s below-teacher arm dropped course staffing and the homeroom column and stopped there, so a demoted teacher's `appointment_slot` rows outlived the role that published them — and no route could reach them again: the teacher+ branch of `list_slots` lists the caller's OWN slots, so no manager ever learns the id; the below-teacher branch filters out slots whose owner is no longer staff, so neither students nor the demoted owner see them; and both slot deletes are `RequireTeacher`. One undeletable row per slot ever published, forever. A live booking on one was worse. `approve`/`reject`/`reschedule` go through `for_decision`, which needs `can_manage` AND `RequireTeacher`: the demoted owner fails the extractor, and the manager who would pass `can_manage` has no route that yields the id. The requester's `cancel` is refused once the window opens. So the booking sat `pending` in their list for good, pinning the slot's `occupied` at one — which also makes `delete_free`'s `(occupied ?? 0) = 0` guard unsatisfiable. The sweep now runs in the role write's own transaction, beside the other arms: live bookings are flipped to `cancelled` with the ex-teacher on `cancelled_by` and the reason on `cancel_reason`, then the slots go. Cancelled rather than deleted, deliberately. Deleting them is what the slot's own delete cascade does, but that path refuses while a booking is live — precisely because someone is expecting the meeting — and a demotion cannot refuse. This crate has no notification of any kind, so the strongest defined end available to a requester is a settled row they can still read, naming who dropped it and why; deleting it would make a confirmed meeting vanish with no trace at all. The slot goes either way, which is what releases the seat and keeps this convergent; the booking then renders without a window, the shape `AppointmentResponse` already documents for a vanished slot. The race is closed at both ends. A booking landing mid-demotion claims the slot row the sweep deletes, so the store settles it. A slot *published* mid-demotion shared no key with anything the demotion wrote and survived it, so `AppointmentSlot::create`/`publish_weekly` now claim the publisher's own record (`cap::role_claim`, the enrollment/registration pattern): either the sweep sees the slot, or the publish sees the new role and answers 403. Tests: the sweep and the refusal are unit-tested (both go RED on the reverted fix), and the publish-vs-demotion race is a real-server test held open with a DEFINE EVENT — 4/4 rounds strand a slot without the claim, 0/4 with it.
🎟️ fix: stop a profile handing out classes the reader is 403'd fromAhmet Kaan Gümüş · abe75ba
🎟️ fix: stop a profile handing out classes the reader is 403'd from
`profile_of` intersected only the *course* block with what the viewer may
already read; the class block was a bare `ClassMember::list_for_user`. So
`GET /users/{peer}/profile` handed any authenticated non-parent account — a
plain student sufficed — that peer's class ids, names and grades, while both
dedicated reads of exactly that data refuse: `GET /classes/{id}` is teacher+
and `GET /classes/user/{id}` is teacher-or-linked-parent. The module's own doc
comment claimed "nothing here crosses a gate the viewer would fail directly",
which was false for every class it served.
The direction is a product decision, taken deliberately: tighten the profile to
the class routes rather than loosen the class routes to the profile. The block
now runs through `ensure_can_observe`, the same predicate `/classes/user/{id}`
holds, and a viewer who fails it gets an empty `classes` array rather than a
403 — the rest of the profile is still public to them, and the response shape
does not move, so a client degrades instead of failing to parse. The gate is
all-or-nothing (there is no "the class we share"), so it drops the whole
window or none of it and no DB `LIMIT` ends up in front of a Rust filter.
`stats.classes` deliberately stays the owner's true total, like `stats.courses`
one paragraph above: the counters are motivational, a per-reader magnitude
would be meaningless, and a magnitude names no class. The doc comment now says
that instead of claiming the surface is clean of it.
Pinned in `regress_profile`: the peer's empty block asserted next to the 403 it
mirrors, the teacher/manager/parent/owner reads that prove the gate bites
rather than the read being broken, the true total, and a drift guard that
compares the profile's class block against `GET /classes/user/{id}` (or
`/classes/me` for the owner) reader by reader, so the two surfaces cannot
diverge silently again. Three of the four go red without the fix.
The frontend will lose class chips on peers a viewer cannot observe; the
backend defines the contract and the FE aligns.👤 fix: keep a school from losing its last adminAhmet Kaan Gümüş · bd9005e
👤 fix: keep a school from losing its last admin set_role blocked only self-demotion. Two admins each demoting the other resolved both RequireAdmin extractors before either transaction committed, so both writes landed and no admin remained — and ensure_admin refuses to promote an existing non-admin row on later boots, so recovery meant hand-run SurrealQL against the volume. ADMIN_FLOOR_LOCK now serializes every demotion with a last-admin check that asks the live rows, not a possibly-stale snapshot. The 409 is unreachable sequentially over HTTP — demoting an admin requires a second admin — which is why the guard lives in the writer. students_page listed parent links without re-reading the student side's live role, unlike every other reader. Stale links already on the volume go inert with no migration.
docs: 📝 make six doc surfaces say what the code now doesAhmet Kaan Gümüş · 2e0b57a
docs: 📝 make six doc surfaces say what the code now does The batch that gated `lessons_held_total` on the lesson having started, made un-grading refund both counters, taught `Course::delete` to prune blueprints, held both meal date bounds to the calendar and turned a half-configured TLS pair into a boot error moved only README. The utoipa annotations and the tag descriptions still carried the old rules, and one README bullet list stated two opposite decrement rules 24 lines apart.
2026-08-04
feat: 🎖️ earn badges on both sides of the classroomAhmet Kaan Gümüş · 46c76f5
feat: 🎖️ earn badges on both sides of the classroom Pass 2 gave badges only to students doing their own homework. Seven new families cover the rest of the school and the two shapes a plain tally could not express. Teachers earn `marks_given` (a grade recorded, once per pair — a regrade moves nothing), `lessons_held` (credited at the first roll call taken for a session, so a lesson scheduled and cancelled counts for nothing), and `pool_approved`. Students earn `pool_published`, `high_mark` (an exam mark at or above 90, once per sitting), `lessons_attended` (marked present or late at roll call, moved back down by a correction), and `study_streak` — the longest run of consecutive days finishing a pomodoro, read as a high-water mark so breaking it never takes the badge back. Days end at midnight UTC, like every other day calculation here. Both counters of the question pool skip a self-approval: a counter moves only when one person's work was judged by somebody else, which closes the ask-approve-delete farm on the staff side the way crediting at approval closes it on the student side. Every counter moves inside the transaction of the write that causes it. The streak needs two statements rather than one because sibling SET clauses read the row's before-state, so `longest` would lag `current` forever; the pair sits in one transaction, and `max` keeps it monotone under every interleaving, verified on a real 3.2.3 server. No backfill and no migration mark: every counter starts at zero at this deploy.
feat: 🏅 earn badges for the work already doneAhmet Kaan Gümüş · a00880e
feat: 🏅 earn badges for the work already done Thirteen badges a student earns by doing the work, so the profile has something to be proud of rather than just a photo and a bio. Nothing awards a badge by hand and nothing takes one away. A badge is earned when a counter crosses a threshold, and it is permanent: withdraw the submission that earned it and the count falls while the badge stays, because a stamped `earned_at` is the motivational payload and a badge that evaporates is worse than no badge. The catalog is hardcoded, so changing a threshold is a deploy and the evaluator stays a pure function of the counters. It rides GET /limits as a group like every other bound; labels and icons are the frontend's, keyed by badge id. The counters are the real work. Homework, exam and attempt tables are indexed for the questions the rest of the API asks, so counting a single student's history meant a full table scan — the numbers are therefore tallied at write time, in the same transaction as the write that causes them. Existing accounts are seeded once from their real history, gated by a mark whose skip is proven rather than assumed, so nobody starts at zero for work they already did. Withdrawing your own submission decrements, and that is the only decrement in the codebase: withdrawal is student-callable, so without it submit/delete/submit would farm the counter. Cascades never decrement — history a teacher erased is still history the student lived. The cost is that a re-run seed, which can only count rows that still exist, comes out lower than the live tally; documented where someone would otherwise "repair" it. Deadlines move, so the on-time verdict is now stored on the submission beside the count it fed. Judging it again at withdrawal read whatever the deadline had become since, which drifted the tally in both directions — far enough that on-time could exceed submitted. Attendance counters were dropped: those tables already carry per-user indexes, so there is no scan to fix, the status list is school-editable, and roll-call corrections would need a decrement that fights permanence.
feat: 🪪 give every person a public profileAhmet Kaan Gümüş · b326165
feat: 🪪 give every person a public profile Avatar, bio, display name, live class/course blocks and read-time stat counters, so the school has something to motivate students with. The fields ride the user row rather than a profile table: the row already carries the self-service columns and their field-scoped writers, so a separate table would only add a "profile row missing" state every read must degrade, plus a second write to the admin-seed path. DDL only, no backfill — every pre-existing row reads null, or 0 for derived stats. Contact fields stay off the public projection and keep their old gate. Reads are school-wide except for parents, who reach only their own profile and their currently-linked students'; the link and the target's live role are re-read per call, so a promoted-out student stops being readable at once. The courses block is intersected with what the viewer can already see, since a course title a caller is 403'd from reading directly must not leak through someone else's profile. stats.courses stays the owner's true total — an aggregate reveals magnitude, not identity — so a stranger sees an empty block beside a non-zero count. Classes stay a narrowed id/name/grade projection: a homeroom section is the social signal, a private club name is not. Stats are computed at read and floored at 0. Exam average, homework rate and attendance rate are deliberately absent: those tables are indexed such that a per-user aggregate is a full table scan. Avatars reuse the one-image-on-the-owning-row pattern and the school's existing max_file_bytes, raster only. Deleting one is admin-reachable because an offensive avatar is a real school problem and no user-delete route exists to fall back on. Also floors pomodoro focus time at both ends: a backwards clock could record a negative stint, which the profile would have served as a negative total. No badges yet — those are auto-earned only and land next.
2026-08-02
fix: 🔩 clear the deferred backlog and ship class phase 2Ahmet Kaan Gümüş · afff737
fix: 🔩 clear the deferred backlog and ship class phase 2 Ten defects and two features, worked as one series because the doc surfaces and the const table are shared. Defects closed: - Cross-exam answer-key leak. The bank copies `correct` into every instantiation, so reviewing exam A handed out the key to a question the caller was still writing in exam B. Review now blanks those questions rather than closing: the join matches on `from_bank` AND `banked_as` (a question can carry both — instantiated, then re-saved to the bank — so a coalesce misses a copy), redacting `correct`, the correctness flag and that question's `auto_score` share. Keyed on the template, never the exam, so the rest of the review reads normally. - `set_role` was not atomic with its sweeps. The role write and every grant it invalidates now commit as one transaction; the board rooms are told after COMMIT from the cascade's own result slot. Built best-of-N; the losing charter left the one sweep outside whose failure strands an event seat no route can free. - Board rosters held below-student ids, which 400d the creator's next roster PATCH. Repaired at boot, and a PATCH may now send back the roster it was served: an id already present that stopped qualifying is dropped, a new one still refused. - `note_file` blobs leaked. The delete transaction returns the rows it removed and the handler unlinks exactly those, not a pre-read snapshot. - Rate limiting failed open on a saturated map. Never-seen clients now share one metered overflow budget instead of arriving unmetered. - Whiteboards: `GET /boards` takes `?open=`, `/strokes` no longer leaks a clear marker the socket filters out, and a locked board refuses its creator's clear (409) — the lock now means one thing on every path. - Blueprint skips named the wrong record: `Attached::Gone` was two facts under one name, split into `Gone` (class) and `PivotGone` (course). Features: - Event audience `kind=class` — live from `class_member`, membership checked in one select because the (class, user) pair is the row id. - Grade blueprints: a grade's course template, retro-pumped best-effort with a skip list. Attachments carry a provenance tag, so removal spares what a human placed. A course deleted out from under a blueprint is pruned from the template by the pump that finds it. Forcing functions, because a hand-kept copy drifts: - `protected_routes_require_session` is derived from the emitted OpenAPI: 248 -> 254 operations swept, was 80 typed by hand. - Every JSON-bodied operation declares 422 (74 sites), pinned both ways — and multipart routes, which answer 400, are pinned to NOT declare it. - The SurrealQL registration-freeze guard is pinned against the Rust it copies; both mutations of it fail the test. - `migration_mark` gates one-time backfills. The roster repair rescanned every board against every user on every boot (773ms at 300/2000 with nothing to write); it is now skipped once done. Verified by a three-lens verifier panel — which caught the `banked_as` half of the answer-key leak by executing a probe, after the first fix had been reported complete — and by a podman boot against the existing volume: both new fields defined, the marker written, boot 2 skipping the scan, and the live API answering on the new routes.
feat: 🧑🏫 give a class section a homeroom teacher and open it to studentsAhmet Kaan Gümüş · e590b84
feat: 🧑🏫 give a class section a homeroom teacher and open it to students
Two gaps in the class-section layer, closed together because the
second is what makes the first worth storing: a section could name no
homeroom teacher, and a student could never learn which section they were
in — every /classes route was teacher+, so the layer was invisible to the
people inside it.
A section carries an optional `teacher`. The named account must be
teacher+, `null` and `""` both clear it, and an omitted field is left
alone rather than re-stated from the caller's snapshot. The column is
additive: rows written before it carry no key at all, which reads back
as null, so nothing is backfilled and no whole-row write coerces a
counter. A demotion clears the column everywhere — only teacher+ may
hold a section, and the sweep set_role already ran for course staffing
now runs for sections too.
Two reads sit outside the teacher+ bar. GET /classes/me serves any
authenticated caller their own section; GET /classes/user/{user} serves
teacher+ or a linked parent, through the same observer gate marks,
attendance and pomodoro use — which 403s before it 404s, so a parent
never gets an existence oracle.
Opening those reads meant the response could no longer carry `creator`.
A section's creator is always manager+, and below teacher+ that identity
was unreachable: GET /users is admin-only and /users/search is teacher+.
So `creator` is null for those callers and the join never even fetches
it, which keeps the response and the person map from drifting apart.
The role bar was a read-then-write with nothing between them. A demotion
landing in that window left the account homeroom teacher forever, since
its sweep had already run and matched nothing — and course assignment
had carried the same hole since it was written. Both now re-read the
live role after the write and undo the assignment with a 409. A create
that loses this way rolls the whole section back rather than leaving a
teacherless one standing, and the rollback releases the term reference
inside its own transaction, so no term is left undeletable. A rollback
the delete guard refuses is a 500, not a 409 whose text promises nothing
was created.
Every guard here is pinned by a test that fails when the guard is
removed, including the three race sites: a DEFINE EVENT on the table
being written fires inside the handler's own write, which is exactly the
window between the role check and the re-read. No production code knows
the seam exists.
Verified against the real volume: the migration applies to a database
whose section rows predate the column, those rows come back byte-identical
with every refcount intact, a second boot changes nothing, and both new
reads answer correctly on stored data.
The English prose calls this a class section throughout, keeping şube as
a parenthetical gloss — the word has a plain equivalent and the docs were
carrying the Turkish as though it did not.
Known and left: can_manage_course still trusts Course.creator without
re-reading the live role, so a demoted creator keeps course-management
reads — its own series. set_role writes the role before its sweeps and
they are not one transaction; every sweep is idempotent and grants
nothing, so a re-sent PATCH repairs the residue.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.
fix: 🔩 close the bug hunt across meals, classes and capsAhmet Kaan Gümüş · 7198cea
fix: 🔩 close the bug hunt across meals, classes and caps A three-domain hunt, its fixes, and a verifier panel that refuted two of them. Kept as one commit because the pieces interlock — cap.rs, the settings pair and the pump all move together, and no smaller cut compiles. Money can no longer be lost or stranded. Both seat transitions carry their ledger line inside their own transaction: the claim writes the charge, the flip writes the reversal. Before, a crash between the two left a seat held with no bill, or a bill with no seat, keyed to an attempt no later request could ever reach. A lost cancel could refund a live seat. The menu revision was bumped in a query of its own, so a booking reading in the gap claimed against a capacity or a price the menu had already left. Deleting a menu now takes its marks and its dishes with it, in the transaction that deletes the row. The id is deterministic on (date, slot), so anything left behind came back on the next publish — the kitchen reading "served" for a student who never came. A seat is always releasable: manager+ cancels any booking and is not bound by the cutoff, so a promoted student's seat no longer wedges its menu forever, and a debt that outlived its owner's role can be settled. Canteen money follows /payments and is manager+, not teacher+ — what a family owes the school is not classroom information. The class pump claims its pivot in-transaction. An attach racing a course delete used to commit a link to a row that was gone, and nothing could then detach it or delete the class. A hand enroll now disowns a pumped row, so a sweep cannot take back a roster decision an operator made by hand. The role sweep is one transaction. Rosters are ordered by when a student was added, which is what they always claimed. Both class axes have a ceiling, and each refuses on the other's, because a pump writes one row per member per course in a single transaction. Settings edits are serialized: retire is idempotent, so an undo log cannot tell the attempt that flipped a name from one that found it already flipped, and the loser un-retired what the winner had legally retired — leaving a kind gone from the list, gradable, and unremovable for good. Grading now checks the school's list, not only the counter. Three caps that read a snapshot integer now read the live column. A clear marker is charged to the board's lifetime counter and boot repairs the boards that predate it. Blank canvases refuse the clear, and the room reports that as its own code: the refusal text had drifted into the substring the WebSocket read as "closed", which told a live room it was permanently read-only. Verified against the real volume: both boot backfills, the slot-name rule and its grandfather clause, and the new money gate.
2026-08-01
2026-07-30
feat: 🎨 sync the accent color like theme and languageAhmet Kaan Gümüş · 9490623
feat: 🎨 sync the accent color like theme and language
The frontend's palette picker kept the chosen accent in localStorage, so
it never followed the user to another device. `palette_color` joins
`theme` and `language` as a third per-user preference: a nullable hex
color on the user row, self-managed and admin-editable through the same
two PATCH routes, `null` until chosen.
The value set is deliberately open — any `#rrggbb` — rather than an enum
of the frontend's palette entries, so adding a palette is a frontend-only
change. Mixed case is accepted and stored lowercase, which is why
`/limits` publishes the accept-set pattern (`^#[0-9a-fA-F]{6}$`) and not
the storage form: a client validating its own input against the published
regex has to agree with the server, and a test now compiles that regex
and runs it over the validator's own accept/reject examples.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-25
feat: 📐 publish every hard limit instead of making the frontend guessAhmet Kaan Gümüş · 7152aa9
feat: 📐 publish every hard limit instead of making the frontend guess
Every bound the API enforces lived in one of two places the frontend
could not read: a `pub const` in `constant.rs`, or English prose in a
doc comment ("1–20 entries", "`1`–`100`"). So the frontend kept its own
copy of each number, and the copies drifted the moment one moved.
Two surfaces now carry them, because clients consume them two ways.
`GET /limits` is one JSON document grouped by resource, built by naming
the constants directly — a runtime fetch, no codegen step, and it
carries what OpenAPI holds awkwardly (`reserved_usernames`, the raster
`image_content_types`, the closed role/kind/mode/status sets). The spec
gets the other half: 105 `max_length`/`minimum`/`min_items` bounds on the
request DTOs, which is what `openapi-typescript` and friends turn into
validators for free.
`/limits` is unauthenticated — the register form needs the username and
password bounds before a session exists, and none of it is secret, it is
the same rule a 400 already spells out. It is also exempt from the
database guard: it reads no row, and a frontend booting against a
reconnecting backend is exactly when it needs the contract, not a 503
that sends it back to the hard-coded copy.
Its `rate` group is the one part that is not compile-time. The
rate-limit tiers are env-tunable, so the endpoint reports this server's
live values off `AppState` rather than the shipped defaults — a client
should learn its budget here, not by collecting a 429.
`MAX_CHATBOT_THREAD_TITLE_LEN` moves to `constant.rs` on the way past.
It was private in `domain/chatbot_thread.rs`, reaching neither surface,
and its own comment asked to be moved the next time anyone was here.
Three tests keep both surfaces honest, because each is a hand-kept
mirror and a mirror nothing checks is one that goes stale. A constant
must reach `/limits` or an exclusion list that states why it does not; a
bound may not be declared outside `constant.rs` at all; and the emitted
spec is fetched and compared field by field against the constants —
never against literals, which would just be a third copy that passes
while both are wrong. That last one is unavoidable rather than
belt-and-braces: utoipa 5.5 takes a literal only, so
`max_length = MAX_NOTE_TITLE_LEN` does not compile.
Two duplicated `maximum = 500` literals are now pinned to
`MAX_PAGE_LIMIT`, which `constant.rs` previously only asked a human to
keep in step.fix: 🧩 finish the partial-PATCH sweep — 4 more handlers lost writesAhmet Kaan Gümüş · d773e7e
fix: 🧩 finish the partial-PATCH sweep — 4 more handlers lost writes 32bca26 routed six resources through `FieldUpdate` so a PATCH writes only the fields it was given. It stopped at six of ten. The remaining four still read the row unguarded and then wrote a field-scoped `SET` bound to that stale snapshot, so two concurrent PATCHes of different fields reverted each other, 200 OK, silently: - subjects and the two user routes (`apply_profile`/`apply_preferences`, four endpoints) move to `FieldUpdate`. No lock needed — neither has a cross-field check, so request-scoped values alone close it - course sessions get `SESSION_LOCK`, taken *before* the row read whenever `starts_at`/`ends_at` arrives, with the range merged and revalidated against the stored other end. The lock is not optional: converting to `FieldUpdate` without it re-introduces 9e25e0c, verified by disabling it and watching a one-ended PATCH store `starts_at > ends_at` with both requests answering 200 - bank questions instead take `BANK_LOCK.write()` before `owned_question`. This one is a genuine read-modify-write — the kind/choices/correct trio must merge from the stored row because choice ids carry the option pictures — so an exclusive lease over read+merge+write is the fix, the same shape as the exam PATCH. Per-field writes cannot express it - `subject.rs` also mints ids via `monotonic_id::next_ulid()` now, since subjects list `ORDER BY id ASC`; `bank_questions.rs` rustdoc stops calling a choice id a position Also verified safe and left alone: the exam and exam-question PATCHes already hold `EXAM_LOCK.write()` across read and write, settings uses a CAS retry, and messages/chatbot/questions/appointments write single fields. Each new suite races 20 rounds and reads the row back; every one fails if the stale refill is restored.
2026-07-21
✨ feat(courses): manager-assigned course teachersAhmet Kaan Gümüş · 5ff771b
✨ feat(courses): manager-assigned course teachers
A course used to have exactly one manager: its creator. A teacher taking
over someone else's class needed manager+, which is the wrong bar for
ordinary staffing.
Courses now carry a `teachers` list alongside the (still immutable)
`creator`. Manager+ assigns and unassigns via POST/DELETE
/courses/{id}/teachers; the assignee must already hold teacher+, since
every gate behind the assignment re-checks that bar anyway.
The rights split in two:
- can_manage_course: creator, assigned teacher, or manager+. Everything
inside the course — edit, enroll, exams, sessions, subjects, grading,
roll call. Every existing gate routes through this one helper, so
assignment reaches all of them at once.
- owns_course: creator or manager+ only. Deleting the course and changing
who teaches it. An assigned teacher runs a course; they don't own it,
and can't delete it out from under the person who made it.
Staffing is deliberately manager-only: a course's own creator cannot hand
management rights to their peers.
Stale data: rows written before the field decode as unassigned (a serde
default on the field) and the boot backfill fills them to []. DDL and
backfill stay in separate batches — sharing one silently strips keys on
SurrealDB 3. Verified against the real volume, not just the in-memory
tests: a legacy-shaped row backfilled, rendered, and took an assignment.
A demotion below teacher sweeps the user off every course they were
assigned to, mirroring how promotion drops enrollments.2026-07-19
🐛 fix: authz holes and stale-read races from the bug huntAhmet Kaan Gümüş · de938d8
🐛 fix: authz holes and stale-read races from the bug hunt - messages: a PATCH rejected on the folder no longer half-applies the read flag; the whole body validates before any write - messages: the delete-from-trash gate rides in the UPDATE's WHERE instead of a check-then-act window - notes: all nine handlers now require the student role — the read-only parent role could create notes and upload files (new RequireStudent) - reports: a parent link whose student side changed role is inert; ensure_can_observe re-reads the target's live role like enrollments - exams: update_exam takes the EXAM_LOCK writer lease before reading the row its merge defaults and draft/mode gates judge Re-link keeping one tie while linked_by moves to the latest linker is deliberate (matches re-enroll); doc reworded to say so.
✨ feat(users): read-only parent role with student tiesAhmet Kaan Gümüş · ec44315
✨ feat(users): read-only parent role with student ties
Parent sits below student in the hierarchy: clears no staff bar and
fails every exact student gate, so it can only observe. Admins tie
students to a parent under /users/{id}/students; the tie alone opens
the student's marks/attendance/pomodoro reports (full, unnarrowed)
plus the parent's own /users/me/students list. A role change off
either end of a tie sweeps it, mirroring the enrollment sweep.🐛 fix(users): blank search query lists the whole roleAhmet Kaan Gümüş · f658a4e
🐛 fix(users): blank search query lists the whole role /users/search?q=&role=student was a 400, but the frontend pickers use exactly that shape as their initial unfiltered listing. A blank q now skips the fragment clause, so blank + role lists everyone in that role (still ordered by username, still paged). Blank q without a role stays a 400 — an unscoped full dump was never a search.
2026-07-18
🐛 fix(users): drop enrollments when a user leaves the student roleAhmet Kaan Gümüş · 6917977
🐛 fix(users): drop enrollments when a user leaves the student role
Enrollment is student-only, but promotion left the rows behind: the
ex-student stayed on course rosters, inflated the live monitor's
enrolled/absent counts, and kept course view access. Security paths
always re-checked the live role — this is roster hygiene, not a hole.
PATCH /users/{id}/role to any non-student role now sweeps the target's
enrollments, and a boot backfill deletes rows already stale on disk
(including rows whose user record is gone: user.role = NONE).2026-07-16
✨ feat(users): per-user UI preferences (theme, language)Ahmet Kaan Gümüş · 7168ba0
✨ feat(users): per-user UI preferences (theme, language)
Theme (light/dark) and language (tr/en) live on the user row and
return on every user response. PATCH /users/me/preferences is
self-service for any role; PATCH /users/{id}/preferences is the
admin path. Same merge semantics as the profile patch: omitted
keeps, "" clears, anything else validates or the patch is a 400.
Null means "never chose": clients fall back to the device
preference (prefers-color-scheme, browser language), so there is
deliberately no server-side default to stomp device detection.
Pre-feature rows read back null through the option<string> columns
— no backfill needed.