forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to src/main.rsClear filter

2026-09-17

🐛 fix(tenant): the boot sweeps every school database to the school-schema headAhmet Kaan Gümüş · ee72900
🐛 fix(tenant): the boot sweeps every school database to the school-schema head

A school database is migrated exactly twice in its life — at mint (`bring_up`,
through the create path and the provisioning finish) and at boot (the
template, and now this sweep). Nothing else ever touches its schema: a re-dial
applies no migrations, and the boot's reconcile only reaches rows still marked
`provisioning`. A school minted before a migration landed therefore kept
yesterday's tables for good — which is how the live deployment answered

    relation "podcast_job" does not exist

on POST /podcast/jobs while the template already carried the podcast migration.

The missing half of the boot is now there: after the control database and the
template are ensured, every school database in the registry is dialled,
brought to the school-schema head and closed again. Nothing about a school no
request has reached is cached, so no pool for an unserved school survives the
sweep. The invariant it restores: **every school database in the control
database is at the school-schema head after boot.**

- Failure policy: one school failing never takes the boot down. It is logged
  at ERROR with its id and slug and left exactly as it stood — the sweep
  writes no registry row and no status, so a failed school is as usable (or
  unusable) as it was and the next boot retries it; sqlx's tracking table is
  what makes a retry of a half-applied migration safe.
- Observability: one INFO line per boot (`school schema sweep: N schools,
  M migrated`) plus one line per school, only when it actually applied
  something — the pending count comes off `_sqlx_migrations` before the
  migrator runs, so a school already at head costs one connection and no line.
- `migrate_school`, not the bare migrator: the chatbot/RAG interrupted-turn
  sweep is exactly as due on a school being swept as on one being minted.

The witness is in tests/persistence.rs: a school created through the normal
path, then rolled back to what an older head left behind — the table a later
migration created dropped and its `_sqlx_migrations` row deleted — reads
`relation "podcast_job" does not exist` before the sweep, and after it the
table is back, empty and recorded as applied, so the next boot is a no-op.
Every persistence test's second boot runs the sweep too (reboot()).
cargo check --all-targets and clippy -D warnings clean; persistence 11/11.
Local-Gate: 05ce93b5c478baa9a9ae80dd0bc8f99044a31f53 (1470 passed, 450s)
✨ feat: add the /rag nest over the course-note RAG bridgeAhmet Kaan Gümüş · a61e0a6
✨ feat: add the /rag nest over the course-note RAG bridge

A separate rag_thread/rag_message pair of tables and a Module::Chatbot gated
/rag nest, mirroring the chatbot's asynchronous send: POST answers 202 with a
pending assistant row, an in-process task settles it, and both the poll read
and the SSE stream project a stale pending row as failed.

Every question is scoped server-side to the asker's own (sinif, ders) pairs —
class-section instances, a linked parent's children, school-wide club/study memberships
— never from the body. Each citation's corpus doc_id is resolved per candidate
to a course-note file the asker may view, and the two storage caps refuse an
over-bound reply whole rather than clipping it. rag.index replies now stamp
each file's rag_doc_id, the missing link between a citation and its file.

The chatbot's SSE helpers move to web/mod.rs so both nests stream through one
implementation, and the instance/course visibility gates move from web to
service so the scope deriver and the routes share one rule.

Gates: cargo check --all-targets, clippy -D warnings, limits_completeness,
spec_bounds, doc_sync (README regenerated), protected_routes_require_session
(MIN_PROTECTED 269 -> 318, the real swept count), ai_bridge (75 tests).

2026-09-12

2026-09-07

🔒 fix: telemetry privacy sweep, in-flight gauge guards, request-id validation, tenant gauge on createAhmet Kaan Gümüş · ae0957a
🔒 fix: telemetry privacy sweep, in-flight gauge guards, request-id validation, tenant gauge on create

- No account name reaches an exported log record: the admin seed
  (domain/user.rs), the ADMIN_USERNAME refusal and the builder seed
  (domain/builder.rs) log the event without the `username` field.
- The forbidden-key list moves to tests/common (`FORBIDDEN_TELEMETRY_KEYS`,
  `is_forbidden_key`), gains `username`/`email` and the header prefixes, and
  is used by both the HTTP-edge and the AI-bridge guard tests. The telemetry
  suite now also exports tracing EVENTS through an in-memory log exporter and
  holds log records to the same rule.
- `http.server.active_requests` and `ai_requests_inflight` are closed by a
  `Drop` guard, so a dropped request future (client hang-up, outer timeout)
  no longer leaks the gauge upwards. A cancelled request is recorded as 499.
- A caller-supplied `x-request-id` is only kept when it is at most 64 chars of
  `[A-Za-z0-9._-]`; anything else is dropped and a UUID is minted, so a client
  cannot write free text onto `http.request.id` of every span.
- `tenant_cache_size` is reported by `Tenants::create` and by the bootstrap
  insert, not only by the lazy-dial path.
- The keepalive logs its first `up` verdict, which its comment already claimed.

Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s
✨ feat: rate-limit, DB liveness, WebSocket and tenant-cache telemetryAhmet Kaan Gümüş · e87c2a2
✨ feat: rate-limit, DB liveness, WebSocket and tenant-cache telemetry

Four instruments that were declared at the OpenTelemetry bootstrap and
recorded by nobody now have their call sites.

The rate limiter counts every refusal under the tier that refused it. The
tier's name already exists — `share()` is told it — so the limiter learns
it there instead of growing a constructor argument the router would have
to pass. Counting sits in one wrapper around `check`, so the overflow
budget's refusals cannot slip past it, and it is a counter only: a log
line per rejection is a flood amplifier, and the fields that would make
one useful (who, from where) are exactly the ones telemetry may not carry.
For the same reason the two existing warnings no longer name the client's
IP or the user — with events now exported as OTLP logs, those fields would
leave the process.

The keepalive ping is timed and its verdict published, and the log is now
about the transitions rather than the tick: down once, up once, with the
outage's length on recovery.

Every room socket is counted by a `Connected` guard whose `Drop` is the
decrement, since a room has several ways out and a decrement written at
one of them is a gauge that only ever climbs. It names the exam, not the
attempt — an attempt names one student.

The instruments reach those places through `Metrics::global()`, published
by `init`: the limiter is built before the state exists, and the keepalive
task and the tenant cache have no handle to one either.

Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s
✨ feat: OpenTelemetry bootstrap — OTLP traces/metrics/logs, request spans, request idsAhmet Kaan Gümüş · 057a7fa
✨ feat: OpenTelemetry bootstrap — OTLP traces/metrics/logs, request spans, request ids

Telemetry is off unless OTEL_EXPORTER_OTLP_ENDPOINT is set, mirroring the
AI bridge's "off unless configured" shape. With it unset the process logs
exactly as before; every instrument binds to the noop meter provider, so
call sites never branch on whether telemetry is on.

Privacy is the design constraint (KVKK): a span carries the method, the
route TEMPLATE, the status, a random request id and the school slug —
never a user, an IP, a URL path, a body, a header or a cookie.
tests/telemetry.rs fails the build if a forbidden attribute key appears.

New variables (all documented in .env.example):
  OTEL_EXPORTER_OTLP_ENDPOINT   presence turns export on
  OTEL_EXPORTER_OTLP_PROTOCOL   grpc (default) | http/protobuf
  OTEL_EXPORTER_OTLP_HEADERS    read by the SDK
  OTEL_SERVICE_NAME             read by the SDK, defaults hezarfen_backend
  OTEL_TRACES_SAMPLER(_ARG)     read by the SDK, parent-based always-on
  LOG_FORMAT                    pretty (default) | json; anything else refuses to boot
  DEPLOY_ENV                    deployment.environment.name

Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s

2026-09-05

✨ feat: one database per school behind a control registry; login names the schoolAhmet Kaan Gümüş · b7dfc0c
✨ feat: one database per school behind a control registry; login names the school

Namespace `hezarfen` now holds one DATABASE per school (name = slug) plus a
`control` database with the school registry, builder accounts and builder
sessions. `Tenants` keeps one separately-connected handle per school; the
shadow `web::tenant_state::State` resolves the school from the
`<slug>.<token>` cookie so every handler's `st.db` is school-scoped by
construction. `POST /auth/login` / `register` carry `school`; a suspended
school answers 403 everywhere. `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed the
vendor account; the boot admin seed is gone. No customers, no compat shims.

2026-08-13

chore: rename ponytail: comment marker to corner-cut:Ahmet Kaan Gümüş · ed88733
chore: rename ponytail: comment marker to corner-cut:

Marker convention renamed after uninstalling the ponytail plugin;
semantics unchanged (deliberate corner-cut, known ceiling + upgrade path).
Token-only rename, 26 comment lines, no code change.

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

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

2026-07-25

fix: 🔑 bound argon2's memory, and stop register leaking usernamesAhmet Kaan Gümüş · d31f9ce
fix: 🔑 bound argon2's memory, and stop register leaking usernames

Two auth problems, both about a cost paid off the request path.

684f18b correctly moved argon2 onto `spawn_blocking`, but that pool is
unbounded: tokio grows it to 512 threads and argon2's default `m_cost`
is 19 MiB, so a distributed login flood could claim ~8.7 GB and get the
process OOM-killed. Before the move, concurrency was implicitly capped
at the 12 async workers. A semaphore of `nproc * 2` now gates all three
wrappers — 200 concurrent hashes drop from ~2.2 GB to ~0.63 GB peak RSS
with no wall-clock cost, since throughput was already core-bound. Both
login branches take a permit, and a (impossible) closed-semaphore error
maps exactly like a pool panic does, so no branch becomes
distinguishable by status.

The decoy hash is also pre-warmed at boot, off the runtime: it used to
initialise lazily, so the first unknown-username login paid two argon2
hashes instead of one and stood out.

`POST /auth/register` answered 409 on a taken username, which handed out
the entire user list to anyone unauthenticated and made the login-side
decoy that 684f18b preserved decorative. It now answers 201 with a body
shaped exactly like a real creation. The write is still rejected — only
the response is uniform. Register already hashed before the availability
check, so both paths already cost the same argon2 work; a comment and a
timing floor in the test pin that ordering, since reversing it would
re-open the oracle by latency.

Accepted cost, deliberately: a user who collides gets no distinct error.

The three tests that proved their point *via* the 409 could not just be
flipped to expect 201 — that would assert nothing. They now observe the
rejection where it is still visible: exactly one row exists, and the
first registration's password still logs in while the duplicate's is
refused. That is strictly stronger than the old assertion, which never
checked that the row had not been overwritten.

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.
✅ test(ai): cover the bridge's boot wiringAhmet Kaan Gümüş · 266e175
✅ test(ai): cover the bridge's boot wiring

`start_ai_bridge` sat in main.rs, so the branches an operator actually
hits had no test: unset address boots fine, bad address fails the boot,
and a set address with no token refuses rather than listening
unauthenticated. Moved to `ai::start_bridge` and tested there, including
a real dial-in against what it returns — a constructed value proves
nothing, a completed handshake does.

The token assertion pins this layer's wording. `AiBridge::bind` rejects
an empty token too, so matching only on "AI_SHARED_TOKEN" passed with
the branch deleted; the test now names AI_QUIC_ADDR and fails without it.

Returns AiError rather than anyhow::Error, keeping anyhow to the binary.
✨ feat(chat): relay chatbot over the AI bridgeAhmet Kaan Gümüş · b0aa0a1
✨ feat(chat): relay chatbot over the AI bridge

The backend relays between the frontend and an out-of-process AI service:
it owns auth, rate limiting, persistence and payload format, and may
inspect an answer before the frontend sees it. No rule or intent tables —
conversation is free-form.

Two-phase by design. POST persists the pending assistant row *before*
dispatching, then returns 202, so a reload never loses an answer; the
client either polls the message or opens an SSE stream. Both read the
same DTO, so they cannot disagree. Deltas are sliced from the finished
text because hab/1 is unary — the event shape exists so real streaming
drops in later without a client change.

A turn always settles. Every failure after the rows are written marks the
row failed with a machine-readable code, a boot sweep flips rows orphaned
by a restart, and a pending row older than five minutes reads as timed
out — projected at read, never written back, so a slow-but-alive answer
is not raced. An over-long answer is clipped and flagged rather than
dropped; an empty one fails.

Message ids come from a monotonic ULID generator: the two rows one POST
writes share a millisecond routinely, and a random tie-break rendered the
answer above its own question and handed the service [assistant, user],
breaking the documented oldest-first history contract.

The conversation cap counts and creates under a lock — SurrealDB
BEGIN/COMMIT does not serialize cross-record counts, and 16 concurrent
creators over-admitted a cap of 5 to 20 without it.

Every authenticated role may chat, parents included. Foreign threads are
404, never 403.
✨ feat(ai): QUIC bridge for out-of-process AI servicesAhmet Kaan Gümüş · dc49954
✨ feat(ai): QUIC bridge for out-of-process AI services

The AI features live in separate projects, so they need a transport. QUIC:
each request rides its own bidirectional stream on the service's single
long-lived connection, which puts multiplexing in the transport — no
correlation-id bookkeeping, no head-of-line blocking between concurrent
requests, one handshake instead of one per request.

The backend listens and the services dial in, so a service can sit behind
NAT, restart without the backend knowing its address, and scale out by
opening a second connection (each connection is an independent worker).

Protocol "hab/1", also the ALPN so an incompatible service is refused at the
TLS handshake rather than one frame later. Frames are length-prefixed JSON
(u32 big-endian) because the services will not be Rust; the length is checked
against an 8 MiB cap before any buffer is allocated. The control stream
carries Hello/Greeting and then stays open — its closure is the goodbye, so
there is no heartbeat frame, and a silent death is caught by the QUIC idle
timeout.

Routing is least-inflight rather than round-robin: AI request costs are
wildly uneven, and taking turns would pile a second long inference onto a
busy worker while an idle one sits next to it. Selection and the in-flight
increment happen under one lock so concurrent dispatches cannot overshoot a
worker's declared max_concurrent, which a Lease releases on drop.

Services authenticate with a shared token (constant-time compare); the
certificate only proves the backend, and is self-signed at boot unless a PEM
pair is configured. Since that regenerates per boot, GET /ai/certificate
publishes it (PEM + sha256) for a service to pin — public because a server
certificate is handed to every peer in the TLS handshake anyway, and 404 when
the bridge is off. A service must re-fetch on every reconnect, not once at
startup.

Off unless AI_QUIC_ADDR is set, so the API is unchanged for deployments
without AI. Set without AI_SHARED_TOKEN it refuses to boot rather than listen
unauthenticated.

2026-07-21

🎨 style: cargo fmt the question-pool and keepalive codeAhmet Kaan Gümüş · bdde827
🎨 style: cargo fmt the question-pool and keepalive code

Leftover unformatted lines from the two most recent commits; `cargo fmt`
picked them up during unrelated work. Line wrapping and import order only,
no behavior change.
🐛 fix(db): retry boot connect, refuse while socket downAhmet Kaan Gümüş · bebca49
🐛 fix(db): retry boot connect, refuse while socket down

Two failures survived 6627128, which only classified errors from queries
in flight *at* the drop — queries arriving after it produce no error at
all, so there was nothing to classify.

Boot did one connect() and exited on refusal. The runtime then restarted
the process, it failed again in ~100ms, and a few seconds of startup skew
burned the whole restart budget: 6 deaths in 0.6s in the field log, then
down for 12h. Now retries 1s doubling to 5s, forever — only the dial,
since bad credentials never heal by waiting.

A query issued while the socket is down does not fail. The SDK's
router_reconnect loops on 1s retries and stops draining route_rx, so the
query parks until the database returns and only then executes. Reproduced:
POST /auth/login gave no response at 25s, and the keepalive went silent
4m17s before firing two pings in the same millisecond on heal.

Those two pings rule out a plain timeout middleware — a parked query still
runs, so a timeout-sourced 503 would let a client retry double-apply a
mark or an exam answer. Instead the keepalive (now 5s) publishes DbHealth
and db_guard refuses at the edge, before anything is queued, which is what
keeps Retry-After: 1 honest. The 30s request timeout is only a backstop
for requests racing detection; those answer DbTimeout — same 503, no
Retry-After, "may or may not have applied". WS and SSE are unaffected:
both return their response immediately and stream afterwards.

Known gap: exam_ws socket-loop queries run after the upgrade response, so
db_guard does not cover them; they still park and heal on reconnect.

Verified in podman against the existing volume: boot with the database
down backs off and stays alive, requests during an outage answer 503 in
0.3ms, recovery needs no restart.
🐛 fix(db): map ws session-replay races to 503 + keepaliveAhmet Kaan Gümüş · 6627128
🐛 fix(db): map ws session-replay races to 503 + keepalive

The SDK's reconnect replays signin/use_ns fire-and-forget, so queued
queries can race it and get refused pre-execution ("Specify a
namespace" / "Anonymous access"), and a query in flight at the drop
dies as a connection error — all surfaced as 500s. Classify those
(narrow strings + is_connection) as DbUnavailable → 503 with
Retry-After: 1; refused-pre-execution makes a client retry always
safe, unlike a body-replaying retry middleware. A 30s RETURN 1
keepalive task makes drops heal between requests, not under one.
Restart storm (2× DB restarts under 200ms hammer): 0×500.
✨ feat(db)!: swap embedded surrealkv for a SurrealDB serverAhmet Kaan Gümüş · 60b4509
✨ feat(db)!: swap embedded surrealkv for a SurrealDB server

BREAKING CHANGE: the backend no longer opens a database file. DB_PATH
is gone; DB_URL/DB_USER/DB_PASS point at a SurrealDB server over
WebSocket (compose ships one on surrealkv storage in its own volume,
backend waits on its healthcheck). Pre-switch data was wiped on
purpose — fresh volumes seed from scratch. Tests keep the in-memory
engine; persistence.rs re-runs the boot migration on a live handle
instead of reopening a file.

2026-07-15

✨ feat(notes): file attachments with school-set size capAhmet Kaan Gümüş · f1b532b
✨ feat(notes): file attachments with school-set size cap

Blobs live on disk under FILES_PATH (same volume as the DB), named by
the row's ULID so user input never shapes a path; the note_file row
keeps only metadata. DB-blob storage rejected: multi-MB PDFs bloat
surrealkv's LSM tree and buffer whole in RAM on every read.

- POST/GET /notes/{id}/files, GET/DELETE /notes/{id}/files/{file_id};
  owner-only through the owning note, staff included
- max_file_bytes in settings (1 KiB-25 MiB hard cap, default 5 MiB),
  enforced on streamed bytes (413), inside the settings CAS guard;
  option<int> so pre-field volumes boot without a backfill
- 10 files per note; deleting a note removes rows first, blobs after,
  so a crash strands at worst an unreachable blob

2026-07-13

🐛 fix(exams): stamp walk-outs per sitting, wipe retakes atomicallyAhmet Kaan Gümüş · 6eb0a28
🐛 fix(exams): stamp walk-outs per sitting, wipe retakes atomically

Three bugs in the attempts/rejoin build, each a wrongful lockout or
data loss once allow_rejoin is off:

- A room's teardown stamped left_at on the *latest* attempt, so a
  stale socket from a finished sitting marked a fresh retake as left,
  locking the student out of a room they never entered. Rooms now
  bind to the sitting they were opened for: state frames and the
  walk-out stamp re-read that attempt by id, never "latest", so a
  superseded room announces its own terminal state and closes.
- Closing one of two tabs counted as leaving while the student was
  still connected. ExamPresence (AppState) counts sockets per
  attempt; only the last socket out stamps the walk-out.
- The retake answer-wipe ran before the attempt create, so a lost
  double-start race could delete answers freshly saved into the
  winner's sitting — or destroy a graded sheet with no retake ever
  created. Wipe + create now run in one transaction and a failed
  create rolls the wipe back. (SurrealDB counts BEGIN/COMMIT as
  response slots: the CREATE result is slot 2.)

Regression tests: e2e rooms for the retake stamp and the second tab,
domain tests for the atomic wipe and the lost race (verified red
against the old ordering), presence unit test. README rejoin
paragraph aligned with the per-sitting semantics.

2026-07-11

✨ feat(admin): seed an admin account at startupAhmet Kaan Gümüş · ea497d9
✨ feat(admin): seed an admin account at startup

ADMIN_USERNAME and ADMIN_PASSWORD (both-or-neither; half a pair aborts
boot, blank counts as unset) create an admin at startup when the
username doesn't exist. The seed is idempotent and never rewrites
credentials: an existing admin is left as-is, and a non-admin holding
the name is never promoted — that would be a privilege escalation, so
it only logs a warning pointing at the out-of-band paths.

compose.yaml ships local-dev credentials for first boot; .env.example
documents the knob.
✨ feat(app): router assembly, OpenAPI/Swagger, CORS, and bootstrapAhmet Kaan Gümüş · c4d0a23
✨ feat(app): router assembly, OpenAPI/Swagger, CORS, and bootstrap

state.rs defines AppState — the db handle, cookie_secure flag, and
rate-limit config shared by every handler.

lib.rs build_router assembles the whole app (shared by main and the
test suites): it mounts each feature router, serves /health and root,
and layers the catch-all per-IP rate limiter inside CORS so a 429 still
carries the headers a browser needs. CORS is credential-aware — it
reflects the request Origin, or a CORS_ALLOWED_ORIGINS allowlist when
set, never a wildcard. utoipa collects the OpenAPI spec from the
handlers and serves Swagger UI at /swagger with the session cookie as
a documented security scheme.

main.rs is the bootstrap: load .env, init tracing, read Config, open
the database, serve with per-connection peer info (the limiter's key),
and shut down cleanly on SIGINT/SIGTERM so the embedded store closes —
important as PID 1 in a container.