Commits
2026-09-17
✨ 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-16
✨ feat: the class×course instance is the academic anchor (K-12 remodel)Ahmet Kaan Gümüş · ae84034
✨ feat: the class×course instance is the academic anchor (K-12 remodel)
`course` was a school-wide singleton: enrollment, exams, sessions,
roll-call and homework all keyed on it, so two class sections teaching the same
course shared one roster, one exam set and one timetable. This moves the
academic anchor to `class_course` — the per-class instance — and rebuilds
the academic model around Turkish K-12.
Schema (migrations/school/20260916000001_k12_remodel.sql): `class_course`
becomes an instance (ders_saati, counts_toward_karne, enrollment_count,
class_course_teacher); enrollment re-keys to (class_course, app_user);
exam carries class_course + term (+ exam_audience for shared exams);
course_session / session_attendance / homework re-key; `class_member` is a
soft-leave history table (uuid PK, joined_at/left_at, partial unique index
on the live stint); `academic_year` sits above `term`; `class_group` links
a year, not a term; new `course_membership` (clubs/study), `karne_snapshot`;
settings gain branches/excuse_kinds/absence limits/timezone; profile gains
branch. Drops/recreates the identity-changing tables (pre-customer; the
migration resets every counter on a kept table that pointed at a dropped
one).
Layers: domain/db/service/web rewritten to the instance seam, with
`ensure_instance_teacher` gating instance writes (D10), the report card computed per
instance and weighted by ders_saati, an absence report, `/instances`
and `/academic-years` nests, and `/classes/{id}/instances`. Capacity and
the seat-claim 409 are gone; detach sweeps the whole instance subtree and
unlinks its blob keys.
Gates: cargo check --all-targets, SQLX_OFFLINE check (cache regenerated),
doc_sync, spec_bounds, limits_completeness, clippy -D warnings all green;
cargo nextest run 1370/1370.2026-09-14
🔧 chore: default HTTP bind port 7656Ahmet Kaan Gümüş · 81ac0fb
🔧 chore: default HTTP bind port 7656 Unset PORT now binds 7656 instead of 8080: parse_port, the user unit, compose, Containerfile, CI health-gate fallback, and README.
2026-09-12
2026-09-07
✨ 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-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.
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
✨ 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 blob2026-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(config): environment-sourced runtime configurationAhmet Kaan Gümüş · d6dd881
✨ feat(config): environment-sourced runtime configuration Config::from_env reads host/port, the embedded DB path + namespace, the cookie Secure toggle, and the rate-limit tiers. Every value has a safe default, so the server boots with no .env at all. Parsing is lenient: unset or garbage falls back to the default, an explicit 0 rate limit is honoured (disables that tier), and boolean flags accept 1/true/yes/on in any case. main loads .env via dotenvy. .env.example documents every knob, including the production-only COOKIE_SECURE, CORS_ALLOWED_ORIGINS, rate limits, and TRUST_PROXY.