forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/database.rsClear filter

2026-09-23

✨ 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

🐛 fix(tenant): the boot sweeps every school database to the school-schema headAhmet Kaan Gümüş · ee72900
🐛 fix(tenant): the boot sweeps every school database to the school-schema head

A school database is migrated exactly twice in its life — at mint (`bring_up`,
through the create path and the provisioning finish) and at boot (the
template, and now this sweep). Nothing else ever touches its schema: a re-dial
applies no migrations, and the boot's reconcile only reaches rows still marked
`provisioning`. A school minted before a migration landed therefore kept
yesterday's tables for good — which is how the live deployment answered

    relation "podcast_job" does not exist

on POST /podcast/jobs while the template already carried the podcast migration.

The missing half of the boot is now there: after the control database and the
template are ensured, every school database in the registry is dialled,
brought to the school-schema head and closed again. Nothing about a school no
request has reached is cached, so no pool for an unserved school survives the
sweep. The invariant it restores: **every school database in the control
database is at the school-schema head after boot.**

- Failure policy: one school failing never takes the boot down. It is logged
  at ERROR with its id and slug and left exactly as it stood — the sweep
  writes no registry row and no status, so a failed school is as usable (or
  unusable) as it was and the next boot retries it; sqlx's tracking table is
  what makes a retry of a half-applied migration safe.
- Observability: one INFO line per boot (`school schema sweep: N schools,
  M migrated`) plus one line per school, only when it actually applied
  something — the pending count comes off `_sqlx_migrations` before the
  migrator runs, so a school already at head costs one connection and no line.
- `migrate_school`, not the bare migrator: the chatbot/RAG interrupted-turn
  sweep is exactly as due on a school being swept as on one being minted.

The witness is in tests/persistence.rs: a school created through the normal
path, then rolled back to what an older head left behind — the table a later
migration created dropped and its `_sqlx_migrations` row deleted — reads
`relation "podcast_job" does not exist` before the sweep, and after it the
table is back, empty and recorded as applied, so the next boot is a no-op.
Every persistence test's second boot runs the sweep too (reboot()).
cargo check --all-targets and clippy -D warnings clean; persistence 11/11.
Local-Gate: 05ce93b5c478baa9a9ae80dd0bc8f99044a31f53 (1470 passed, 450s)
✨ feat: add the /rag nest over the course-note RAG bridgeAhmet Kaan Gümüş · a61e0a6
✨ feat: add the /rag nest over the course-note RAG bridge

A separate rag_thread/rag_message pair of tables and a Module::Chatbot gated
/rag nest, mirroring the chatbot's asynchronous send: POST answers 202 with a
pending assistant row, an in-process task settles it, and both the poll read
and the SSE stream project a stale pending row as failed.

Every question is scoped server-side to the asker's own (sinif, ders) pairs —
class-section instances, a linked parent's children, school-wide club/study memberships
— never from the body. Each citation's corpus doc_id is resolved per candidate
to a course-note file the asker may view, and the two storage caps refuse an
over-bound reply whole rather than clipping it. rag.index replies now stamp
each file's rag_doc_id, the missing link between a citation and its file.

The chatbot's SSE helpers move to web/mod.rs so both nests stream through one
implementation, and the instance/course visibility gates move from web to
service so the scope deriver and the routes share one rule.

Gates: cargo check --all-targets, clippy -D warnings, limits_completeness,
spec_bounds, doc_sync (README regenerated), protected_routes_require_session
(MIN_PROTECTED 269 -> 318, the real swept count), ai_bridge (75 tests).

2026-09-15

🆔 fix: one id convention — every id is a v7 uuid, none is a v4Ahmet Kaan Gümüş · d40e4c9
🆔 fix: one id convention — every id is a v7 uuid, none is a v4

The crate mints UUIDv7 from the process-wide monotonic generator, but four
sites still minted a v4:

- ChoiceId (an exam choice's stable id) and the blob names of answer
  images, bank-question images and homework files: now next_uuid(), like
  their siblings (question_image already was)
- test_suffix()'s 5-hex tail is not an id — it is the random half of a test
  database's name — so it draws from the OS rng: a v7's leading hex digits
  *are* the mint time, which is exactly what two processes minting in the
  same millisecond share
- the request-id layer installed tower-http's MakeRequestUuid (a v4); it
  now mints through the crate's own generator, same wire shape

The manifest drops uuid's v4 feature, and a guard test scans src/ so a
stray v4 fails the suite. (tower-http's request-id feature still enables
uuid/v4 in the dependency graph; nothing here calls it.)
🐛 fix: a school's registry row and its database are never one writeAhmet Kaan Gümüş · 8e58afe
🐛 fix: a school's registry row and its database are never one write

Three consequences of that one fact — partial states the code could leave
behind and nothing could repair.

**A school is `provisioning` until its schema exists** (new control
migration). The row commits before the database does (`CREATE DATABASE` cannot
join that transaction), so a boot cut short in between used to advertise a
school that answered every request with a `500`; the next boot's
`reconcile_provisioning` now finishes it. While it is being made, the school's
own doors refuse it (`403`) and the two builder routes that need its database
(`enter`, `admin-password`) answer `409` instead of a table-less 500.
`provisioning` is the boot's word alone — the PATCH parser still refuses it,
and a client can never ask for it.

**`Tenants::drop` dropped the database last**, after destroying the memberships
and the entitlements: a transient failure left a school that still stood with
every one of its people locked out and nothing able to put them back. The
database goes first (it is the half that can fail on its own — `DROP DATABASE`
cannot join a transaction either) and everything after it is one transaction,
so a failure leaves "database gone, registry rows intact", which re-running the
same call completes.

**`PATCH /schools/{slug}` wrote name and status as two statements**; a failure
between them left half a patch. Both fields are one statement now, with
`COALESCE` over the row being written — an omitted field keeps its stored value
and a concurrent patch of the other field cannot be reverted.

Local: cargo nextest run --no-fail-fast → 1375 passed. clippy clean.
Live: a seeded `provisioning` row comes back `active` with a 70-table database
and the boot logs the finish; lifecycle probe 200/400/201/204 on the running
server; 8-boot template race 8/8 up, 0 refusals; 4-boot race on a fresh control
database 4/4 up.
🐛 fix: idempotent school-template create across bootsAhmet Kaan Gümüş · 331ae93
🐛 fix: idempotent school-template create across boots

The boot template was created by an unconditional `CREATE DATABASE` whose
`already exists` refusal was swallowed, so every restart logged a server-side
`ERROR: database "…" already exists`. Worse, two boots racing on a missing
template killed each other: Postgres reports the *losing* create as
`23505 duplicate key value violates unique constraint
"pg_database_datname_index"`, never `42P04`, and the guard matched only
`42P04` (measured: four boots racing, three died).

`CREATE DATABASE` has no `IF NOT EXISTS` in Postgres (syntax error), so the
create now probes `pg_database` first, the swallow accepts both SQLSTATEs
(`is_database_exists`), and the boot's create-and-migrate runs under its own
advisory lock — the pattern the test harness already uses for its template.
`scripts/boot_race.sh` is the reproduction.

Local: cargo nextest run --no-fail-fast → 1373 passed. clippy clean.
N=8 bash scripts/boot_race.sh → 8/8 boots up, 0 create-refusal lines.

2026-09-14

✨ feat: compose-stack deploy plus in-tree schema workAhmet Kaan Gümüş · 57fad2c
✨ feat: compose-stack deploy plus in-tree schema work

Production deploy is podman compose (postgres + backend + openobserve)
instead of a systemd binary. CI stays a throwaway postgres sidecar.
Operator credentials live in ~/hezarfen_backend/hezarfen_backend.env
(0600); the deploy never writes that file.

Also lands the working-tree schema/junction and .sqlx updates that were
already sitting next to this change.

2026-09-13

🗃️ feat: VPS deploy workflow + exe-relative migrations + CORS anywhere modeAhmet Kaan Gümüş · b2780eb
🗃️ feat: VPS deploy workflow + exe-relative migrations + CORS anywhere mode

- .github/workflows/main.yml: im-style deploy on push to main — pinned
  ubuntu-24.04 runner, Postgres sidecar (max_connections=500) for the
  per-test-database suite, clippy -D warnings + full nextest gate,
  --release build under SQLX_OFFLINE, SSH release-dir swap + systemd user
  unit restart, /health gated on THIS build's process (MainPID exe) with
  rollback, independent after-the-fact verify.
- deploy/hezarfen.service: the shipped user unit; secrets and deployment
  knobs live in ~/hezarfen/hezarfen.env on the server (never in-repo).
- migrations_path: fall back to migrations/ beside the executable when the
  compile-time CARGO_MANIFEST_DIR path is absent — a deployed binary was
  looking for its schema on the build machine and aborting boot.
- CORS_ALLOWED_ORIGINS=*: anywhere-mode, every origin mirrored WITH
  credentials ("allow CORS to anywhere for now"); SameSite=Lax stays the
  cross-site guard. Default mirror mode unchanged; test pins star mode.

2026-09-12

2026-09-11

Merge branch 'layer-split/fee_attendance'Ahmet Kaan Gümüş · 08aa13e
Merge branch 'layer-split/fee_attendance'

# Conflicts:
#	src/db/mod.rs
#	src/domain/attendance.rs
#	src/domain/event.rs
#	src/domain/session_attendance.rs
#	src/service/mod.rs
#	src/web/payments.rs
#	src/web/sessions.rs
🧹 chore: split profile, badge, builder into domain/db/service layersAhmet Kaan Gümüş · 7f616c0
🧹 chore: split profile, badge, builder into domain/db/service layers

C3 identity lane. Moves, not rewrites:

- badge: BadgeStats::load / BadgeAward::list_for / sync (UPSERT with the
  earned_at = NONE idempotency stays whole) -> db::badge, with the
  award-key mint and the persistence tests; BadgeStat/BadgeStats/earned/
  BadgeAward (pure rules) stay in domain::badge; service::badge wraps
  list_for/sync for the web layer.
- profile: ProfileStats::load (+ PomodoroTotals, persistence tests) ->
  db::profile; newtypes + getters stay; service::profile::load wraps.
- builder: find_by_username/read/create(create_session)/find_by_token/
  delete_by_token -> db::builder; the idempotent seed ensure ->
  service::builder (ensure_admin precedent); both tests ride their fns.
- preferences, key: fully pure (validated newtypes, composite-id
  helpers) — stay domain-only, no db/service modules created.

Entity fields the split constructs from are now pub(crate) (Builder,
BuilderSession, ProfileStats), matching the user split.

Callers re-pointed crate-wide: web/{users,exams/mod,questions,homework,
sessions,auth,extractor,builder,tenant_state}, service/exam_attempt.rs
(badge::sync after start), database.rs (control seed), tests/
{builder_api,e2e,integration}; cross-lane compile fixups in
domain/pomodoro.rs and domain/session_attendance.rs (their lanes
re-point on merge). constant.rs doc link -> crate::db::badge::list_for.

2026-09-05

✨ feat: per-school modules; a disabled module answers 403 on every route in its nestAhmet Kaan Gümüş · 5d7f87c
✨ feat: per-school modules; a disabled module answers 403 on every route in its nest

Twenty-one modules, one per router nest, with an explicit dependency graph
derived from the record links (exams need courses and subjects, marks need
exams, …) and four packages for the catalog. The enabled set lives on the
school's control row and rides the tenant resolution that already happens
once per request; every nest carries a route_layer gate, the four child
creates inside /courses are gated by their own module, and the AI blob
stream refuses `module_disabled` when course notes are off.
✅ test: isolation probes across two schools; the builder seed is both-or-neitherAhmet Kaan Gümüş · 1b12ff7
✅ test: isolation probes across two schools; the builder seed is both-or-neither

Ten verifier probes: lists show only the caller's school, foreign ids 404 on
paths and are refused in bodies, school rows never reach the control
database, suspension closes login, live cookies and both WebSocket rooms
until resume, cookies cannot cross the builder/school line, uploads are
school-scoped, and two hyphenated schools stay apart on a real server.
✨ 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.

2026-08-05

🔏 fix: let a one-time migration block be corrected after it is markedAhmet Kaan Gümüş · cd6a00a
🔏 fix: let a one-time migration block be corrected after it is marked

`migration_mark` recorded only *that* a block had run, so its content froze
the moment any volume booted once: the `exam_sat_total` seed correction
shipped today inside the `profile_counters` block and would never have run on
a single existing database, leaving that counter holding the attempt count
while the live path credits sittings — and badge awards are permanent, so the
ones that fired early could not be taken back.

The mark now stores a fingerprint of the block's own SQL (FNV-1a over its
statements, comments and indentation dropped) and the gate compares it against
the text this binary would run. An edited block runs once more and re-stamps;
an unedited one still costs one record read. Nothing is hand-maintained — the
number comes from the very string the server executes, so there is no version
anyone must remember to bump — and blocks are discovered by their gate idiom,
with a test that fails for one written any other way.

A mark written before the column carries no fingerprint, so every existing
volume re-runs both blocks exactly once. Safe here: the board sweep is
idempotent and the counter seed's SETs are absolute. Its one ceiling — the
lifetime tallies whose rows can be deleted read *lower* on a recount — is
written into the block as a `ponytail:` with its upgrade path, because
correcting that block is a trade rather than a free edit.

Also stamps `exam_attempt.seq`, left out when its three sibling tables got
their backfill: `DEFAULT 1` fills a CREATE, and 3.2.3 neither synthesizes it
on read nor lets such a row be written again, so a sitting stored before
2026-07-24 would 500 on finish and on leave.

2026-08-04

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.

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.

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-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.
fix: 🧊 freeze a fee plan the moment it is assignedAhmet Kaan Gümüş · ac70cc0
fix: 🧊 freeze a fee plan the moment it is assigned

The 409 that stops an assigned plan being edited or deleted was a scan
followed, some microseconds later, by the write it licensed. An assign
landing in that gap left a plan edited and assigned, or deleted with a
live assignment still naming it. The comment called it an accepted race
and blamed the other replica; there was never another replica, and two
concurrent requests in one process were always enough.

A plan now carries an assignment refcount. The assign claims it in the
same transaction that writes the row, and the edit and the delete are
conditional writes that refuse while it stands. The plan freezes at the
instant of the claim, so the assign re-reads it afterwards and bills the
copy that froze — the refcount alone still let an edit slip in front and
bill the snapshot the handler had read.

Existing plans are seeded from the assignments they already carry. An
absent counter reads as zero, which is the value that licenses an edit,
so a plan assigned before this would otherwise have come unfrozen.

Two things this uncovered. A cap claim that lost a write conflict was
answered as a 500 five times in six: the retryable conflict shared the
error batch with the sibling statements it aborted, and an arbitrary one
of those was returned. And a guarded write had no retry at all, so a
raced PATCH or DELETE failed outright rather than trying again.

The race tests run against a real server. On the embedded engine they
watched a 45-in-50 failure rate and passed.
chore: 🧹 drop the coordination for replicas we never runAhmet Kaan Gümüş · a9cfe7b
chore: 🧹 drop the coordination for replicas we never run

The backend runs as one process against one database, deployed
stop-the-world. The machinery that let several of them agree was built
ahead of a multi-replica rollout that stayed parked, so none of it was
ever load-bearing: the boot lease elected a leader out of a field of
one, the ai_worker table announced a worker to nobody, and the chat
claim queue only ever claimed its own writes.

Boot now migrates and seeds straight-line; a chat turn is dispatched by
the handler that accepted it; the 503 gate reads the in-process
registry. The retired columns and tables are unset and removed in
separate batches, repair before REMOVE.

What stays, with its reason corrected rather than removed: cap.rs,
field_update.rs, the refcounts, the CAS retry loops and the in-process
locks. Those close write skew between concurrent requests inside one
process, which two replicas made worse but never caused.

A turn orphaned by a restart or a panic is no longer reclaimed. It
settles as timed_out within CHATBOT_PENDING_STALE_SECS.

The design survives in the ledger if a second process is ever wanted.

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

feat: 🗳️ elect the boot, and make a chat turn a claimed jobAhmet Kaan Gümüş · 0787b14
feat: 🗳️ elect the boot, and make a chat turn a claimed job

Two things assumed there was only ever one process. Both stop assuming it,
and both pay off on a single replica today, where a rolling restart already
overlaps two containers.

**The boot is elected.** Every process ran the whole migration, backfill and
admin seed on startup, so two overlapping ones raced all three. A process now
claims `migration_lock:boot` with a deterministic-id CREATE, renews a lease
while it works, and stamps a sha256 of the SQL it applied; the others wait for
that stamp and only trust it when the fingerprint is their own, so a new binary
never serves on the previous one's schema. A leader that loses its lease fails
its boot rather than reporting a success it no longer owns, and an abandoned
lock is taken over once the lease lapses.

Seeding the admin was two writes — create as a student, then promote — and a
process killed between them left a student holding ADMIN_USERNAME that no later
boot would ever promote, because nothing can tell that row from a stranger who
registered the name. The role is now minted with the row.

**A chat turn is a claimed job.** The answer used to ride on a `tokio::spawn`
belonging to whichever process took the POST, so a restart orphaned it and the
turn only settled at the stale horizon. The POST now just writes the pending
row; a replica holding a `chat.reply` worker claims it with a conditional
update and answers over its own socket. A claim left behind by a dead process
expires and is retried, and a configured AI timeout is capped below that
horizon so a slow inference is never reclaimed out from under itself.

The gate and the dispatcher are deliberately separate: `ai_worker` is a
heartbeated table that only answers "could anything, anywhere, serve this",
may be stale, and never guards a write; the in-process registry owns the
socket and is the only thing that decides who dispatches.

hab/1 is untouched. Verified on two live replicas against one SurrealDB: a
turn posted to a worker-less replica was answered by its peer, survived a
restart of the other replica mid-flight, and was dispatched exactly once.
fix: 🕰️ stop the boot sweep from killing chat turns still being answeredAhmet Kaan Gümüş · f77d48a
fix: 🕰️ stop the boot sweep from killing chat turns still being answered

The migration failed every `pending` chatbot_message on startup, so any
deploy or restart shot down answers that were dispatched seconds earlier
and whose AI worker was still on the other end of the bridge.

The sweep now only claims rows past `CHATBOT_PENDING_STALE_SECS`, bound
into the statement so the constant stays the single source of truth. A
younger row is left alone: the reader already presents an over-age
`pending` as failed, and the next boot sweeps for real whatever crossed
the horizon meanwhile.
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: 🗃️ backfill the rows the choice-identity retype left unwritableAhmet Kaan Gümüş · b005e15
fix: 🗃️ backfill the rows the choice-identity retype left unwritable

dde4896 retyped fields but shipped no backfill, so every row written
before it survived the DDL unchanged and then failed on the next write:

  Couldn't coerce value for field `choices` of `exam_question:q1`:
  Expected `none | array<object>` but found `['3','4','5']`

- convert `exam_question`/`bank_question` `choices` from `array<string>`
  to id-carrying objects, minting one id per position, and remap
  `correct`, `question_image.slot`, `bank_question_image.slot` and
  `exam_answer.selected` from the old integer index to the id minted at
  that same position — a student's stored answer keeps resolving to the
  option they actually saw
- f90014b's `source_bank` needed `UNSET` before `REMOVE FIELD` takes it
  away, so that repair runs as its own PRE_REPAIR query ahead of the DDL
  batch; it is guarded by `IF 'exam_question' IN
  object::keys((INFO FOR DB).tables)` because `UPDATE` on an undefined
  table errors rather than returning empty on a fresh database
- the conversion has to precede the `seq = 1` stamps and set
  `seq = seq ?? 1` itself: a legacy `exam_answer` lacks `seq` *and* has
  an int `selected`, and a write coerces the whole record, so either fix
  alone fails on the other and the whole loop rolled back
- every statement is shape-guarded, so re-running on a converted row is
  a no-op and no id is ever re-minted

Proven on a scratch surrealkv db with these consts: old-shaped rows read
back converted, previously-failing writes succeed, index 2 still
resolves to "5", and a second boot changes nothing.
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
  identity

2026-07-24

✨ feat(exams): add a reusable school-wide question bankAhmet Kaan Gümüş · 8b07cfa
✨ feat(exams): add a reusable school-wide question bank

Teachers weld a question to one exam today, so reusing it next year means
retyping. This adds a bank of question templates that copy into an exam on
demand: a fresh exam question with its own id, images, and answers, so the
copy never shares state with the template (a bank edit can't rewrite a
graded exam). Bank rows carry no exam tie and never freeze.

Reads and instantiate are school-wide (any teacher+); editing or deleting
a template needs ownership (admins aside). A template's subject is origin
metadata only — the same-course rule is checked at instantiate time
against the target exam's course. Both directions exist: author in the
bank, or save an existing exam question back into it.

Routes: CRUD + image slots under /bank-questions, plus
/exams/{id}/questions/from-bank/{bid} (instantiate) and
/exams/{id}/questions/{qid}/to-bank (save). Blob copies are all-or-nothing
and roll back on failure; a subject delete is guarded against live
templates, and bank writes serialize against it under BANK_LOCK. Copies
record provenance (source_bank / source_exam).
✨ feat(appointments): record who cancelled or rejected and whyAhmet Kaan Gümüş · 5d48a8d
✨ feat(appointments): record who cancelled or rejected and why

Reject and cancel now take an optional free-text reason and stamp the
actor: bookings gain cancelled_by, cancel_reason, and reject_reason, all
#[surreal(default)] so rows written before these existed still read back
as None. The reason is validated (400 if over-long) before it touches the
row; a blank or absent one records nothing. AppointmentResponse exposes
the new fields, and decline_reschedule cancels with no reason.
✨ feat(exams): let students review their own graded examAhmet Kaan Gümüş · 4db4ff2
✨ feat(exams): let students review their own graded exam

Add a per-exam teacher toggle `allow_review` (default false, opt-in,
mirrors `allow_rejoin`) and three student self-review endpoints:

  GET /exams/{id}/review/attempts
  GET /exams/{id}/review/attempts/{seq}/answers
  GET /exams/{id}/review/attempts/{seq}/answers/{qid}/image

All are CurrentUser-scoped (no {user} param, so a student only ever
sees their own data) and gated by reviewable_exam(): 404 on missing or
draft exam, 403 when allow_review is off, 404 until an ExamResult row
exists for that student (proves the teacher marked them). Readers are
the same ones the teacher history endpoints use.

Schema: DEFINE FIELD allow_review DEFAULT false + a separate backfill
query flipping legacy NONE rows to false — no existing exam auto-exposes
answer sheets. Podman-verified: 9 legacy rows migrated null->false.

2026-07-23

✨ feat(exams): keep every attempt's answers, drawings, and markAhmet Kaan Gümüş · 3668684
✨ feat(exams): keep every attempt's answers, drawings, and mark

Retakes wiped the prior sitting's answer sheet and overwrote the single
mark row, so a re-sit erased any record of how the student did before.
Teachers need that history to understand a student.

Each sitting now keeps its own rows, keyed by the attempt `seq` (in the
record id + a denormalized field). `seq==1` maps to the old bare key, so
existing rows need no migration beyond a `seq=1` backfill; the unique
indexes move to include `seq`. The retake answer/image wipe and the
per-retake blob GC are gone.

Grade-of-record stays the latest sitting: roster, report, and by-user
reads return the newest `seq`. Prior sittings are read-only, exposed to
course managers via new history endpoints:
  GET /exams/{id}/students/{user}/attempts
  GET /exams/{id}/students/{user}/attempts/{seq}/answers
  GET /exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image
  GET /exams/{id}/students/{user}/marks
Live reads (autosave, exam-room WS, monitor) scope to the current seq.
🎨 style(chatbot): rename thread/message off the mail collisionAhmet Kaan Gümüş · 92b232b
🎨 style(chatbot): rename thread/message off the mail collision

The AI chatbot's storage and web layer reused "conversation" and
"chat_message", the latter one underscore away from the human-to-human
mail `message` feature — every reader had to disambiguate two unrelated
tables by eye.

Rename the whole chatbot feature to a `chatbot_*` vocabulary:

  conversation  -> chatbot_thread    (ChatbotThread*, CHATBOT_THREAD_*)
  chat_message  -> chatbot_message   (ChatbotMessage*, CHATBOT_MESSAGE_*)
  /chat/conversations -> /chatbot/threads
  max_chat_conversations -> max_chatbot_threads
  max_chat_message_len   -> max_chatbot_message_len
  chat_history_turns     -> chatbot_history_turns
  RATE_LIMIT_CHAT_PER_MINUTE -> RATE_LIMIT_CHATBOT_PER_MINUTE
  DTO conversation_id -> thread_id

The out-of-process AI-service wire contract is deliberately untouched:
ai/chat.rs payload types, AI_CHAT_CAPABILITY ("chat.reply"), the serde
field names and the hab/1 ALPN stay as-is — other-language services
match on those literals. ai/chat.rs remains "the chat.reply payloads",
a separate concern from the chatbot feature it feeds.

Clean break, no row migration (pre-customer, FE not yet synced): old
conversation/chat_message rows in the volume are abandoned. Frontend
must adopt the new routes, the thread_id field, and the renamed
settings keys.
✨ feat(appointments): teachers publish slots, students book themAhmet Kaan Gümüş · 771936e
✨ feat(appointments): teachers publish slots, students book them

Teachers keep a calendar of availability windows; students and parents
book one with a reason. Publishing a window is not consent to a specific
person and topic, so a booking lands pending until the teacher approves,
rejects, or counter-proposes another time — a counter-proposal returns it
to pending for the requester to accept or decline.

A slot holds one live booking, with occupancy derived under
APPOINTMENT_LOCK rather than stored, so rejecting or cancelling frees the
slot for someone else. No two approved meetings may overlap for the
teacher or the requester.

Cancelling refuses a meeting whose window has opened, so every path that
could land a booking on a past window is closed at the source: booking a
started slot, approving a started window, and proposing a started time
all refuse. Otherwise a booking could exist that nobody was able to
cancel.

Weekly repetition expands eagerly into concrete rows sharing a series id,
capped at 52, so cancelling one occurrence is an ordinary delete.
✨ feat(messages): remember where a filed copy came fromAhmet Kaan Gümüş · 79189b8
✨ feat(messages): remember where a filed copy came from

Archiving or trashing a copy stamps the folder it left onto that side's
origin field, exposed as `previous_folder`, so restoring puts it back
where it came from instead of always in the inbox.

The trash is never stamped — pulling a copy out of it must not leave the
copy pointing back at the discard pile — and a no-op move keeps the stamp
it had. `null` means "restore to the home folder", which is also how rows
filed before the field existed read (option columns, no backfill).

Folder names become a `Folder` enum: the DB columns, the list filter and
the stamp all pass through it, so the stale string arrays are gone and a
typo is a compile error rather than a silently empty folder.
✨ feat(chat): relay chatbot over the AI bridgeAhmet Kaan Gümüş · b0aa0a1
✨ feat(chat): relay chatbot over the AI bridge

The backend relays between the frontend and an out-of-process AI service:
it owns auth, rate limiting, persistence and payload format, and may
inspect an answer before the frontend sees it. No rule or intent tables —
conversation is free-form.

Two-phase by design. POST persists the pending assistant row *before*
dispatching, then returns 202, so a reload never loses an answer; the
client either polls the message or opens an SSE stream. Both read the
same DTO, so they cannot disagree. Deltas are sliced from the finished
text because hab/1 is unary — the event shape exists so real streaming
drops in later without a client change.

A turn always settles. Every failure after the rows are written marks the
row failed with a machine-readable code, a boot sweep flips rows orphaned
by a restart, and a pending row older than five minutes reads as timed
out — projected at read, never written back, so a slow-but-alive answer
is not raced. An over-long answer is clipped and flagged rather than
dropped; an empty one fails.

Message ids come from a monotonic ULID generator: the two rows one POST
writes share a millisecond routinely, and a random tie-break rendered the
answer above its own question and handed the service [assistant, user],
breaking the documented oldest-first history contract.

The conversation cap counts and creates under a lock — SurrealDB
BEGIN/COMMIT does not serialize cross-record counts, and 16 concurrent
creators over-admitted a cap of 5 to 20 without it.

Every authenticated role may chat, parents included. Foreign threads are
404, never 403.

2026-07-22

2026-07-21

feat: 🎨 student answer-image endpoints mirroring question imagesAhmet Kaan Gümüş · 2c83c6f
feat: 🎨 student answer-image endpoints mirroring question images

- new AnswerImage domain keyed by (exam, user, question), stored as an
  image/png blob with upsert-overwrite, mirroring QuestionImage
- routes: POST/DELETE/GET /exams/{id}/attempt/answers/{qid}/image (student
  own, gated by the save_answer writable-attempt chain) and GET
  /exams/{id}/attempts/{user}/answers/{qid}/image (teacher grading)
- answer_image (Option<ImageMetaResponse>) on the student sitting view and
  the teacher grading sheet; live monitor and exam_ws untouched
- a drawing-only answer creates a blank text answer row so the drawing
  surfaces in both views; removing the drawing grooms that blank row away
- cascade blobs+rows on exam delete, course delete, and retake wipe (rows
  in the wipe transaction, blobs swept in start_attempt)
- integration tests: raster wall, own/teacher auth walls, upsert, retake +
  exam-delete cascade, drawing-only surfacing and its cleanup
🐛 fix(db): share one session, stop cloning the handle per requestAhmet Kaan Gümüş · 11fa250
🐛 fix(db): share one session, stop cloning the handle per request

The database was never reconnecting. `Surreal`'s own `Clone` mints a fresh
server-side session — `Uuid::new_v4()` plus a fire-and-forget
`SessionId::Clone` to the router (SDK lib.rs:340) — and axum clones the
application state on every request, so `db: Surreal<Any>` in `AppState`
meant a new session, and a matching `SessionId::Drop`, per request served.

Under concurrency those lifecycle events race the queries riding on them.
Sessions vanish outright ("Session not found", surfaced as a 500), and a
session whose signin has not been replayed yet answers "Anonymous access
not allowed" / "Specify a namespace" — the exact strings
`is_session_replay_error` attributes to a post-reconnect replay. So the
failures were reported as a transient reconnect and a retryable 503, which
is why the field logs showed sporadic 503s while the keepalive pinged `ok`
every 5s without a single miss. A healthy socket the whole time.

`Arc<Surreal<Any>>` shares the one session established at boot; cloning the
state is now a refcount bump. `Deref` covers all 175 call sites unchanged.

Same storm, 200 logins at 40 parallel, before → after:
  23×200 / 16×500 / 161×503  →  200×200, zero "Session not found"
600 at 80 parallel also clean.

The classifier is left alone: with the churn gone those two strings can
only come from a real post-reconnect replay, which is what it was for.
✨ 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.
🐛 fix(db): retry boot connect, refuse while socket downAhmet Kaan Gümüş · bebca49
🐛 fix(db): retry boot connect, refuse while socket down

Two failures survived 6627128, which only classified errors from queries
in flight *at* the drop — queries arriving after it produce no error at
all, so there was nothing to classify.

Boot did one connect() and exited on refusal. The runtime then restarted
the process, it failed again in ~100ms, and a few seconds of startup skew
burned the whole restart budget: 6 deaths in 0.6s in the field log, then
down for 12h. Now retries 1s doubling to 5s, forever — only the dial,
since bad credentials never heal by waiting.

A query issued while the socket is down does not fail. The SDK's
router_reconnect loops on 1s retries and stops draining route_rx, so the
query parks until the database returns and only then executes. Reproduced:
POST /auth/login gave no response at 25s, and the keepalive went silent
4m17s before firing two pings in the same millisecond on heal.

Those two pings rule out a plain timeout middleware — a parked query still
runs, so a timeout-sourced 503 would let a client retry double-apply a
mark or an exam answer. Instead the keepalive (now 5s) publishes DbHealth
and db_guard refuses at the edge, before anything is queued, which is what
keeps Retry-After: 1 honest. The 30s request timeout is only a backstop
for requests racing detection; those answer DbTimeout — same 503, no
Retry-After, "may or may not have applied". WS and SSE are unaffected:
both return their response immediately and stream afterwards.

Known gap: exam_ws socket-loop queries run after the upgrade response, so
db_guard does not cover them; they still park and heal on reconnect.

Verified in podman against the existing volume: boot with the database
down backs off and stays alive, requests during an outage answer 503 in
0.3ms, recovery needs no restart.
✨ feat(questions): student Q&A pool with moderated solutionsAhmet Kaan Gümüş · 0df048b
✨ feat(questions): student Q&A pool with moderated solutions

Students ask (one photo, pending-only edits), teacher+ approve into a
school-wide pool — approval freezes content so nothing unmoderated
slips in after review; rejection is deletion, no rejected state.
Anyone above parent offers solutions: text + one photo, author-edited
anytime (unmoderated), delete-only moderation. Question rows carry
solution_count; deletes cascade solutions and image blobs (zero
orphans). Question and solution photos reuse the exam-image raster
allowlist and size cap via serve helpers shared out of exams.
✨ feat(db)!: swap embedded surrealkv for a SurrealDB serverAhmet Kaan Gümüş · 60b4509
✨ feat(db)!: swap embedded surrealkv for a SurrealDB server

BREAKING CHANGE: the backend no longer opens a database file. DB_PATH
is gone; DB_URL/DB_USER/DB_PASS point at a SurrealDB server over
WebSocket (compose ships one on surrealkv storage in its own volume,
backend waits on its healthcheck). Pre-switch data was wiped on
purpose — fresh volumes seed from scratch. Tests keep the in-memory
engine; persistence.rs re-runs the boot migration on a live handle
instead of reopening a file.