forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/web/exam_ws.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-16

✨ feat: the class×course instance is the academic anchor (K-12 remodel)Ahmet Kaan Gümüş · ae84034
✨ feat: the class×course instance is the academic anchor (K-12 remodel)

`course` was a school-wide singleton: enrollment, exams, sessions,
roll-call and homework all keyed on it, so two class sections teaching the same
course shared one roster, one exam set and one timetable. This moves the
academic anchor to `class_course` — the per-class instance — and rebuilds
the academic model around Turkish K-12.

Schema (migrations/school/20260916000001_k12_remodel.sql): `class_course`
becomes an instance (ders_saati, counts_toward_karne, enrollment_count,
class_course_teacher); enrollment re-keys to (class_course, app_user);
exam carries class_course + term (+ exam_audience for shared exams);
course_session / session_attendance / homework re-key; `class_member` is a
soft-leave history table (uuid PK, joined_at/left_at, partial unique index
on the live stint); `academic_year` sits above `term`; `class_group` links
a year, not a term; new `course_membership` (clubs/study), `karne_snapshot`;
settings gain branches/excuse_kinds/absence limits/timezone; profile gains
branch. Drops/recreates the identity-changing tables (pre-customer; the
migration resets every counter on a kept table that pointed at a dropped
one).

Layers: domain/db/service/web rewritten to the instance seam, with
`ensure_instance_teacher` gating instance writes (D10), the report card computed per
instance and weighted by ders_saati, an absence report, `/instances`
and `/academic-years` nests, and `/classes/{id}/instances`. Capacity and
the seat-claim 409 are gone; detach sweeps the whole instance subtree and
unlinks its blob keys.

Gates: cargo check --all-targets, SQLX_OFFLINE check (cache regenerated),
doc_sync, spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1370/1370.

2026-09-12

🗃️ feat!: port exams domain to sqlx/PostgresAhmet Kaan Gümüş · 381e16c
🗃️ feat!: port exams domain to sqlx/Postgres

- db/{exam,exam_question,exam_attempt,exam_answer,exam_result,question_image,answer_image}:
  SurrealQL -> static query!/query_as! (PagedList exemption kept for
  exam_question listing); composite natural PKs (exam,user,seq) everywhere;
  sitting scoping via key.rs wire helpers unchanged.
- Freeze gate: write_unfrozen/IndexedResults/FROZEN_SLOT deleted; freeze is
  a shared in-tx freeze_gate() (exam row FOR UPDATE + EXISTS(attempts)) run
  inside each question/image write's own tx_with_retry.
- EXAM_LOCK deleted: sitting create re-judges sittable/window gates on the
  locked exam row (guard_start) then claims exam_sat_total in one CTE;
  exam delete locks the exam row before its ordered cascade and collects
  blob keys inside the tx; answer/answer-image saves lock the exam row
  ahead of their upserts (bump-and-restore touch tricks deleted).
- PRESENCE_LOCK deleted: join = unconditional left_at clear; last-out =
  single conditional stamp_left_if_running (left_at IS NULL AND
  finished_at IS NULL AND live-schedule in-progress); ExamPresence map
  mutex stays for counts.
- Grade tx: exam row FOR UPDATE, draft gate in-tx, kind_ref claim
  (retired=false), 4-counter first-vs-regrade precedence preserved exactly;
  remove() refunds via data-modifying CTE.
- THROW markers -> early returns: exam_redraft, questions_frozen, no_exam,
  question_subject_gone, question_row_gone, question_stale_move,
  exam_missing, exam_draft, kind_retired.
- cfg(test) mods left for wave 3.

2026-09-11

Merge branch 'layer-split/exam'Ahmet Kaan Gümüş · e0fb40e
Merge branch 'layer-split/exam'

# Conflicts:
#	src/db/mod.rs
#	src/domain/course_session.rs
#	src/domain/exam.rs
#	src/domain/exam_question.rs
#	src/service/mod.rs
#	tests/regress_course_child_orphans.rs
🧹 chore: split exam_attempt into domain/db/service layersAhmet Kaan Gümüş · c13b51d
🧹 chore: split exam_attempt into domain/db/service layers

src/domain/exam_attempt.rs keeps the pure core (ExamAttemptId, AttemptStatus,
the entity + getters, deadline/status arithmetic); fields went pub(crate) so
the layers can mint and target rows.

src/db/exam_attempt.rs takes every query: finish/set_left (the two
field-scoped writes), the reads (read, read_latest_for_user, list_*,
any_for_exam), and the write_unfrozen[_with] freeze-gate transaction gateway
with FROZEN_SLOT and the THROW markers.

src/service/exam_attempt.rs owns the workflows and the cross-call state:
EXAM_LOCK moves here from web/exams/mod.rs (it spans multi-call workflows —
start's writer lease, saves' reader leases), the sitting gates
(ensure_sittable/ensure_student/ensure_student_now/ensure_enrolled/
check_rejoin/writable_attempt) move out of the handlers, as do course_of
(web may not be imported from service) and question_of_exam (the answer
funnel's lookup). start keeps its name from the domain; start_attempt /
finish_attempt / save_answer_checked are the handler workflows extracted
whole, windows and term gates and all, in the original gate order.

web/exams/attempts.rs keeps authz extractors, DTOs, and response assembly
only; exam_ws.rs, exams/{mod,questions,images,review}.rs and courses.rs
re-point to the service paths; domain/exam_question.rs and
question_image.rs call the db-layer write_unfrozen* directly. Doc links to
moved items re-pointed. Tests ride with their layer: persistence
(field-scoped write) tests in db, workflow (start/retake/race) tests in
service; assertions unchanged, only paths and call shapes.

2026-09-07

✨ feat: rate-limit, DB liveness, WebSocket and tenant-cache telemetryAhmet Kaan Gümüş · e87c2a2
✨ feat: rate-limit, DB liveness, WebSocket and tenant-cache telemetry

Four instruments that were declared at the OpenTelemetry bootstrap and
recorded by nobody now have their call sites.

The rate limiter counts every refusal under the tier that refused it. The
tier's name already exists — `share()` is told it — so the limiter learns
it there instead of growing a constructor argument the router would have
to pass. Counting sits in one wrapper around `check`, so the overflow
budget's refusals cannot slip past it, and it is a counter only: a log
line per rejection is a flood amplifier, and the fields that would make
one useful (who, from where) are exactly the ones telemetry may not carry.
For the same reason the two existing warnings no longer name the client's
IP or the user — with events now exported as OTLP logs, those fields would
leave the process.

The keepalive ping is timed and its verdict published, and the log is now
about the transitions rather than the tick: down once, up once, with the
outage's length on recovery.

Every room socket is counted by a `Connected` guard whose `Drop` is the
decrement, since a room has several ways out and a decrement written at
one of them is a gauge that only ever climbs. It names the exam, not the
attempt — an attempt names one student.

The instruments reach those places through `Metrics::global()`, published
by `init`: the limiter is built before the state exists, and the keepalive
task and the tenant cache have no handle to one either.

Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s

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: archive academic terms; an archived year is read-onlyAhmet Kaan Gümüş · c4232e6
🗄️ feat: archive academic terms; an archived year is read-only

`Term.archived_at` (nullable, no backfill) plus `POST /terms/{id}/archive`
and `POST /terms/{id}/unarchive` (manager+, idempotent: a repeat archive
keeps the original stamp). While a term is archived its own PATCH/DELETE,
linking a new course or class to it, and every write to a course or
class on it — enrollment, teacher assignment, class membership and
attach/detach/blueprint apply, sessions and roll call, subjects, exams
with their questions, images, attempts and answers, the exam-room
WebSocket door and `finish` frame, grading, homework and submissions,
course notes and files — answer `409` with `code: "term_archived"`.
Reads stay open. The guard is a pre-flight read of the term row: an
archive landing in the same instant as a write lets that one write
through (documented as the third accepted race).

Out of scope on purpose: personal notes, messages, pomodoro, meals,
payments, boards, appointments, chatbot, question pool/bank, events,
blueprint templates, the staff work log, and the role-demotion and
subject-delete integrity sweeps.

Coverage: 155 write routes classified (59 guarded, 93 out of scope);
e2e over real TCP covers archive → refused writes → open reads → the WS
handshake 409 → unarchive; the class refusal-code pin gains
`term_archived`; README prose, tag text and endpoint table regenerated.

Closes #22.

2026-08-13

chore: rename ponytail: comment marker to corner-cut:Ahmet Kaan Gümüş · ed88733
chore: rename ponytail: comment marker to corner-cut:

Marker convention renamed after uninstalling the ponytail plugin;
semantics unchanged (deliberate corner-cut, known ceiling + upgrade path).
Token-only rename, 26 comment lines, no code change.

2026-07-31

chore: 🧵 fold the two rooms' shared plumbing into src/web/room.rsAhmet Kaan Gümüş · 6208c97
chore: 🧵 fold the two rooms' shared plumbing into src/web/room.rs

The exam room and the board room share the plumbing around their difference,
not the difference itself: how a frame goes out, how an incoming message is
classified, how an `AppError` becomes words a client may read, and how a
correlation id is echoed back untouched. Both now import that one copy.

Behaviour-preserving on the exam side: `public_message` interpolates the room
label, so "exam room: database reconnecting", "exam room: database timed out"
and "exam room error: {err}" come out byte-identical, and all ten
`exam_room_*` e2e tests stay green.

The `select!` loops, the pre-upgrade gates and presence stay per-room on
purpose — room.rs names each one and why. The boards tag description now
documents the room itself: the 404 door, current-epoch replay,
persist-then-publish, and a `forbidden` that keeps the socket.

2026-07-30

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-25

style: 🏷️ rename the echoed exam-room seq to client_seqAhmet Kaan Gümüş · 61bd820
style: 🏷️ rename the echoed exam-room seq to client_seq

`seq` already means the attempt number everywhere else in this domain —
it is the key of an exam sitting, and the room's own `state` frame ships
it as `attempt`. A second `seq` on the neighbouring frames read as the
same thing.

Wire rename only, and the field shipped minutes ago, so nothing is
depending on the old spelling yet.
feat: 🏷️ echo the client's seq on exam-room saved and error framesAhmet Kaan Gümüş · 9e25eac
feat: 🏷️ echo the client's seq on exam-room saved and error frames

`question_id` is not an identity. A student who saves q1, times out, and
saves q1 again has two sends outstanding for the same question, and the
first reply settles the second send — the badge read "Saved" for an
answer the server never accepted. That shipped.

The answer frame now takes an optional `seq`, echoed verbatim on both
the `saved` and the `error` reply. The server never reads it: uniqueness
and monotonicity are the client's problem, and a repeated value is
echoed as sent. Errors carry it even where `question_id` is not
attributable, which is exactly the case a client could not match before.

Omit it and every frame is byte-identical to before — the key is absent,
never null. `deny_unknown_fields` stays, since that is what made a
correlation id unsendable until now.
fix: 🔒 cap the echoed question_id, and de-flake the exam-room testAhmet Kaan Gümüş · f62fb74
fix: 🔒 cap the echoed question_id, and de-flake the exam-room test

cd6c1e4 started echoing `question_id` back in the per-question error
frame, but the field was an unvalidated `String` and axum's default
WebSocket message limit is 64 MiB, so a client could make the server
echo ~64 MiB to itself. It is now length-checked against
`MAX_QUESTION_ID_LEN` (64 — real values are 26-char ULID keys) before any
lock or database work, and rejected *unattributed* so nothing of the
oversized id is reflected.

`exam_room_expires_mid_session` was flaky for a real reason, not a tight
sleep: the fixture sampled `GET /time`, then made five more HTTP calls
including a full argon2 login — costlier since 684f18b — and all of it
had to fit inside the 2.6 s window it had just set. On a loaded run the
setup outlived the exam and the attempt hit a closed window, 409. Setup
now happens outside the window and the teacher shortens `ends_at` after
the answer lands, which drives the same live-schedule path the extension
test already covers, in the other direction. 20 runs, 20 passes.
fix: 🔎 Turkish search folding for users, per-question exam-room errorsAhmet Kaan Gümüş · e0f9d63
fix: 🔎 Turkish search folding for users, per-question exam-room errors

- User::search folded its needle with Rust to_lowercase and its columns
  with SurrealQL string::lowercase; both turn İ into i + U+0307, so
  searching "ilker" never found "İLKER". It now runs both sides through
  the shared text_fold table, like the question bank already does
- exam-room error frames carry question_id when the failure belongs to
  one save — a validation reject or an unknown question, raised inside
  the save past the sitting gates. The client could not tell which save
  failed and had to fail every one in flight
- auth, conflict, malformed-frame and database errors stay unattributed
  on purpose: they doom the next save too, and a failed database is not
  a per-question fact. An absent question_id keeps its old meaning
- Subject::update is field-scoped: the handler holds no lock across its
  read and write, so a whole-row save reverted a concurrent edit of the
  other field
- annotate the three whole-row saves that genuinely cannot be raced
  (exam update holds EXAM_LOCK across the read; the two image upserts
  build their struct in place under a deterministic slot id)
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-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.
🔥 feat(exams): drop the live-monitor SSE stream for poll-onlyAhmet Kaan Gümüş · bacd9ed
🔥 feat(exams): drop the live-monitor SSE stream for poll-only

Remove `GET /exams/{id}/live/stream`. The teacher monitor now polls the
one-shot `GET /exams/{id}/live` (kept, untouched) on a 2s interval — the
SSE feed ran at the same cadence, so it added no freshness, only a second
snapshot build per watcher and a permanently-dead-on-first-error path in
the client.

Drops the `exam_live_stream` handler, its route + utoipa block, the
`EXAM_LIVE_STREAM_INTERVAL_SECS` constant, and the now-unused SSE imports
(Sse/Event/KeepAlive/IntervalStream/Stream). Removes the two e2e stream
tests + the `next_matching_snapshot` helper and the integration
route-auth cases. README route table and prose updated; KB re-ingested.

2026-07-22

2026-07-21

🐛 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.
🐛 fix(db): map ws session-replay races to 503 + keepaliveAhmet Kaan Gümüş · 6627128
🐛 fix(db): map ws session-replay races to 503 + keepalive

The SDK's reconnect replays signin/use_ns fire-and-forget, so queued
queries can race it and get refused pre-execution ("Specify a
namespace" / "Anonymous access"), and a query in flight at the drop
dies as a connection error — all surfaced as 500s. Classify those
(narrow strings + is_connection) as DbUnavailable → 503 with
Retry-After: 1; refused-pre-execution makes a client retry always
safe, unlike a body-replaying retry middleware. A 30s RETURN 1
keepalive task makes drops heal between requests, not under one.
Restart storm (2× DB restarts under 200ms hammer): 0×500.
✨ 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.

2026-07-19

✨ feat(exams): draft exams hidden until publishedAhmet Kaan Gümüş · d8fdbf0
✨ feat(exams): draft exams hidden until published

Exam prep is long work: draft: true keeps an exam private to its
course's managers while it's written. Students get 404s (not 403/409 —
existence must not leak) on get/attempt/ws and filtered lists; sitting
and grading are blocked. Publish via PATCH draft: false; re-drafting is
409 once attempts or results exist. grade now holds an EXAM_LOCK read
lease so a mark can't race a re-draft. Modeless exams renamed
offline-graded/unscheduled everywhere — "draft" now means only this.
Old rows backfill published at boot.
🐛 fix: five holes from fan-out auditAhmet Kaan Gümüş · 7d8df31
🐛 fix: five holes from fan-out audit

- serialize exam-subsystem check-then-writes with EXAM_LOCK RwLock
  (answer saves read, structural writes write): freeze gate vs first
  attempt, subject delete vs question write, retake wipe vs in-flight
  save; start_attempt re-derives the sittable gate under the lock
- field-scope User::set_role/set_profile/set_preferences: whole-row
  content() writes let a stale PATCH /users/me carry the snapshot role
  back over a concurrent admin demotion (exploitable by hammering the
  endpoint); each writer now updates only the fields it owns
- CORS: expose Retry-After and Content-Disposition so cross-origin JS
  can read the documented 429 backoff and download filename

2026-07-18

🐛 fix(exams)!: make room presence atomic with left_at writesAhmet Kaan Gümüş · 2aed950
🐛 fix(exams)!: make room presence atomic with left_at writes

The door cleared left_at before the upgrade while enter() ran later in
the socket task; a dying socket's last-out teardown landing in that gap
stamped left_at back on — student present but marked left, and with
allow_rejoin off every save 409s and reconnects are refused: locked out
until a teacher flips the door. Deferred on 2026-07-14 pending an
atomic design; this is that design.

Join (enter + clear) and teardown (leave + maybe-stamp) are now whole
critical sections under a process-wide PRESENCE_LOCK: any two run
wholly-before or wholly-after. Teardown first — the join's clear
overwrites its stamp; join first — the teardown sees the socket counted
and never stamps. No ordering leaves a present student stamped.

The door's rejoin gate stays as read-only fast-fail; the authoritative
clear moved into the room task (ms-scale shift, not HTTP-observable).
Race has no deterministic injection point — correctness by
construction; the two-socket e2e and rejoin/binding suites cover the
invariants.

2026-07-15

✨ feat(notes): file attachments with school-set size capAhmet Kaan Gümüş · f1b532b
✨ feat(notes): file attachments with school-set size cap

Blobs live on disk under FILES_PATH (same volume as the DB), named by
the row's ULID so user input never shapes a path; the note_file row
keeps only metadata. DB-blob storage rejected: multi-MB PDFs bloat
surrealkv's LSM tree and buffer whole in RAM on every read.

- POST/GET /notes/{id}/files, GET/DELETE /notes/{id}/files/{file_id};
  owner-only through the owning note, staff included
- max_file_bytes in settings (1 KiB-25 MiB hard cap, default 5 MiB),
  enforced on streamed bytes (413), inside the settings CAS guard;
  option<int> so pre-field volumes boot without a backfill
- 10 files per note; deleting a note removes rows first, blobs after,
  so a crash strands at worst an unreachable blob
✨ feat(web)!: gate enrollment, exams, grading, roll call to studentsAhmet Kaan Gümüş · 32949bd
✨ feat(web)!: gate enrollment, exams, grading, roll call to students

Only Role::Student may enroll, sit exams, be graded, or appear on a
class roster; teachers and above run those, they never take part. The
manager+ teacher-presence roll call is unchanged.

Two enforcement layers:
- Enroll-time: `enroll` rejects a non-student target (400). Enrollment
  is student membership -- the choke point the rest ride on.
- Action-time: `ensure_student` guards the exam sit paths (start, room
  WS door, answer save; 403) and the grade + roll-call targets (400),
  checked against the live role -- a post-enroll promotion can't smuggle
  staff in, and a stale enrollment goes inert instead of active. The
  answer tail re-judges the role per save (`ensure_student_now`, beside
  the enrollment wall on the path REST and the exam room share), so a
  promotion mid-exam also cuts an already-open room socket -- the door
  check is never the last word for a connection that outlives the role.

Passive reads (own attempt/result, question view, finish) stay ungated:
a non-student has no attempt to read and finish only submits saved work.
Event attendance stays open -- events are school-wide, not classes.

Behavior change: a user can be both course creator and enrollee only
across a demotion now (staff create, students enroll), so the
catalog-dedup regression drives that overlap via set_role.

Docs updated per the surfaces checklist (utoipa 400/403 + endpoint docs,
lib.rs exams/courses tags + intro, README matrix/route table/prose).
Adds regression tests: only_students_can_be_enrolled,
promotion_out_of_student_freezes_the_seat, and (e2e, over a live
socket) exam_room_promotion_mid_exam_closes_the_sheet.

2026-07-14

🐛 fix: bind room writes to their sitting, wall unenrolled sittersAhmet Kaan Gümüş · 3375565
🐛 fix: bind room writes to their sitting, wall unenrolled sitters

Four bugs, each reproduced by a failing test first:

- A stale exam room's answer/finish acted on the *latest* attempt, so
  a lingering socket from a finished sitting could scribble on — or
  instantly submit — a retake it never hosted, burning a limited
  sitting. Messages now refuse any sitting but the room's own.
- The sitting's content endpoints (GET /attempt/questions, POST
  /attempt/answers) skipped the enrollment wall that guards the room
  door and the attempt start, so an unenrolled ex-student kept the
  question list and a writable answer sheet forever. Both are 403 now;
  finishing stays open, exactly like under a closed rejoin door.
- PATCH /settings merged over a snapshot and wrote the whole row back,
  so concurrent edits of different fields silently reverted each
  other. Saves are compare-and-set against the merged-from snapshot
  now, re-merging on refusal (409 only when still contended).
- Work-entry duration_ms overflowed i64 on absurd manager-corrected
  instants — a panic in debug, a wrapped negative in release, and a
  row that 500d every later read. The subtraction saturates now.

2026-07-13

🐛 fix(exams): stamp walk-outs per sitting, wipe retakes atomicallyAhmet Kaan Gümüş · 6eb0a28
🐛 fix(exams): stamp walk-outs per sitting, wipe retakes atomically

Three bugs in the attempts/rejoin build, each a wrongful lockout or
data loss once allow_rejoin is off:

- A room's teardown stamped left_at on the *latest* attempt, so a
  stale socket from a finished sitting marked a fresh retake as left,
  locking the student out of a room they never entered. Rooms now
  bind to the sitting they were opened for: state frames and the
  walk-out stamp re-read that attempt by id, never "latest", so a
  superseded room announces its own terminal state and closes.
- Closing one of two tabs counted as leaving while the student was
  still connected. ExamPresence (AppState) counts sockets per
  attempt; only the last socket out stamps the walk-out.
- The retake answer-wipe ran before the attempt create, so a lost
  double-start race could delete answers freshly saved into the
  winner's sitting — or destroy a graded sheet with no retake ever
  created. Wipe + create now run in one transaction and a failed
  create rolls the wipe back. (SurrealDB counts BEGIN/COMMIT as
  response slots: the CREATE result is slot 2.)

Regression tests: e2e rooms for the retake stamp and the second tab,
domain tests for the atomic wipe and the lost race (verified red
against the old ordering), presence unit test. README rejoin
paragraph aligned with the per-sitting semantics.
✨ feat(exams): open mode, attempt limits, retakes, rejoin doorAhmet Kaan Gümüş · 9835fe7
✨ feat(exams): open mode, attempt limits, retakes, rejoin door

Unscheduled exams were dead ends: attempts answered 409 "nothing to
sit", and every exam was hard-wired to a single sitting.

- mode "open": sittable anytime, no window; duration_ms optional per
  attempt (absent = unlimited time). Modeless exams stay offline
  drafts — still 409, so a student can't freeze a draft's questions.
- max_attempts (0 = unlimited, default 1): terminal attempts can be
  followed by numbered retakes that start from a blank answer sheet;
  the previous sitting's answers are wiped on the next start.
- allow_rejoin: live teacher toggle. Leaving the exam room (WS close
  mid-attempt) stamps left_at; with the door closed, re-entry and all
  saves 409 until reopened. Finish stays allowed either way.
- Attempt deadline generalized to min(ends_at, started_at + duration),
  either side optional; none = ends only by submission.

Boot migration backfills max_attempts/allow_rejoin/seq on existing
rows and replaces the single-attempt unique index (exam, user) with
(exam, user, seq) via REMOVE INDEX IF EXISTS. Sitting #1 keeps the
legacy {exam}_{user} record id, so pre-upgrade attempts stay valid.

2026-07-12

✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam roomAhmet Kaan Gümüş · ade4fed
✨ feat(exams): scheduled attempts, live monitor, questions, answers, exam room

- exam scheduling as one validated unit: mode sync|async + window
  (+ per-student duration_ms for async); unscheduled stays offline-graded
- exam_attempt: one row per exam+user by composite id; start = attendance
  signal, finish = submission; status/deadline recomputed from the current
  schedule on every read (mode frozen once attempts exist, times extend live)
- teacher live monitor: GET /exams/{id}/live snapshot + SSE /live/stream
- exam_question: choice|text authored per exam, kind bundle (choices+correct)
  validated as a unit, frozen once attempts start, ULID order
- exam_answer: upsert per question+user via composite id, kind-coherent,
  server-clock stamped; pure auto_score over choice questions as a grading
  suggestion — final mark stays human via /results
- student exam room WebSocket at /exams/{id}/attempt/ws: state ticks,
  autosave acks, finish/expire lifecycle, gates rejected pre-upgrade with
  proper HTTP statuses; shares the REST write path
- PersonRef embeds (id + username + display name) in people-bearing
  responses, plus teacher+ GET /users/search
- cascades: exam/course deletes sweep attempts, questions, answers, results