forge
Explore
Log in

Don't you dare go Hollow

Commits

Commits on mainFiltered to tests/rate_limit.rsClear filter

2026-09-25

🧹 chore(rate-limit): raise the shipped budgets 100xAhmet Kaan Gümüş · 51e5c7b
🧹 chore(rate-limit): raise the shipped budgets 100x

Default budgets when the env is unset: auth 1000/min per IP,
API 30000/min per IP, chatbot 2000/min per user, RAG 600/min per
user, keyless overflow 60000/min. An explicit RATE_LIMIT_* still
wins. The per-route enforcement census uses a small census budget
so CI does not hammer 30000 requests per route; production-scale
boundary stays in the in-memory limiter tests.

2026-09-23

✨ feat: school identity is the uuid; drop the slugAhmet Kaan Gümüş · 2918040
✨ feat: school identity is the uuid; drop the slug

The school slug is gone from every surface: the session cookie prefix,
the /schools/{id} builder routes, FILES_PATH blob dirs, the hab/2 frame
school value, DTOs, and the /limits contract. SchoolId::try_parse is the
one wire parse (hyphenated uuid only); a non-uuid frame school answers
unknown_school. Register gets a public picker via the new unauthenticated
GET /auth/schools returning active [{id, name}]. The control migration
drops school_slug and the slug column, which invalidates every existing
session — old cookie prefixes cannot resolve.
Local-Gate: 3fafffd98aec59c68e2606833b87785d0abf2fee (1510 passed, 425s)

2026-09-17

fix: 🌙 two clock-dependent assertions in the suiteAhmet Kaan Gümüş · 1675e73
fix: 🌙 two clock-dependent assertions in the suite

- the rate-limit outage test asserted a single-shot read of a row a parked fold
  may write the instant the table returns; it now asserts the arithmetic (never
  folded twice, nothing lost) after two round barriers. This is the failure
  that reddened CI run 35170750886.
- the cross-tenant search probe matched a username as a substring of the raw
  JSON, which also hits the hex of a UUIDv7 id: "ada" rides inside
  01a0adad-…, so a correctly scoped response failed for a slice of every
  ~17.5-minute wall-clock window and passed outside it. It compares the parsed
  username/display_name now.
✨ 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-14

🐛 fix: load-luck asserts in pomodoro race and rate-limit outageAhmet Kaan Gümüş · b6d7046
🐛 fix: load-luck asserts in pomodoro race and rate-limit outage

Streak==round is not the concurrent-finish claim. Down-database empty-row
assert waited out parked folds (RATE_SYNC_TIMEOUT) before restore.

Local: cargo nextest run --no-fail-fast → 1373 passed.
rate_limit binary ×3 passed. pomodoro concurrent ×20 passed.
🐛 fix: shared rate-limit tests wait a second sync roundAhmet Kaan Gümüş · 7c429b6
🐛 fix: shared rate-limit tests wait a second sync round

Each limiter's fold is its own statement. One round leaves the first
finisher with a stale remote total (CI: expected 0 admits, got 3).

Local: cargo nextest run --no-fail-fast → 1373 passed.
rate_limit binary ×3 passed.

2026-09-13

✨ feat: person-scoped login; select school afterAhmet Kaan Gümüş · fae1f79
✨ feat: person-scoped login; select school after

Login is username+password only. A person is global, memberships are
per-school (role stays on app_user), and POST /auth/school binds when
the account belongs to more than one school.

2026-09-12

🧪 test: port e2e, rate_limit, ai_bridge, ai_protocol to the Postgres harnessAhmet Kaan Gümüş · e0e3597
🧪 test: port e2e, rate_limit, ai_bridge, ai_protocol to the Postgres harness

e2e: spawn_server_with_ai re-pointed at init_test_tenants; the board
helpers read and seed through runtime sqlx (stroke ids, payloads,
epoch, participants roster); promote writes app_user; ULID literals
became common::ABSENT_ID.

rate_limit: the durable-window trio stands on one control database's
rate_limit table (two UserRateLimiters, pools dialed before the clock
freezes); fold reads are query_scalar; the down-database leg takes the
fold's table away and hands it back instead of flipping the deleted
health flag; embedded-engine caveats deleted.

ai_bridge/ai_protocol: bootstrap renames plus the chatbot history seed
inserted over sqlx; the down-socket test outages the school registry
table and recovers, keeping both original assertions.

src/rate_limit.rs: rebuilt the wave-1-deleted epoch-roll unit test
(a_wall_epoch_roll_charges_no_request_twice + its admits helper) over
the control database, driving sync_once's epochs directly.

2026-09-07

✨ 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: builder API — the vendor creates, suspends, enters and deletes schoolsAhmet Kaan Gümüş · 1ab298d
✨ feat: builder API — the vendor creates, suspends, enters and deletes schools

`POST /builder/login|logout`, `GET /builder/me`; `POST|GET /schools`,
`GET|PATCH|DELETE /schools/{slug}`, `POST /schools/{slug}/admin-password`,
`POST /schools/{slug}/enter`. Builder sessions live in the control database
behind their own strict per-IP login tier; deleting a school drops its
database and its files subtree.
✨ feat: one database per school behind a control registry; login names the schoolAhmet Kaan Gümüş · b7dfc0c
✨ feat: one database per school behind a control registry; login names the school

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

2026-08-05

🧪 test: name the sharing tests after the deployment we haveAhmet Kaan Gümüş · cb766df
🧪 test: name the sharing tests after the deployment we have

The shared `rate_limit` row survived the multi-replica machinery that was
deleted on 07-30, because it also covers the case the deployment still
has: a restart mid-window must not hand every client a fresh budget. Two
limiters over one row model the process before a restart and the process
after, not two replicas.

The tests kept the old spelling and read as coverage of a topology that
no longer exists, which invites deleting them — they are the only
coverage of the readback path, where a limiter learns a total it did not
itself admit.
🧪 test: let the sharing tests choose their wall window instead of drawing oneAhmet Kaan Gümüş · e6f927b
🧪 test: let the sharing tests choose their wall window instead of drawing one

The three tests built on `two_replicas` assert about *the* shared row: one
row holding both replicas' hits, or a replica reading back the other's
spend. Nothing made the two agree on a row, though — each sync round calls
`current_epoch`, which reads the real clock, so a minute boundary landing
between the two tasks' rounds gives them a row each and the assertions turn
over. Small window (the two rounds are milliseconds apart) but the same
class of accidental clock dependency that kept the epoch-roll double-charge
out of this suite: a test that passes because of when it ran.

`share_pinned` takes the wall window as an argument, so the suite names one
instead of drawing whichever the clock offers. Splitting the two replicas
across two pinned windows fails all three tests, which is what the pin is
holding shut. Rolling *between* windows stays a unit test, where
`sync_once`'s epoch argument drives the boundary directly.

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.
fix: 🔩 close the leaks a five-domain hunt turned upAhmet Kaan Gümüş · a3fe8cf
fix: 🔩 close the leaks a five-domain hunt turned up

Five hunters swept exams, homework/attendance, identity, money/scheduling
and messaging/courses; a three-lens verifier panel then refuted three of
the first fixes, and those corrections are folded in here.

Leaks and races closed:

- exam self-review gated on *any* mark, so a seq-1 grade opened the
  answer key forever — a student mid-retake read `correct` and
  `is_correct` off the sheet they were still writing. All four review
  reads now 409 while the caller's latest sitting is in progress.
- roll call could land after its session was deleted, and the orphan was
  unremovable (its delete route 404s on the vanished session) while the
  attendance report went on counting it. The write now proves its parent
  exists in the same transaction, the way ExamResult::grade does.
- a teacher could counter-propose and then approve their own proposal,
  committing the requester to a time only the teacher ever named; and
  even after that, re-proposing between the requester's read and their
  accept moved the meeting under them. Approve refuses while a proposal
  stands, and accept now pins the window it is answering.
- two concurrent chatbot posts on one thread cross-attributed their
  answers — both replied to the second prompt, the first was never
  answered. The prompt id rides the request instead of being re-derived
  from write order.
- a whiteboard participant demoted to `parent` kept drawing, and kept
  *reading* the live canvas for up to 15s. Every frame is authorized
  before delivery now, and a demotion sweeps the account off rosters.
- a demotion to `parent` stranded event signups no one could free.
  Promotions are left alone (staff free their own seats) and closed
  lists are never rewritten.
- the rate-limit bucket map was unbounded past 10k live keys and then
  scanned O(n) under the global mutex on every request. Eviction is
  bounded and never frees an exhausted bucket — the first attempt did,
  which traded a memory bug for an auth-bypass, so it is pinned by a
  test that floods at the victim's own spend.
- session and event cascades ran as loose queries; a concurrent write
  slipped between them and orphaned rows, and for notes a blob nothing
  could ever reclaim. All three are one transaction now.
- sixteen id generators still used Ulid::new(), whose random low bits
  scramble same-millisecond rows under the "newest first" the docs
  promise; five listings had no tie-break at all, so offset paging could
  skip or duplicate a row.

Also: $session is a protected SurrealDB 3 variable — binding it fails
the whole query as a bare 500, which is what hid the attendance fix.

Accepted, documented, not fixed: one bank template instantiated into two
exams copies `correct` into both, and the review gate is per-exam.

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

fix: 🪢 guard writes in the database, not the processAhmet Kaan Gümüş · 6c87eca
fix: 🪢 guard writes in the database, not the process

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

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

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

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

2026-07-26

chore: 📦 give every constant one homeAhmet Kaan Gümüş · 78b25b5
chore: 📦 give every constant one home

Constants were scattered across 18 modules: table names and migration SQL in
database.rs, limits in config.rs and rate_limit.rs, magic strings sitting next
to the only code that read them. Nobody could answer "what are all the hard
values in this service?" without a grep.

They all live in constant.rs now — validation bounds, the 37 SurrealDB table
names, the PRE_REPAIR/MIGRATION/BACKFILL schema SQL, and the enum value tables
that used to hide as associated consts (Role::ALL -> ROLES, Folder::SENDER ->
SENDER_FOLDERS, and friends). Values are byte-identical; this changes no
behavior. constant.rs now imports crate::domain for the enum types, an
intra-crate cycle that compiles fine.

Statics stayed where they were. A Mutex or a ULID generator is runtime state,
not a constant, and moving them would only blur that line.

Two guards keep the consolidation honest. limits_completeness.rs already
failed on any pub const in constant.rs that is neither published through
/limits nor excluded with a reason; the *_TABLE names are excused by shape
rather than by 37 lines of boilerplate, but the excuse now requires the
absence of a MAX_/MIN_/DEFAULT_ prefix so a real bound cannot hide behind the
naming convention. And the move quietly dropped three rules off the end of the
text-fold table, which every existing test still passed — so the circumflexed
vowels are pinned, and search_fold_sql must emit one string::replace per rule
or the needle and the column drift apart.

2026-07-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.
✨ 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

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

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

✅ test: integration, e2e, persistence, and rate-limit suitesAhmet Kaan Gümüş · 905da44
✅ test: integration, e2e, persistence, and rate-limit suites

End-to-end coverage over the assembled router:

- integration.rs: tower::oneshot against an in-memory database — the
  fast path for handler, validation, and access-control behavior.
- e2e.rs: a real TCP listener driven by a reqwest cookie jar,
  exercising the actual session-cookie round trip.
- persistence.rs: the file-backed engine on a tempfile, including
  close-and-reopen to prove data survives a restart.
- rate_limit.rs: both tiers, peer-address vs X-Forwarded-For keying,
  and the shipped limits over every route.
- common/mod.rs: the shared harness — builds the router with limits
  disabled so unrelated suites never trip a limit.