forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/domain/chatbot_thread.rsClear filter

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

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-09-08

2026-08-05

🎟️ fix: stop a demotion sweep leaving grants it cannot reachAhmet Kaan Gümüş · 70591d4
🎟️ fix: stop a demotion sweep leaving grants it cannot reach

User::set_role lowers the role and sweeps every grant it implied in one
transaction, but those sweeps are snapshot-based. A child create landing
after the snapshot survives them, because all three wrote their other
parent — the event, course or class row — and never the user row, which
is the only key the sweep writes.

The event seat was the bad one: a seat held by someone now a parent
could be freed by nobody. unregister 403s on a non-student target, and a
parent fails RequireTeacher, so the only exits were deleting the event
or round-tripping the role. It permanently consumed a capped place.

All three now claim the holder's user row through cap::role_claim, whose
UPDATE returns the live role and so is both the colliding write and the
guard. unregister additionally bars staff rather than non-students, so a
seat already stranded on the volume is freeable by any teacher+.

undo_if_demoted was not reused here: it repairs columns, while the
residue in these three is a row plus a counter — and for the seat, the
repair would have to run before anything could free it.
test: 🧪 pin the two fixes no mutation could reachAhmet Kaan Gümüş · 12f2280
test: 🧪 pin the two fixes no mutation could reach

The thread stamp: neither existing test could see `math::max` vs a plain
`$now`, because timing cannot reach the elision window on demand — every
append is a transaction of its own and costs about a millisecond. So the
state that window produces is set up instead, a stamp ahead of the clock,
and the two rules are told apart with no race at all.

The course cascade: `delete_course` holds `EXAM_LOCK.write()` and nothing
raced it. Its own test binary, because `EXAM_LOCK` is process-wide and
`regress_exam_delete` running beside it hid the mutation.
fix: 🤖 answer a contended thread delete 204, not 500Ahmet Kaan Gümüş · c998c0d
fix: 🤖 answer a contended thread delete 204, not 500

`ChatbotThread::delete` was the one delete in this domain sent as a bare
guarded transaction with no retry loop, the shape `Board::delete`
documents. It writes the thread row, and so does every turn, every
rename and every other thread's cap claim on the same user — a lost
round therefore surfaced as `AppError::Db`, a 500 for a delete that
merely raced and would have succeeded on a re-send. Now that a turn
deliberately collides with this batch, that round is no longer rare.

Admissible by the stated rule: the batch is DELETE / DELETE / UPDATE
only, none of which can legitimately answer "already exists". On a
re-sent round the thread is already gone, the `RETURN` is empty, and the
caller gets the 404 that is the truth rather than a 500.
fix: 🤖 stop a chatbot turn from outliving its threadAhmet Kaan Gümüş · 2351107
fix: 🤖 stop a chatbot turn from outliving its thread

Sending gated itself by reading the thread and then created two rows
that wrote only `chatbot_message`. A delete sweeps its turns and drops
the thread in one transaction, so a create landing after that sweep but
before the commit read a thread that was still there (uncommitted) while
the sweep had run on a snapshot predating the new row — both committed,
and the prompt and its answer survived under a thread that was gone.

Reads do not conflict, and `SET x = x` is elided before it reaches the
write set, so only a write that MOVES a value on a key the delete also
writes serializes the two. Turns now ride `touch_and_write`, which bumps
the thread's `updated_at` in the same transaction as the create — the
shape a dish and an exam answer already use. That bump is also the
activity stamp the send path used to issue afterwards as a separate,
best-effort query whose failure was a `warn!`, so the stamp can no
longer be lost either. It is written strictly upwards rather than to
`$now`: a turn's two rows routinely share a millisecond with the
thread's own creation, and an UPDATE that changes nothing is elided —
which would collide with nothing.

Nothing swept the orphans: no migration sweep, and boot repair only
fails `pending` rows. They also stayed readable — `own_message` checked
the owner and the thread key but never that the thread existed — so
`GET /chatbot/threads/{deleted}/messages/{mid}` and its `/stream`
answered 200 with text the user had deleted. That read now re-reads the
thread, which is defence in depth for rows an older binary already left
on a live volume; the SSE poll loop is untouched, so it costs one extra
record read per polling client and not one per tick.

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

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: 🪢 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

feat: 📐 publish every hard limit instead of making the frontend guessAhmet Kaan Gümüş · 7152aa9
feat: 📐 publish every hard limit instead of making the frontend guess

Every bound the API enforces lived in one of two places the frontend
could not read: a `pub const` in `constant.rs`, or English prose in a
doc comment ("1–20 entries", "`1`–`100`"). So the frontend kept its own
copy of each number, and the copies drifted the moment one moved.

Two surfaces now carry them, because clients consume them two ways.
`GET /limits` is one JSON document grouped by resource, built by naming
the constants directly — a runtime fetch, no codegen step, and it
carries what OpenAPI holds awkwardly (`reserved_usernames`, the raster
`image_content_types`, the closed role/kind/mode/status sets). The spec
gets the other half: 105 `max_length`/`minimum`/`min_items` bounds on the
request DTOs, which is what `openapi-typescript` and friends turn into
validators for free.

`/limits` is unauthenticated — the register form needs the username and
password bounds before a session exists, and none of it is secret, it is
the same rule a 400 already spells out. It is also exempt from the
database guard: it reads no row, and a frontend booting against a
reconnecting backend is exactly when it needs the contract, not a 503
that sends it back to the hard-coded copy.

Its `rate` group is the one part that is not compile-time. The
rate-limit tiers are env-tunable, so the endpoint reports this server's
live values off `AppState` rather than the shipped defaults — a client
should learn its budget here, not by collecting a 429.

`MAX_CHATBOT_THREAD_TITLE_LEN` moves to `constant.rs` on the way past.
It was private in `domain/chatbot_thread.rs`, reaching neither surface,
and its own comment asked to be moved the next time anyone was here.

Three tests keep both surfaces honest, because each is a hand-kept
mirror and a mirror nothing checks is one that goes stale. A constant
must reach `/limits` or an exclusion list that states why it does not; a
bound may not be declared outside `constant.rs` at all; and the emitted
spec is fetched and compared field by field against the constants —
never against literals, which would just be a third copy that passes
while both are wrong. That last one is unavoidable rather than
belt-and-braces: utoipa 5.5 takes a literal only, so
`max_length = MAX_NOTE_TITLE_LEN` does not compile.

Two duplicated `maximum = 500` literals are now pinned to
`MAX_PAGE_LIMIT`, which `constant.rs` previously only asked a human to
keep in step.
🎨 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.

2026-07-23

🎨 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.