Commits
2026-09-12
2026-09-11
🧹 chore: split note/session/settings into domain/db/service layersAhmet Kaan Gümüş · efea304
🧹 chore: split note/session/settings into domain/db/service layers
Pilot wave of the three-layer split. All query execution for the three
domains now lives in src/db/{note,session,settings}.rs as free fns taking
db first; web handlers call service::<x>::* only; domain keeps pure types.
- service/settings.rs gains the PATCH workflow (apply) and SETTINGS_LOCK —
it spans a multi-call pair (retire names, CAS save, restore), so it is a
service lock, not a db lock. The service takes its own input records
(SettingsPatch/*Input) so wire DTOs stay in web and list validation keeps
its original order, including the try_kept grandfathering that needs the
stored list.
- Note/Session/Settings fields the db layer mints or CAS-binds become
pub(crate); Settings::record_id becomes pub(crate).
- Unit tests rode with their fns: note delete cascade → db/note, session
purge → db/session, settings load/save/CAS → db/settings, the whole
settings edit workflow suite → service/settings.
- Doc links re-pointed (user, class_blueprint, bank_question, exam,
note_file, tests/regress_roles); NoteId::generate's stale
'Note::list_for_user' link now names db::note::list_for.
- Known residual for a later wave: web/notes.rs:411 file.delete() is
note_file-domain persistence (note_file splits in C3).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.
fix: 🔩 close the leaks a five-domain hunt turned upAhmet Kaan Gümüş · a3fe8cf
fix: 🔩 close the leaks a five-domain hunt turned up Five hunters swept exams, homework/attendance, identity, money/scheduling and messaging/courses; a three-lens verifier panel then refuted three of the first fixes, and those corrections are folded in here. Leaks and races closed: - exam self-review gated on *any* mark, so a seq-1 grade opened the answer key forever — a student mid-retake read `correct` and `is_correct` off the sheet they were still writing. All four review reads now 409 while the caller's latest sitting is in progress. - roll call could land after its session was deleted, and the orphan was unremovable (its delete route 404s on the vanished session) while the attendance report went on counting it. The write now proves its parent exists in the same transaction, the way ExamResult::grade does. - a teacher could counter-propose and then approve their own proposal, committing the requester to a time only the teacher ever named; and even after that, re-proposing between the requester's read and their accept moved the meeting under them. Approve refuses while a proposal stands, and accept now pins the window it is answering. - two concurrent chatbot posts on one thread cross-attributed their answers — both replied to the second prompt, the first was never answered. The prompt id rides the request instead of being re-derived from write order. - a whiteboard participant demoted to `parent` kept drawing, and kept *reading* the live canvas for up to 15s. Every frame is authorized before delivery now, and a demotion sweeps the account off rosters. - a demotion to `parent` stranded event signups no one could free. Promotions are left alone (staff free their own seats) and closed lists are never rewritten. - the rate-limit bucket map was unbounded past 10k live keys and then scanned O(n) under the global mutex on every request. Eviction is bounded and never frees an exhausted bucket — the first attempt did, which traded a memory bug for an auth-bypass, so it is pinned by a test that floods at the victim's own spend. - session and event cascades ran as loose queries; a concurrent write slipped between them and orphaned rows, and for notes a blob nothing could ever reclaim. All three are one transaction now. - sixteen id generators still used Ulid::new(), whose random low bits scramble same-millisecond rows under the "newest first" the docs promise; five listings had no tie-break at all, so offset paging could skip or duplicate a row. Also: $session is a protected SurrealDB 3 variable — binding it fails the whole query as a bare 500, which is what hid the attendance fix. Accepted, documented, not fixed: one bank template instantiated into two exams copies `correct` into both, and the review gate is per-exam.
2026-07-27
fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process
Two replicas are live; every process-local lock silently stopped
meaning anything. Move the invariants into the writes themselves:
- count caps (enroll/register/files/threads) become a counter column
claimed by UPDATE .. WHERE n < cap (domain/cap.rs), backfilled once,
decremented in the same transaction as every child delete
- exam freeze, re-draft and grade gates ride inside the write's own
transaction (IF .. THROW); SESSION/WORK_ENTRY/EVENT locks die, range
checks fold into the UPDATE's WHERE (FieldUpdate::ordered)
- appointment decisions CAS on status+proposed window+decided_by;
bank/exam updates CAS on their editable columns
- rate limiter syncs local windows to a shared minute row every 2s,
fail-open when the database is down
- paged GETs run LIMIT/START in the database (domain/page.rs); sites
that post-filter in Rust stay web-sliced and say so
- exams.rs (3629 lines) splits into web/exams/{mod,attempts,questions,
images,review}; image uploads single-source in web/image.rs; the
bare-seq key rule lives once in domain/key.rs; migration SQL moves
to migration_sql.rs
Every new guard is mutation-proven (removing it fails a named test).
Migration adds counter columns + rate_limit table; backfill is
one-time, guarded by = NONE, and verified against the live volume.
Traps recorded: SurrealQL 'x ?? 0 > 0' parses as 'x ?? (0 > 0)'; the
embedded mem engine drops one of two concurrent writes yet answers Ok.2026-07-26
chore: 📦 give every constant one homeAhmet Kaan Gümüş · 78b25b5
chore: 📦 give every constant one home Constants were scattered across 18 modules: table names and migration SQL in database.rs, limits in config.rs and rate_limit.rs, magic strings sitting next to the only code that read them. Nobody could answer "what are all the hard values in this service?" without a grep. They all live in constant.rs now — validation bounds, the 37 SurrealDB table names, the PRE_REPAIR/MIGRATION/BACKFILL schema SQL, and the enum value tables that used to hide as associated consts (Role::ALL -> ROLES, Folder::SENDER -> SENDER_FOLDERS, and friends). Values are byte-identical; this changes no behavior. constant.rs now imports crate::domain for the enum types, an intra-crate cycle that compiles fine. Statics stayed where they were. A Mutex or a ULID generator is runtime state, not a constant, and moving them would only blur that line. Two guards keep the consolidation honest. limits_completeness.rs already failed on any pub const in constant.rs that is neither published through /limits nor excluded with a reason; the *_TABLE names are excused by shape rather than by 37 lines of boilerplate, but the excuse now requires the absence of a MAX_/MIN_/DEFAULT_ prefix so a real bound cannot hide behind the naming convention. And the move quietly dropped three rules off the end of the text-fold table, which every existing test still passed — so the circumflexed vowels are pinned, and search_fold_sql must emit one string::replace per rule or the needle and the column drift apart.
2026-07-25
fix: 🧩 a PATCH writes only the fields it was givenAhmet Kaan Gümüş · 85b408e
fix: 🧩 a PATCH writes only the fields it was given - every PATCH handler loaded the row and refilled the fields the request omitted from that stale snapshot, so two concurrent partial PATCHes touching different fields lost each other: whoever wrote last silently reverted a field it was never asked to change - field-scoping the write did not fix this — the value bound to the SET still came from a stale read - add domain/field_update.rs: .set(column, Option<T>) skips an absent field entirely, so it is neither written nor bound, and an all-absent PATCH writes nothing at all - convert notes, events, terms, homework, work entries and courses, each with a 20-round concurrent-PATCH regression that fails against the old code on round 0 and passes after - nullable columns stay clearable: an event's schedule, a course's capacity and term, and homework's assigned subset keep the double-option so an explicit null still writes NONE, while an omitted field is left alone - homework's old fallback was worse than a no-op: it could re-narrow the assigned subset over a concurrent widening, behind the guard that exists to stop exactly that - cross-field validation still reads the stored row where it must (event and term ranges need both ends) — read for the check, never written back - HOMEWORK_LOCK was taken after the row read, so it never covered the read-modify-write it looked like it guarded
fix: 🔒 drain the whole-row save backlogAhmet Kaan Gümüş · 19ba18a
fix: 🔒 drain the whole-row save backlog - a whole-row .content(self) reverts any write that landed between the struct's read and its save; the gate flagged 14 sites and this empties it - course.rs was the only genuinely raceable one, in both directions: teachers[] is written by assign, unassign and the demotion sweep while Course::update rewrites the text columns, so staffing a course reverted a concurrent rename and a rename dropped a concurrent assignment. Both reproduced as failing tests first - assign/unassign now use array::distinct(array::append(...)) and teachers -= $usr rather than rewriting the array from a stale read - session, event, note, term, homework and work-entry updates are each their row's only writer and rewrite every mutable field, so no failing interleaving exists today; converted defensively anyway, following Subject::update, and not test-proven - the five create/upsert sites are annotated instead: each builds its struct in place from the request and never reads it back
2026-07-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 blob2026-07-11
✨ feat(domain): validated newtypes and entity persistenceAhmet Kaan Gümüş · ba2b9b1
✨ feat(domain): validated newtypes and entity persistence Every value is a newtype constructed only after its validator passes (Username, Password, NoteTitle, Mark, ...), so an invalid value can't be represented. Each type derives SurrealValue, so one typed value flows unchanged from HTTP input into the SCHEMAFULL store, and each entity module owns its own persistence. - user/role: argon2-hashed passwords; four hierarchical roles (student < teacher < manager < admin) with at_least() checks. - session: an opaque random token, 7-day expiry, server-side lookup. - note: per-user notes. - event/attendance: events own attendance rows keyed by event+user; optional unix-millisecond starts_at/ends_at with ends >= starts. - exam/exam_result: homework|quiz exams; one 0-100 mark per exam+user in its own row, never on a note. - timestamp: the unix-millisecond instant shared across entities. Record ids are ULIDs — time-sortable and safe to expose.