forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to tests/limits_completeness.rsClear filter

2026-09-24

🐛 fix(schedule): code-review findings on the holiday and section surfacesAhmet Kaan Gümüş · ecd544b
🐛 fix(schedule): code-review findings on the holiday and section surfaces

A PATCH that moves a lesson onto an instant another lesson of the same section
already starts at now answers the coded 409 session_time_taken instead of a
500 — the new UNIQUE (class_course, starts_at) was mapped on the create door
only.

The materialize route rejects an unrepresentable from/to (i64::MAX and friends)
with a 400 naming the field, instead of panicking inside the day math; the
guard is checked arithmetic over the largest offset the timezone allow-list can
produce, and zoned_day's own contract is untouched.

The profile course block withholds class, class_name and grade_level from a
viewer who fails the same bar the classes block in the same response applies —
a student could read another student's class name and grade through a shared
catalogue course.

visible_instances resolves the sections a teacher is assigned in with one
statement instead of a query per taught course plus one per instance; every new
per-section surface pays that read.

2026-09-23

✨ feat(profile): add gender, address, and emergency contact to the user row Local-Gate: 1f2b0abcf3798a63b2c5365e0d15c9f708f45833 (1523 passed, 430s)Ahmet Kaan Gümüş · f151345
✨ feat(profile): add gender, address, and emergency contact to the user row
Local-Gate: 1f2b0abcf3798a63b2c5365e0d15c9f708f45833 (1523 passed, 430s)
✨ feat(podcast): persist the transcript and serve it on the result doorAhmet Kaan Gümüş · 64eabd4
✨ feat(podcast): persist the transcript and serve it on the result door

The service's done report now carries the narration text; the backend
stores it in podcast_job.transcript (fill-once, blank means absent so a
progress report cannot stick an empty string) and returns it from
GET /podcast/jobs/{id}/result under the same owner-scoping and expiry
rules as the audio. Reports without the field keep passing, so older
service builds are unaffected.
Local-Gate: 2824ca0c3e6cf2366b8f62c09f5babe384f6e0db (1512 passed, 449s)

2026-09-18

✨ feat(rag): relay rag.summarize and rag.questions over the bridgeAhmet Kaan Gümüş · 69d4295
✨ feat(rag): relay rag.summarize and rag.questions over the bridge

The RAG service has had two study features the backend never dispatched:
a scope summary and a set of generated practice questions, each one-shot
and addressed to exactly one (sınıf, ders) corpus.

- constant.rs: AI_RAG_SUMMARIZE_CAPABILITY / AI_RAG_QUESTIONS_CAPABILITY
  with 25 s deadlines — a waiting door must finish under the 30 s request
  envelope; MAX_RAG_QUESTIONS is published at /limits.
- ai/rag_study.rs: the two payload/reply contracts and their dispatch,
  wire-key pinned.
- web/rag.rs: POST /rag/summarize and POST /rag/questions over the same
  QUIC bridge and the same 503 capability gate as the rest of the nest.
  The asker's (sınıf, ders) pairs come from their memberships; the body
  only names a target inside them (403/400 otherwise). An abstention is a
  complete 200; only role_required/scope_mismatch — the backend's own bug —
  is a 502.

README endpoints table regenerated; AI bridge prose extended with both
contracts and the honest RAG-side limits.
Local-Gate: 852ea13260383ac5c071fce412db110becbcbdde (1505 passed, 473s)
📄 feat(insight): render and serve a school-level report documentAhmet Kaan Gümüş · 541d9b7
📄 feat(insight): render and serve a school-level report document

`insight.report` is the third outbound ZEKA dispatch, and the first that
carries its data: the service may not read a school database, so the backend
reads its own `zeka_*` rows (four new school-wide bulk reads, projected
straight into the serde rows the storage surface already writes) and sends
them in the request. The service renders, the backend stores.

* `POST /insights/runs/{run_day}/report` — manager+, synchronous: build the
  payload, dispatch with `AI_INSIGHT_REPORT_TIMEOUT_SECS`, store the returned
  HTML under the school's own blob directory (`zeka_report/<day>.html`, temp
  name + rename, never a partial file), answer `200` with what was stored.
  A run day with no ledger row is a legal request; the service's `notes` say
  what it found. Its typed refusals map per class: `bad_request` 400,
  `insufficient_rows` 409 `report_empty`, `document_too_large` 413,
  `internal` 500, anything else 409 `report_refused`. An empty document is
  refused, never persisted — a blank page must not read as a report.
* `GET /insights/runs/{run_day}/report` — manager+, streams the stored
  document (`text/html; charset=utf-8`, nosniff, private no-store);
  `409 report_missing` when nothing was generated, a day the ledger has never
  heard of included.

Both doors share one path (one `routes!(generate_report, serve_report)`), so
no nest or `MODULE_PREFIXES` change; `MIN_PROTECTED` 338 → 340 (derived).
`pump` moves from the podcast nest to `web` as a shared blob-stream helper.

Known gap, reported rather than widened here: the wire `RecommendationRow`
carries no `dismissed_at`, so the service's dismissal gate cannot fire on
this payload.
✨ feat(insight): name the requester and fill a school-wide refresh rosterAhmet Kaan Gümüş · 0f55f34
✨ feat(insight): name the requester and fill a school-wide refresh roster

Every `insight.*` dispatch now carries `requested_by` — the caller the door
authenticated, which the service passes as `on_behalf_of` so its per-student
reads (`/marks/{user}` and the rest) answer as that teacher or manager instead
of the synthetic `ai` principal those reads refuse with a 403.

`insight.refresh` also always fills `user_ids`: a caller-named list passes
through exactly as given, while an empty body is filled from the school's own
student roster (every user holding the `student` role), because the service's
own roster discovery reads homework `assigned` lists, which a live school
rarely fills — so an empty body used to sweep nobody. The payload's new
`roster_source` records which roster the list was, and the refresh log names it
so the run ledger's counts are explainable. A school with no students dispatches
an empty list and answers 0 honestly; a roster past
`MAX_INSIGHT_REFRESH_STUDENTS` is refused rather than clipped.
Local-Gate: 644eaaee78ddae2e35af223da2719c3a55697a86 (1488 passed, 466s)

2026-09-17

✨ feat: ZEKA no longer touches the database directly - the insight.* storage surfaceAhmet Kaan Gümüş · 7c96e47
✨ feat: ZEKA no longer touches the database directly - the insight.* storage surface

No AI service may hold a school database credential, so the nine reads and
writes ZEKA performed against its own zeka_* tables become named operations
the backend serves: insight.summary|recommendation|segment|profile|run.upsert,
insight.pending.list, insight.retention.sweep, insight.departed.purge and the
deployment-scoped insight.schools.list.

They ride a new client-initiated capability call (CapabilityRequest ->
CapabilityResponse, mirroring Request/Response field for field) and are
mounted as HTTP doors on the same functions (manager+; the school directory is
the builder's, outside the school gate). Every statement runs inside the
school the frame named, in one transaction per batch.
fix: 🧪 [TEST] the podcast capability constants are declared, not published limits - limits_completeness demands every pub const in constant.rs be either in GET /limits or in EXCLUDED with a reason; the podcast lane never owned this fileAhmet Kaan Gümüş · d079eff
fix: 🧪 [TEST] the podcast capability constants are declared, not published limits - limits_completeness demands every pub const in constant.rs be either in GET /limits or in EXCLUDED with a reason; the podcast lane never owned this file
✨ feat: ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nestAhmet Kaan Gümüş · b0b5e0c
✨ feat: ZEKA's insight capabilities — its school schema, the dispatch contract, and the /insights nest

`hezarfen_zeka` already dials the QUIC bridge correctly and declares three
capabilities the backend did not know (`insight.student`, `insight.class`,
`insight.refresh`), and it writes nine `zeka_*` tables the school schema did
not contain — so nothing could route to it and nothing could read what it
computed. This lands all three missing pieces.

* the migration: `migrations/school/20260917000002_zeka.sql`, the service's
  DDL copied verbatim (every FK resolved against the existing school schema:
  `app_user`, `course`, `subject` and `exam_question (exam, id)`).
* `src/ai/insight.rs`: the payload contract for the three capabilities,
  mirroring the service's TypedDicts, plus the two dispatches the backend can
  route today — `compute_student` and `refresh`. `insight.class` stays
  contract-only: its request names a course the service would have to
  enumerate a roster for, and the bridge's read allowlist carries no member
  listing yet (`hezarfen_zeka/service/docs/BACKEND-GEREKSINIMLERI.md` item 3).
* `src/web/insights.rs`: the nest. `POST /insights/students/{id}` and
  `POST /insights/refresh` (manager+) queue a detached dispatch and answer
  `202` — the service writes its own rows, so a client polls the read routes;
  `503` when no worker offers the capability and nothing is queued.
  `GET /insights/me`, `GET /insights/students/{id}` (teacher+ narrowed to the
  students they reach through a shared instance, or a parent holding a live
  link; anyone else reads `404`, never `403`) and `GET /insights/runs`
  (manager+) read the tables back. The service's output contract's own gates
  hold on the read side: the attention list never reaches the student it is
  about, a card's `about` never reaches a student caller, dismissed/expired
  cards and `confidence: none` segments are filtered out.

Gated on `Module::Chatbot` like the other two AI nests, with its tag prose in
`src/lib.rs`, the README endpoints table regenerated, and the `.sqlx` cache
refreshed for the seven new statements.
✨ 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).
🔧 chore: give ResolvedTenant its core home and make constant.rs a leafAhmet Kaan Gümüş · d0dce85
🔧 chore: give ResolvedTenant its core home and make constant.rs a leaf

Two structural defects a knowledge-graph pass over src/+tests/+migrations
surfaced. Both were verified against the real `use` lines before being called
defects — a module cycle is legal Rust, so only the layering facts count.
No behavior change: every moved item is byte-identical in name, type, value,
element order and doc text.

- `ResolvedTenant` was *declared* in `src/web/tenant_state.rs` but *built and
  returned* by `Tenants::resolve` (`src/tenant.rs`), so the core tenant
  registry imported the web layer. The struct moves to `src/tenant.rs`; its
  `impl FromRequestParts` stays in the web module (same crate, local type).
  That deletes the crate's only core→web import edge, and with it the three
  module cycles running through `state.rs` and `ai::server`.
- `constant.rs` is documented "Validation limits, in one place" but imported
  four domain enums to hold non-limit vocabularies: `ROLES` → `domain/role.rs`,
  `THEMES`/`LANGUAGES` → `domain/preferences.rs`, `SENDER_FOLDERS`/
  `RECIPIENT_FOLDERS` → `domain/message.rs`, and the 34-row `BADGES` catalogue
  → `domain/badge.rs`. Each now lives in the module that owns its type, so
  `constant.rs` imports nothing from `crate::domain` and ten
  `constant ↔ domain` cycles disappear. `AI_PRINCIPAL_KEY` and
  `PALETTE_COLOR_*` stayed put.

Measured on the same corpus: 20 → 7 reported import cycles — all ten
constant↔domain and all three tenant↔web cycles gone. The surviving seven are
intra-layer domain cycles plus the ai↔web pair; the AI bridge is a peer
front-end reusing web authorization helpers, which is deliberate, not an
inversion.

Tests: the published-or-excluded guard in `limits_completeness` read only
`src/constant.rs`, so the five moved tables silently left its scan — the one
place this move weakened coverage. It now covers them by name, and its
`references()` check no longer counts a bare `use` line as "published", which
the first witness attempt proved had made the guard vacuous. Witnessed by
mutating BADGES and then ROLES out of `/limits`: each FAILs naming the moved
table, and each restore is sha256-identical.

Gates: no SQL touched (.sqlx and migrations clean), prepare DB unchanged;
SQLX_OFFLINE=true cargo check --all-targets, clippy -D warnings,
limits_completeness, spec_bounds all green; cargo nextest run 1386/1386 across
47 binaries (doc_sync included).

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

🧪 test: port T4 regress/partial-patch suites to the Postgres harnessAhmet Kaan Gümüş · f553d14
🧪 test: port T4 regress/partial-patch suites to the Postgres harness

- fixture SQL → runtime sqlx (kind_ref/slot_ref upserts, settings JSONB,
  point-row UPDATEs, count/scalar helpers); ULID idioms re-pointed
- SurrealDB DEFINE EVENT injections → PG-native: RAISE triggers (roles/
  classes/blueprints pending), pg_sleep window trigger (exam delete),
  lock-queueing probe (attendance), row-snapshot probe (badge awards)
- EXTRA: drop DB_KEEPALIVE_INTERVAL_SECS/DB_PING_TIMEOUT_SECS + their
  /limits EXCLUDED pins; drop stale BOARD_OPEN_GUARD pin (wave-2 leftover)
- production fixes pinned by these suites: exam_result grade claim mints
  an absent kind_ref (absent = in service); field_update run() emitted a
  double WHERE (every guarded PATCH 500'd); attendance event mark now
  locks the event row (orphan race); admin floor takes the admin-set row
  locks (cross-target demotions raced); profile focus sum cast to BIGINT
- delete the two appointment store-property tests: their subject was the
  SurrealDB engine's write-skew; Postgres closes it by constraint
- .sqlx refreshed for the changed query macros

2026-09-05

🐛 fix: blob stream resets on write stall, client-stream routing without a Value cloneAhmet Kaan Gümüş · bc43602
🐛 fix: blob stream resets on write stall, client-stream routing without a Value clone

A blob body that makes no progress for AI_BLOB_WRITE_STALL_SECS is reset
rather than parking the copy task and an open fd for the connection's life.

Ref #27
✨ feat: rag_output table + rag.index dispatch for course notesAhmet Kaan Gümüş · d42a1c3
✨ feat: rag_output table + rag.index dispatch for course notes

The backend now owns the RAG side of a course note: a new `rag_output`
table stores whatever an AI service produced for a note, and the backend
asks for it — the AI service still writes no human data, and the api-read
bridge stays GET-only.

`rag.index` is dispatched fire-and-forget (tokio::spawn) after a note is
created, edited, or gains/loses a file, so no HTTP handler waits on, or
fails because of, an AI service; with no worker carrying the capability
the trigger is a silent no-op. The request carries the note's text plus
attachment METADATA only (file bytes deliberately off the wire — open
with the service owner). Rows are derived data, so they cascade: the note
delete drops its outputs, and a file delete drops every output built from
it even when no service is connected.

HTTP GET/DELETE routes over the rows are part 2.

Ref #27

2026-08-12

🤖 feat: allowlist the GET paths ai services may readAhmet Kaan Gümüş · 317ef9c
🤖 feat: allowlist the GET paths ai services may read

Deny-by-default: the bridge will only ever dispatch a service's read into
the router when the path matches AI_API_ALLOWLIST segment for segment. No
prefix match, no wildcard tail, so a new route family is unreachable to
the services until it is listed on purpose.

v1 is JSON-only and scoped to what a study companion needs: identity and
profile, notes, homework reads, and the marks/attendance/pomodoro
reports. Byte-serving routes (note files, submission files, avatars,
question images) are left out — the frames carry JSON.

The entries are router paths kept by hand, so integration.rs pins each
one to a GET in the emitted OpenAPI document: a route rename now breaks
the test instead of silently shrinking the services' scope.
🤖 feat: add service-only Role::AiAhmet Kaan Gümüş · 3a01d26
🤖 feat: add service-only Role::Ai

The principal an out-of-process AI service carries over the QUIC bridge.
Declared first in the enum so the derived Ord puts it under every role: it
clears no `at_least` bar and fails every exact `== Role::Student` /
`== Role::Parent` gate. Absent from ROLES, which is what makes it
unassignable — `try_from_str` searches that table, so "ai" is rejected like
any unknown word, and /limits keeps listing the five human roles. Role still
carries no serde derive, so nothing deserializes it off the wire.

`User::ai_principal` builds it in memory only, on the literal record key
`ai_service` that no minted ULID can collide with, with an empty password
hash that verifies against nothing. Never written to the database.

The web DTO gains the variant because the mapping is exhaustive, so "ai"
appears in the OpenAPI Role schema — documented there as never assignable.

2026-08-02

fix: 🔩 clear the deferred backlog and ship class phase 2Ahmet Kaan Gümüş · afff737
fix: 🔩 clear the deferred backlog and ship class phase 2

Ten defects and two features, worked as one series because the doc
surfaces and the const table are shared.

Defects closed:

- Cross-exam answer-key leak. The bank copies `correct` into every
  instantiation, so reviewing exam A handed out the key to a question
  the caller was still writing in exam B. Review now blanks those
  questions rather than closing: the join matches on `from_bank` AND
  `banked_as` (a question can carry both — instantiated, then re-saved
  to the bank — so a coalesce misses a copy), redacting `correct`, the
  correctness flag and that question's `auto_score` share. Keyed on the
  template, never the exam, so the rest of the review reads normally.
- `set_role` was not atomic with its sweeps. The role write and every
  grant it invalidates now commit as one transaction; the board rooms
  are told after COMMIT from the cascade's own result slot. Built
  best-of-N; the losing charter left the one sweep outside whose failure
  strands an event seat no route can free.
- Board rosters held below-student ids, which 400d the creator's next
  roster PATCH. Repaired at boot, and a PATCH may now send back the
  roster it was served: an id already present that stopped qualifying is
  dropped, a new one still refused.
- `note_file` blobs leaked. The delete transaction returns the rows it
  removed and the handler unlinks exactly those, not a pre-read snapshot.
- Rate limiting failed open on a saturated map. Never-seen clients now
  share one metered overflow budget instead of arriving unmetered.
- Whiteboards: `GET /boards` takes `?open=`, `/strokes` no longer leaks
  a clear marker the socket filters out, and a locked board refuses its
  creator's clear (409) — the lock now means one thing on every path.
- Blueprint skips named the wrong record: `Attached::Gone` was two facts
  under one name, split into `Gone` (class) and `PivotGone` (course).

Features:

- Event audience `kind=class` — live from `class_member`, membership
  checked in one select because the (class, user) pair is the row id.
- Grade blueprints: a grade's course template, retro-pumped best-effort
  with a skip list. Attachments carry a provenance tag, so removal
  spares what a human placed. A course deleted out from under a
  blueprint is pruned from the template by the pump that finds it.

Forcing functions, because a hand-kept copy drifts:

- `protected_routes_require_session` is derived from the emitted
  OpenAPI: 248 -> 254 operations swept, was 80 typed by hand.
- Every JSON-bodied operation declares 422 (74 sites), pinned both ways
  — and multipart routes, which answer 400, are pinned to NOT declare it.
- The SurrealQL registration-freeze guard is pinned against the Rust it
  copies; both mutations of it fail the test.
- `migration_mark` gates one-time backfills. The roster repair rescanned
  every board against every user on every boot (773ms at 300/2000 with
  nothing to write); it is now skipped once done.

Verified by a three-lens verifier panel — which caught the `banked_as`
half of the answer-key leak by executing a probe, after the first fix
had been reported complete — and by a podman boot against the existing
volume: both new fields defined, the marker written, boot 2 skipping the
scan, and the live API answering on the new routes.

2026-08-01

docs: 🧹 stop the migration comments claiming a fleetAhmet Kaan Gümüş · 079af73
docs: 🧹 stop the migration comments claiming a fleet

Multi-replica support was deleted; the rate_limit row is restart
continuity for one process, the capacity/delete guards close write skew
between concurrent request tasks, and the = NONE seeds are about
migrate() rerunning on an existing volume — not about a peer serving.
Comment prose only; no SQL byte changed.

2026-07-31

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

fix: 🧊 freeze a fee plan the moment it is assignedAhmet Kaan Gümüş · ac70cc0
fix: 🧊 freeze a fee plan the moment it is assigned

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

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

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

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

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

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

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

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

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

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

2026-07-27

fix: 🧷 close the cross-table races the locks never closedAhmet Kaan Gümüş · 4f7bdaf
fix: 🧷 close the cross-table races the locks never closed

Every remaining check-then-write that spanned tables becomes a
single-record conditional write, so it holds across replicas:

- subject delete: refcounts (exam_question_count/homework_count) claimed
  and released by every question/homework write; the triple lock hold
  dies, BANK/TERM/ENROLL locks die outright
- exam kinds: kind_ref {count,retired} records; grading claims, removal
  retires only at zero — grading a removed kind and re-kinding a graded
  exam are now 409 (both previously silently mis-weighted marks)
- homework: the grade stamps the submission row in its own transaction;
  student writes are conditional on the stamp being absent
- appointments: slot occupancy is a cap-1 counter; the lock survives
  only for the within-replica approved-overlap check
- meals: seat counter + menu version CAS (price can no longer tear mid
  booking) + deterministic menu:date_slot id kills duplicate publish
- cap::claim_and_create: member gate, then seat, then child CREATE in
  one transaction — a duplicate loser no longer eats a stranger's seat
  or gets refused for a row it already owns
- boot: the two unguarded lease statements now retry on transaction
  conflict (the escape was ~1-in-15 under full-suite load)

Two races reviewed and accepted, documented in README ## Concurrency
model: the attempt-seq late save (one history row, grade of record
untouched) and cross-replica approved-overlap (visible, cancellable).

Deployment contract (README): counter-adding releases restart all
replicas together — an old binary's writes skip new counters and the
= NONE backfill guard rightly refuses to re-seed.

Every guard is mutation-proven; backfills are one-time, = NONE-guarded,
ordered after the destructive sweeps, and verified against the live
volume.
fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process

Two replicas are live; every process-local lock silently stopped
meaning anything. Move the invariants into the writes themselves:

- count caps (enroll/register/files/threads) become a counter column
  claimed by UPDATE .. WHERE n < cap (domain/cap.rs), backfilled once,
  decremented in the same transaction as every child delete
- exam freeze, re-draft and grade gates ride inside the write's own
  transaction (IF .. THROW); SESSION/WORK_ENTRY/EVENT locks die, range
  checks fold into the UPDATE's WHERE (FieldUpdate::ordered)
- appointment decisions CAS on status+proposed window+decided_by;
  bank/exam updates CAS on their editable columns
- rate limiter syncs local windows to a shared minute row every 2s,
  fail-open when the database is down
- paged GETs run LIMIT/START in the database (domain/page.rs); sites
  that post-filter in Rust stay web-sliced and say so
- exams.rs (3629 lines) splits into web/exams/{mod,attempts,questions,
  images,review}; image uploads single-source in web/image.rs; the
  bare-seq key rule lives once in domain/key.rs; migration SQL moves
  to migration_sql.rs

Every new guard is mutation-proven (removing it fails a named test).
Migration adds counter columns + rate_limit table; backfill is
one-time, guarded by = NONE, and verified against the live volume.

Traps recorded: SurrealQL 'x ?? 0 > 0' parses as 'x ?? (0 > 0)'; the
embedded mem engine drops one of two concurrent writes yet answers Ok.

2026-07-26

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

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

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

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

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

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

hab/1 is untouched. Verified on two live replicas against one SurrealDB: a
turn posted to a worker-less replica was answered by its peer, survived a
restart of the other replica mid-flight, and was dispatched exactly once.
feat: 🍽️ run the canteen: menus, seats, allergens and a ledgerAhmet Kaan Gümüş · fd5cfd1
feat: 🍽️ run the canteen: menus, seats, allergens and a ledger

Published menu calendar (manager+ authors, everyone reads), per-student
dietary profiles that mark conflicting dishes, meal booking with an
optional per-menu capacity, meal attendance, and booking-triggered
billing.

Booking is the charge trigger: reserving a seat stamps a charge at a
price snapshot, so later dish edits never rewrite what a student owes.
No-show still pays, because the kitchen already bought the food, which
is why attendance has no billing effect at all. Money enters only as
admin-recorded credit entries; there is no gateway and no card data.

The ledger is append-only. Cancelling appends a reversal rather than
deleting the charge, balance is always folded from the rows, and the
sign lives in exactly one function. A deletable ledger row would
rewrite a student's financial history leaving no trace.

Charges and reversals are keyed per (booking, attempt) and written
under MENU_LOCK alongside the seat, so a double-click, a retry, or a
cancel cut short mid-flight all settle to one charge and one refund.
That lock is in-process only: a second replica would break every
capacity and charge guarantee here.

A parent may book for a linked student, the first write parent_link
has ever authorised, and sees only seats whose link is still live.
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.