diff --git a/src/ai/rag.rs b/src/ai/rag.rs index cc35d4e..039af97 100644 --- a/src/ai/rag.rs +++ b/src/ai/rag.rs @@ -18,7 +18,6 @@ use crate::constant::AI_RAG_INDEX_TIMEOUT_SECS; use crate::database::Database; use crate::domain::course_note::CourseNote; use crate::domain::course_note_file::CourseNoteFile; -use crate::domain::rag_output::RagOutput; use crate::module::Module; use crate::state::AppState; use crate::web::tenant_state::ResolvedTenant; @@ -159,14 +158,15 @@ pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note: /// Swap the note's outputs for the fresh one. Create-then-drop-older, not an /// update: the previous output belongs to a previous version of the note, and /// this order is what makes two concurrent index tasks converge on one row -/// ([`RagOutput::replace_for_note`]). +/// ([`replace_for_note`](crate::db::rag_output::replace_for_note)). async fn replace( db: &Database, note: &CourseNote, sources: Vec, payload: serde_json::Value, ) -> Result<(), crate::error::AppError> { - RagOutput::replace_for_note(note.get_id(), note.get_course(), sources, payload, db).await?; + crate::db::rag_output::replace_for_note(db, note.get_id(), note.get_course(), sources, payload) + .await?; Ok(()) } diff --git a/src/db/chatbot_message.rs b/src/db/chatbot_message.rs new file mode 100644 index 0000000..4830a7b --- /dev/null +++ b/src/db/chatbot_message.rs @@ -0,0 +1,302 @@ +//! The `chatbot_message` table: the turns of a thread, both sides persisted. +//! The user's prompt lands `complete`, and the assistant's row is written +//! `pending` *before* the AI call so a reload never loses an answer in +//! flight. The task that owns the bridge round trip then flips it to +//! `complete` (with the text) or `failed` (with a code), and the boot sweep +//! in `database.rs` fails whatever a process death left behind past the +//! staleness window. Every turn is written *through* its thread's own row +//! ([`touch_and_write`]), so a turn can never outlive the thread it belongs +//! to. The row shape lives in [`crate::domain::chatbot_message`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::MAX_ERROR_CODE_LEN; +use crate::database::Database; +use crate::db::chatbot_thread::touch_and_write; +use crate::db::page::PagedList; +use crate::domain::chatbot_message::{ + ChatContent, ChatbotMessage, ChatbotMessageId, MessageStatus, +}; +use crate::domain::chatbot_thread::ChatbotThreadId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Write one turn *through its thread's own row* ([`touch_and_write`]), +/// which is what makes the thread's existence something this write writes +/// rather than something the caller read and then trusted: a +/// [`delete`](crate::db::chatbot_thread::delete) +/// racing it touches the very key this transaction moves, so the two cannot +/// both commit and no turn is left under a thread that is gone. It also +/// carries the thread's activity stamp, so a turn and its `updated_at` land +/// together. +/// +/// [`AppError::NotFound`] = the thread is gone, and nothing was written. +async fn insert(db: &Database, message: ChatbotMessage) -> Result { + let thread = message.thread_id.clone(); + let id = message.id.record(); + touch_and_write( + db, + &thread, + "CREATE $id CONTENT $row RETURN AFTER", + vec![ + ("id".into(), id.into_value()), + ("row".into(), message.into_value()), + ], + ) + .await? + .ok_or_else(|| AppError::Internal("failed to create chat message".into())) +} + +/// Append the user's prompt. Nothing is awaited for it, so it is born +/// complete. +pub async fn append_user( + db: &Database, + thread: &ChatbotThreadId, + user: &UserId, + content: ChatContent, +) -> Result { + let now = Timestamp::now(); + insert( + db, + ChatbotMessage { + id: ChatbotMessageId::generate(), + thread_id: thread.clone(), + user_id: user.clone(), + role: crate::domain::chatbot_message::MessageRole::User, + content, + status: MessageStatus::Complete, + truncated: false, + error_code: None, + created_at: now, + completed_at: Some(now), + }, + ) + .await +} + +/// Reserve the assistant's answer *before* the AI call: the row exists, +/// empty and `pending`, so a reload finds the turn and can wait on it. +pub async fn append_pending_assistant( + db: &Database, + thread: &ChatbotThreadId, + user: &UserId, +) -> Result { + insert( + db, + ChatbotMessage { + id: ChatbotMessageId::generate(), + thread_id: thread.clone(), + user_id: user.clone(), + role: crate::domain::chatbot_message::MessageRole::Assistant, + content: ChatContent::empty(), + status: MessageStatus::Pending, + truncated: false, + error_code: None, + created_at: Timestamp::now(), + completed_at: None, + }, + ) + .await +} + +/// The whole thread, oldest first — the order both the UI and the AI +/// history payload read in. +pub async fn list_for_thread( + db: &Database, + thread: &ChatbotThreadId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let (rows, total) = PagedList::new( + "chatbot_message WHERE thread_id = $conv", + "ORDER BY created_at ASC, id ASC", + ) + .bind("conv", thread.record()) + .run::(limit, offset, db) + .await?; + Ok(( + rows.into_iter().map(ChatbotMessage::projected).collect(), + total, + )) +} + +/// The last `limit` turns, still oldest-first — the tail replayed to the +/// AI service as context. Taken newest-first in the database (so the +/// `LIMIT` keeps the *recent* end) and flipped back here. +pub async fn list_tail( + db: &Database, + thread: &ChatbotThreadId, + limit: usize, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM chatbot_message WHERE thread_id = $conv \ + ORDER BY created_at DESC, id DESC LIMIT $limit", + ) + .bind(("conv", thread.record())) + .bind(("limit", limit as i64)) + .await? + .check()?; + let mut messages: Vec = result + .take::>(0)? + .into_iter() + .map(ChatbotMessage::projected) + .collect(); + messages.reverse(); + Ok(messages) +} + +/// The last `limit` *settled* turns that carry text, still oldest-first — +/// the tail replayed to the AI service as context. The filter runs in the +/// query, not after it: a `LIMIT` over the raw tail hands back fewer usable +/// rows the moment a run of answers fails, silently shrinking the context +/// instead of reaching further back. No projection is applied — it only +/// ever rewrites a `pending` row, and none is selected here. +pub async fn list_settled_tail( + db: &Database, + thread: &ChatbotThreadId, + limit: usize, +) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM chatbot_message WHERE thread_id = $conv \ + AND status = 'complete' AND content != '' \ + ORDER BY created_at DESC, id DESC LIMIT $limit", + ) + .bind(("conv", thread.record())) + .bind(("limit", limit as i64)) + .await? + .check()?; + let mut messages: Vec = result.take(0)?; + messages.reverse(); + Ok(messages) +} + +/// The user turn a reserved answer belongs to, by *identity*: the prompt +/// row of the very POST that reserved it, whose id the answering task +/// carries. +/// +/// Never derived from write order. Two POSTs on one thread interleave +/// across the two creates — the rows land `userA, userB, asstA, asstB` — +/// so "the newest user row written before this answer" resolves *both* +/// answers to prompt B, and prompt A is never answered. +pub async fn prompt_of( + db: &Database, + id: &ChatbotMessageId, +) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Read one turn only if `user` owns it — the poll loop's read. +pub async fn read_for( + db: &Database, + id: &ChatbotMessageId, + user: &UserId, +) -> Result, AppError> { + let message: Option = db.select(id.record()).await?; + Ok(message + .filter(|message| &message.user_id == user) + .map(ChatbotMessage::projected)) +} + +/// Land the answer, recording whether it had to be clipped to fit the +/// school's cap. Field-scoped and gated on `status = 'pending'` in the +/// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a +/// timeout) already failed, and two answers can't both apply. +pub async fn complete( + db: &Database, + id: &ChatbotMessageId, + text: ChatContent, + truncated: bool, +) -> Result { + settle(db, id, Some(text), truncated, None).await +} + +/// Mark the answer failed with a short code (`unavailable`, the service's +/// own error code, …). Same pending gate as [`complete`]. +pub async fn fail( + db: &Database, + id: &ChatbotMessageId, + error_code: &str, +) -> Result { + // A failed turn has no text, so there is nothing that could be clipped. + settle(db, id, None, false, Some(error_code)).await +} + +async fn settle( + db: &Database, + id: &ChatbotMessageId, + text: Option, + truncated: bool, + error_code: Option<&str>, +) -> Result { + let status = if text.is_some() { + MessageStatus::Complete + } else { + MessageStatus::Failed + }; + let mut result = db + .query( + "UPDATE $id SET content = $content, status = $status, truncated = $truncated, \ + error_code = $code, completed_at = $now WHERE status = 'pending' RETURN AFTER", + ) + .bind(("id", id.record())) + .bind(("content", text.map(|t| t.0).unwrap_or_default())) + .bind(("status", status.as_str().to_string())) + .bind(("truncated", truncated)) + .bind(( + "code", + error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::()), + )) + .bind(("now", Timestamp::now().as_millis())) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::chatbot_message::MessageRole; + + #[tokio::test] + async fn a_turns_two_rows_never_sort_inverted() { + // Both rows of a turn land in the same millisecond routinely, so the + // `id` tie-break decides the thread's order. With a random ULID this + // inverted a fifth of the pairs; here every pair must read back + // question-then-answer, from both read paths. + let db = crate::database::init_mem().await.unwrap(); + // A real thread row: every turn is written through it, so a turn with + // no thread is refused (see [`insert`]). + db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0") + .await + .unwrap() + .check() + .unwrap(); + let thread = ChatbotThreadId::from_key("c"); + let user = UserId::from_key("u"); + const TURNS: usize = 200; + + for turn in 0..TURNS { + let content = ChatContent::try_new(&format!("soru {turn}")).unwrap(); + append_user(&db, &thread, &user, content).await.unwrap(); + append_pending_assistant(&db, &thread, &user).await.unwrap(); + } + + let (whole, _) = list_for_thread(&db, &thread, None, 0).await.unwrap(); + let tail = list_tail(&db, &thread, TURNS * 2).await.unwrap(); + for messages in [&whole, &tail] { + assert_eq!(messages.len(), TURNS * 2); + for (turn, pair) in messages.chunks(2).enumerate() { + assert_eq!(pair[0].get_role(), MessageRole::User, "turn {turn}"); + assert_eq!(pair[0].get_content().as_str(), format!("soru {turn}")); + assert_eq!(pair[1].get_role(), MessageRole::Assistant, "turn {turn}"); + } + } + } +} diff --git a/src/db/chatbot_thread.rs b/src/db/chatbot_thread.rs new file mode 100644 index 0000000..f471b3c --- /dev/null +++ b/src/db/chatbot_thread.rs @@ -0,0 +1,522 @@ +//! The `chatbot_thread` table: one user's AI-chat threads, listed +//! newest-activity-first, deleted together with every turn in them. The +//! entity and its validated newtypes live in +//! [`crate::domain::chatbot_thread`]; this module is where their rows are +//! read and written. + +use surrealdb::types::{SurrealValue, Value}; + +use crate::constant::{ + CHATBOT_THREAD_COUNT_FIELD, DEFAULT_MAX_CHATBOT_THREADS, SETTINGS_KEY, SETTINGS_TABLE, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::db::page::PagedList; +use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Move the thread's `updated_at` **and** run `statement` — a write to a turn +/// hanging off that thread — in one transaction, handing back the row it +/// returned. [`AppError::NotFound`] means the thread is gone and `statement` +/// wrote nothing. +/// +/// The bump is what ties a turn's fate to its thread, and reading the thread +/// first does not: [`delete`] sweeps `chatbot_message` and drops +/// the thread in one transaction, so a create landing after that sweep but +/// before its commit reads a thread that is still there (uncommitted) while the +/// sweep ran on a snapshot predating the new row — both commit, and the turn +/// outlives the thread it was deleted with, readable and deletable by nothing. +/// Reads do not conflict; only a write that *moves* a value on a key the delete +/// also writes does. That is the shape +/// [`bump_menu_and_write`](crate::domain::menu::bump_menu_and_write) and +/// [`ExamAnswer::save`](crate::domain::exam_answer::ExamAnswer::save) already +/// use, and the sweep's ordering inside the delete stops mattering once it is +/// in place. +/// +/// `updated_at` is the value moved, and it doubles as the stamp the thread list +/// sorts on — this *is* the activity touch the send path used to issue +/// afterwards as a separate, best-effort query whose failure was only logged. +/// It is written strictly upwards rather than to `$now`: an `UPDATE` that +/// leaves the document unchanged is elided and never reaches the store's write +/// set, a turn's two rows are routinely written inside one millisecond, and a +/// write that does not happen collides with nothing. The stamp can therefore +/// sit a few milliseconds ahead of the clock, which an ordering key does not +/// care about. +/// +/// Admissible for [`transaction_with_retry`] as long as `statement` is: the +/// `UPDATE`, the `IF`/`THROW` and the `RETURN` can never answer "already +/// exists", and neither can a `CREATE` on a freshly minted ULID on a table with +/// no `UNIQUE` index — no rival can have aimed at it, and a lost round wrote +/// nothing, so re-sending it is the recovery. +pub(crate) async fn touch_and_write( + db: &Database, + thread: &ChatbotThreadId, + statement: &str, + mut bindings: Vec<(String, Value)>, +) -> Result, AppError> { + bindings.push(("conv".into(), thread.record().into_value())); + bindings.push(("now".into(), Timestamp::now().as_millis().into_value())); + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $touched = (UPDATE $conv SET updated_at = \ + math::max([$now, updated_at + 1]) RETURN VALUE id); + IF array::len($touched) = 0 {{ THROW 'no_thread' }}; + LET $row = ({statement}); + RETURN $row; + COMMIT TRANSACTION;" + ), + &bindings, + &["no_thread"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_thread")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. + Ok(result.take::>(4)?.into_iter().next()) +} + +/// Start a thread unless `user` is already at the school's +/// `max_chatbot_threads`. The slot is taken on the user row in the same +/// transaction as the thread ([`cap::claim_live_and_create`]) — an atomic +/// single-record write, so two requests racing the same user's last slot +/// cannot both win and the counter can never count a row that did not +/// commit. +/// +/// The cap is the one *live* on the settings singleton, sub-queried inside +/// that same conditional write rather than bound as a number: this cap does +/// not live on the parent row (the seat is on the user, the limit is the +/// school's), and a snapshot of it admits every request already in flight +/// when a `PATCH /settings` lowers it. The subquery costs one extra record +/// read per claim on a path that already reads the row it writes. +/// `DEFAULT_MAX_CHATBOT_THREADS` is the fallback the settings row's own +/// absent column means — no row, or a school that never set the knob. +pub async fn create_capped( + db: &Database, + user: &UserId, + title: Option, +) -> Result { + let now = Timestamp::now(); + let thread = ChatbotThread { + id: ChatbotThreadId::generate(), + user_id: user.clone(), + title, + created_at: now, + updated_at: now, + }; + match cap::claim_live_and_create( + &user.record(), + CHATBOT_THREAD_COUNT_FIELD, + &format!( + "(SELECT VALUE max_chatbot_threads FROM ONLY {SETTINGS_TABLE}:{SETTINGS_KEY}) ?? $num" + ), + DEFAULT_MAX_CHATBOT_THREADS, + // No holder claim: the parent row *is* the user's, so this write + // already lands on the key a role change writes. + None, + (&thread.id.record(), &thread), + db, + ) + .await? + { + cap::Claimed::Made(saved) => Ok(saved), + // Full, or the user's row is gone — the conditional write matches + // nothing either way. + cap::Claimed::Full => Err(AppError::Conflict( + "you have reached the school's limit on saved threads — delete one first", + )), + // The id is a freshly minted ULID on a table with no UNIQUE index, + // so no rival can have aimed at it. + cap::Claimed::Duplicate => Err(AppError::Internal("thread id collided".into())), + } +} + +/// A user's threads, most recently active first — the sort the +/// `chatbot_thread_user_updated` index exists for. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "chatbot_thread WHERE user_id = $usr", + "ORDER BY updated_at DESC, id DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await +} + +/// How many threads `user` keeps — the `max_chatbot_threads` cap check. +pub async fn count_for_user(db: &Database, user: &UserId) -> Result { + let mut result = db + .query("SELECT VALUE count() FROM chatbot_thread WHERE user_id = $usr GROUP ALL") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result + .take::>(0)? + .first() + .copied() + .unwrap_or_default() + .max(0) as usize) +} + +/// Read a thread only if `user` owns it — a foreign id reads as absent, so +/// the web layer answers 404 rather than leaking that it exists. +pub async fn read_for( + db: &Database, + id: &ChatbotThreadId, + user: &UserId, +) -> Result, AppError> { + let thread: Option = db.select(id.record()).await?; + Ok(thread.filter(|thread| &thread.user_id == user)) +} + +// Stamping new activity is not a call of its own: it is the bump inside +// [`touch_and_write`], which every turn already rides, so a stamp can no +// longer be lost (it used to be a best-effort query after the two creates, +// whose failure was a `warn!`) and no turn can be written without it. + +/// Rename the thread (`None` clears the name back to untitled), stamping +/// the edit as activity. Field-scoped for the same reason as +/// [`touch_and_write`]: a turn may be landing concurrently. +pub async fn rename( + db: &Database, + thread: &ChatbotThread, + title: Option, +) -> Result { + let mut result = db + .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER") + .bind(("id", thread.id.record())) + .bind(("title", title.map(|title| title.0))) + .bind(("now", Timestamp::now().as_millis())) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +/// Delete the thread and every turn in it — one transaction, so a crash +/// can't orphan messages under a vanished thread. The owner's slot comes +/// back in that same transaction, or the cap would ratchet shut. +/// +/// A turn, a rename and this delete all write the thread row (see +/// [`touch_and_write`]), so the store aborting one of them is ordinary +/// here — that collision is exactly what keeps a turn from outliving the +/// thread — and a lost round is re-sent rather than reported as the `500` +/// it used to be. Re-sending is sound: every statement is a `DELETE` or a +/// field-scoped `UPDATE`, none of which can ever answer "already exists" +/// (see [`transaction_with_retry`]). On the re-sent round the thread is +/// already gone, so the `RETURN` is empty and the caller gets the `404` +/// that is the truth. +pub async fn delete(db: &Database, thread: ChatbotThread) -> Result { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + DELETE chatbot_message WHERE thread_id = $conv; + LET $gone = (DELETE $conv RETURN BEFORE); + UPDATE $usr SET chatbot_thread_count = math::max([(chatbot_thread_count ?? 0) - array::len($gone), 0]); + RETURN $gone; + COMMIT TRANSACTION;", + &[ + ("conv".into(), thread.id.record().into_value()), + ("usr".into(), thread.user_id.record().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN + // is slot 4. + let deleted: Option = result.take::>(4)?.into_iter().next(); + deleted.ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use surrealdb::types::RecordId; + + use crate::db::chatbot_message; + use crate::domain::chatbot_message::ChatContent; + use crate::domain::settings::{Settings, SettingsParams}; + + /// The owner's counter and the threads it counts, both re-read out of the + /// store — never off a return value, which the in-memory engine forges + /// wins on (see [`cap`]). + async fn stored(db: &Database) -> (i64, usize) { + let mut result = db + .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u") + .query("SELECT VALUE id FROM chatbot_thread") + .await + .unwrap() + .check() + .unwrap(); + let counter = result.take::>(0).unwrap(); + let rows = result.take::>(1).unwrap(); + (counter[0], rows.len()) + } + + async fn a_user_capped_at(threads: i64) -> Database { + let db = crate::database::init_mem().await.unwrap(); + db.query("CREATE user:u SET username = 'u', password_hash = 'x';") + .await + .unwrap() + .check() + .unwrap(); + crate::db::settings::save( + &db, + Settings::try_new(SettingsParams { + max_chatbot_threads: threads, + ..Settings::defaults().params() + }) + .unwrap(), + ) + .await + .unwrap(); + db + } + + /// The seat and the row commit together, so the counter the cap reads can + /// never disagree with the threads it counts — and a create refused at the + /// cap advances neither. + #[tokio::test] + async fn a_capped_create_moves_the_counter_with_the_row() { + let db = a_user_capped_at(1).await; + let user = UserId::from_key("u"); + + create_capped(&db, &user, None).await.expect("first thread"); + assert_eq!(stored(&db).await, (1, 1)); + + let refused = create_capped(&db, &user, None).await; + assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap"); + assert_eq!( + stored(&db).await, + (1, 1), + "a refused create advances neither" + ); + } + + /// A turn is written *through* its thread's row, so a thread that is gone + /// takes the write with it — and one that is there is stamped by it. + /// The race this shape exists to close is the `#[ignore]`d test below; + /// this one pins the logic, which the in-memory engine can answer. + #[tokio::test] + async fn a_turn_writes_its_thread_and_dies_with_it() { + let db = a_user_capped_at(2).await; + let user = UserId::from_key("u"); + let thread = create_capped(&db, &user, None).await.expect("thread"); + let opened = thread.get_updated_at().as_millis(); + + let say = || ChatContent::try_new("selam").unwrap(); + chatbot_message::append_user(&db, thread.get_id(), &user, say()) + .await + .expect("append"); + let stamped = read_for(&db, thread.get_id(), &user) + .await + .expect("re-read") + .expect("still there") + .get_updated_at() + .as_millis(); + // Strictly upwards, never merely re-stamped: an `UPDATE` that leaves + // the row unchanged is elided, and both rows of a turn are routinely + // written inside one millisecond of the thread's own creation. + assert!(stamped > opened, "{stamped} !> {opened}"); + + let id = thread.get_id().clone(); + delete(&db, thread).await.expect("delete"); + let orphan = chatbot_message::append_user(&db, &id, &user, say()).await; + assert!( + matches!(orphan, Err(AppError::NotFound)), + "a turn on a deleted thread must be refused: {orphan:?}" + ); + assert_eq!( + chatbot_message::list_for_thread(&db, &id, None, 0) + .await + .expect("list") + .1, + 0, + "the refused turn wrote nothing" + ); + } + + /// The stamp moves **strictly upwards**, never to the clock — the property + /// the whole shape rests on, since an `UPDATE` that leaves the row + /// unchanged is elided, never reaches the store's write set, and so + /// collides with the racing delete not at all. + /// + /// The test above cannot see it: it compares one append against + /// `create_capped`, which costs a millisecond or so on its own, and a plain + /// `$now` clears that. Nor can a burst of appends — each is a transaction + /// of its own and takes about as long, so the clock has moved on by the + /// time the next one reads it. Timing cannot reach the window on demand. + /// + /// So the *state* the window produces is set up directly instead: a stamp + /// **ahead of the clock**, which is precisely what `math::max` leaves + /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a + /// contrived one. From there the two rules are told apart with no race at + /// all — upwards keeps climbing off the stored value, the clock drags the + /// stamp back down to itself. The lead is a second, far more than two + /// writes can burn, and the guard below fails loudly rather than vacuously + /// on a machine that manages to burn it. + #[tokio::test] + async fn a_stamp_ahead_of_the_clock_still_climbs() { + const LEAD: i64 = 1_000; + + let db = a_user_capped_at(1).await; + let user = UserId::from_key("u"); + let thread = create_capped(&db, &user, None).await.expect("thread"); + + let parked = Timestamp::now().as_millis() + LEAD; + db.query("UPDATE $id SET updated_at = $parked") + .bind(("id", thread.get_id().record())) + .bind(("parked", parked)) + .await + .unwrap() + .check() + .unwrap(); + + for _ in 0..2 { + chatbot_message::append_user( + &db, + thread.get_id(), + &user, + ChatContent::try_new("selam").unwrap(), + ) + .await + .expect("append"); + } + let stamped = read_for(&db, thread.get_id(), &user) + .await + .expect("re-read") + .expect("still there") + .get_updated_at() + .as_millis(); + + assert!( + Timestamp::now().as_millis() < parked, + "the clock caught the {LEAD}ms lead up during two appends, so this \ + probe proves nothing" + ); + assert_eq!( + stamped, + parked + 2, + "two appends off a stamp of {parked} must leave {}: a stamp that \ + follows the clock instead is one an unchanged-row UPDATE elides", + parked + 2 + ); + } + + /// No turn may survive the delete that swept its thread. An orphan is not + /// litter: nothing sweeps `chatbot_message` afterwards, and both + /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered + /// `200` with the text of a thread the user had deleted. + /// + /// The window is between [`delete`]'s sweep and its commit: + /// a create landing in there reads a thread that is still present + /// (uncommitted) while the sweep ran on a snapshot predating the new row, + /// so both commit. It is closed by making the create **write** the thread + /// row ([`touch_and_write`]) instead of reading it — the two transactions + /// then touch one key and the store refuses to commit both. + /// + /// The window is opened by the database itself rather than by a lucky + /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the + /// delete's own transaction, the instant the row goes, so the `SLEEP` lands + /// after the message sweep and before the commit every single time. + /// + /// Real server, and `#[ignore]`d for it: the subject is the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — + /// it commits both writes and answers `Ok` to each, which would fail this + /// test on correct code (see [`crate::database::init_test_server`]). + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { + let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await; + db.query("CREATE user:u SET username = 'u', password_hash = 'x';") + .await + .unwrap() + .check() + .unwrap(); + // Hold the delete open for a full second after the thread row is gone, + // while its transaction still has to commit. + db.query( + "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let user = UserId::from_key("u"); + let (mut orphans, mut swept) = (0, 0); + for round in 0..4 { + let thread = create_capped(&db, &user, None).await.expect("thread"); + let id = thread.get_id().clone(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { delete(&db, thread).await }) + }; + // The turn starts inside the held window — the thread row is gone + // but uncommitted, which is exactly what a read believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let turn = { + let (id, db, user) = (id.clone(), db.clone(), user.clone()); + tokio::spawn(async move { + chatbot_message::append_user( + &db, + &id, + &user, + ChatContent::try_new("selam").unwrap(), + ) + .await + .map(|_| ()) + }) + }; + let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); + // A 404 for the turn, or a NotFound for the delete, is a correct + // answer — the only defect is stored state. + assert!( + !matches!(turn, Err(AppError::Db(_))), + "round {round}: a raced turn must be answered, not 500: {turn:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if read_for(&db, &id, &user).await.unwrap().is_none() { + swept += 1; + orphans += chatbot_message::list_for_thread(&db, &id, None, 0) + .await + .unwrap() + .1; + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the thread is still there"); + } + } + eprintln!("chatbot_thread::delete raced by a turn: {swept}/4 rounds deleted the thread"); + assert!( + swept > 0, + "no round ever deleted the thread, so the window was never reached" + ); + assert_eq!(orphans, 0, "a turn outlived its thread"); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 4780c07..a817767 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -5,6 +5,8 @@ pub mod appointment_slot; pub mod badge; pub mod builder; pub mod cap; +pub mod chatbot_message; +pub mod chatbot_thread; pub mod class_blueprint; pub mod course; pub mod course_session; @@ -22,6 +24,7 @@ pub mod parent_link; pub mod payment_ledger; pub mod pomodoro; pub mod profile; +pub mod rag_output; pub mod registration; pub mod session; pub mod settings; diff --git a/src/db/rag_output.rs b/src/db/rag_output.rs new file mode 100644 index 0000000..005d8ab --- /dev/null +++ b/src/db/rag_output.rs @@ -0,0 +1,242 @@ +//! The `rag_output` table: what an AI service produced for a course note — +//! an index, a summary, an embedding manifest — stored as this side's own +//! copy of the answer. The AI service never writes here (it answers a +//! request over the bridge, and this side stores the answer), which is what +//! keeps the api-read bridge GET-only. Derived, disposable data: the row is +//! dropped and regenerated whenever its input changes, so the cascades +//! below — [`delete_for_note`] when the note goes, [`delete_with_source`] +//! when one of the attachments it was built from goes — keep a stale output +//! from outliving its input, even in a deployment with no AI service +//! connected. The row shape lives in [`crate::domain::rag_output`]. + +use crate::database::Database; +use crate::db::page::PagedList; +use crate::domain::course::CourseId; +use crate::domain::course_note::CourseNoteId; +use crate::domain::course_note_file::CourseNoteFileId; +use crate::domain::rag_output::{RagOutput, RagOutputId}; +use crate::domain::timestamp::Timestamp; +use crate::error::AppError; +use serde_json::Value; + +/// Store one service output against `note`. +pub async fn create( + db: &Database, + note: &CourseNoteId, + course: &CourseId, + sources: Vec, + payload: Value, +) -> Result { + let row = RagOutput { + id: RagOutputId::generate(), + course_note: note.clone(), + course: course.clone(), + sources, + payload, + generated_at: Timestamp::now(), + }; + // whole-row-save-ok: create of a fresh ULID row built in place — there is no prior row to clobber + let created: Option = db.create(row.id.record()).content(row).await?; + created.ok_or_else(|| AppError::Internal("failed to create rag output".into())) +} + +pub async fn read(db: &Database, id: &RagOutputId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// A note's outputs, newest first. +pub async fn list_for( + db: &Database, + note: &CourseNoteId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC") + .bind("note", note.record()) + .run(limit, offset, db) + .await +} + +pub async fn delete(db: &Database, id: &RagOutputId) -> Result { + let deleted: Option = db.delete(id.record()).await?; + deleted.ok_or(AppError::NotFound) +} + +/// Cascade: every output of `note`. Deleting none is a success — a note +/// no service ever indexed has nothing to drop. +pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { + db.query("DELETE rag_output WHERE course_note = $note") + .bind(("note", note.record())) + .await? + .check()?; + Ok(()) +} + +/// Newest-wins replace, without a lock: store `payload` first, then drop +/// this note's older rows. Two concurrent index tasks can interleave in any +/// order and still leave exactly one row — the newest — because ids come +/// from the process-wide monotonic generator, so "older" is `id <` the row +/// just written and the loser's row is always below the winner's. +pub async fn replace_for_note( + db: &Database, + note: &CourseNoteId, + course: &CourseId, + sources: Vec, + payload: Value, +) -> Result { + let created = create(db, note, course, sources, payload).await?; + db.query("DELETE rag_output WHERE course_note = $note AND id < $new") + .bind(("note", note.record())) + .bind(("new", created.id.record())) + .await? + .check()?; + Ok(created) +} + +/// Cascade: every output built from `file`. Runs on a file delete even +/// with no AI service connected, so a stale output cannot survive its +/// source. +pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { + db.query("DELETE rag_output WHERE sources CONTAINS $file") + .bind(("file", file.record())) + .await? + .check()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; + use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; + use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; + use serde_json::json; + + async fn note_of(db: &Database, title: &str) -> CourseNote { + let creator = crate::domain::user::UserId::generate(); + let course = crate::db::course::create( + db, + &creator, + CourseTitle::try_new("c").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::try_new("course").unwrap(), + None, + None, + ) + .await + .unwrap(); + CourseNote::create( + course.get_id(), + &creator, + CourseNoteTitle::try_new(title).unwrap(), + CourseNoteContent::try_new("body").unwrap(), + db, + ) + .await + .unwrap() + } + + async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId { + CourseNoteFile::new( + note, + FileName::try_new("plan.pdf").unwrap(), + FileContentType::try_new("application/pdf").unwrap(), + 3, + ) + .insert(db) + .await + .unwrap() + .get_id() + .clone() + } + + /// Replace converges on one row — the newest — even when an earlier + /// interleaving already left two rows behind for the note. + #[tokio::test] + async fn replace_keeps_only_the_newest_output() { + let db = crate::database::init_mem().await.unwrap(); + let note = note_of(&db, "a").await; + let stale = create( + &db, + note.get_id(), + note.get_course(), + Vec::new(), + json!({ "n": 1 }), + ) + .await + .unwrap(); + // The race this fixes: a second row for the same note. + create( + &db, + note.get_id(), + note.get_course(), + Vec::new(), + json!({ "n": 2 }), + ) + .await + .unwrap(); + + let fresh = replace_for_note( + &db, + note.get_id(), + note.get_course(), + Vec::new(), + json!({ "n": 3 }), + ) + .await + .unwrap(); + + let rows = list_for(&db, note.get_id(), None, 0).await.unwrap().0; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get_id(), fresh.get_id()); + assert!(fresh.get_id().key() > stale.get_id().key()); + } + + /// The payload survives the round trip unread, and both cascades take only + /// what they are aimed at. + #[tokio::test] + async fn outputs_round_trip_and_cascade() { + let db = crate::database::init_mem().await.unwrap(); + let note = note_of(&db, "a").await; + let other = note_of(&db, "b").await; + let file = file_on(&db, note.get_id()).await; + + let stored = create( + &db, + note.get_id(), + note.get_course(), + vec![file.clone()], + json!({ "summary": "x", "chunks": [{ "text": "y" }] }), + ) + .await + .unwrap(); + let roundtrip = read(&db, stored.get_id()).await.unwrap().unwrap(); + assert_eq!(roundtrip.get_payload()["summary"], "x"); + assert_eq!(roundtrip.get_payload()["chunks"][0]["text"], "y"); + assert_eq!(roundtrip.get_sources(), std::slice::from_ref(&file)); + assert_eq!(roundtrip.get_course(), note.get_course()); + let untouched = create( + &db, + other.get_id(), + other.get_course(), + Vec::new(), + json!({ "summary": "z" }), + ) + .await + .unwrap(); + + let listed = + async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0.len(); + assert_eq!(listed(note.get_id()).await, 1); + + // Losing a source drops the output that cited it, and nothing else. + delete_with_source(&db, &file).await.unwrap(); + assert_eq!(listed(note.get_id()).await, 0); + assert_eq!(listed(other.get_id()).await, 1); + + // Cascading a note with no outputs left is still a success. + delete_for_note(&db, note.get_id()).await.unwrap(); + delete_for_note(&db, other.get_id()).await.unwrap(); + assert!(read(&db, untouched.get_id()).await.unwrap().is_none()); + } +} diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index fd14f85..fdad891 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -1,12 +1,13 @@ -//! One turn of a chatbot thread. Both sides are persisted: the user's prompt -//! lands `complete`, and the assistant's row is written `pending` *before* the -//! AI call so a reload never loses an answer in flight. The task that owns the -//! bridge round trip then flips it to `complete` (with the text) or `failed` -//! (with a code), and the boot sweep in `database.rs` fails whatever a process -//! death left behind past the staleness window. +//! One turn of a chatbot thread — the row shape and its read-time +//! presentation. `user_id` is duplicated from the thread onto every message +//! so an ownership check is one read, with no join. //! -//! `user_id` is duplicated from the thread onto every message so an -//! ownership check is one read, with no join. +//! Persistence lives in [`crate::db::chatbot_message`]: the assistant's row +//! is written `pending` *before* the AI call and flipped to `complete` or +//! `failed` by the task that owns the bridge round trip, and a read +//! projects a long-stale `pending` as failed without writing +//! ([`ChatbotMessage::projected`]) — the durable repair for a dead process +//! happens once, at boot, in `database.rs`. use std::sync::{LazyLock, Mutex}; @@ -14,21 +15,19 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::{Generator, Ulid}; use crate::constant::{ - CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN, - STALE_ERROR_CODE, + CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, }; -use crate::database::Database; -use crate::domain::chatbot_thread::{ChatbotThreadId, touch_and_write}; -use crate::db::page::PagedList; +use crate::domain::chatbot_thread::ChatbotThreadId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_required; /// Mints message ids in write order. Unlike `Ulid::new()`, whose 80 random /// low bits sort arbitrarily among ids minted in the same millisecond, this /// increments the previous id — so the `id` tie-break in the `ORDER BY` of -/// [`ChatbotMessage::list_for_thread`] / [`ChatbotMessage::list_tail`] is the +/// [`list_for_thread`](crate::db::chatbot_message::list_for_thread) / +/// [`list_tail`](crate::db::chatbot_message::list_tail) is the /// order the rows were written. The user prompt and the assistant row one POST /// writes back-to-back routinely share a millisecond, and a random tie-break /// there renders the answer *above* its own question — and hands the AI @@ -112,7 +111,7 @@ impl MessageStatus { /// One turn's text. The hard ceiling only — the school-adjustable /// `max_chatbot_message_len` is the web layer's to enforce, below this. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ChatContent(String); +pub struct ChatContent(pub(crate) String); impl ChatContent { pub fn try_new(value: &str) -> Result { @@ -121,8 +120,9 @@ impl ChatContent { } /// The placeholder a `pending` assistant row carries until its answer - /// lands. Private: every content that comes from outside is non-empty. - fn empty() -> Self { + /// lands. Crate-visible: only the persistence layer writes it, for the + /// reserved row before the answer exists. + pub(crate) fn empty() -> Self { Self(String::new()) } @@ -133,19 +133,19 @@ impl ChatContent { #[derive(Debug, Clone, SurrealValue)] pub struct ChatbotMessage { - id: ChatbotMessageId, - thread_id: ChatbotThreadId, - user_id: UserId, - role: MessageRole, - content: ChatContent, - status: MessageStatus, + pub(crate) id: ChatbotMessageId, + pub(crate) thread_id: ChatbotThreadId, + pub(crate) user_id: UserId, + pub(crate) role: MessageRole, + pub(crate) content: ChatContent, + pub(crate) status: MessageStatus, /// Whether the stored `content` is a clipped version of what the AI /// service actually answered. Only an assistant turn can ever set it: a /// user prompt over the cap is refused (400), never trimmed. - truncated: bool, - error_code: Option, - created_at: Timestamp, - completed_at: Option, + pub(crate) truncated: bool, + pub(crate) error_code: Option, + pub(crate) created_at: Timestamp, + pub(crate) completed_at: Option, } impl ChatbotMessage { @@ -198,7 +198,7 @@ impl ChatbotMessage { /// reply that is still coming — and the durable repair for the real cause /// (a dead process) already happens once, at boot. The stored row stays /// truthful; only the answer handed to the caller is projected. - fn projected(mut self) -> Self { + pub(crate) fn projected(mut self) -> Self { let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000; if self.status == MessageStatus::Pending && Timestamp::now().as_millis() > stale_at { self.status = MessageStatus::Failed; @@ -206,249 +206,11 @@ impl ChatbotMessage { } self } - - /// Write one turn *through its thread's own row* ([`touch_and_write`]), - /// which is what makes the thread's existence something this write writes - /// rather than something the caller read and then trusted: a - /// [`ChatbotThread::delete`](crate::domain::chatbot_thread::ChatbotThread::delete) - /// racing it touches the very key this transaction moves, so the two cannot - /// both commit and no turn is left under a thread that is gone. It also - /// carries the thread's activity stamp, so a turn and its `updated_at` land - /// together. - /// - /// [`AppError::NotFound`] = the thread is gone, and nothing was written. - async fn insert(message: ChatbotMessage, db: &Database) -> Result { - let thread = message.thread_id.clone(); - let id = message.id.record(); - touch_and_write( - &thread, - "CREATE $id CONTENT $row RETURN AFTER", - vec![ - ("id".into(), id.into_value()), - ("row".into(), message.into_value()), - ], - db, - ) - .await? - .ok_or_else(|| AppError::Internal("failed to create chat message".into())) - } - - /// Append the user's prompt. Nothing is awaited for it, so it is born - /// complete. - pub async fn append_user( - thread: &ChatbotThreadId, - user: &UserId, - content: ChatContent, - db: &Database, - ) -> Result { - let now = Timestamp::now(); - Self::insert( - ChatbotMessage { - id: ChatbotMessageId::generate(), - thread_id: thread.clone(), - user_id: user.clone(), - role: MessageRole::User, - content, - status: MessageStatus::Complete, - truncated: false, - error_code: None, - created_at: now, - completed_at: Some(now), - }, - db, - ) - .await - } - - /// Reserve the assistant's answer *before* the AI call: the row exists, - /// empty and `pending`, so a reload finds the turn and can wait on it. - pub async fn append_pending_assistant( - thread: &ChatbotThreadId, - user: &UserId, - db: &Database, - ) -> Result { - Self::insert( - ChatbotMessage { - id: ChatbotMessageId::generate(), - thread_id: thread.clone(), - user_id: user.clone(), - role: MessageRole::Assistant, - content: ChatContent::empty(), - status: MessageStatus::Pending, - truncated: false, - error_code: None, - created_at: Timestamp::now(), - completed_at: None, - }, - db, - ) - .await - } - - /// The whole thread, oldest first — the order both the UI and the AI - /// history payload read in. - pub async fn list_for_thread( - thread: &ChatbotThreadId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - let (rows, total) = PagedList::new( - "chatbot_message WHERE thread_id = $conv", - "ORDER BY created_at ASC, id ASC", - ) - .bind("conv", thread.record()) - .run::(limit, offset, db) - .await?; - Ok(( - rows.into_iter().map(ChatbotMessage::projected).collect(), - total, - )) - } - - /// The last `limit` turns, still oldest-first — the tail replayed to the - /// AI service as context. Taken newest-first in the database (so the - /// `LIMIT` keeps the *recent* end) and flipped back here. - pub async fn list_tail( - thread: &ChatbotThreadId, - limit: usize, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM chatbot_message WHERE thread_id = $conv \ - ORDER BY created_at DESC, id DESC LIMIT $limit", - ) - .bind(("conv", thread.record())) - .bind(("limit", limit as i64)) - .await? - .check()?; - let mut messages: Vec = result - .take::>(0)? - .into_iter() - .map(ChatbotMessage::projected) - .collect(); - messages.reverse(); - Ok(messages) - } - - /// The last `limit` *settled* turns that carry text, still oldest-first — - /// the tail replayed to the AI service as context. The filter runs in the - /// query, not after it: a `LIMIT` over the raw tail hands back fewer usable - /// rows the moment a run of answers fails, silently shrinking the context - /// instead of reaching further back. No projection is applied — it only - /// ever rewrites a `pending` row, and none is selected here. - pub async fn list_settled_tail( - thread: &ChatbotThreadId, - limit: usize, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM chatbot_message WHERE thread_id = $conv \ - AND status = 'complete' AND content != '' \ - ORDER BY created_at DESC, id DESC LIMIT $limit", - ) - .bind(("conv", thread.record())) - .bind(("limit", limit as i64)) - .await? - .check()?; - let mut messages: Vec = result.take(0)?; - messages.reverse(); - Ok(messages) - } - - /// The user turn a reserved answer belongs to, by *identity*: the prompt - /// row of the very POST that reserved it, whose id the answering task - /// carries. - /// - /// Never derived from write order. Two POSTs on one thread interleave - /// across the two creates — the rows land `userA, userB, asstA, asstB` — - /// so "the newest user row written before this answer" resolves *both* - /// answers to prompt B, and prompt A is never answered. - pub async fn prompt_of( - id: &ChatbotMessageId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Read one turn only if `user` owns it — the poll loop's read. - pub async fn read_for( - id: &ChatbotMessageId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let message: Option = db.select(id.record()).await?; - Ok(message - .filter(|message| &message.user_id == user) - .map(ChatbotMessage::projected)) - } - - /// Land the answer, recording whether it had to be clipped to fit the - /// school's cap. Field-scoped and gated on `status = 'pending'` in the - /// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a - /// timeout) already failed, and two answers can't both apply. - pub async fn complete( - id: &ChatbotMessageId, - text: ChatContent, - truncated: bool, - db: &Database, - ) -> Result { - Self::settle(id, Some(text), truncated, None, db).await - } - - /// Mark the answer failed with a short code (`unavailable`, the service's - /// own error code, …). Same pending gate as [`ChatbotMessage::complete`]. - pub async fn fail( - id: &ChatbotMessageId, - error_code: &str, - db: &Database, - ) -> Result { - // A failed turn has no text, so there is nothing that could be clipped. - Self::settle(id, None, false, Some(error_code), db).await - } - - async fn settle( - id: &ChatbotMessageId, - text: Option, - truncated: bool, - error_code: Option<&str>, - db: &Database, - ) -> Result { - let status = if text.is_some() { - MessageStatus::Complete - } else { - MessageStatus::Failed - }; - let mut result = db - .query( - "UPDATE $id SET content = $content, status = $status, truncated = $truncated, \ - error_code = $code, completed_at = $now WHERE status = 'pending' RETURN AFTER", - ) - .bind(("id", id.record())) - .bind(("content", text.map(|t| t.0).unwrap_or_default())) - .bind(("status", status.as_str().to_string())) - .bind(("truncated", truncated)) - .bind(( - "code", - error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::()), - )) - .bind(("now", Timestamp::now().as_millis())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } } #[cfg(test)] mod tests { use super::*; - use surrealdb::types::Value; #[tokio::test] async fn content_is_required_and_capped() { @@ -463,7 +225,10 @@ mod tests { // write, and a junk string must read back as an error, not a panic. for role in [MessageRole::User, MessageRole::Assistant] { let value = role.into_value(); - assert_eq!(value, Value::String(role.as_str().to_string())); + assert_eq!( + value, + surrealdb::types::Value::String(role.as_str().to_string()) + ); assert_eq!(MessageRole::from_value(value).unwrap(), role); } for status in [ @@ -472,55 +237,16 @@ mod tests { MessageStatus::Failed, ] { let value = status.into_value(); - assert_eq!(value, Value::String(status.as_str().to_string())); + assert_eq!( + value, + surrealdb::types::Value::String(status.as_str().to_string()) + ); assert_eq!(MessageStatus::from_value(value).unwrap(), status); } - assert!(MessageRole::from_value(Value::String("system".into())).is_err()); - assert!(MessageStatus::from_value(Value::String("queued".into())).is_err()); - } - - #[tokio::test] - async fn a_turns_two_rows_never_sort_inverted() { - // Both rows of a turn land in the same millisecond routinely, so the - // `id` tie-break decides the thread's order. With a random ULID this - // inverted a fifth of the pairs; here every pair must read back - // question-then-answer, from both read paths. - let db = crate::database::init_mem().await.unwrap(); - // A real thread row: every turn is written through it, so a turn with - // no thread is refused (see [`ChatbotMessage::insert`]). - db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0") - .await - .unwrap() - .check() - .unwrap(); - let thread = ChatbotThreadId::from_key("c"); - let user = UserId::from_key("u"); - const TURNS: usize = 200; - - for turn in 0..TURNS { - let content = ChatContent::try_new(&format!("soru {turn}")).unwrap(); - ChatbotMessage::append_user(&thread, &user, content, &db) - .await - .unwrap(); - ChatbotMessage::append_pending_assistant(&thread, &user, &db) - .await - .unwrap(); - } - - let (whole, _) = ChatbotMessage::list_for_thread(&thread, None, 0, &db) - .await - .unwrap(); - let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db) - .await - .unwrap(); - for messages in [&whole, &tail] { - assert_eq!(messages.len(), TURNS * 2); - for (turn, pair) in messages.chunks(2).enumerate() { - assert_eq!(pair[0].get_role(), MessageRole::User, "turn {turn}"); - assert_eq!(pair[0].get_content().as_str(), format!("soru {turn}")); - assert_eq!(pair[1].get_role(), MessageRole::Assistant, "turn {turn}"); - } - } + assert!(MessageRole::from_value(surrealdb::types::Value::String("system".into())).is_err()); + assert!( + MessageStatus::from_value(surrealdb::types::Value::String("queued".into())).is_err() + ); } #[tokio::test] diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index 7cbc018..0ecbb59 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -1,21 +1,16 @@ //! A chatbot thread. It only groups turns and carries the ordering key the //! list view sorts on: `updated_at` moves on every new turn, so a user's //! threads list newest-activity-first. The turns themselves live in -//! [`crate::domain::chatbot_message`], and deleting a thread cascades them. +//! [`crate::db::chatbot_message`], and deleting a thread cascades them; the +//! threads' own persistence lives in [`crate::db::chatbot_thread`]. -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, DEFAULT_MAX_CHATBOT_THREADS, - MAX_CHATBOT_THREAD_TITLE_LEN, SETTINGS_KEY, SETTINGS_TABLE, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; -use crate::db::page::PagedList; +use crate::constant::{CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN}; use crate::domain::monotonic_id::next_ulid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_required; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -45,82 +40,10 @@ impl ChatbotThreadId { } } } - -/// Move the thread's `updated_at` **and** run `statement` — a write to a turn -/// hanging off that thread — in one transaction, handing back the row it -/// returned. [`AppError::NotFound`] means the thread is gone and `statement` -/// wrote nothing. -/// -/// The bump is what ties a turn's fate to its thread, and reading the thread -/// first does not: [`ChatbotThread::delete`] sweeps `chatbot_message` and drops -/// the thread in one transaction, so a create landing after that sweep but -/// before its commit reads a thread that is still there (uncommitted) while the -/// sweep ran on a snapshot predating the new row — both commit, and the turn -/// outlives the thread it was deleted with, readable and deletable by nothing. -/// Reads do not conflict; only a write that *moves* a value on a key the delete -/// also writes does. That is the shape -/// [`bump_menu_and_write`](crate::domain::menu::bump_menu_and_write) and -/// [`ExamAnswer::save`](crate::domain::exam_answer::ExamAnswer::save) already -/// use, and the sweep's ordering inside the delete stops mattering once it is -/// in place. -/// -/// `updated_at` is the value moved, and it doubles as the stamp the thread list -/// sorts on — this *is* the activity touch the send path used to issue -/// afterwards as a separate, best-effort query whose failure was only logged. -/// It is written strictly upwards rather than to `$now`: an `UPDATE` that -/// leaves the document unchanged is elided and never reaches the store's write -/// set, a turn's two rows are routinely written inside one millisecond, and a -/// write that does not happen collides with nothing. The stamp can therefore -/// sit a few milliseconds ahead of the clock, which an ordering key does not -/// care about. -/// -/// Admissible for [`transaction_with_retry`] as long as `statement` is: the -/// `UPDATE`, the `IF`/`THROW` and the `RETURN` can never answer "already -/// exists", and neither can a `CREATE` on a freshly minted ULID on a table with -/// no `UNIQUE` index — no rival can have aimed at it, and a lost round wrote -/// nothing, so re-sending it is the recovery. -pub(crate) async fn touch_and_write( - thread: &ChatbotThreadId, - statement: &str, - mut bindings: Vec<(String, Value)>, - db: &Database, -) -> Result, AppError> { - bindings.push(("conv".into(), thread.record().into_value())); - bindings.push(("now".into(), Timestamp::now().as_millis().into_value())); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $touched = (UPDATE $conv SET updated_at = \ - math::max([$now, updated_at + 1]) RETURN VALUE id); - IF array::len($touched) = 0 {{ THROW 'no_thread' }}; - LET $row = ({statement}); - RETURN $row; - COMMIT TRANSACTION;" - ), - &bindings, - &["no_thread"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_thread")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. - Ok(result.take::>(4)?.into_iter().next()) -} - /// A user-chosen thread name. Required-and-bounded here; "untitled" is /// `Option` on the row. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] -pub struct ChatbotThreadTitle(String); +pub struct ChatbotThreadTitle(pub(crate) String); impl ChatbotThreadTitle { pub fn try_new(value: &str) -> Result { @@ -135,11 +58,11 @@ impl ChatbotThreadTitle { #[derive(Debug, Clone, SurrealValue)] pub struct ChatbotThread { - id: ChatbotThreadId, - user_id: UserId, - title: Option, - created_at: Timestamp, - updated_at: Timestamp, + pub(crate) id: ChatbotThreadId, + pub(crate) user_id: UserId, + pub(crate) title: Option, + pub(crate) created_at: Timestamp, + pub(crate) updated_at: Timestamp, } impl ChatbotThread { @@ -162,454 +85,11 @@ impl ChatbotThread { pub fn get_updated_at(&self) -> Timestamp { self.updated_at } - - /// Start a thread unless `user` is already at the school's - /// `max_chatbot_threads`. The slot is taken on the user row in the same - /// transaction as the thread ([`cap::claim_live_and_create`]) — an atomic - /// single-record write, so two requests racing the same user's last slot - /// cannot both win and the counter can never count a row that did not - /// commit. - /// - /// The cap is the one *live* on the settings singleton, sub-queried inside - /// that same conditional write rather than bound as a number: this cap does - /// not live on the parent row (the seat is on the user, the limit is the - /// school's), and a snapshot of it admits every request already in flight - /// when a `PATCH /settings` lowers it. The subquery costs one extra record - /// read per claim on a path that already reads the row it writes. - /// `DEFAULT_MAX_CHATBOT_THREADS` is the fallback the settings row's own - /// absent column means — no row, or a school that never set the knob. - pub async fn create_capped( - user: &UserId, - title: Option, - db: &Database, - ) -> Result { - let now = Timestamp::now(); - let thread = ChatbotThread { - id: ChatbotThreadId::generate(), - user_id: user.clone(), - title, - created_at: now, - updated_at: now, - }; - match cap::claim_live_and_create( - &user.record(), - CHATBOT_THREAD_COUNT_FIELD, - &format!( - "(SELECT VALUE max_chatbot_threads FROM ONLY {SETTINGS_TABLE}:{SETTINGS_KEY}) ?? $num" - ), - DEFAULT_MAX_CHATBOT_THREADS, - // No holder claim: the parent row *is* the user's, so this write - // already lands on the key a role change writes. - None, - (&thread.id.record(), &thread), - db, - ) - .await? - { - cap::Claimed::Made(saved) => Ok(saved), - // Full, or the user's row is gone — the conditional write matches - // nothing either way. - cap::Claimed::Full => Err(AppError::Conflict( - "you have reached the school's limit on saved threads — delete one first", - )), - // The id is a freshly minted ULID on a table with no UNIQUE index, - // so no rival can have aimed at it. - cap::Claimed::Duplicate => Err(AppError::Internal("thread id collided".into())), - } - } - - /// A user's threads, most recently active first — the sort the - /// `chatbot_thread_user_updated` index exists for. - pub async fn list_for_user( - user: &UserId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "chatbot_thread WHERE user_id = $usr", - "ORDER BY updated_at DESC, id DESC", - ) - .bind("usr", user.record()) - .run(limit, offset, db) - .await - } - - /// How many threads `user` keeps — the `max_chatbot_threads` cap check. - pub async fn count_for_user(user: &UserId, db: &Database) -> Result { - let mut result = db - .query("SELECT VALUE count() FROM chatbot_thread WHERE user_id = $usr GROUP ALL") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result - .take::>(0)? - .first() - .copied() - .unwrap_or_default() - .max(0) as usize) - } - - /// Read a thread only if `user` owns it — a foreign id reads as absent, so - /// the web layer answers 404 rather than leaking that it exists. - pub async fn read_for( - id: &ChatbotThreadId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let thread: Option = db.select(id.record()).await?; - Ok(thread.filter(|thread| &thread.user_id == user)) - } - - // Stamping new activity is not a call of its own: it is the bump inside - // [`touch_and_write`], which every turn already rides, so a stamp can no - // longer be lost (it used to be a best-effort query after the two creates, - // whose failure was a `warn!`) and no turn can be written without it. - - /// Rename the thread (`None` clears the name back to untitled), stamping - /// the edit as activity. Field-scoped for the same reason as - /// [`ChatbotThread::touch`]: a turn may be landing concurrently. - pub async fn rename( - &self, - title: Option, - db: &Database, - ) -> Result { - let mut result = db - .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER") - .bind(("id", self.id.record())) - .bind(("title", title.map(|title| title.0))) - .bind(("now", Timestamp::now().as_millis())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } - - /// Delete the thread and every turn in it — one transaction, so a crash - /// can't orphan messages under a vanished thread. The owner's slot comes - /// back in that same transaction, or the cap would ratchet shut. - /// - /// A turn, a rename and this delete all write the thread row (see - /// [`touch_and_write`]), so the store aborting one of them is ordinary - /// here — that collision is exactly what keeps a turn from outliving the - /// thread — and a lost round is re-sent rather than reported as the `500` - /// it used to be. Re-sending is sound: every statement is a `DELETE` or a - /// field-scoped `UPDATE`, none of which can ever answer "already exists" - /// (see [`transaction_with_retry`]). On the re-sent round the thread is - /// already gone, so the `RETURN` is empty and the caller gets the `404` - /// that is the truth. - pub async fn delete(self, db: &Database) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE chatbot_message WHERE thread_id = $conv; - LET $gone = (DELETE $conv RETURN BEFORE); - UPDATE $usr SET chatbot_thread_count = math::max([(chatbot_thread_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - &[ - ("conv".into(), self.id.record().into_value()), - ("usr".into(), self.user_id.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN - // is slot 4. - let deleted: Option = - result.take::>(4)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) - } } #[cfg(test)] mod tests { use super::*; - use crate::domain::settings::{Settings, SettingsParams}; - - /// The owner's counter and the threads it counts, both re-read out of the - /// store — never off a return value, which the in-memory engine forges - /// wins on (see [`cap`]). - async fn stored(db: &Database) -> (i64, usize) { - let mut result = db - .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u") - .query("SELECT VALUE id FROM chatbot_thread") - .await - .unwrap() - .check() - .unwrap(); - let counter = result.take::>(0).unwrap(); - let rows = result.take::>(1).unwrap(); - (counter[0], rows.len()) - } - - async fn a_user_capped_at(threads: i64) -> Database { - let db = crate::database::init_mem().await.unwrap(); - db.query("CREATE user:u SET username = 'u', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - crate::db::settings::save( - &db, - Settings::try_new(SettingsParams { - max_chatbot_threads: threads, - ..Settings::defaults().params() - }) - .unwrap(), - ) - .await - .unwrap(); - db - } - - /// The seat and the row commit together, so the counter the cap reads can - /// never disagree with the threads it counts — and a create refused at the - /// cap advances neither. - #[tokio::test] - async fn a_capped_create_moves_the_counter_with_the_row() { - let db = a_user_capped_at(1).await; - let user = UserId::from_key("u"); - - ChatbotThread::create_capped(&user, None, &db) - .await - .expect("first thread"); - assert_eq!(stored(&db).await, (1, 1)); - - let refused = ChatbotThread::create_capped(&user, None, &db).await; - assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap"); - assert_eq!( - stored(&db).await, - (1, 1), - "a refused create advances neither" - ); - } - - /// A turn is written *through* its thread's row, so a thread that is gone - /// takes the write with it — and one that is there is stamped by it. - /// The race this shape exists to close is the `#[ignore]`d test below; - /// this one pins the logic, which the in-memory engine can answer. - #[tokio::test] - async fn a_turn_writes_its_thread_and_dies_with_it() { - use crate::domain::chatbot_message::{ChatContent, ChatbotMessage}; - - let db = a_user_capped_at(2).await; - let user = UserId::from_key("u"); - let thread = ChatbotThread::create_capped(&user, None, &db) - .await - .expect("thread"); - let opened = thread.get_updated_at().as_millis(); - - let say = || ChatContent::try_new("selam").unwrap(); - ChatbotMessage::append_user(thread.get_id(), &user, say(), &db) - .await - .expect("append"); - let stamped = ChatbotThread::read_for(thread.get_id(), &user, &db) - .await - .expect("re-read") - .expect("still there") - .get_updated_at() - .as_millis(); - // Strictly upwards, never merely re-stamped: an `UPDATE` that leaves - // the row unchanged is elided, and both rows of a turn are routinely - // written inside one millisecond of the thread's own creation. - assert!(stamped > opened, "{stamped} !> {opened}"); - - let id = thread.get_id().clone(); - thread.delete(&db).await.expect("delete"); - let orphan = ChatbotMessage::append_user(&id, &user, say(), &db).await; - assert!( - matches!(orphan, Err(AppError::NotFound)), - "a turn on a deleted thread must be refused: {orphan:?}" - ); - assert_eq!( - ChatbotMessage::list_for_thread(&id, None, 0, &db) - .await - .expect("list") - .1, - 0, - "the refused turn wrote nothing" - ); - } - - /// The stamp moves **strictly upwards**, never to the clock — the property - /// the whole shape rests on, since an `UPDATE` that leaves the row - /// unchanged is elided, never reaches the store's write set, and so - /// collides with the racing delete not at all. - /// - /// The test above cannot see it: it compares one append against - /// `create_capped`, which costs a millisecond or so on its own, and a plain - /// `$now` clears that. Nor can a burst of appends — each is a transaction - /// of its own and takes about as long, so the clock has moved on by the - /// time the next one reads it. Timing cannot reach the window on demand. - /// - /// So the *state* the window produces is set up directly instead: a stamp - /// **ahead of the clock**, which is precisely what `math::max` leaves - /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a - /// contrived one. From there the two rules are told apart with no race at - /// all — upwards keeps climbing off the stored value, the clock drags the - /// stamp back down to itself. The lead is a second, far more than two - /// writes can burn, and the guard below fails loudly rather than vacuously - /// on a machine that manages to burn it. - #[tokio::test] - async fn a_stamp_ahead_of_the_clock_still_climbs() { - use crate::domain::chatbot_message::{ChatContent, ChatbotMessage}; - - const LEAD: i64 = 1_000; - - let db = a_user_capped_at(1).await; - let user = UserId::from_key("u"); - let thread = ChatbotThread::create_capped(&user, None, &db) - .await - .expect("thread"); - - let parked = Timestamp::now().as_millis() + LEAD; - db.query("UPDATE $id SET updated_at = $parked") - .bind(("id", thread.get_id().record())) - .bind(("parked", parked)) - .await - .unwrap() - .check() - .unwrap(); - - for _ in 0..2 { - ChatbotMessage::append_user( - thread.get_id(), - &user, - ChatContent::try_new("selam").unwrap(), - &db, - ) - .await - .expect("append"); - } - let stamped = ChatbotThread::read_for(thread.get_id(), &user, &db) - .await - .expect("re-read") - .expect("still there") - .get_updated_at() - .as_millis(); - - assert!( - Timestamp::now().as_millis() < parked, - "the clock caught the {LEAD}ms lead up during two appends, so this \ - probe proves nothing" - ); - assert_eq!( - stamped, - parked + 2, - "two appends off a stamp of {parked} must leave {}: a stamp that \ - follows the clock instead is one an unchanged-row UPDATE elides", - parked + 2 - ); - } - - /// No turn may survive the delete that swept its thread. An orphan is not - /// litter: nothing sweeps `chatbot_message` afterwards, and both - /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered - /// `200` with the text of a thread the user had deleted. - /// - /// The window is between [`ChatbotThread::delete`]'s sweep and its commit: - /// a create landing in there reads a thread that is still present - /// (uncommitted) while the sweep ran on a snapshot predating the new row, - /// so both commit. It is closed by making the create **write** the thread - /// row ([`touch_and_write`]) instead of reading it — the two transactions - /// then touch one key and the store refuses to commit both. - /// - /// The window is opened by the database itself rather than by a lucky - /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the - /// delete's own transaction, the instant the row goes, so the `SLEEP` lands - /// after the message sweep and before the commit every single time. - /// - /// Real server, and `#[ignore]`d for it: the subject is the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both writes and answers `Ok` to each, which would fail this - /// test on correct code (see [`crate::database::init_test_server`]). - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_turn_written_inside_a_delete_never_outlives_the_thread() { - use crate::domain::chatbot_message::{ChatContent, ChatbotMessage}; - - let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await; - db.query("CREATE user:u SET username = 'u', password_hash = 'x';") - .await - .unwrap() - .check() - .unwrap(); - // Hold the delete open for a full second after the thread row is gone, - // while its transaction still has to commit. - db.query( - "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let user = UserId::from_key("u"); - let (mut orphans, mut swept) = (0, 0); - for round in 0..4 { - let thread = ChatbotThread::create_capped(&user, None, &db) - .await - .expect("thread"); - let id = thread.get_id().clone(); - - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { thread.delete(&db).await }) - }; - // The turn starts inside the held window — the thread row is gone - // but uncommitted, which is exactly what a read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let turn = { - let (id, db, user) = (id.clone(), db.clone(), user.clone()); - tokio::spawn(async move { - ChatbotMessage::append_user( - &id, - &user, - ChatContent::try_new("selam").unwrap(), - &db, - ) - .await - .map(|_| ()) - }) - }; - let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap()); - // A 404 for the turn, or a NotFound for the delete, is a correct - // answer — the only defect is stored state. - assert!( - !matches!(turn, Err(AppError::Db(_))), - "round {round}: a raced turn must be answered, not 500: {turn:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if ChatbotThread::read_for(&id, &user, &db) - .await - .unwrap() - .is_none() - { - swept += 1; - orphans += ChatbotMessage::list_for_thread(&id, None, 0, &db) - .await - .unwrap() - .1; - } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the thread is still there"); - } - } - eprintln!("ChatbotThread::delete raced by a turn: {swept}/4 rounds deleted the thread"); - assert!( - swept > 0, - "no round ever deleted the thread, so the window was never reached" - ); - assert_eq!(orphans, 0, "a turn outlived its thread"); - } #[tokio::test] async fn title_is_required_and_bounded() { diff --git a/src/domain/rag_output.rs b/src/domain/rag_output.rs index b0356d3..248c99d 100644 --- a/src/domain/rag_output.rs +++ b/src/domain/rag_output.rs @@ -6,30 +6,30 @@ //! //! Derived data, so it is disposable: the note is the source of truth and a //! row here can be dropped and regenerated at any time. It therefore cascades -//! from both sides of what it was built from — [`Self::delete_for_note`] when -//! the note goes, [`Self::delete_with_source`] when one of the attachments it -//! was built from goes — so a stale output never outlives its input, even in a -//! deployment with no AI service connected. +//! from both sides of what it was built from — +//! [`delete_for_note`](crate::db::rag_output::delete_for_note) when the note +//! goes, [`delete_with_source`](crate::db::rag_output::delete_with_source) +//! when one of the attachments it was built from goes — so a stale output +//! never outlives its input, even in a deployment with no AI service +//! connected. Persistence lives in [`crate::db::rag_output`]. use serde_json::Value; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::RAG_OUTPUT_TABLE; -use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::course_note::CourseNoteId; use crate::domain::course_note_file::CourseNoteFileId; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct RagOutputId(RecordId); impl RagOutputId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// a note's outputs list `id DESC` (newest first, [`RagOutput::list_for`]). + /// a note's outputs list `id DESC` (newest first, + /// [`list_for`](crate::db::rag_output::list_for)). pub fn generate() -> Self { Self(RecordId::new(RAG_OUTPUT_TABLE, next_ulid().to_string())) } @@ -52,20 +52,20 @@ impl RagOutputId { #[derive(Debug, Clone, SurrealValue)] pub struct RagOutput { - id: RagOutputId, - course_note: CourseNoteId, + pub(crate) id: RagOutputId, + pub(crate) course_note: CourseNoteId, /// The note's course, denormalised so a course-wide read needs no join. - course: CourseId, + pub(crate) course: CourseId, /// The attachments the output was built from, as they stood at generation /// time. Deleting any one of them drops this row - /// ([`Self::delete_with_source`]) rather than leaving an output citing a - /// file that no longer exists. - sources: Vec, + /// ([`delete_with_source`](crate::db::rag_output::delete_with_source)) + /// rather than leaving an output citing a file that no longer exists. + pub(crate) sources: Vec, /// The service's answer, stored verbatim. Opaque to the backend — it is a /// service-owned shape, so this side neither validates nor interprets it, /// beyond it having to be a JSON **object** (the stored column is one). - payload: Value, - generated_at: Timestamp, + pub(crate) payload: Value, + pub(crate) generated_at: Timestamp, } impl RagOutput { @@ -92,250 +92,4 @@ impl RagOutput { pub fn get_generated_at(&self) -> Timestamp { self.generated_at } - - /// Store one service output against `note`. - pub async fn create( - note: &CourseNoteId, - course: &CourseId, - sources: Vec, - payload: Value, - db: &Database, - ) -> Result { - let row = RagOutput { - id: RagOutputId::generate(), - course_note: note.clone(), - course: course.clone(), - sources, - payload, - generated_at: Timestamp::now(), - }; - // whole-row-save-ok: create of a fresh ULID row built in place — there is no prior row to clobber - let created: Option = db.create(row.id.record()).content(row).await?; - created.ok_or_else(|| AppError::Internal("failed to create rag output".into())) - } - - pub async fn read(id: &RagOutputId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// A note's outputs, newest first. - pub async fn list_for( - note: &CourseNoteId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC") - .bind("note", note.record()) - .run(limit, offset, db) - .await - } - - pub async fn delete(id: &RagOutputId, db: &Database) -> Result { - let deleted: Option = db.delete(id.record()).await?; - deleted.ok_or(AppError::NotFound) - } - - /// Cascade: every output of `note`. Deleting none is a success — a note - /// no service ever indexed has nothing to drop. - pub async fn delete_for_note(note: &CourseNoteId, db: &Database) -> Result<(), AppError> { - db.query("DELETE rag_output WHERE course_note = $note") - .bind(("note", note.record())) - .await? - .check()?; - Ok(()) - } - - /// Newest-wins replace, without a lock: store `payload` first, then drop - /// this note's older rows. Two concurrent index tasks can interleave in any - /// order and still leave exactly one row — the newest — because ids come - /// from the process-wide monotonic generator, so "older" is `id <` the row - /// just written and the loser's row is always below the winner's. - pub async fn replace_for_note( - note: &CourseNoteId, - course: &CourseId, - sources: Vec, - payload: Value, - db: &Database, - ) -> Result { - let created = Self::create(note, course, sources, payload, db).await?; - db.query("DELETE rag_output WHERE course_note = $note AND id < $new") - .bind(("note", note.record())) - .bind(("new", created.id.record())) - .await? - .check()?; - Ok(created) - } - - /// Cascade: every output built from `file`. Runs on a file delete even - /// with no AI service connected, so a stale output cannot survive its - /// source. - pub async fn delete_with_source( - file: &CourseNoteFileId, - db: &Database, - ) -> Result<(), AppError> { - db.query("DELETE rag_output WHERE sources CONTAINS $file") - .bind(("file", file.record())) - .await? - .check()?; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; - use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; - use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; - use serde_json::json; - - async fn note_of(db: &Database, title: &str) -> CourseNote { - let creator = crate::domain::user::UserId::generate(); - let course = crate::db::course::create( - db, - &creator, - CourseTitle::try_new("c").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::try_new("course").unwrap(), - None, - None, - ) - .await - .unwrap(); - CourseNote::create( - course.get_id(), - &creator, - CourseNoteTitle::try_new(title).unwrap(), - CourseNoteContent::try_new("body").unwrap(), - db, - ) - .await - .unwrap() - } - - async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId { - CourseNoteFile::new( - note, - FileName::try_new("plan.pdf").unwrap(), - FileContentType::try_new("application/pdf").unwrap(), - 3, - ) - .insert(db) - .await - .unwrap() - .get_id() - .clone() - } - - /// Replace converges on one row — the newest — even when an earlier - /// interleaving already left two rows behind for the note. - #[tokio::test] - async fn replace_keeps_only_the_newest_output() { - let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await; - let stale = RagOutput::create( - note.get_id(), - note.get_course(), - Vec::new(), - json!({ "n": 1 }), - &db, - ) - .await - .unwrap(); - // The race this fixes: a second row for the same note. - RagOutput::create( - note.get_id(), - note.get_course(), - Vec::new(), - json!({ "n": 2 }), - &db, - ) - .await - .unwrap(); - - let fresh = RagOutput::replace_for_note( - note.get_id(), - note.get_course(), - Vec::new(), - json!({ "n": 3 }), - &db, - ) - .await - .unwrap(); - - let rows = RagOutput::list_for(note.get_id(), None, 0, &db) - .await - .unwrap() - .0; - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].get_id(), fresh.get_id()); - assert!(fresh.get_id().key() > stale.get_id().key()); - } - - /// The payload survives the round trip unread, and both cascades take only - /// what they are aimed at. - #[tokio::test] - async fn outputs_round_trip_and_cascade() { - let db = crate::database::init_mem().await.unwrap(); - let note = note_of(&db, "a").await; - let other = note_of(&db, "b").await; - let file = file_on(&db, note.get_id()).await; - - let stored = RagOutput::create( - note.get_id(), - note.get_course(), - vec![file.clone()], - json!({ "summary": "x", "chunks": [{ "text": "y" }] }), - &db, - ) - .await - .unwrap(); - let read = RagOutput::read(stored.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(read.get_payload()["summary"], "x"); - assert_eq!(read.get_payload()["chunks"][0]["text"], "y"); - assert_eq!(read.get_sources(), std::slice::from_ref(&file)); - assert_eq!(read.get_course(), note.get_course()); - - let untouched = RagOutput::create( - other.get_id(), - other.get_course(), - Vec::new(), - json!({ "summary": "z" }), - &db, - ) - .await - .unwrap(); - - let listed = async |note: &CourseNoteId| { - RagOutput::list_for(note, None, 0, &db) - .await - .unwrap() - .0 - .len() - }; - assert_eq!(listed(note.get_id()).await, 1); - - // Losing a source drops the output that cited it, and nothing else. - RagOutput::delete_with_source(&file, &db).await.unwrap(); - assert_eq!(listed(note.get_id()).await, 0); - assert_eq!(listed(other.get_id()).await, 1); - - // Cascading a note with no outputs left is still a success. - RagOutput::delete_for_note(note.get_id(), &db) - .await - .unwrap(); - RagOutput::delete_for_note(other.get_id(), &db) - .await - .unwrap(); - assert!( - RagOutput::read(untouched.get_id(), &db) - .await - .unwrap() - .is_none() - ); - } } diff --git a/src/service/chatbot_message.rs b/src/service/chatbot_message.rs new file mode 100644 index 0000000..4730aec --- /dev/null +++ b/src/service/chatbot_message.rs @@ -0,0 +1,97 @@ +//! Chatbot message workflows: the turns of a thread. Sending is +//! asynchronous by design — the send path writes the user's prompt plus a +//! `pending` assistant row and answers at once; the answering task settles +//! that row later with [`complete`] or [`fail`], and the read paths present +//! a long-stale `pending` as failed via the domain's read-time projection +//! (see [`ChatbotMessage::projected`]). The queries live in +//! [`crate::db::chatbot_message`]. + +use crate::database::Database; +use crate::db::chatbot_message; +use crate::domain::chatbot_message::{ChatContent, ChatbotMessage, ChatbotMessageId}; +use crate::domain::chatbot_thread::ChatbotThreadId; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Append the user's prompt. Nothing is awaited for it, so it is born +/// complete. +pub async fn append_user( + db: &Database, + thread: &ChatbotThreadId, + user: &UserId, + content: ChatContent, +) -> Result { + chatbot_message::append_user(db, thread, user, content).await +} + +/// Reserve the assistant's answer *before* the AI call: the row exists, +/// empty and `pending`, so a reload finds the turn and can wait on it. +pub async fn append_pending_assistant( + db: &Database, + thread: &ChatbotThreadId, + user: &UserId, +) -> Result { + chatbot_message::append_pending_assistant(db, thread, user).await +} + +/// The whole thread, oldest first — the order both the UI and the AI +/// history payload read in. +pub async fn list_for_thread( + db: &Database, + thread: &ChatbotThreadId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + chatbot_message::list_for_thread(db, thread, limit, offset).await +} + +/// The last `limit` *settled* turns that carry text, still oldest-first — +/// the tail replayed to the AI service as context. +pub async fn list_settled_tail( + db: &Database, + thread: &ChatbotThreadId, + limit: usize, +) -> Result, AppError> { + chatbot_message::list_settled_tail(db, thread, limit).await +} + +/// The user turn a reserved answer belongs to, by *identity*: the prompt +/// row of the very POST that reserved it, whose id the answering task +/// carries. +pub async fn prompt_of( + db: &Database, + id: &ChatbotMessageId, +) -> Result, AppError> { + chatbot_message::prompt_of(db, id).await +} + +/// Read one turn only if `user` owns it — the poll loop's read. +pub async fn read_for( + db: &Database, + id: &ChatbotMessageId, + user: &UserId, +) -> Result, AppError> { + chatbot_message::read_for(db, id, user).await +} + +/// Land the answer, recording whether it had to be clipped to fit the +/// school's cap. Gated on `status = 'pending'`, so a late reply can't +/// overwrite a row that was already failed. +pub async fn complete( + db: &Database, + id: &ChatbotMessageId, + text: ChatContent, + truncated: bool, +) -> Result { + chatbot_message::complete(db, id, text, truncated).await +} + +/// Mark the answer failed with a short code (`unavailable`, the service's +/// own error code, …). Same pending gate as [`complete`]. +pub async fn fail( + db: &Database, + id: &ChatbotMessageId, + error_code: &str, +) -> Result { + chatbot_message::fail(db, id, error_code).await +} diff --git a/src/service/chatbot_thread.rs b/src/service/chatbot_thread.rs new file mode 100644 index 0000000..fe2d097 --- /dev/null +++ b/src/service/chatbot_thread.rs @@ -0,0 +1,59 @@ +//! Chatbot thread workflows: the create, rename and delete paths the +//! chatbot surface drives, all scoped to the owning user — a foreign id +//! reads as absent. The queries live in [`crate::db::chatbot_thread`]. + +use crate::database::Database; +use crate::db::chatbot_thread; +use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle}; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Start a thread unless `user` is already at the school's +/// `max_chatbot_threads` (409 at the cap — the cap is storage protection, +/// not a usage quota). The cap check and the row write are one atomic +/// conditional write, so two requests racing the same user's last slot +/// cannot both win. +pub async fn create_capped( + db: &Database, + user: &UserId, + title: Option, +) -> Result { + chatbot_thread::create_capped(db, user, title).await +} + +/// The caller's own threads, most recently active first. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + chatbot_thread::list_for_user(db, user, limit, offset).await +} + +/// Read a thread only if `user` owns it — a foreign id reads as absent, so +/// the web layer answers 404 rather than leaking that it exists. +pub async fn read_for( + db: &Database, + id: &ChatbotThreadId, + user: &UserId, +) -> Result, AppError> { + chatbot_thread::read_for(db, id, user).await +} + +/// Rename the thread (`None` clears the name back to untitled), stamping +/// the edit as activity so the thread moves to the top of the list. +pub async fn rename( + db: &Database, + thread: &ChatbotThread, + title: Option, +) -> Result { + chatbot_thread::rename(db, thread, title).await +} + +/// Delete the thread and every turn in it — one transaction, so a crash +/// can't orphan messages under a vanished thread — and give the owner's +/// cap slot back in the same transaction. +pub async fn delete(db: &Database, thread: ChatbotThread) -> Result { + chatbot_thread::delete(db, thread).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index c10835d..cbecf12 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -5,6 +5,8 @@ pub mod appointment; pub mod appointment_slot; pub mod badge; pub mod builder; +pub mod chatbot_message; +pub mod chatbot_thread; pub mod class_blueprint; pub mod course; pub mod course_session; @@ -20,6 +22,7 @@ pub mod parent_link; pub mod payment_ledger; pub mod pomodoro; pub mod profile; +pub mod rag_output; pub mod registration; pub mod session; pub mod settings; diff --git a/src/service/rag_output.rs b/src/service/rag_output.rs new file mode 100644 index 0000000..2c09fe8 --- /dev/null +++ b/src/service/rag_output.rs @@ -0,0 +1,43 @@ +//! RAG-output workflows on the course-notes surface: list a note's outputs, +//! read and delete one, and cascade-drop every output of a note or of one +//! of its source files. The rows are derived data (the note is the source +//! of truth), so every path here is disposable by design. The queries live +//! in [`crate::db::rag_output`]. + +use crate::database::Database; +use crate::db::rag_output; +use crate::domain::course_note::CourseNoteId; +use crate::domain::course_note_file::CourseNoteFileId; +use crate::domain::rag_output::{RagOutput, RagOutputId}; +use crate::error::AppError; + +pub async fn read(db: &Database, id: &RagOutputId) -> Result, AppError> { + rag_output::read(db, id).await +} + +/// A note's outputs, newest first. +pub async fn list_for( + db: &Database, + note: &CourseNoteId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + rag_output::list_for(db, note, limit, offset).await +} + +pub async fn delete(db: &Database, id: &RagOutputId) -> Result { + rag_output::delete(db, id).await +} + +/// Cascade: every output of `note`. Deleting none is a success — a note +/// no service ever indexed has nothing to drop. +pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> { + rag_output::delete_for_note(db, note).await +} + +/// Cascade: every output built from `file`. Runs on a file delete even +/// with no AI service connected, so a stale output cannot survive its +/// source. +pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> { + rag_output::delete_with_source(db, file).await +} diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 8e7881a..9a3bba7 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -131,7 +131,7 @@ async fn create_thread( // The cap is checked and the row written as one critical section in the // domain: counting here and creating after would over-admit under // concurrency (the database does not serialize a count against inserts). - let thread = ChatbotThread::create_capped(user.get_id(), title, &st.db).await?; + let thread = service::chatbot_thread::create_capped(&st.db, user.get_id(), title).await?; Ok(( StatusCode::CREATED, Json(ChatbotThreadResponse::new(&thread)), @@ -159,7 +159,7 @@ async fn list_threads( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let (threads, total) = - ChatbotThread::list_for_user(user.get_id(), limit, offset, &st.db).await?; + service::chatbot_thread::list_for_user(&st.db, user.get_id(), limit, offset).await?; let items = threads.iter().map(ChatbotThreadResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -205,7 +205,7 @@ async fn rename_thread( value => Some(ChatbotThreadTitle::try_new(value)?), }; let thread = own_thread(&id, user.get_id(), &st.db).await?; - let renamed = thread.rename(title, &st.db).await?; + let renamed = service::chatbot_thread::rename(&st.db, &thread, title).await?; Ok(Json(ChatbotThreadResponse::new(&renamed))) } @@ -229,14 +229,14 @@ async fn delete_thread( Path(id): Path, ) -> Result { let thread = own_thread(&id, user.get_id(), &st.db).await?; - thread.delete(&st.db).await?; + service::chatbot_thread::delete(&st.db, thread).await?; Ok(StatusCode::NO_CONTENT) } /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable /// from a missing one. async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result { - ChatbotThread::read_for(&ChatbotThreadId::from_key(id), user, db) + service::chatbot_thread::read_for(db, &ChatbotThreadId::from_key(id), user) .await? .ok_or(AppError::NotFound) } @@ -341,7 +341,7 @@ async fn list_messages( let (limit, offset) = page.resolve()?; let thread = own_thread(&id, user.get_id(), &st.db).await?; let (messages, total) = - ChatbotMessage::list_for_thread(thread.get_id(), limit, offset, &st.db).await?; + service::chatbot_message::list_for_thread(&st.db, thread.get_id(), limit, offset).await?; let items = messages.iter().map(ChatbotMessageResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -422,9 +422,11 @@ async fn send_message( // creates therefore refuses the second one with a 404 — and the first is // swept by that same delete, so the turn leaves no half of itself behind. let prompt = - ChatbotMessage::append_user(thread.get_id(), user.get_id(), content, &st.db).await?; + service::chatbot_message::append_user(&st.db, thread.get_id(), user.get_id(), content) + .await?; let answer = - ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?; + service::chatbot_message::append_pending_assistant(&st.db, thread.get_id(), user.get_id()) + .await?; let message_id = answer.get_id().key().to_string(); // Never awaited inline: the bridge round trip can outlast the request @@ -502,13 +504,13 @@ async fn answer_turn( // This request's own question, read back by id — the text is already // stored, so carrying the id rather than the string keeps the prompt and // its answer paired however two POSTs on one thread interleave. - let prompt = match ChatbotMessage::prompt_of(&prompt_id, &db).await { + let prompt = match service::chatbot_message::prompt_of(&db, &prompt_id).await { Ok(Some(prompt)) => prompt, Ok(None) => { // The prompt row is gone — only reachable if the thread was deleted // out from under this task. There is nothing to ask, so settle. tracing::warn!("chat answer {} has no prompt to send", answer_id.key()); - let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await; + let _ = service::chatbot_message::fail(&db, &answer_id, "internal").await; return; } Err(err) => { @@ -516,7 +518,7 @@ async fn answer_turn( // used to reclaim an unsettled row is gone, so leaving it `pending` // means a spinner until the 300s stale horizon. Settle it here. tracing::warn!("could not read the prompt for {}: {err}", answer_id.key()); - let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await; + let _ = service::chatbot_message::fail(&db, &answer_id, "internal").await; return; } }; @@ -532,10 +534,12 @@ async fn answer_turn( ) .await { - Ok((text, truncated)) => ChatbotMessage::complete(&answer_id, text, truncated, &db).await, + Ok((text, truncated)) => { + service::chatbot_message::complete(&db, &answer_id, text, truncated).await + } Err(code) => { tracing::warn!("chat answer {} failed: {code}", answer_id.key()); - ChatbotMessage::fail(&answer_id, &code, &db).await + service::chatbot_message::fail(&db, &answer_id, &code).await } }; match settled { @@ -624,7 +628,8 @@ async fn history_for( // what "the last `chatbot_history_turns` settled turns" means. +2 so dropping // this turn's own two rows cannot shorten it either (only the user one can // match: the assistant row is still `pending`). - let tail = ChatbotMessage::list_settled_tail(thread, turns.saturating_add(2), db).await?; + let tail = + service::chatbot_message::list_settled_tail(db, thread, turns.saturating_add(2)).await?; let mut history: Vec = tail .iter() .filter(|message| !fresh.contains(message.get_id())) @@ -709,7 +714,7 @@ async fn own_message( db: &Database, ) -> Result { own_thread(thread, user, db).await?; - ChatbotMessage::read_for(&ChatbotMessageId::from_key(message), user, db) + service::chatbot_message::read_for(db, &ChatbotMessageId::from_key(message), user) .await? .filter(|message| message.get_thread_id().key() == thread) .ok_or(AppError::NotFound) @@ -769,7 +774,8 @@ async fn stream_message( _ = ticker.tick() => {} _ = tx.closed() => return, } - let message = match ChatbotMessage::read_for(&message_id, &user_id, &db).await { + let message = match service::chatbot_message::read_for(&db, &message_id, &user_id).await + { Ok(Some(message)) => message, // Deleted mid-stream (the thread went away) — say so and stop. Ok(None) => { @@ -907,33 +913,43 @@ mod tests { let say = |text: String| ChatContent::try_new(&text).unwrap(); for turn in 0..10 { - ChatbotMessage::append_user(&thread, &user, say(format!("soru {turn}")), &db) - .await - .unwrap(); - let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db) + service::chatbot_message::append_user(&db, &thread, &user, say(format!("soru {turn}"))) .await .unwrap(); - ChatbotMessage::complete(answer.get_id(), say(format!("cevap {turn}")), false, &db) + let answer = service::chatbot_message::append_pending_assistant(&db, &thread, &user) .await .unwrap(); + service::chatbot_message::complete( + &db, + answer.get_id(), + say(format!("cevap {turn}")), + false, + ) + .await + .unwrap(); } // Five turns in a row whose answer never landed. for turn in 0..5 { - ChatbotMessage::append_user(&thread, &user, say(format!("kayıp {turn}")), &db) - .await - .unwrap(); - let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db) + service::chatbot_message::append_user( + &db, + &thread, + &user, + say(format!("kayıp {turn}")), + ) + .await + .unwrap(); + let answer = service::chatbot_message::append_pending_assistant(&db, &thread, &user) .await .unwrap(); - ChatbotMessage::fail(answer.get_id(), "timed_out", &db) + service::chatbot_message::fail(&db, answer.get_id(), "timed_out") .await .unwrap(); } // And this turn's own two rows, which never belong in the history. - let prompt = ChatbotMessage::append_user(&thread, &user, say("yeni".into()), &db) + let prompt = service::chatbot_message::append_user(&db, &thread, &user, say("yeni".into())) .await .unwrap(); - let pending = ChatbotMessage::append_pending_assistant(&thread, &user, &db) + let pending = service::chatbot_message::append_pending_assistant(&db, &thread, &user) .await .unwrap(); let fresh = [prompt.get_id().clone(), pending.get_id().clone()]; diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index 163a6c9..48b2c9a 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -305,7 +305,7 @@ async fn delete_one( // disposable, so failing here leaves the note intact and the 500 truthful, // whereas dropping them after the note would strand every blob on an error // — and if the note delete then fails, the next change regenerates them. - RagOutput::delete_for_note(note.get_id(), &st.db).await?; + service::rag_output::delete_for_note(&st.db, note.get_id()).await?; // Rows go first (the note delete cascades them), blobs after: a crash in // between strands at worst an unreachable blob, never a row whose blob is // already gone. The files to unlink come from the delete itself, not a @@ -542,7 +542,7 @@ async fn delete_file( // stale index cannot outlive its source in a deployment with no AI service // at all, and a failure here leaves the file whole instead of stranding its // blob; the re-index rebuilds from what is left, if a service is connected. - RagOutput::delete_with_source(file.get_id(), &st.db).await?; + service::rag_output::delete_with_source(&st.db, file.get_id()).await?; let file = file.delete(&st.db).await?; remove_blob(&st.files_path, file.get_id().key()).await; spawn_index(&st, &tenant, note); @@ -612,7 +612,8 @@ async fn list_rag( "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's AI outputs", )); } - let (outputs, total) = RagOutput::list_for(note.get_id(), limit, offset, &st.db).await?; + let (outputs, total) = + service::rag_output::list_for(&st.db, note.get_id(), limit, offset).await?; let items = outputs.iter().map(RagOutputResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -651,10 +652,10 @@ async fn delete_rag( crate::service::course::require_open(&st.db, &course).await?; // Scoped to the note in the path, like `CourseNoteFile::read_for`: an // output of another note is a 404 here, never a cross-note delete. - let output = RagOutput::read(&RagOutputId::from_key(&output_id), &st.db) + let output = service::rag_output::read(&st.db, &RagOutputId::from_key(&output_id)) .await? .filter(|output| output.get_course_note() == note.get_id()) .ok_or(AppError::NotFound)?; - RagOutput::delete(output.get_id(), &st.db).await?; + service::rag_output::delete(&st.db, output.get_id()).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 5c88fee..879e273 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1722,7 +1722,7 @@ use hezarfen_backend::domain::rag_output::RagOutput; /// Every stored output of `note`, newest first. async fn outputs(db: &Database, note: &str) -> Vec { - RagOutput::list_for(&CourseNoteId::from_key(note), None, 0, db) + hezarfen_backend::db::rag_output::list_for(&db, &CourseNoteId::from_key(note), None, 0) .await .expect("list rag outputs") .0 diff --git a/tests/integration.rs b/tests/integration.rs index 9ab7dd2..69f97af 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -19,13 +19,11 @@ use hezarfen_backend::db::exam_attempt::any_for_exam; use hezarfen_backend::db::session; use hezarfen_backend::domain::board::{Board, BoardId}; use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId}; -use hezarfen_backend::domain::chatbot_message::ChatbotMessage; use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId; use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::course_note::CourseNoteId; use hezarfen_backend::domain::course_note_file::CourseNoteFileId; use hezarfen_backend::domain::exam::ExamId; -use hezarfen_backend::domain::rag_output::RagOutput; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::{Password, User, UserId, Username}; use hezarfen_backend::module::ModuleSet; @@ -16976,12 +16974,14 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() { let thread = new_thread(&app, &ali).await; let me = send(&app, "GET", "/auth/me", Some(&ali), None).await; let user = UserId::from_key(me.body["id"].as_str().unwrap()); - let pending = - ChatbotMessage::append_pending_assistant(&ChatbotThreadId::from_key(&thread), &user, &db) - .await - .expect("reserve an assistant row"); + let pending = hezarfen_backend::db::chatbot_message::append_pending_assistant( + &db, + &ChatbotThreadId::from_key(&thread), + &user, + ) + .await + .expect("reserve an assistant row"); let mid = pending.get_id().key().to_string(); - // The witness is the runtime's task count, so it is read only once the // setup's short-lived database tasks have drained — otherwise one of those // finishing mid-measurement looks like the stream's own task. @@ -27280,22 +27280,22 @@ async fn course_note_rag_outputs_read_and_delete() { assert_eq!(up.status, StatusCode::CREATED, "{}", up.body); let file_id = id_of(&up.body); - let output = RagOutput::create( + let output = hezarfen_backend::db::rag_output::create( + &db, &CourseNoteId::from_key(¬e), &CourseId::from_key(&course), vec![CourseNoteFileId::from_key(&file_id)], json!({ "summary": "acids and bases" }), - &db, ) .await .unwrap(); let output_id = output.get_id().key().to_string(); - let sibling_output = RagOutput::create( + let sibling_output = hezarfen_backend::db::rag_output::create( + &db, &CourseNoteId::from_key(&sibling), &CourseId::from_key(&course), Vec::new(), json!({ "summary": "other" }), - &db, ) .await .unwrap(); @@ -27363,7 +27363,7 @@ async fn course_note_rag_outputs_read_and_delete() { .await; assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); assert!( - RagOutput::read(sibling_output.get_id(), &db) + hezarfen_backend::db::rag_output::read(&db, sibling_output.get_id()) .await .unwrap() .is_some() diff --git a/tests/persistence.rs b/tests/persistence.rs index e3b5174..b16e0b7 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -1065,8 +1065,8 @@ async fn attempt_history_survives_remigration() { /// second user reads neither the thread nor its messages. #[tokio::test] async fn chat_thread_delete_cascades_and_stays_owner_scoped() { - use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage, MessageStatus}; - use hezarfen_backend::domain::chatbot_thread::ChatbotThread; + use hezarfen_backend::db::{chatbot_message, chatbot_thread}; + use hezarfen_backend::domain::chatbot_message::{ChatContent, MessageStatus}; use hezarfen_backend::domain::user::UserId; let (app, db) = common::app_and_db().await; @@ -1075,28 +1075,28 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { let owner = UserId::from_key(&me_id(&app, &owner_cookie).await); let other = UserId::from_key(&me_id(&app, &other_cookie).await); - let thread = ChatbotThread::create_capped(&owner, None, &db) + let thread = chatbot_thread::create_capped(&db, &owner, None) .await .expect("create"); let id = thread.get_id().clone(); - let prompt = ChatbotMessage::append_user( + let prompt = chatbot_message::append_user( + &db, &id, &owner, ChatContent::try_new("selam").expect("content"), - &db, ) .await .expect("append user"); - let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db) + let reply = chatbot_message::append_pending_assistant(&db, &id, &owner) .await .expect("append assistant"); assert_eq!(reply.get_status(), MessageStatus::Pending); - let reply = ChatbotMessage::complete( + let reply = chatbot_message::complete( + &db, reply.get_id(), ChatContent::try_new("aleykum selam").expect("content"), false, - &db, ) .await .expect("complete"); @@ -1104,7 +1104,7 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { assert_eq!(reply.get_content().as_str(), "aleykum selam"); assert!(reply.get_completed_at().is_some()); assert_eq!( - ChatbotMessage::list_for_thread(&id, None, 0, &db) + chatbot_message::list_for_thread(&db, &id, None, 0) .await .expect("thread") .0 @@ -1114,39 +1114,39 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { // The other user sees nothing of it, by thread or by message. assert!( - ChatbotThread::read_for(&id, &other, &db) + chatbot_thread::read_for(&db, &id, &other) .await .expect("cross-user thread") .is_none() ); assert!( - ChatbotMessage::read_for(prompt.get_id(), &other, &db) + chatbot_message::read_for(&db, prompt.get_id(), &other) .await .expect("cross-user message") .is_none() ); assert_eq!( - ChatbotThread::count_for_user(&other, &db) + chatbot_thread::count_for_user(&db, &other) .await .expect("count"), 0 ); assert_eq!( - ChatbotThread::count_for_user(&owner, &db) + chatbot_thread::count_for_user(&db, &owner) .await .expect("count"), 1 ); - thread.delete(&db).await.expect("delete"); + chatbot_thread::delete(&db, thread).await.expect("delete"); assert!( - ChatbotThread::read_for(&id, &owner, &db) + chatbot_thread::read_for(&db, &id, &owner) .await .expect("deleted thread") .is_none() ); assert_eq!( - ChatbotThread::list_for_user(&owner, None, 0, &db) + chatbot_thread::list_for_user(&db, &owner, None, 0) .await .unwrap() .0 @@ -1172,8 +1172,8 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { /// read back as whole, which is exactly how they were shown at the time. #[tokio::test] async fn legacy_chat_turns_backfill_to_untruncated() { - use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage}; - use hezarfen_backend::domain::chatbot_thread::ChatbotThread; + use hezarfen_backend::db::{chatbot_message, chatbot_thread}; + use hezarfen_backend::domain::chatbot_message::ChatContent; use hezarfen_backend::domain::user::UserId; let (app, db) = common::app_and_db().await; @@ -1190,26 +1190,26 @@ async fn legacy_chat_turns_backfill_to_untruncated() { .unwrap(); let owner = UserId::from_key(&me_id(&app, &cookie).await); - let thread = ChatbotThread::create_capped(&owner, None, &db) + let thread = chatbot_thread::create_capped(&db, &owner, None) .await .expect("create"); let id = thread.get_id().clone(); - ChatbotMessage::append_user( + chatbot_message::append_user( + &db, &id, &owner, ChatContent::try_new("selam").expect("content"), - &db, ) .await .expect("append user"); - let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db) + let reply = chatbot_message::append_pending_assistant(&db, &id, &owner) .await .expect("append assistant"); - ChatbotMessage::complete( + chatbot_message::complete( + &db, reply.get_id(), ChatContent::try_new("aleykum selam").expect("content"), false, - &db, ) .await .expect("complete"); diff --git a/tests/regress_appointments.rs b/tests/regress_appointments.rs index e97fd4a..d3af8c6 100644 --- a/tests/regress_appointments.rs +++ b/tests/regress_appointments.rs @@ -15,9 +15,9 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, id_of, login, login_as, me_id, send}; +use hezarfen_backend::db::{chatbot_message, chatbot_thread}; use hezarfen_backend::domain::appointment::AppointmentId; -use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage}; -use hezarfen_backend::domain::chatbot_thread::ChatbotThread; +use hezarfen_backend::domain::chatbot_message::ChatContent; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use serde_json::json; @@ -271,29 +271,29 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() { let (app, db) = app_and_db().await; let cookie = login(&app, "veli").await; let owner = UserId::from_key(&me_id(&app, &cookie).await); - let thread = ChatbotThread::create_capped(&owner, None, &db) + let thread = chatbot_thread::create_capped(&db, &owner, None) .await .expect("create thread"); let id = thread.get_id().clone(); let say = |text: &str| ChatContent::try_new(text).expect("content"); // Exactly the order the interleave produces. - let prompt_a = ChatbotMessage::append_user(&id, &owner, say("soru A"), &db) + let prompt_a = chatbot_message::append_user(&db, &id, &owner, say("soru A")) .await .expect("prompt A"); - let prompt_b = ChatbotMessage::append_user(&id, &owner, say("soru B"), &db) + let prompt_b = chatbot_message::append_user(&db, &id, &owner, say("soru B")) .await .expect("prompt B"); - let answer_a = ChatbotMessage::append_pending_assistant(&id, &owner, &db) + let answer_a = chatbot_message::append_pending_assistant(&db, &id, &owner) .await .expect("answer A"); - let answer_b = ChatbotMessage::append_pending_assistant(&id, &owner, &db) + let answer_b = chatbot_message::append_pending_assistant(&db, &id, &owner) .await .expect("answer B"); // The interleave is real: by write order the newest user row before *both* // answers is B, which is what used to be handed to both of them. - let (stored, _) = ChatbotMessage::list_for_thread(&id, None, 0, &db) + let (stored, _) = chatbot_message::list_for_thread(&db, &id, None, 0) .await .expect("thread"); let texts: Vec<&str> = stored @@ -304,11 +304,11 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() { // Identity decides instead, so each answer keeps its own question — the id // the answering task carries is the prompt of its own POST. - let carried_a = ChatbotMessage::prompt_of(prompt_a.get_id(), &db) + let carried_a = chatbot_message::prompt_of(&db, prompt_a.get_id()) .await .expect("read A") .expect("prompt A exists"); - let carried_b = ChatbotMessage::prompt_of(prompt_b.get_id(), &db) + let carried_b = chatbot_message::prompt_of(&db, prompt_b.get_id()) .await .expect("read B") .expect("prompt B exists"); @@ -317,13 +317,13 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() { // And the answers each settle with the reply to their own question — the // stored state, not just what a lookup returned. - ChatbotMessage::complete(answer_a.get_id(), say("cevap A"), false, &db) + chatbot_message::complete(&db, answer_a.get_id(), say("cevap A"), false) .await .expect("settle A"); - ChatbotMessage::complete(answer_b.get_id(), say("cevap B"), false, &db) + chatbot_message::complete(&db, answer_b.get_id(), say("cevap B"), false) .await .expect("settle B"); - let (stored, _) = ChatbotMessage::list_for_thread(&id, None, 0, &db) + let (stored, _) = chatbot_message::list_for_thread(&db, &id, None, 0) .await .expect("thread"); let texts: Vec<&str> = stored