forge
Explore
Log in

Don't you dare go Hollow

Drop keepalive-era telemetry instruments + tighten claim-fn visibility

Browse files at this commit

a2a344c462746fb61110dfc29bb2601b14f1cc72Ahmet Kaan GümüşParent: 3d61a9e
  • chore
    • drop keepalive-era telemetry instruments + tighten claim-fn visibility
    • Postgres docs (README/CLAUDE.md)
    • ship migrations/ in the image
Show full message
🧹 chore: drop keepalive-era telemetry instruments + tighten claim-fn visibility; Postgres docs (README/CLAUDE.md); ship migrations/ in the image
CLAUDE.mdmodified+16 -10
@@ -1,7 +1,7 @@
11 # hezarfen_backend
22
33 Rust/axum school-management API (auth, roles, exams, notes, messaging,
4-courses, attendance, pomodoro, meals) on SurrealDB v3. Swagger UI at `/swagger`.
4+courses, attendance, pomodoro, meals) on PostgreSQL (sqlx). Swagger UI at `/swagger`.
55
66 ## Project docs — query the knowledge base, do NOT read README.md
77
@@ -30,23 +30,27 @@ python3 ~/.claude/kb/ingest.py README.md | KB
3030 python3 ~/.claude/kb/ingest-endpoints.py README.md | KB
3131 ```
3232
33-The project's own SurrealDB (container `hezarfen-surrealdb`, ns/db
34-`hezarfen`) is runtime data — never write knowledge-base rows there.
33+The project's own PostgreSQL (container `hezarfen-postgres`) is runtime data —
34+never write knowledge-base rows there (the KB lives in `~/.claude/kb/kb.db`).
3535
3636 ## Code map — orient here, skip discovery greps
3737
38-Pattern: `src/domain/<x>.rs` = validated newtypes + entity + its own
39-persistence (SurrealValue). `src/web/<x>.rs` = DTOs + axum handlers, one file
40-per resource, routes wired in `lib.rs`.
38+Pattern: `src/domain/<x>.rs` = validated newtypes + entity. `src/db/<x>.rs` =
39+its SQL (the only layer that executes queries). `src/service/<x>.rs` =
40+workflows (one `tx_with_retry` transaction per invariant). `src/web/<x>.rs` =
41+DTOs + axum handlers, one file per resource, routes wired in `lib.rs`.
4142
4243 - core: `main`(bootstrap) `lib`(build_router+OpenAPI) `config` `constant`(limits)
43- `validate` `error` `database`(connect+SCHEMAFULL migration)
44+ `validate` `error` `database`(PgPool + tx_with_retry + the two sqlx migrator sets)
4445 `rate_limit`(fixed-window per-IP) `state`
4546 - `domain/`: user role session timestamp profile preferences note note_file
4647 message parent_link event attendance registration course course_session
4748 session_attendance enrollment subject term settings work_entry pomodoro
4849 exam exam_attempt exam_question exam_answer exam_result question_image
4950 menu menu_dish dietary_profile meal_booking meal_attendance meal_ledger
51+- `db/`: per-resource SQL; `cap`(count-cap CTE recipes + verdict types)
52+ `field_update` `page`(PagedList)
53+- `service/`: per-resource workflows (booking, minting, cascades)
5054 - `ai/`: QUIC bridge to the out-of-process AI services (backend listens,
5155 services dial in). `protocol`(frames) `server`(AiBridge: listen+dispatch)
5256 `registry`(workers, capability routing) `tls` `error`. Off unless
@@ -55,9 +59,11 @@ per resource, routes wired in `lib.rs`.
5559 responses) `page`(pagination) `exam_ws`(exam-room WebSocket) + per-resource:
5660 auth users notes messages events courses subjects sessions exams marks work
5761 pomodoro attendance settings terms meals
58-- `tests/`: integration(oneshot+mem db) e2e(real TCP+cookies) rate_limit
59- pagination persistence ai_bridge(real QUIC + fake AI service)
60- ai_protocol(hab/1 wire contract; raw byte-level client, imports no protocol
62+- `tests/`: integration(oneshot over per-test Postgres databases — tests/common
63+ mints `init_test_tenants`/`init_test_db`/`deployment_with`, template-clone)
64+ e2e(real TCP+cookies) rate_limit
65+ pagination persistence(idempotent re-migration over a live db) ai_bridge(real QUIC + fake AI service)
66+ ai_protocol(hab/2 wire contract; raw byte-level client, imports no protocol
6167 types — the only suite that catches a wire-format change)
6268
6369 Note: README `## Layout` lags src/ (missing newer domain files); this map +
Containerfilemodified+4 -0
@@ -13,6 +13,9 @@ COPY src ./src
1313 # so the build must never reach for a live database.
1414 ENV SQLX_OFFLINE=true
1515 COPY .sqlx ./.sqlx
16+# The migrators read these at boot/mint (control set on the control pool,
17+# school set for the template + every school database).
18+COPY migrations ./migrations
1619
1720 # Cache mounts keep the registry and incremental build artifacts between
1821 # builds. The binary must be copied out of /app/target inside the same RUN,
@@ -32,6 +35,7 @@ RUN apt-get update && \
3235 mkdir /data && chown hezarfen:hezarfen /data
3336
3437 COPY --from=builder /usr/local/bin/hezarfen_backend /usr/local/bin/hezarfen_backend
38+COPY --from=builder /app/migrations /app/migrations
3539
3640 USER hezarfen
3741
README.mdmodified+146 -159
@@ -1,6 +1,6 @@
11 # hezarfen_backend
22
3-Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · axum · SurrealDB 3 (server, WebSocket) · tokio.**
3+Note, attendance, course + weighted exam mark backend. **Rust (edition 2024) · axum · PostgreSQL (sqlx) · tokio.**
44
55 Session-cookie auth with five hierarchical roles (`parent < student < teacher
66 < manager < admin`). A **`parent`** observes and changes nothing: admins tie
@@ -201,24 +201,31 @@ represented. Those restrictions are published rather than left to be guessed:
201201 **`GET /limits`** (no auth) serves every fixed bound and closed value set the
202202 API enforces, read straight from the constants the newtypes use, so a frontend
203203 validates against the server's own rules instead of a hand-kept copy (see
204-"Validation limits"). Those same types derive `surrealdb::types::SurrealValue`, so one
205-typed value flows from HTTP request into the `SCHEMAFULL` database. Record ids
206-are ULIDs (time-sortable).
204+"Validation limits"). Persistence is PostgreSQL through sqlx: every statement
205+is checked at compile time against the schema (see `## Run`), and a row is a
206+plain typed struct in `src/db/`. Ids are UUIDv7s (time-sortable), served in
207+the hyphenated wire form.
207208
208209 ## Run
209210
210211 ```sh
211-surreal start --user root --pass root surrealkv:./data/hezarfen.db # the DB server
212-cp .env.example .env # optional
212+podman compose up -d postgres # PostgreSQL 18 on 127.0.0.1:5432 (hezarfen/hezarfen)
213+cp .env.example .env # recommended: DATABASE_URL feeds the build too
213214 cargo run
214215 ```
215216
216-Boots on `http://127.0.0.1:8080`, talking to the SurrealDB server at
217-`DB_URL` (default `ws://127.0.0.1:8000`, root credentials via
218-`DB_USER`/`DB_PASS`) and storing uploaded note files in
219-`./data/files/` (`FILES_PATH`, created at startup). Interactive API docs
220-(Swagger UI) are served at `/swagger`, the raw OpenAPI spec at
221-`/api-docs/openapi.json`.
217+Boots on `http://127.0.0.1:8080`, talking to PostgreSQL at `DATABASE_URL`
218+(default `postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control` —
219+the control database) and storing uploaded note files in `./data/files/`
220+(`FILES_PATH`, created at startup). `DATABASE_URL` is also read by sqlx's
221+compile-time query macros, so `cargo check` prepares every query against a
222+live database; `scripts/prepare_db.sh` refreshes the one union-schema
223+prepare database those checks run against, and the committed `.sqlx` cache
224+lets a build run with `SQLX_OFFLINE=true` and no database at all. On boot
225+the sqlx migrator applies `migrations/control` to the control database and
226+ensures the school template; each school database runs `migrations/school`
227+the same way at mint. Interactive API docs (Swagger UI) are served at
228+`/swagger`, the raw OpenAPI spec at `/api-docs/openapi.json`.
222229
223230 ## Run in a container (podman)
224231
@@ -229,11 +236,15 @@ podman compose down # stop (data survives in the volume)
229236 ```
230237
231238 The `Containerfile` is a two-stage build (Rust builder with cargo cache
232-mounts, `debian:trixie-slim` runtime, non-root user). Two services: the
233-`surrealdb` server (official image, surrealkv storage) and the backend, which
234-waits for the server's healthcheck and connects over `ws://surrealdb:8000`.
235-Each has its own named volume — `surreal-data` holds the database,
236-`hezarfen-data` the uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the
239+mounts, `debian:trixie-slim` runtime, non-root user, `SQLX_OFFLINE=true`
240+so the build never touches a database — the macros read the committed
241+`.sqlx` cache). Two primary services: `postgres` (the official
242+`postgres:18-alpine` image, `max_connections=500` so the test suite's
243+parallel control+school pools fit) and the backend, which waits for the
244+database's healthcheck and connects over `DATABASE_URL`
245+(`postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control`). Each has
246+its own named volume — `pgdata` holds the database, `hezarfen-data` the
247+uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the
237248 container so the published port works. Production knobs (`COOKIE_SECURE`,
238249 `CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in
239250 `compose.yaml` — uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset
@@ -257,27 +268,20 @@ http/protobuf` instead.
257268
258269 The backend survives the database going away, at boot and at runtime.
259270
260-At boot it retries the connection (1s doubling to 5s) until the server
261-answers, rather than exiting. Exiting looks tidier but is worse: the container
262-runtime restarts the process, it fails again in milliseconds, and a few
263-seconds of startup skew burns the whole restart budget and leaves the backend
264-down for good.
265-
266-At runtime a keepalive query every 5s doubles as a liveness probe. This
267-matters more than it sounds: a query issued while the socket is down does
268-*not* fail — the SDK's reconnect loop stops draining its request queue, so the
269-query parks until the database returns and only *then* runs. Left alone, a
270-request waits out the entire outage and any write it carries lands long after
271-the caller gave up.
272-
273-So while the probe says the socket is down, requests are refused at the edge
274-with `503` and `Retry-After: 1`, before they can reach the database. Nothing
275-is queued, which is what makes that retry safe. Requests that slip through in
276-the window between the socket dying and the probe noticing are capped at 30s
277-and answer `503` *without* `Retry-After`, with a message saying the write may
278-or may not have applied — they were already queued, so retrying them could
279-apply the same write twice. WebSocket and SSE routes are unaffected: both
280-return their response immediately and stream afterwards.
271+At boot it retries the connection (a one-second cadence, indefinitely)
272+until the server answers, rather than exiting. Exiting looks tidier but is
273+worse: the container runtime restarts the process, it fails again in
274+milliseconds, and a few seconds of startup skew burns the whole restart
275+budget and leaves the backend down for good.
276+
277+At runtime nothing queues behind a dead server: a request that cannot get
278+a connection is refused with `503`. The two flavors are distinguished
279+honestly — an acquire that times out means nothing executed, so the
280+answer is retry-safe; a request whose connection died mid-flight may have
281+applied server-side (the commit can race the connection dropping), so its
282+503 says the write may or may not have landed and must not be blindly
283+retried. When the database comes back the pool dials again on the next
284+request; there is nothing to re-arm.
281285
282286 Without compose:
283287
@@ -288,13 +292,13 @@ podman run -d --name hezarfen -p 8080:8080 -v hezarfen-data:/data hezarfen-backe
288292
289293 ## Multi-school (SaaS)
290294
291-One deployment serves many schools. Every school gets a SurrealDB **database**
292-of its own inside the one namespace (`DB_NAMESPACE`, default `hezarfen`),
293-named by its slug, next to a **control** database (`DB_DATABASE`, default
294-`control`) that holds the school registry, the builder accounts and the shared
295-rate-limit window. Isolation is the store's, not the handlers': a school
296-database sees only its own rows, so no query carries a `WHERE school = ...`
297-somebody could forget.
295+One deployment serves many schools. Every school gets a PostgreSQL
296+**database** of its own, named `{control}_school_{slug}` after the
297+**control** database `DATABASE_URL` points at (`hezarfen_control` by
298+default), which holds the school registry, the builder accounts and the
299+shared rate-limit window. Isolation is the store's, not the handlers': a
300+school database sees only its own rows, so no query carries a
301+`WHERE school = ...` somebody could forget.
298302
299303 **Slugs.** 2-32 characters of `a-z`, `0-9` and `-`, starting with a letter or
300304 digit (`MIN_SLUG_LEN`/`MAX_SLUG_LEN`); `builder` and `control` are reserved and
@@ -916,21 +920,22 @@ That admin can then promote everyone else through `PATCH /users/{id}/role`.
916920 The admin set cannot be emptied through the API: an admin never changes their
917921 own role, and a `PATCH /users/{id}/role` that would demote the last admin
918922 answers `409` — including when two admins demote each other at the same
919-instant, since that guard is serialized school-wide rather than left to the
920-database (which conflict-checks neither a cross-record count nor a read).
923+instant, since the guard is a predicate on the role write itself: the
924+`UPDATE` that lowers the row counts the remaining admins in the same
925+statement, so the count and the write it guards contend on the row lock
926+like any other write.
921927
922928 A locked-out school is the builder's `POST /schools/{slug}/admin-password`,
923929 which re-keys an admin that still exists. Manual fallback (the recovery path
924930 if an older build already emptied a school's admin set): run
925931
926-```surql
927-UPDATE user SET role = 'admin' WHERE username = 'ada';
932+```sql
933+UPDATE app_user SET role = 'admin' WHERE username = 'ada';
928934 ```
929935
930-against the SurrealDB server, with `--db` naming the **school's** database (its
931-slug), not the control one — e.g.
932-`surreal sql --conn ws://127.0.0.1:8000 --user root --pass root --ns hezarfen --db demo`
933-(in the container setup, `podman exec -it hezarfen-surrealdb /surreal sql ...`).
936+against the **school's** database (`{control}_school_{slug}`), not the
937+control one — e.g. `podman exec -it hezarfen-postgres psql -U hezarfen -d
938+hezarfen_control_school_demo` for the compose stack.
934939
935940 ## Endpoints
936941
@@ -1344,7 +1349,7 @@ A course may carry a `term_id` (`null` = unassigned); on `PATCH
13441349 /courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`
13451350 clears it.
13461351 `role` ∈ `parent | student | teacher | manager | admin`. Ids in responses are
1347-ULIDs. `parent` accounts are made by an admin (register as `student`, then
1352+hyphenated UUIDv7s. `parent` accounts are made by an admin (register as `student`, then
13481353 `PATCH /users/{id}/role`) and observe only the students an admin tied to them
13491354 — see "Roles & access control".
13501355 An exam `mark` is an integer `0`–`100`; it lives in its own `exam_result` row,
@@ -1991,7 +1996,7 @@ asker withdrawing, or teacher+ moderating — takes its solutions and every
19911996 photo blob (its own and its solutions') with it. Each question row reports
19921997 its `solution_count`, and questions and solutions embed their people as
19931998 person refs (`{id, username, display_name}`), so the UI never shows a raw
1994-ULID.
1999+uuid.
19952000
19962001 ## Per-school policy (settings & terms)
19972002
@@ -2257,7 +2262,7 @@ teacher or manager ordering a child's lunch is a `403`.
22572262 is a decision, not a side effect.
22582263 - **The capacity check is a single conditional write, decided by the
22592264 database.** Counting rows and then writing one would be write-skew —
2260- SurrealDB does not conflict-check a cross-record count against a concurrent
2265+ a count read in one statement does not conflict-check against a concurrent
22612266 insert, so 24 students racing for 3 seats would all pass the count — so the
22622267 seat is instead claimed on a counter kept on the **menu row itself**, taken
22632268 and spent by one `UPDATE … WHERE` that also places the booking row in the
@@ -2469,7 +2474,7 @@ is a counter that can drift.
24692474 the separator inside a ledger line's id) and the line is keyed
24702475 `<student>_k_<key>`, so a client retry after a network timeout returns the
24712476 line the first attempt wrote instead of crediting the money twice. Without
2472- one the id is a fresh ulid and a resent request is a second credit, as a desk
2477+ one the id is a fresh uuid and a resent request is a second credit, as a desk
24732478 taking the same amount twice really is — and since nothing here edits or
24742479 deletes a line, that doubled credit can only be corrected by a compensating
24752480 one. The same key with a different `amount_minor` is a `409`, never the
@@ -2624,16 +2629,17 @@ account.
26242629 room back and the charge **can be paid again** — and reversing that refund
26252630 takes the room back with it. Money that came back out is not money the school
26262631 still holds.
2627-- **The over-payment cap is not the database's.** The `409` past a charge's or
2628- a credit's worth is a cross-record fold, which SurrealDB cannot enforce on
2629- its own; it holds because the backend is one process and the fold, and the
2630- append it authorizes, are taken under one lock. Should an over-payment ever
2632+- **The over-payment cap is not the database's.** The `409` past a charge's or a
2633+ credit's worth is a cross-record fold, which no constraint can enforce on
2634+ its own; it holds because the fold, and the append it authorizes, are
2635+ taken under the target's ancestor-chain row locks (`FOR UPDATE`) — writers
2636+ on one subtree take turns, different subtrees never contend. Should an over-payment ever
26312637 be recorded anyway it is not a crisis: this is human data entry at an office
26322638 desk, the outcome is an over-paid charge that is plainly visible in the
26332639 statement, and it is undone by appending a refund. Both lines are true
26342640 records of money that really arrived — refusing them would be the worse lie.
26352641 - **A line carries at most 20 applied lines.** The cap above is folded one
2636- query per line of the target's subtree, all of them while that single lock is
2642+ query per line of the target's subtree, all of them while those row locks are
26372643 held, so a charge settled in a thousand pieces would stall every other
26382644 payment in the school behind its own arithmetic. Past 20 (payments under a
26392645 charge, refunds under a payment, and the reversals among them) a further
@@ -2803,24 +2809,12 @@ question + answer images (blobs included) along with results; unenrolling mid-ex
28032809 hides the student from the monitor roster but keeps the attempt and mark
28042810 rows, mirroring the marks report.
28052811
2806-> **Upgrading a pre-course database**: `exam` rows created before courses
2807-> existed lack the now-required `course` field and will fail to deserialize.
2808-> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data,
2809-> backfill manually with the SurrealDB CLI (server stopped), e.g.
2810-> `UPDATE exam SET course = course:<id> WHERE course = NONE;`
2811-> after creating a course to attach them to.
2812->
2813-> **Upgrading to the attempts/rejoin build needs nothing manual**: the boot
2814-> migration backfills `max_attempts = 1`, `allow_rejoin = true`, and attempt
2815-> `seq = 1` on existing rows, and swaps the single-attempt unique index for
2816-> the per-sitting one. Pre-upgrade attempts keep their record ids and count
2817-> as sitting #1.
2818->
2819-> **Upgrading to the kind-weight build is a clean break**: weights moved off
2820-> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with
2821-> no data migration. A database from an older build has string kinds and a
2822-> per-exam `weight` column the code no longer understands — delete
2823-> `./data/hezarfen.db` and reboot.
2812+> **Schema changes are migrations, not boot batches.** The sqlx migrator
2813+> applies `migrations/control` to the control database at boot and
2814+> `migrations/school` to the school template and every newly minted school
2815+> database, tracked in `_sqlx_migrations` — an up-to-date database boots
2816+> without touching a row, and there is no manual backfill. The SurrealDB-era
2817+> `surreal sql` repair notes died with the old store.
28242818
28252819 ## Taking an exam: questions, answers & the exam room
28262820
@@ -2907,7 +2901,7 @@ no-store`. The metadata rides the answer as `answer_image: {content_type,
29072901 size} | null` on both the sitting view and the grading sheet. To the backend
29082902 it is a normal raster PNG; the frontend piggybacks its editable stroke data in
29092903 a PNG `tEXt` chunk, opaque here — stored on disk under `Config::files_path`
2910-by a ULID, metadata in the `answer_image` table, structurally identical to
2904+under a fresh uuid, metadata in the `answer_image` table, structurally identical to
29112905 question images.
29122906
29132907 **Grading view** (course-management rights): `GET /exams/{id}/attempts/{user}/answers` returns
@@ -3439,7 +3433,7 @@ way — the ambiguity `matched` closes on the grade-wide pumps).
34393433 Stocking is best-effort all the way to the end of that route: a template that
34403434 could not be read, or a pump that faulted part-way, leaves `stocked_from` null
34413435 rather than turning a class that *exists* into a `500` whose caller never learns
3442-its id — a class id is a ULID and `POST /classes` is the only place it is
3436+its id — a class id is a uuid and `POST /classes` is the only place it is
34433437 returned from, unlike a blueprint, whose id is the grade label the caller sent.
34443438 The retry is `POST /classes/{id}/blueprint`, which is idempotent and is also
34453439 what a caller runs when there is genuinely no template, so the two cases need
@@ -4557,9 +4551,9 @@ const send = (payload) =>
45574551 The backend runs as **one process against one database**, and that buys less
45584552 than it sounds like: every request is an async task, dozens are in flight at
45594553 once, and each of them awaits the database in the middle of its work. So
4560-"read, decide, write" is never safe on its own — SurrealDB does not
4561-conflict-check a cross-record `count()` against a concurrent insert
4562-(write-skew), and that fires between two tasks in one process exactly as it
4554+"read, decide, write" is never safe on its own — under `READ COMMITTED` a
4555+count read in one statement does not conflict-check against a concurrent
4556+insert (write-skew), and that fires between two tasks in one process exactly as it
45634557 would between two machines. The mutex-only design this replaced was already
45644558 losing races at one process. Every invariant is therefore guarded where the
45654559 database itself decides the winner. Three tiers:
@@ -4569,8 +4563,11 @@ database itself decides the winner. Three tiers:
45694563 atomic, so of N concurrent tasks exactly the allowed number get a non-empty
45704564 result: the database decides the winner, the loser retries
45714565 (`CAS_UPDATE_RETRIES`) or gets a 409.
4572-2. **In-transaction `IF … THROW` gates** — the check runs inside the same
4573- statement as the write it authorizes, so it is atomic with it. Used where
4566+2. **One-statement gates** — the check runs inside the same statement as
4567+ the write it authorizes, so it is atomic with it: a guarded
4568+ `UPDATE … WHERE` (the last-admin floor), an
4569+ `INSERT … SELECT … WHERE EXISTS` behind a real `FOREIGN KEY` (the
4570+ existence proofs), the CTE recipes in `db::cap`. Used where
45744571 the rule reads the row being written (state machines, delete guards).
45754572 "Is anything still attached?" is answered the same way, by a counter on the
45764573 row being deleted rather than a `SELECT` over the children: a course is
@@ -4583,52 +4580,43 @@ database itself decides the winner. Three tiers:
45834580 Where the child also carries a deterministic id — one enrollment per
45844581 (course, user), one registration per (event, user), one fee-plan assignment
45854582 per (plan, student) — the seat and the row
4586- are claimed in one transaction (`cap::claim_and_create`), so a duplicate
4587- `CREATE` rolls its own seat back instead of costing a stranger their place.
4588-3. **Three accepted races**, reviewed and deliberately left open:
4583+ are claimed in one statement (`db::cap`'s `claim_and_create` recipes), so a
4584+ duplicate insert rolls its own seat back instead of costing a stranger their
4585+ place. Where no single statement can decide the rule — an appointment
4586+ approval reads other rows that may not exist yet — that one decision
4587+ escalates to `SERIALIZABLE`, and `tx_with_retry` re-sends it when Postgres
4588+ aborts the loser (`40001`); the re-run sees the winner committed and
4589+ refuses with the ordinary `409`.
4590+3. **Two accepted races**, reviewed and deliberately left open:
45894591 - *Attempt-seq late save* — an exam-room socket writes into the sitting it
45904592 joined with, a choice made before any lock is taken, so a save racing a
45914593 retake can stamp an answer onto the just-terminal previous sitting.
45924594 Damage: one history row; the grade of record (latest `seq`) is never
45934595 touched.
4594- - *Approved-overlap* — two approvals landing in the same instant can
4595- double-book a teacher. Damage: one overlapping half-hour, visible to both
4596- parties, fixable by cancelling either side.
45974596 - *Archive-vs-write* — the archived-term guard is a pre-flight read on the
45984597 term row, so an archive committing in the same instant as a write already
45994598 in flight lets that one write through. Damage: one write on a
46004599 just-archived term; nothing corrupts, and every later write is refused.
46014600
4602-In-process locks remain, and they are a *second* line, never the guarantee:
4603-`PRESENCE_LOCK` guards in-process socket state (there is no row to conditional
4604--write), `CLAIM_LOCK` keeps one counter writer at a time (the `WHERE` clause is
4605-the cap — the lock only tames the retry loop, and keeps the tests' in-memory
4606-engine deterministic), `APPOINTMENT_LOCK` collapses the common overlap case in
4607-front of a rule no single-record write can express. Removing one of them costs
4608-throughput or an accepted race; removing the conditional write behind it costs
4609-the invariant.
4610-
4611-Boot is unconditional: the schema batches, the backfills and the admin seed all
4612-run on every start, because exactly one process ever starts (the one exception
4613-is the marked one-time repair below). Deployment is
4614-stop-the-world — `podman compose down` then `up`, never overlapping — and a
4615-release that adds or renames a stored counter *requires* it. An old binary
4616-writes rows without touching the new counter, the `= NONE` backfill guard
4617-(correctly) refuses to re-seed, and the resulting permanent under-count lets a
4618-guard approve exactly what it exists to refuse. The one exception is a counter
4619-that is not an opinion but a plain row count — a board's `total_stroke_count`,
4620-recomputed from its strokes on every boot rather than seeded once, which is why
4621-that repair heals an under-count the `= NONE` guard would have skipped.
4622-In-flight work does not survive
4623-a restart either: a chatbot turn mid-inference settles `failed`/`interrupted`.
4624-
4625-The one thing boot does *not* redo is tracked in `migration_mark` — one row per
4626-backfill that is genuinely one-time, keyed by the backfill's own name. Most
4627-backfills converge to a `WHERE` that matches nothing and are free to re-run, so
4628-they carry no mark; the board-roster repair is different because its cost is
4629-the **scan** (a `user` pass per board) rather than the write, so it is gated on
4630-`migration_mark:board_roster` and skipped entirely once done. A volume that
4631-never ran the repair holds no mark and still gets repaired on its next boot.
4601+One in-process lock remains, and it is a *second* line, never the guarantee:
4602+`PRESENCE_LOCK` guards the exam-room presence map (in-process socket state;
4603+there is no row to conditional-write). The other two are gone with the old
4604+store: `CLAIM_LOCK` tamed a retry loop that `tx_with_retry` now owns, and
4605+what `APPOINTMENT_LOCK` serialized is three database guarantees — the seat
4606+claim's one-statement write, the publish-overlap exclusion constraint, and
4607+the serializable approval.
4608+
4609+Boot is idempotent: the sqlx migrators apply `migrations/control` to the
4610+control database (and `migrations/school` to the school template, and to
4611+every school database at mint), tracked in `_sqlx_migrations`, so a second
4612+boot touches nothing; the builder seed runs on every start but writes only
4613+when the username is absent. A release that adds a migration simply applies
4614+it on the next boot — there is no stop-the-world counter backfill to
4615+schedule and no `migration_mark`: the counters the guards lean on
4616+(`total_stroke_count` among them) are maintained by the same conditional
4617+writes that spend them. In-flight work does not survive a restart either:
4618+a chatbot turn left `pending` by a dead process reads back as `failed`
4619+(a read-time projection, not a sweep).
46324620
46334621 ## Layout
46344622
@@ -4640,19 +4628,26 @@ src/
46404628 constant.rs validation limits
46414629 validate.rs field validators (used by every newtype's try_new)
46424630 error.rs ValidationError + AppError -> HTTP responses
4643- database.rs SurrealDB server connect (ws) + SCHEMAFULL migration; init()
4644- brings up the control database, migrate() a school's
4645- tenant.rs Slug · SchoolStatus · School · Tenants: one database per
4646- school inside one namespace, plus the control database that
4647- registers them (DEMO_SLUG is the in-memory test school)
4648- migration_sql.rs the three boot batches as SurrealQL text (PRE_REPAIR,
4649- MIGRATION, BACKFILL) + MIGRATION_BATCHES, the only list of them,
4650- and CONTROL_MIGRATION_BATCHES for the control database
4631+ database.rs PgPool + tx_with_retry (a guarded BEGIN…COMMIT that re-runs
4632+ while Postgres says "contended") + the two sqlx migrator
4633+ sets; init() brings up the control database, a mint
4634+ migrates a school's from the shared template
4635+ tenant.rs Slug · SchoolStatus · School · Tenants: one Postgres
4636+ database per school (`{control}_school_{slug}`), plus the
4637+ control database that registers them (DEMO_SLUG is the
4638+ tests' school)
4639+ db/ the only layer that executes queries: per-table SQL, one
4640+ file per resource · cap.rs (the count-cap CTE recipes and
4641+ their verdict types) · field_update.rs (one UPDATE … SET
4642+ from only the fields a PATCH carried) · page.rs (PagedList:
4643+ one paged SELECT — the window and its `total`)
4644+ service/ workflows the handlers call: each multi-step invariant is
4645+ one tx_with_retry-guarded transaction
46514646 module.rs Module (one router nest a school may buy) · Package ·
46524647 ModuleSet: dependency edges, validation, stored names
46534648 rate_limit.rs fixed-window limiter: per-IP tiers + middleware, per-user chat tier
46544649 state.rs AppState { db, tenants, files_path, cookie_secure, rate_limit,
4655- chatbot_limit, exam_presence, board_hub, db_up, ai }
4650+ chatbot_limit, exam_presence, board_hub, ai, metrics }
46564651 ai/ QUIC bridge to the out-of-process AI services
46574652 (see "AI bridge (QUIC)"; the HTTP half is web/ai.rs)
46584653 protocol.rs Hello/Greeting/Request/Response + length-prefixed JSON framing
@@ -4665,33 +4660,23 @@ src/
46654660 changed, so its stored output is refreshed in a background task
46664661 api.rs AI_API_ALLOWLIST: the exact REST paths an AI service may read
46674662 (deny-by-default, segment-for-segment, no wildcard tail)
4668- domain/ validated newtypes + entities (derive SurrealValue),
4669- each owning its persistence
4663+ domain/ validated newtypes + entities (pure data and validation;
4664+ persistence lives in db/)
46704665 user.rs UserId · Username · Password · PasswordHash · User (has role)
46714666 role.rs Role enum (student < teacher < manager < admin), at_least()
4672- field_update.rs FieldUpdate: one UPDATE ... SET built from only the fields a
4673- PATCH actually carried (an omitted field is never written)
4674- monotonic_id.rs next_ulid: ids that sort in write order — one process-wide
4675- Generator, so same-millisecond rows never scramble
4667+ monotonic_id.rs next_uuid: UUIDv7 ids that sort in write order — one
4668+ process-wide ContextV7, so same-millisecond rows never scramble
46764669 key.rs sitting(): the deterministic per-sitting record key shared by
46774670 attempts, answers, answer images and results (seq 1 stays bare)
4678- cap.rs claim()/release(): the count caps the database enforces — an
4679- atomic `UPDATE parent SET n += 1 WHERE n < cap` on a counter
4680- column of the parent row, replacing count-then-write mutexes
4681- that could not see a concurrent insert;
4682- claim_and_create() commits that seat and the child row in
4683- one transaction, for children with a deterministic id
46844671 text_fold.rs case- and diacritic-insensitive folding for search, shared by
4685- the Rust needle and the SurrealQL column (Turkish İ/ı, ü, ö…)
4686- page.rs PagedList: one paged SELECT — the window and its `total`, both
4687- done by the database rather than by slicing a full scan
4672+ the Rust needle and the SQL column (Turkish İ/ı, ü, ö…)
46884673 session.rs SessionId · SessionToken · Session (7-day expiry)
46894674 builder.rs BuilderId · Builder · BuilderSession: the deployment operator
46904675 who creates and suspends schools, in the control database
46914676 timestamp.rs Timestamp (unix-millisecond instant)
46924677 note.rs NoteId · NoteTitle · NoteContent · Note
46934678 note_file.rs NoteFileId · FileName · FileContentType · NoteFile (metadata row;
4694- blob on disk under FILES_PATH, named by the row's ULID)
4679+ blob on disk under FILES_PATH, named by the row's uuid)
46954680 event.rs EventId · EventTitle · EventDescription · Event
46964681 attendance.rs AttendanceId · AttendanceStatus · Attendance
46974682 course.rs CourseId · CourseTitle · CourseDescription · Course
@@ -4842,19 +4827,21 @@ src/
48424827 limits.rs GET /limits: every constant.rs bound served as JSON
48434828 ```
48444829
4845-Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory
4846-db), rate-limit (both tiers, proxy-header and peer-address keying, shipped
4830+Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` over
4831+per-test PostgreSQL databases), rate-limit (both tiers, proxy-header and peer-address keying, shipped
48474832 limits over every route, two limiters sharing one budget over one db), e2e
48484833 (real TCP + reqwest cookie jar), persistence
4849-(tempfile file engine, including close + reopen), ai-bridge (real QUIC on
4834+(an idempotent re-migration over a live database must leave its seeded rows
4835+intact), ai-bridge (real QUIC on
48504836 loopback against a fake AI service), ai-protocol (the `hab/2` wire contract,
48514837 driven by a client that shares no code with the backend).
48524838
4853-The cross-school isolation probes run twice: once in memory mode, once against
4854-a **real** SurrealDB, because production is remote mode and there a school is a
4855-database inside one namespace rather than its own datastore. So `cargo test`
4856-starts a throwaway `surreal start … memory` server on a free port, taken from
4857-`~/.surrealdb/surreal`, and kills it when the last test using it finishes. A
4858-missing binary is a hard failure, not a skip — install it with
4859-`curl -sSf https://install.surrealdb.com | sh`, or set `HEZARFEN_SKIP_REMOTE=1`
4860-to skip the remote half deliberately.
4839+Every suite runs against a **real** PostgreSQL, because production is real
4840+PostgreSQL. The harness (tests/common) mints each test a private pair of
4841+databases on one server — `heztest_<16 hex>` for the control side and its
4842+`heztest_<…>_school_demo` school, template-cloned so a schema edit migrates
4843+the shared template once — and drops them when the deployment's last handle
4844+dies; a janitor sweeps what a crashed run left behind. The server comes from
4845+`HEZARFEN_TEST_DATABASE_URL` (default: the compose stack's maintenance
4846+database). A missing server is a hard failure, not a skip — start it with
4847+`podman compose up -d postgres`.
src/db/appointment.rsmodified+1 -1
@@ -245,7 +245,7 @@ pub async fn list_for_slot(
245245 /// bump back with it. Zero rows means "full, or the slot was deleted since
246246 /// the caller read it": the marker is one, and the caller re-reads to pick
247247 /// the 404/409.
248-pub async fn claim_slot_and_create(
248+pub(crate) async fn claim_slot_and_create(
249249 db: &Database,
250250 appointment: Appointment,
251251 ) -> Result<Claimed<Appointment>, AppError> {
src/db/exam_attempt.rsmodified+1 -1
@@ -360,7 +360,7 @@ pub(crate) async fn create_in(
360360 /// [`create_in`]. Retried while Postgres answers "contended"; a duplicate
361361 /// or a missing student row is a verdict, not a conflict, and is never
362362 /// re-sent.
363-pub async fn create(
363+pub(crate) async fn create(
364364 db: &Database,
365365 attempt: &ExamAttempt,
366366 count_sitting: bool,
src/db/fee_plan_assignment.rsmodified+1 -1
@@ -41,7 +41,7 @@ pub async fn read(
4141 /// pair first; their row is the answer); zero rows → [`Claimed::Full`] (the
4242 /// counter is uncapped, so the only miss is a plan a concurrent delete
4343 /// already removed); one row → [`Claimed::Made`].
44-pub async fn create(
44+pub(crate) async fn create(
4545 db: &Database,
4646 plan: &FeePlanId,
4747 student: &UserId,
src/db/registration.rsmodified+1 -1
@@ -61,7 +61,7 @@ pub async fn list_for_event(db: &Database, event: &EventId) -> Result<Vec<Regist
6161 /// `registration_event_user`); `Full` — the event is at its capacity, was
6262 /// deleted, or the holder fell to `parent` (all one marker; the caller
6363 /// re-reads to pick the message).
64-pub async fn claim_seat(
64+pub(crate) async fn claim_seat(
6565 db: &Database,
6666 event: &EventId,
6767 user: &UserId,
src/telemetry.rsmodified+0 -13
@@ -143,10 +143,6 @@ pub struct Metrics {
143143 pub panics_total: Counter<u64>,
144144 /// Requests refused by the rate limiter (attr: `tier`).
145145 pub rate_limit_rejections_total: Counter<u64>,
146- /// Database keepalive ping latency in seconds.
147- pub db_ping_duration: Histogram<f64>,
148- /// 1 when the last database ping answered, 0 when it did not.
149- pub db_up: Gauge<u64>,
150146 /// AI services currently registered on the QUIC bridge.
151147 pub ai_workers: Gauge<u64>,
152148 /// AI requests dispatched and not yet answered.
@@ -197,15 +193,6 @@ impl Metrics {
197193 .u64_counter("rate_limit_rejections_total")
198194 .with_description("Requests refused by a rate limit tier")
199195 .build(),
200- db_ping_duration: meter
201- .f64_histogram("db_ping_duration")
202- .with_unit("s")
203- .with_description("Database keepalive ping round trip")
204- .build(),
205- db_up: meter
206- .u64_gauge("db_up")
207- .with_description("1 when the last database ping answered")
208- .build(),
209196 ai_workers: meter
210197 .u64_gauge("ai_workers")
211198 .with_description("AI services registered on the QUIC bridge")