Commits
2026-09-24
✨ feat(courses): grade-ladder course templates with per-class overridesAhmet Kaan Gümüş · 450bc8c
✨ feat(courses): grade-ladder course templates with per-class overrides course_offering per (course x grade_level 0..=12), per-class overrides on class_course (nullable scalars + *_inherited flags), subjects/weights/ weekly-plan axis tables, instance_resolve with batched twin, resolved title/description on instance-scoped reads, six new route groups, integration scenario test, README regenerated. Evolution migrations squashed into the base schema (20260912000002_courses + 20260916000001_k12_remodel). Local-Gate: 246daa3fb3ee7b0ff507a95d6ab346bab1333a37 (1556 passed, 455s)
2026-09-23
✨ feat: 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-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-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-15
🐛 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.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: person-scoped login; select school afterAhmet Kaan Gümüş · fae1f79
✨ feat: person-scoped login; select school after Login is username+password only. A person is global, memberships are per-school (role stays on app_user), and POST /auth/school binds when the account belongs to more than one school.
2026-09-12
2026-09-11
Merge branch 'layer-split/notes_board'Ahmet Kaan Gümüş · e1b6791
Merge branch 'layer-split/notes_board' # Conflicts: # src/db/mod.rs # src/domain/rag_output.rs # src/service/course.rs # src/service/mod.rs # src/web/course_notes.rs
2026-09-07
✨ feat: OpenTelemetry bootstrap — OTLP traces/metrics/logs, request spans, request idsAhmet Kaan Gümüş · 057a7fa
✨ feat: OpenTelemetry bootstrap — OTLP traces/metrics/logs, request spans, request ids Telemetry is off unless OTEL_EXPORTER_OTLP_ENDPOINT is set, mirroring the AI bridge's "off unless configured" shape. With it unset the process logs exactly as before; every instrument binds to the noop meter provider, so call sites never branch on whether telemetry is on. Privacy is the design constraint (KVKK): a span carries the method, the route TEMPLATE, the status, a random request id and the school slug — never a user, an IP, a URL path, a body, a header or a cookie. tests/telemetry.rs fails the build if a forbidden attribute key appears. New variables (all documented in .env.example): OTEL_EXPORTER_OTLP_ENDPOINT presence turns export on OTEL_EXPORTER_OTLP_PROTOCOL grpc (default) | http/protobuf OTEL_EXPORTER_OTLP_HEADERS read by the SDK OTEL_SERVICE_NAME read by the SDK, defaults hezarfen_backend OTEL_TRACES_SAMPLER(_ARG) read by the SDK, parent-based always-on LOG_FORMAT pretty (default) | json; anything else refuses to boot DEPLOY_ENV deployment.environment.name Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s
2026-09-05
✅ test: module verifier probes — empty schools, migration idempotence, batch atomicity, gate orderingAhmet Kaan Gümüş · 64fc444Browse files
✨ 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.
✨ 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: stop the canteen billing meals that were already servedAhmet Kaan Gümüş · 0894a5e
🥗 fix: stop the canteen billing meals that were already served
A menu dated 2020 was publishable, bookable and BILLABLE under the shipped
defaults. `check_cutoff` was the only gate a booking passed, and it returns
early twice: with `meal_cancel_cutoff_minutes` unset (the default) and with a
slot carrying no `serving_minute` (the default for all three shipped slots).
`POST /meals/menus` was also the one create path in the crate with no
`check_not_past`. So a manager published `2020-01-01_lunch`, a student booked
it, and `MealLedger::charge_for` wrote a real, permanent charge line for food
nobody could be served.
Both halves, because the create-side check alone does not close it: a menu
published legitimately last week, for a day that has SINCE passed, stays on
the volume and stays addressable. `check_not_past("date", date.day_end())`
refuses publishing a day already over (400, measured against the end of the
day so today publishes at any hour), and `check_day_not_past` refuses a
booking on one (409).
That guard is deliberately NOT part of `check_cutoff` and takes no settings:
the cutoff is policy about the serving *hour* and is unenforced by design when
the school has set none — the decision that keeps the canteen online — while
this is the calendar day itself being over, which no configuration makes
untrue. Today's menu on a slot with no serving hour books exactly as before.
It binds `book` alone: cancelling stays open on a past day, since a cancel
reverses a charge and money already taken has to stay reachable — the same
reason manager+ bypasses the cutoff. Nothing bypasses the past-day guard, and
nothing needs to: only students and their parents book at all.
`MenuDate::try_new` also stops disagreeing with chrono. `"+1".parse::<u32>()`
is `Ok(1)`, so `2026-+1-01` passed the calendar-day check and minted a SECOND
record id for the 1st of January — its own capacity and seat counter, missing
from every `?from=&to=` read (`+` sorts below `0`) and unbookable besides,
since the serving-instant parser could not read it back. The date is now
parsed by chrono and compared to the text it came from, so the two parsers
agree by construction rather than by two checks that can drift.
Test dates in the meal suites move beyond the calendar (2026-09 → 2099-09):
under the new rule a fixture dated next month is a suite that expires. The two
tests that used a past date as a shortcut to "the cutoff has closed" now reach
the cutoff the way a deployment does — today's menu, served at 00:00 UTC, with
the knob set.
Live volume: zero menus, zero bookings, zero ledger lines, so no residue to
repair. The defect was future-affecting only.🔢 fix: give back the seats the boot sweep has been eatingAhmet Kaan Gümüş · 628b5e8
🔢 fix: give back the seats the boot sweep has been eating The boot sweep deletes enrollments whose holder is no longer a student, but never decremented the course's enrollment_count. Every row it has ever swept left a phantom seat: counted against capacity, and enough to make Course::delete's zero guard unsatisfiable forever. The sweep now returns the rows it deletes and decrements per course, the same shape set_role's own sweep uses. A repair pass recomputes enrollment_count per course from its live rows. It carries no migration_mark because it converges — a second run matches nothing once the counters agree — and because a GROUP BY cannot do the job: a course whose last enrollment was swept forms no group at all. The repair runs before the sweep, deliberately. Repair-last would make the decrement unobservable and leave part one unprovable.
2026-08-04
feat: 🏗️ stock a new section from its grade's blueprintAhmet Kaan Gümüş · 67ced09
feat: 🏗️ stock a new section from its grade's blueprint Editing a template reached every section already at the grade, but making a section reached no template — so a blueprint described every section except the ones created after it, and the office had to remember a second call each time. A create now applies its grade's blueprint, after the homeroom demotion rollback and never before it: the rollback deletes the class, and that delete refuses while the class holds courses. The 201 body carries the class, what could not be stocked, and which grade's template stocked it — null when none covers the grade, which is also what a stocking that faulted reports, because a 500 here would strand a section whose id nothing else returns.
2026-08-02
fix: 🔩 close the leaks a five-domain hunt turned upAhmet Kaan Gümüş · a3fe8cf
fix: 🔩 close the leaks a five-domain hunt turned up Five hunters swept exams, homework/attendance, identity, money/scheduling and messaging/courses; a three-lens verifier panel then refuted three of the first fixes, and those corrections are folded in here. Leaks and races closed: - exam self-review gated on *any* mark, so a seq-1 grade opened the answer key forever — a student mid-retake read `correct` and `is_correct` off the sheet they were still writing. All four review reads now 409 while the caller's latest sitting is in progress. - roll call could land after its session was deleted, and the orphan was unremovable (its delete route 404s on the vanished session) while the attendance report went on counting it. The write now proves its parent exists in the same transaction, the way ExamResult::grade does. - a teacher could counter-propose and then approve their own proposal, committing the requester to a time only the teacher ever named; and even after that, re-proposing between the requester's read and their accept moved the meeting under them. Approve refuses while a proposal stands, and accept now pins the window it is answering. - two concurrent chatbot posts on one thread cross-attributed their answers — both replied to the second prompt, the first was never answered. The prompt id rides the request instead of being re-derived from write order. - a whiteboard participant demoted to `parent` kept drawing, and kept *reading* the live canvas for up to 15s. Every frame is authorized before delivery now, and a demotion sweeps the account off rosters. - a demotion to `parent` stranded event signups no one could free. Promotions are left alone (staff free their own seats) and closed lists are never rewritten. - the rate-limit bucket map was unbounded past 10k live keys and then scanned O(n) under the global mutex on every request. Eviction is bounded and never frees an exhausted bucket — the first attempt did, which traded a memory bug for an auth-bypass, so it is pinned by a test that floods at the victim's own spend. - session and event cascades ran as loose queries; a concurrent write slipped between them and orphaned rows, and for notes a blob nothing could ever reclaim. All three are one transaction now. - sixteen id generators still used Ulid::new(), whose random low bits scramble same-millisecond rows under the "newest first" the docs promise; five listings had no tie-break at all, so offset paging could skip or duplicate a row. Also: $session is a protected SurrealDB 3 variable — binding it fails the whole query as a bare 500, which is what hid the attendance fix. Accepted, documented, not fixed: one bank template instantiated into two exams copies `correct` into both, and the review gate is per-exam.
fix: 🔩 close the bug hunt across meals, classes and capsAhmet Kaan Gümüş · 7198cea
fix: 🔩 close the bug hunt across meals, classes and caps A three-domain hunt, its fixes, and a verifier panel that refuted two of them. Kept as one commit because the pieces interlock — cap.rs, the settings pair and the pump all move together, and no smaller cut compiles. Money can no longer be lost or stranded. Both seat transitions carry their ledger line inside their own transaction: the claim writes the charge, the flip writes the reversal. Before, a crash between the two left a seat held with no bill, or a bill with no seat, keyed to an attempt no later request could ever reach. A lost cancel could refund a live seat. The menu revision was bumped in a query of its own, so a booking reading in the gap claimed against a capacity or a price the menu had already left. Deleting a menu now takes its marks and its dishes with it, in the transaction that deletes the row. The id is deterministic on (date, slot), so anything left behind came back on the next publish — the kitchen reading "served" for a student who never came. A seat is always releasable: manager+ cancels any booking and is not bound by the cutoff, so a promoted student's seat no longer wedges its menu forever, and a debt that outlived its owner's role can be settled. Canteen money follows /payments and is manager+, not teacher+ — what a family owes the school is not classroom information. The class pump claims its pivot in-transaction. An attach racing a course delete used to commit a link to a row that was gone, and nothing could then detach it or delete the class. A hand enroll now disowns a pumped row, so a sweep cannot take back a roster decision an operator made by hand. The role sweep is one transaction. Rosters are ordered by when a student was added, which is what they always claimed. Both class axes have a ceiling, and each refuses on the other's, because a pump writes one row per member per course in a single transaction. Settings edits are serialized: retire is idempotent, so an undo log cannot tell the attempt that flipped a name from one that found it already flipped, and the loser un-retired what the winner had legally retired — leaving a kind gone from the list, gradable, and unremovable for good. Grading now checks the school's list, not only the counter. Three caps that read a snapshot integer now read the live column. A clear marker is charged to the board's lifetime counter and boot repairs the boards that predate it. Blank canvases refuse the clear, and the room reports that as its own code: the refusal text had drifted into the substring the WebSocket read as "closed", which told a live room it was permanently read-only. Verified against the real volume: both boot backfills, the slot-name rule and its grandfather clause, and the new money gate.
2026-08-01
test: 🧪 pin the counter backfills to the counts they claimAhmet Kaan Gümüş · c391cb5
test: 🧪 pin the counter backfills to the counts they claim term.course_count, kind_ref and slot_ref were probe-verified by hand and by nothing else. Both tests age a volume to the pre-counter shape, boot, assert the exact seeded values, and then assert the bite: a term with courses refuses its delete, a referenced exam kind and meal slot refuse their drop. Seeding zero instead makes both fail.
2026-07-31
fix: 🖍️ name the board roster the same on the way in as on the way outAhmet Kaan Gümüş · 43bbae8
fix: 🖍️ name the board roster the same on the way in as on the way out
POST /boards read the invite list from `participant_ids` while the board
response and PATCH /boards/{id} both call it `participants`. Serde ignored
the unknown key, so a client that posted back a board it had just read got
a 201 for a board it was silently alone on — no error, no roster, a seat
spent. The create field is now `participants` like the other two; the repo
is pre-customer and the real volume holds zero board rows, so it is a clean
break with no alias and nothing stored to migrate.
Both board request bodies also deny unknown fields now, which makes the
next misspelling a 422 instead of a silent drop. That is deliberate local
deviation: no other REST DTO in this crate does it, and only these two have
already proven what ignoring a key costs.
Board::delete goes through transaction_with_retry. It was a bare query +
check() around a five-statement cascade that writes the stroke rows, the
board row and the creator's board_count; a stroke claim touching the same
board row aborts it, and check() retired that retryable round as a 500. No
statement can legitimately answer "already exists" — the DELETEs are
idempotent and the UPDATE is field-scoped — so re-sending is sound, and a
forced-abort probe confirmed the aborted round leaves the board, its
strokes and the seat untouched. No statement moved: RETURN stays slot 4.test: 🧪 pin the whiteboard's HTTP surface and its stored guaranteesAhmet Kaan Gümüş · a05b319
test: 🧪 pin the whiteboard's HTTP surface and its stored guarantees The board room's socket already has its own e2e suite; this is the REST half beside it. The security boundary first, and exhaustively: an outsider gets a 404 on every one of the ten routes, asserted against a board id that was never minted so the two answers are byte-identical — a 403 anywhere there would confirm the board exists. A participant who is not the creator reads everything and re-titles, but the four commands and the roster/lock arms of PATCH are a 403, and none of those refusals writes a thing. Then the promise the whole storage model exists for: a clear empties /strokes and leaves /history whole, checked at the table and not only through the reader a bug could share with the writer. The epoch index carries one marker per clear, each counting the rows really stored under the epoch it closed. Every cap is asserted on the stored counter, never on the response: a full canvas refuses and stays open, a clear hands the cap back, the lifetime cap stamps closed_at once and the closed board still serves every read, and a delete frees a creator's seat. The mint-order test splits in two on purpose: the DB round trip proves /strokes and /history replay in mint order, while the same-millisecond half of the next_ulid hazard is pinned by a tight mint loop with no database in the way — whether 60 appends share a millisecond depends on how loaded the machine is, and a test must not.
feat: 🖍️ collaborative whiteboard domain, REST and limitsAhmet Kaan Gümüş · 5dfce55
feat: 🖍️ collaborative whiteboard domain, REST and limits Boards are an ad-hoc invite list: the creator names participants, and every participant draws. Clearing, locking, closing and deleting are the creator's alone. Strokes are an append-only log and a clear NEVER deletes — it bumps the board's epoch, so the live canvas empties while the whole history stays replayable. The clear marker row doubles as the epoch index, carrying the epoch it closed and that epoch's final stroke count, which is why there is no epochs table. Growth is bounded by two counters claimed together in one conditional write: epoch_stroke_count resets on a clear and caps the live canvas (recoverable — clear and keep drawing), while total_stroke_count never resets and stamps closed_at when the lifetime cap is hit, leaving the board permanently read-only but fully readable. board_count on user bounds the open-a-new-board escape hatch. Outsiders get 404 everywhere so a board's existence never leaks; a participant lacking creator rights gets 403, since existence has already been disclosed to them. The WebSocket room lands separately.
2026-07-30
feat: 🎨 sync the accent color like theme and languageAhmet Kaan Gümüş · 9490623
feat: 🎨 sync the accent color like theme and language
The frontend's palette picker kept the chosen accent in localStorage, so
it never followed the user to another device. `palette_color` joins
`theme` and `language` as a third per-user preference: a nullable hex
color on the user row, self-managed and admin-editable through the same
two PATCH routes, `null` until chosen.
The value set is deliberately open — any `#rrggbb` — rather than an enum
of the frontend's palette entries, so adding a palette is a frontend-only
change. Mixed case is accepted and stored lowercase, which is why
`/limits` publishes the accept-set pattern (`^#[0-9a-fA-F]{6}$`) and not
the storage form: a client validating its own input against the published
regex has to agree with the server, and a test now compiles that regex
and runs it over the validator's own accept/reject examples.2026-07-29
fix: 🔁 make a retried payment one payment, and page the statementAhmet Kaan Gümüş · 4fe02bc
fix: 🔁 make a retried payment one payment, and page the statement A client that resends POST /payments/credits or /refunds after a timeout may now carry a request_key; the line's id derives from (target, kind, key), so the replay reads back the recorded line instead of minting a second one, even when it filled the charge to the brim. Same key with a different amount or target is answered 409 — the stored line never bends to a retry. Keys are letters, digits and '-' only: '_' joins id parts, so a key like 'abc_r' could spell another line's reversal id; append() now also refuses to hand back a line of another kind, turning any future grammar slip into a 500 instead of money on the wrong line. Statements page their per-charge rows through the usual ?limit&offset envelope; the balance and every rollup still fold the whole ledger before the window is cut.
feat: 💰 track school fees in an append-only ledger of fee plansAhmet Kaan Gümüş · 740e96a
feat: 💰 track school fees in an append-only ledger of fee plans
Fee plans (name + 1..60 installments of {amount_minor, due_at}) are
assigned directly to students; assignment appends every installment as
a charge at once, keyed <plan>_<student>_c<n> so a replay bills nobody.
Payments target one charge, refunds target one credit, and a reversal
undoes only the negative-fold kinds — a mistaken credit is corrected by
a refund, never edited. Balance is never stored; the over-payment cap
folds the target's source subtree under PAYMENT_LOCK and stays advisory
across replicas, which the module doc states outright.
Meal money is untouched: two ledgers, two balances, one shared amount
vocabulary.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
fix: 🕛 anchor the meal cutoff to when lunch is actually servedAhmet Kaan Gümüş · 21f4643
fix: 🕛 anchor the meal cutoff to when lunch is actually served
The booking and cancel deadline counted back from midnight UTC of the
menu date, so a two-hour cutoff on lunch barred bookings from 22:00 the
day before. Meal slots now carry an optional serving time and the
deadline counts back from that; a slot without one keeps the old
midnight behaviour, so nothing changes until a school sets hours.
Times are minutes past midnight UTC. There is deliberately no school
timezone setting, so a UTC+3 school enters 09:00 to mean noon; the
field says so wherever it is described.
Serving time is looked up live rather than snapshotted onto the menu,
because the cutoff minutes already are — freezing one half of a
deadline and not the other would split a single policy in two.
Storing an Option inside an object turned out to break the settings
CAS. SurrealDB drops an object key whose value is NONE, and a stored
{name} never again equals the {name, serving_minute: NONE} the derive
emits, so every PATCH /settings would have answered 409 forever for any
school whose slots predate this field. The guard now compares a rebuilt
projection. Verified against the live volume, whose singleton is
exactly that aged shape.
Also: losing a race to write a ledger line returned 500 rather than the
line the winner had already written. A duplicate record id is now read
back instead, matched on the typed error so real database failures
still surface.2026-07-25
🎨 style: cargo fmt the tree before the audit fixesAhmet Kaan Gümüş · b4a5a00
🎨 style: cargo fmt the tree before the audit fixes Pure reformatting, no behaviour change: rustfmt wrapping plus its alphabetical `use`-list reordering across the files that had drifted. Kept separate so the correctness commits that follow carry only logic.
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
identity2026-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.✅ test(appointments): cover the booking lifecycle and its guardsAhmet Kaan Gümüş · fff77ceBrowse files
✨ 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.
✨ feat(ai): QUIC bridge for out-of-process AI servicesAhmet Kaan Gümüş · dc49954
✨ feat(ai): QUIC bridge for out-of-process AI services The AI features live in separate projects, so they need a transport. QUIC: each request rides its own bidirectional stream on the service's single long-lived connection, which puts multiplexing in the transport — no correlation-id bookkeeping, no head-of-line blocking between concurrent requests, one handshake instead of one per request. The backend listens and the services dial in, so a service can sit behind NAT, restart without the backend knowing its address, and scale out by opening a second connection (each connection is an independent worker). Protocol "hab/1", also the ALPN so an incompatible service is refused at the TLS handshake rather than one frame later. Frames are length-prefixed JSON (u32 big-endian) because the services will not be Rust; the length is checked against an 8 MiB cap before any buffer is allocated. The control stream carries Hello/Greeting and then stays open — its closure is the goodbye, so there is no heartbeat frame, and a silent death is caught by the QUIC idle timeout. Routing is least-inflight rather than round-robin: AI request costs are wildly uneven, and taking turns would pile a second long inference onto a busy worker while an idle one sits next to it. Selection and the in-flight increment happen under one lock so concurrent dispatches cannot overshoot a worker's declared max_concurrent, which a Lease releases on drop. Services authenticate with a shared token (constant-time compare); the certificate only proves the backend, and is self-signed at boot unless a PEM pair is configured. Since that regenerates per boot, GET /ai/certificate publishes it (PEM + sha256) for a service to pin — public because a server certificate is handed to every peer in the TLS handshake anyway, and 404 when the bridge is off. A service must re-fetch on every reconnect, not once at startup. Off unless AI_QUIC_ADDR is set, so the API is unchanged for deployments without AI. Set without AI_SHARED_TOKEN it refuses to boot rather than listen unauthenticated.
2026-07-21
🎨 style: cargo fmt the question-pool and keepalive codeAhmet Kaan Gümüş · bdde827
🎨 style: cargo fmt the question-pool and keepalive code Leftover unformatted lines from the two most recent commits; `cargo fmt` picked them up during unrelated work. Line wrapping and import order only, no behavior change.
🐛 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(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.
2026-07-18
🐛 fix(users): drop enrollments when a user leaves the student roleAhmet Kaan Gümüş · 6917977
🐛 fix(users): drop enrollments when a user leaves the student role
Enrollment is student-only, but promotion left the rows behind: the
ex-student stayed on course rosters, inflated the live monitor's
enrolled/absent counts, and kept course view access. Security paths
always re-checked the live role — this is roster hygiene, not a hole.
PATCH /users/{id}/role to any non-student role now sweeps the target's
enrollments, and a boot backfill deletes rows already stale on disk
(including rows whose user record is gone: user.role = NONE).2026-07-17
✨ feat(subjects)!: course subjects, required on every exam questionAhmet Kaan Gümüş · 022aaaa
✨ feat(subjects)!: course subjects, required on every exam question
Each course now owns its curriculum as subjects (name + optional
description; course link fixed at creation). Every exam question must
be tagged with a subject of its exam's own course, so exam content is
attributable to a topic.
- POST/GET /courses/{id}/subjects (manage / course-visibility, paged)
- GET/PATCH/DELETE /subjects/{id}; delete is a 409 while any question
still references the subject — re-tag or delete those questions first
- course delete cascades its subjects
BREAKING: question create/update payloads require subject_id, and
questions written before subjects existed are destroyed on boot
(answers first) — nothing truthful to backfill, pre-customer clean
break.2026-07-16
✨ feat(events)!: registration audience replaces hand-picked usersAhmet Kaan Gümüş · 31e155a
✨ feat(events)!: registration audience replaces hand-picked users
Events gain a `registration` audience: a signup list built one seat
at a time — teachers place students (students never register, not
even themselves), staff take only their own seat, never another's.
An optional capacity caps the list (seat count re-checked inside the
insert transaction), and the list freezes the moment the event
starts, both directions. Seats resolve live like every audience:
roster, marking gate, and who-missed report inherit unchanged.
- POST /events/{id}/register {user_id?}: idempotent seat upsert
(enrollment's composite-id trick); 409 when full or started
- DELETE /events/{id}/register/{user}: same self-or-student rule;
a deleted account's leftover seat is any teacher's to free
- event delete cascades signup rows; audience switches leave them
inert (they resurface if the kind returns)
- migration split into DDL + backfill queries: statements in one
batch see the batch-start schema, so a backfill next to a fresh
DEFINE FIELD silently lost the keys it wrote (audience became {})
BREAKING CHANGE: the hand-picked `users` audience kind is gone —
requests naming it are rejected. Existing users-audience events
convert on boot: each listed user becomes a registration row
credited to the event creator and the audience becomes an uncapped
registration list.✨ feat(events)!: audience targeting + teacher-only attendanceAhmet Kaan Gümüş · bd9e7d8
✨ feat(events)!: audience targeting + teacher-only attendance
Every event now carries an audience — school (default), one exact
role, a course's live enrollment, or a hand-picked user list (<=100)
— defining its expected-attendee roster. Resolved at read time, never
snapshotted, so role changes and (un)enrollment move people in and
out by themselves. Visibility is unchanged: everyone sees every event.
- GET /events/{id}/roster: who-missed report (teacher+), expected
list joined with marks, status null = never marked
- marks for people later dropped from the audience stay in the
attendance listing but leave the roster report
- pre-audience rows backfill to school-wide on boot
BREAKING CHANGE: POST /events/{id}/attendance requires teacher+ —
students can no longer mark attendance, not even their own — and the
target must be in the event's audience (400 otherwise). Event
responses gain an audience object.✨ feat(users): per-user UI preferences (theme, language)Ahmet Kaan Gümüş · 7168ba0
✨ feat(users): per-user UI preferences (theme, language)
Theme (light/dark) and language (tr/en) live on the user row and
return on every user response. PATCH /users/me/preferences is
self-service for any role; PATCH /users/{id}/preferences is the
admin path. Same merge semantics as the profile patch: omitted
keeps, "" clears, anything else validates or the patch is a 400.
Null means "never chose": clients fall back to the device
preference (prefers-color-scheme, browser language), so there is
deliberately no server-side default to stomp device detection.
Pre-feature rows read back null through the option<string> columns
— no backfill needed.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