forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'layer-split/chatbot'

Browse files at this commit

f360d855e0fa29d53874f7d1df03e6910fdfa601Ahmet Kaan GümüşParent: 8c2ca534ddbd6e
# Conflicts:
#	src/db/mod.rs
#	src/service/mod.rs

18 changed files +1442 -1194

src/ai/rag.rsmodified+3 -3
@@ -18,7 +18,6 @@ use crate::constant::AI_RAG_INDEX_TIMEOUT_SECS;
18 use crate::database::Database;18 use crate::database::Database;
19 use crate::domain::course_note::CourseNote;19 use crate::domain::course_note::CourseNote;
20 use crate::domain::course_note_file::CourseNoteFile;20 use crate::domain::course_note_file::CourseNoteFile;
21-use crate::domain::rag_output::RagOutput;
22 use crate::module::Module;21 use crate::module::Module;
23 use crate::state::AppState;22 use crate::state::AppState;
24 use crate::web::tenant_state::ResolvedTenant;23 use crate::web::tenant_state::ResolvedTenant;
@@ -159,14 +158,15 @@ pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note:
159 /// Swap the note's outputs for the fresh one. Create-then-drop-older, not an158 /// Swap the note's outputs for the fresh one. Create-then-drop-older, not an
160 /// update: the previous output belongs to a previous version of the note, and159 /// update: the previous output belongs to a previous version of the note, and
161 /// this order is what makes two concurrent index tasks converge on one row160 /// this order is what makes two concurrent index tasks converge on one row
162-/// ([`RagOutput::replace_for_note`]).161+/// ([`replace_for_note`](crate::db::rag_output::replace_for_note)).
163 async fn replace(162 async fn replace(
164 db: &Database,163 db: &Database,
165 note: &CourseNote,164 note: &CourseNote,
166 sources: Vec<crate::domain::course_note_file::CourseNoteFileId>,165 sources: Vec<crate::domain::course_note_file::CourseNoteFileId>,
167 payload: serde_json::Value,166 payload: serde_json::Value,
168 ) -> Result<(), crate::error::AppError> {167 ) -> Result<(), crate::error::AppError> {
169- RagOutput::replace_for_note(note.get_id(), note.get_course(), sources, payload, db).await?;168+ crate::db::rag_output::replace_for_note(db, note.get_id(), note.get_course(), sources, payload)
169+ .await?;
170 Ok(())170 Ok(())
171 }171 }
172 172
src/db/chatbot_message.rsadded+302 -0
@@ -0,0 +1,302 @@
1+//! The `chatbot_message` table: the turns of a thread, both sides persisted.
2+//! The user's prompt lands `complete`, and the assistant's row is written
3+//! `pending` *before* the AI call so a reload never loses an answer in
4+//! flight. The task that owns the bridge round trip then flips it to
5+//! `complete` (with the text) or `failed` (with a code), and the boot sweep
6+//! in `database.rs` fails whatever a process death left behind past the
7+//! staleness window. Every turn is written *through* its thread's own row
8+//! ([`touch_and_write`]), so a turn can never outlive the thread it belongs
9+//! to. The row shape lives in [`crate::domain::chatbot_message`].
10+
11+use surrealdb::types::SurrealValue;
12+
13+use crate::constant::MAX_ERROR_CODE_LEN;
14+use crate::database::Database;
15+use crate::db::chatbot_thread::touch_and_write;
16+use crate::db::page::PagedList;
17+use crate::domain::chatbot_message::{
18+ ChatContent, ChatbotMessage, ChatbotMessageId, MessageStatus,
19+};
20+use crate::domain::chatbot_thread::ChatbotThreadId;
21+use crate::domain::timestamp::Timestamp;
22+use crate::domain::user::UserId;
23+use crate::error::AppError;
24+
25+/// Write one turn *through its thread's own row* ([`touch_and_write`]),
26+/// which is what makes the thread's existence something this write writes
27+/// rather than something the caller read and then trusted: a
28+/// [`delete`](crate::db::chatbot_thread::delete)
29+/// racing it touches the very key this transaction moves, so the two cannot
30+/// both commit and no turn is left under a thread that is gone. It also
31+/// carries the thread's activity stamp, so a turn and its `updated_at` land
32+/// together.
33+///
34+/// [`AppError::NotFound`] = the thread is gone, and nothing was written.
35+async fn insert(db: &Database, message: ChatbotMessage) -> Result<ChatbotMessage, AppError> {
36+ let thread = message.thread_id.clone();
37+ let id = message.id.record();
38+ touch_and_write(
39+ db,
40+ &thread,
41+ "CREATE $id CONTENT $row RETURN AFTER",
42+ vec![
43+ ("id".into(), id.into_value()),
44+ ("row".into(), message.into_value()),
45+ ],
46+ )
47+ .await?
48+ .ok_or_else(|| AppError::Internal("failed to create chat message".into()))
49+}
50+
51+/// Append the user's prompt. Nothing is awaited for it, so it is born
52+/// complete.
53+pub async fn append_user(
54+ db: &Database,
55+ thread: &ChatbotThreadId,
56+ user: &UserId,
57+ content: ChatContent,
58+) -> Result<ChatbotMessage, AppError> {
59+ let now = Timestamp::now();
60+ insert(
61+ db,
62+ ChatbotMessage {
63+ id: ChatbotMessageId::generate(),
64+ thread_id: thread.clone(),
65+ user_id: user.clone(),
66+ role: crate::domain::chatbot_message::MessageRole::User,
67+ content,
68+ status: MessageStatus::Complete,
69+ truncated: false,
70+ error_code: None,
71+ created_at: now,
72+ completed_at: Some(now),
73+ },
74+ )
75+ .await
76+}
77+
78+/// Reserve the assistant's answer *before* the AI call: the row exists,
79+/// empty and `pending`, so a reload finds the turn and can wait on it.
80+pub async fn append_pending_assistant(
81+ db: &Database,
82+ thread: &ChatbotThreadId,
83+ user: &UserId,
84+) -> Result<ChatbotMessage, AppError> {
85+ insert(
86+ db,
87+ ChatbotMessage {
88+ id: ChatbotMessageId::generate(),
89+ thread_id: thread.clone(),
90+ user_id: user.clone(),
91+ role: crate::domain::chatbot_message::MessageRole::Assistant,
92+ content: ChatContent::empty(),
93+ status: MessageStatus::Pending,
94+ truncated: false,
95+ error_code: None,
96+ created_at: Timestamp::now(),
97+ completed_at: None,
98+ },
99+ )
100+ .await
101+}
102+
103+/// The whole thread, oldest first — the order both the UI and the AI
104+/// history payload read in.
105+pub async fn list_for_thread(
106+ db: &Database,
107+ thread: &ChatbotThreadId,
108+ limit: Option<i64>,
109+ offset: i64,
110+) -> Result<(Vec<ChatbotMessage>, i64), AppError> {
111+ let (rows, total) = PagedList::new(
112+ "chatbot_message WHERE thread_id = $conv",
113+ "ORDER BY created_at ASC, id ASC",
114+ )
115+ .bind("conv", thread.record())
116+ .run::<ChatbotMessage>(limit, offset, db)
117+ .await?;
118+ Ok((
119+ rows.into_iter().map(ChatbotMessage::projected).collect(),
120+ total,
121+ ))
122+}
123+
124+/// The last `limit` turns, still oldest-first — the tail replayed to the
125+/// AI service as context. Taken newest-first in the database (so the
126+/// `LIMIT` keeps the *recent* end) and flipped back here.
127+pub async fn list_tail(
128+ db: &Database,
129+ thread: &ChatbotThreadId,
130+ limit: usize,
131+) -> Result<Vec<ChatbotMessage>, AppError> {
132+ let mut result = db
133+ .query(
134+ "SELECT * FROM chatbot_message WHERE thread_id = $conv \
135+ ORDER BY created_at DESC, id DESC LIMIT $limit",
136+ )
137+ .bind(("conv", thread.record()))
138+ .bind(("limit", limit as i64))
139+ .await?
140+ .check()?;
141+ let mut messages: Vec<ChatbotMessage> = result
142+ .take::<Vec<ChatbotMessage>>(0)?
143+ .into_iter()
144+ .map(ChatbotMessage::projected)
145+ .collect();
146+ messages.reverse();
147+ Ok(messages)
148+}
149+
150+/// The last `limit` *settled* turns that carry text, still oldest-first —
151+/// the tail replayed to the AI service as context. The filter runs in the
152+/// query, not after it: a `LIMIT` over the raw tail hands back fewer usable
153+/// rows the moment a run of answers fails, silently shrinking the context
154+/// instead of reaching further back. No projection is applied — it only
155+/// ever rewrites a `pending` row, and none is selected here.
156+pub async fn list_settled_tail(
157+ db: &Database,
158+ thread: &ChatbotThreadId,
159+ limit: usize,
160+) -> Result<Vec<ChatbotMessage>, AppError> {
161+ let mut result = db
162+ .query(
163+ "SELECT * FROM chatbot_message WHERE thread_id = $conv \
164+ AND status = 'complete' AND content != '' \
165+ ORDER BY created_at DESC, id DESC LIMIT $limit",
166+ )
167+ .bind(("conv", thread.record()))
168+ .bind(("limit", limit as i64))
169+ .await?
170+ .check()?;
171+ let mut messages: Vec<ChatbotMessage> = result.take(0)?;
172+ messages.reverse();
173+ Ok(messages)
174+}
175+
176+/// The user turn a reserved answer belongs to, by *identity*: the prompt
177+/// row of the very POST that reserved it, whose id the answering task
178+/// carries.
179+///
180+/// Never derived from write order. Two POSTs on one thread interleave
181+/// across the two creates — the rows land `userA, userB, asstA, asstB` —
182+/// so "the newest user row written before this answer" resolves *both*
183+/// answers to prompt B, and prompt A is never answered.
184+pub async fn prompt_of(
185+ db: &Database,
186+ id: &ChatbotMessageId,
187+) -> Result<Option<ChatbotMessage>, AppError> {
188+ Ok(db.select(id.record()).await?)
189+}
190+
191+/// Read one turn only if `user` owns it — the poll loop's read.
192+pub async fn read_for(
193+ db: &Database,
194+ id: &ChatbotMessageId,
195+ user: &UserId,
196+) -> Result<Option<ChatbotMessage>, AppError> {
197+ let message: Option<ChatbotMessage> = db.select(id.record()).await?;
198+ Ok(message
199+ .filter(|message| &message.user_id == user)
200+ .map(ChatbotMessage::projected))
201+}
202+
203+/// Land the answer, recording whether it had to be clipped to fit the
204+/// school's cap. Field-scoped and gated on `status = 'pending'` in the
205+/// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a
206+/// timeout) already failed, and two answers can't both apply.
207+pub async fn complete(
208+ db: &Database,
209+ id: &ChatbotMessageId,
210+ text: ChatContent,
211+ truncated: bool,
212+) -> Result<ChatbotMessage, AppError> {
213+ settle(db, id, Some(text), truncated, None).await
214+}
215+
216+/// Mark the answer failed with a short code (`unavailable`, the service's
217+/// own error code, …). Same pending gate as [`complete`].
218+pub async fn fail(
219+ db: &Database,
220+ id: &ChatbotMessageId,
221+ error_code: &str,
222+) -> Result<ChatbotMessage, AppError> {
223+ // A failed turn has no text, so there is nothing that could be clipped.
224+ settle(db, id, None, false, Some(error_code)).await
225+}
226+
227+async fn settle(
228+ db: &Database,
229+ id: &ChatbotMessageId,
230+ text: Option<ChatContent>,
231+ truncated: bool,
232+ error_code: Option<&str>,
233+) -> Result<ChatbotMessage, AppError> {
234+ let status = if text.is_some() {
235+ MessageStatus::Complete
236+ } else {
237+ MessageStatus::Failed
238+ };
239+ let mut result = db
240+ .query(
241+ "UPDATE $id SET content = $content, status = $status, truncated = $truncated, \
242+ error_code = $code, completed_at = $now WHERE status = 'pending' RETURN AFTER",
243+ )
244+ .bind(("id", id.record()))
245+ .bind(("content", text.map(|t| t.0).unwrap_or_default()))
246+ .bind(("status", status.as_str().to_string()))
247+ .bind(("truncated", truncated))
248+ .bind((
249+ "code",
250+ error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::<String>()),
251+ ))
252+ .bind(("now", Timestamp::now().as_millis()))
253+ .await?
254+ .check()?;
255+ result
256+ .take::<Vec<ChatbotMessage>>(0)?
257+ .into_iter()
258+ .next()
259+ .ok_or(AppError::NotFound)
260+}
261+
262+#[cfg(test)]
263+mod tests {
264+ use super::*;
265+ use crate::domain::chatbot_message::MessageRole;
266+
267+ #[tokio::test]
268+ async fn a_turns_two_rows_never_sort_inverted() {
269+ // Both rows of a turn land in the same millisecond routinely, so the
270+ // `id` tie-break decides the thread's order. With a random ULID this
271+ // inverted a fifth of the pairs; here every pair must read back
272+ // question-then-answer, from both read paths.
273+ let db = crate::database::init_mem().await.unwrap();
274+ // A real thread row: every turn is written through it, so a turn with
275+ // no thread is refused (see [`insert`]).
276+ db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0")
277+ .await
278+ .unwrap()
279+ .check()
280+ .unwrap();
281+ let thread = ChatbotThreadId::from_key("c");
282+ let user = UserId::from_key("u");
283+ const TURNS: usize = 200;
284+
285+ for turn in 0..TURNS {
286+ let content = ChatContent::try_new(&format!("soru {turn}")).unwrap();
287+ append_user(&db, &thread, &user, content).await.unwrap();
288+ append_pending_assistant(&db, &thread, &user).await.unwrap();
289+ }
290+
291+ let (whole, _) = list_for_thread(&db, &thread, None, 0).await.unwrap();
292+ let tail = list_tail(&db, &thread, TURNS * 2).await.unwrap();
293+ for messages in [&whole, &tail] {
294+ assert_eq!(messages.len(), TURNS * 2);
295+ for (turn, pair) in messages.chunks(2).enumerate() {
296+ assert_eq!(pair[0].get_role(), MessageRole::User, "turn {turn}");
297+ assert_eq!(pair[0].get_content().as_str(), format!("soru {turn}"));
298+ assert_eq!(pair[1].get_role(), MessageRole::Assistant, "turn {turn}");
299+ }
300+ }
301+ }
302+}
src/db/chatbot_thread.rsadded+522 -0
@@ -0,0 +1,522 @@
1+//! The `chatbot_thread` table: one user's AI-chat threads, listed
2+//! newest-activity-first, deleted together with every turn in them. The
3+//! entity and its validated newtypes live in
4+//! [`crate::domain::chatbot_thread`]; this module is where their rows are
5+//! read and written.
6+
7+use surrealdb::types::{SurrealValue, Value};
8+
9+use crate::constant::{
10+ CHATBOT_THREAD_COUNT_FIELD, DEFAULT_MAX_CHATBOT_THREADS, SETTINGS_KEY, SETTINGS_TABLE,
11+};
12+use crate::database::{Database, transaction_with_retry};
13+use crate::db::cap;
14+use crate::db::page::PagedList;
15+use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
16+use crate::domain::timestamp::Timestamp;
17+use crate::domain::user::UserId;
18+use crate::error::AppError;
19+
20+/// Move the thread's `updated_at` **and** run `statement` — a write to a turn
21+/// hanging off that thread — in one transaction, handing back the row it
22+/// returned. [`AppError::NotFound`] means the thread is gone and `statement`
23+/// wrote nothing.
24+///
25+/// The bump is what ties a turn's fate to its thread, and reading the thread
26+/// first does not: [`delete`] sweeps `chatbot_message` and drops
27+/// the thread in one transaction, so a create landing after that sweep but
28+/// before its commit reads a thread that is still there (uncommitted) while the
29+/// sweep ran on a snapshot predating the new row — both commit, and the turn
30+/// outlives the thread it was deleted with, readable and deletable by nothing.
31+/// Reads do not conflict; only a write that *moves* a value on a key the delete
32+/// also writes does. That is the shape
33+/// [`bump_menu_and_write`](crate::domain::menu::bump_menu_and_write) and
34+/// [`ExamAnswer::save`](crate::domain::exam_answer::ExamAnswer::save) already
35+/// use, and the sweep's ordering inside the delete stops mattering once it is
36+/// in place.
37+///
38+/// `updated_at` is the value moved, and it doubles as the stamp the thread list
39+/// sorts on — this *is* the activity touch the send path used to issue
40+/// afterwards as a separate, best-effort query whose failure was only logged.
41+/// It is written strictly upwards rather than to `$now`: an `UPDATE` that
42+/// leaves the document unchanged is elided and never reaches the store's write
43+/// set, a turn's two rows are routinely written inside one millisecond, and a
44+/// write that does not happen collides with nothing. The stamp can therefore
45+/// sit a few milliseconds ahead of the clock, which an ordering key does not
46+/// care about.
47+///
48+/// Admissible for [`transaction_with_retry`] as long as `statement` is: the
49+/// `UPDATE`, the `IF`/`THROW` and the `RETURN` can never answer "already
50+/// exists", and neither can a `CREATE` on a freshly minted ULID on a table with
51+/// no `UNIQUE` index — no rival can have aimed at it, and a lost round wrote
52+/// nothing, so re-sending it is the recovery.
53+pub(crate) async fn touch_and_write<T: SurrealValue>(
54+ db: &Database,
55+ thread: &ChatbotThreadId,
56+ statement: &str,
57+ mut bindings: Vec<(String, Value)>,
58+) -> Result<Option<T>, AppError> {
59+ bindings.push(("conv".into(), thread.record().into_value()));
60+ bindings.push(("now".into(), Timestamp::now().as_millis().into_value()));
61+ let (mut result, mut errors) = transaction_with_retry(
62+ db,
63+ &format!(
64+ "BEGIN TRANSACTION;
65+ LET $touched = (UPDATE $conv SET updated_at = \
66+ math::max([$now, updated_at + 1]) RETURN VALUE id);
67+ IF array::len($touched) = 0 {{ THROW 'no_thread' }};
68+ LET $row = ({statement});
69+ RETURN $row;
70+ COMMIT TRANSACTION;"
71+ ),
72+ &bindings,
73+ &["no_thread"],
74+ )
75+ .await?;
76+ // An aborted transaction errors *every* slot, most with a generic "not
77+ // executed" — only the THROW's own slot names the reason.
78+ if errors
79+ .values()
80+ .any(|error| error.to_string().contains("no_thread"))
81+ {
82+ return Err(AppError::NotFound);
83+ }
84+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
85+ return Err(error.into());
86+ }
87+ // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4.
88+ Ok(result.take::<Vec<T>>(4)?.into_iter().next())
89+}
90+
91+/// Start a thread unless `user` is already at the school's
92+/// `max_chatbot_threads`. The slot is taken on the user row in the same
93+/// transaction as the thread ([`cap::claim_live_and_create`]) — an atomic
94+/// single-record write, so two requests racing the same user's last slot
95+/// cannot both win and the counter can never count a row that did not
96+/// commit.
97+///
98+/// The cap is the one *live* on the settings singleton, sub-queried inside
99+/// that same conditional write rather than bound as a number: this cap does
100+/// not live on the parent row (the seat is on the user, the limit is the
101+/// school's), and a snapshot of it admits every request already in flight
102+/// when a `PATCH /settings` lowers it. The subquery costs one extra record
103+/// read per claim on a path that already reads the row it writes.
104+/// `DEFAULT_MAX_CHATBOT_THREADS` is the fallback the settings row's own
105+/// absent column means — no row, or a school that never set the knob.
106+pub async fn create_capped(
107+ db: &Database,
108+ user: &UserId,
109+ title: Option<ChatbotThreadTitle>,
110+) -> Result<ChatbotThread, AppError> {
111+ let now = Timestamp::now();
112+ let thread = ChatbotThread {
113+ id: ChatbotThreadId::generate(),
114+ user_id: user.clone(),
115+ title,
116+ created_at: now,
117+ updated_at: now,
118+ };
119+ match cap::claim_live_and_create(
120+ &user.record(),
121+ CHATBOT_THREAD_COUNT_FIELD,
122+ &format!(
123+ "(SELECT VALUE max_chatbot_threads FROM ONLY {SETTINGS_TABLE}:{SETTINGS_KEY}) ?? $num"
124+ ),
125+ DEFAULT_MAX_CHATBOT_THREADS,
126+ // No holder claim: the parent row *is* the user's, so this write
127+ // already lands on the key a role change writes.
128+ None,
129+ (&thread.id.record(), &thread),
130+ db,
131+ )
132+ .await?
133+ {
134+ cap::Claimed::Made(saved) => Ok(saved),
135+ // Full, or the user's row is gone — the conditional write matches
136+ // nothing either way.
137+ cap::Claimed::Full => Err(AppError::Conflict(
138+ "you have reached the school's limit on saved threads — delete one first",
139+ )),
140+ // The id is a freshly minted ULID on a table with no UNIQUE index,
141+ // so no rival can have aimed at it.
142+ cap::Claimed::Duplicate => Err(AppError::Internal("thread id collided".into())),
143+ }
144+}
145+
146+/// A user's threads, most recently active first — the sort the
147+/// `chatbot_thread_user_updated` index exists for.
148+pub async fn list_for_user(
149+ db: &Database,
150+ user: &UserId,
151+ limit: Option<i64>,
152+ offset: i64,
153+) -> Result<(Vec<ChatbotThread>, i64), AppError> {
154+ PagedList::new(
155+ "chatbot_thread WHERE user_id = $usr",
156+ "ORDER BY updated_at DESC, id DESC",
157+ )
158+ .bind("usr", user.record())
159+ .run(limit, offset, db)
160+ .await
161+}
162+
163+/// How many threads `user` keeps — the `max_chatbot_threads` cap check.
164+pub async fn count_for_user(db: &Database, user: &UserId) -> Result<usize, AppError> {
165+ let mut result = db
166+ .query("SELECT VALUE count() FROM chatbot_thread WHERE user_id = $usr GROUP ALL")
167+ .bind(("usr", user.record()))
168+ .await?
169+ .check()?;
170+ Ok(result
171+ .take::<Vec<i64>>(0)?
172+ .first()
173+ .copied()
174+ .unwrap_or_default()
175+ .max(0) as usize)
176+}
177+
178+/// Read a thread only if `user` owns it — a foreign id reads as absent, so
179+/// the web layer answers 404 rather than leaking that it exists.
180+pub async fn read_for(
181+ db: &Database,
182+ id: &ChatbotThreadId,
183+ user: &UserId,
184+) -> Result<Option<ChatbotThread>, AppError> {
185+ let thread: Option<ChatbotThread> = db.select(id.record()).await?;
186+ Ok(thread.filter(|thread| &thread.user_id == user))
187+}
188+
189+// Stamping new activity is not a call of its own: it is the bump inside
190+// [`touch_and_write`], which every turn already rides, so a stamp can no
191+// longer be lost (it used to be a best-effort query after the two creates,
192+// whose failure was a `warn!`) and no turn can be written without it.
193+
194+/// Rename the thread (`None` clears the name back to untitled), stamping
195+/// the edit as activity. Field-scoped for the same reason as
196+/// [`touch_and_write`]: a turn may be landing concurrently.
197+pub async fn rename(
198+ db: &Database,
199+ thread: &ChatbotThread,
200+ title: Option<ChatbotThreadTitle>,
201+) -> Result<ChatbotThread, AppError> {
202+ let mut result = db
203+ .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER")
204+ .bind(("id", thread.id.record()))
205+ .bind(("title", title.map(|title| title.0)))
206+ .bind(("now", Timestamp::now().as_millis()))
207+ .await?
208+ .check()?;
209+ result
210+ .take::<Vec<ChatbotThread>>(0)?
211+ .into_iter()
212+ .next()
213+ .ok_or(AppError::NotFound)
214+}
215+
216+/// Delete the thread and every turn in it — one transaction, so a crash
217+/// can't orphan messages under a vanished thread. The owner's slot comes
218+/// back in that same transaction, or the cap would ratchet shut.
219+///
220+/// A turn, a rename and this delete all write the thread row (see
221+/// [`touch_and_write`]), so the store aborting one of them is ordinary
222+/// here — that collision is exactly what keeps a turn from outliving the
223+/// thread — and a lost round is re-sent rather than reported as the `500`
224+/// it used to be. Re-sending is sound: every statement is a `DELETE` or a
225+/// field-scoped `UPDATE`, none of which can ever answer "already exists"
226+/// (see [`transaction_with_retry`]). On the re-sent round the thread is
227+/// already gone, so the `RETURN` is empty and the caller gets the `404`
228+/// that is the truth.
229+pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThread, AppError> {
230+ let (mut result, mut errors) = transaction_with_retry(
231+ db,
232+ "BEGIN TRANSACTION;
233+ DELETE chatbot_message WHERE thread_id = $conv;
234+ LET $gone = (DELETE $conv RETURN BEFORE);
235+ UPDATE $usr SET chatbot_thread_count = math::max([(chatbot_thread_count ?? 0) - array::len($gone), 0]);
236+ RETURN $gone;
237+ COMMIT TRANSACTION;",
238+ &[
239+ ("conv".into(), thread.id.record().into_value()),
240+ ("usr".into(), thread.user_id.record().into_value()),
241+ ],
242+ &[],
243+ )
244+ .await?;
245+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
246+ return Err(error.into());
247+ }
248+ // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN
249+ // is slot 4.
250+ let deleted: Option<ChatbotThread> = result.take::<Vec<ChatbotThread>>(4)?.into_iter().next();
251+ deleted.ok_or(AppError::NotFound)
252+}
253+
254+#[cfg(test)]
255+mod tests {
256+ use super::*;
257+ use surrealdb::types::RecordId;
258+
259+ use crate::db::chatbot_message;
260+ use crate::domain::chatbot_message::ChatContent;
261+ use crate::domain::settings::{Settings, SettingsParams};
262+
263+ /// The owner's counter and the threads it counts, both re-read out of the
264+ /// store — never off a return value, which the in-memory engine forges
265+ /// wins on (see [`cap`]).
266+ async fn stored(db: &Database) -> (i64, usize) {
267+ let mut result = db
268+ .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u")
269+ .query("SELECT VALUE id FROM chatbot_thread")
270+ .await
271+ .unwrap()
272+ .check()
273+ .unwrap();
274+ let counter = result.take::<Vec<i64>>(0).unwrap();
275+ let rows = result.take::<Vec<RecordId>>(1).unwrap();
276+ (counter[0], rows.len())
277+ }
278+
279+ async fn a_user_capped_at(threads: i64) -> Database {
280+ let db = crate::database::init_mem().await.unwrap();
281+ db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
282+ .await
283+ .unwrap()
284+ .check()
285+ .unwrap();
286+ crate::db::settings::save(
287+ &db,
288+ Settings::try_new(SettingsParams {
289+ max_chatbot_threads: threads,
290+ ..Settings::defaults().params()
291+ })
292+ .unwrap(),
293+ )
294+ .await
295+ .unwrap();
296+ db
297+ }
298+
299+ /// The seat and the row commit together, so the counter the cap reads can
300+ /// never disagree with the threads it counts — and a create refused at the
301+ /// cap advances neither.
302+ #[tokio::test]
303+ async fn a_capped_create_moves_the_counter_with_the_row() {
304+ let db = a_user_capped_at(1).await;
305+ let user = UserId::from_key("u");
306+
307+ create_capped(&db, &user, None).await.expect("first thread");
308+ assert_eq!(stored(&db).await, (1, 1));
309+
310+ let refused = create_capped(&db, &user, None).await;
311+ assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap");
312+ assert_eq!(
313+ stored(&db).await,
314+ (1, 1),
315+ "a refused create advances neither"
316+ );
317+ }
318+
319+ /// A turn is written *through* its thread's row, so a thread that is gone
320+ /// takes the write with it — and one that is there is stamped by it.
321+ /// The race this shape exists to close is the `#[ignore]`d test below;
322+ /// this one pins the logic, which the in-memory engine can answer.
323+ #[tokio::test]
324+ async fn a_turn_writes_its_thread_and_dies_with_it() {
325+ let db = a_user_capped_at(2).await;
326+ let user = UserId::from_key("u");
327+ let thread = create_capped(&db, &user, None).await.expect("thread");
328+ let opened = thread.get_updated_at().as_millis();
329+
330+ let say = || ChatContent::try_new("selam").unwrap();
331+ chatbot_message::append_user(&db, thread.get_id(), &user, say())
332+ .await
333+ .expect("append");
334+ let stamped = read_for(&db, thread.get_id(), &user)
335+ .await
336+ .expect("re-read")
337+ .expect("still there")
338+ .get_updated_at()
339+ .as_millis();
340+ // Strictly upwards, never merely re-stamped: an `UPDATE` that leaves
341+ // the row unchanged is elided, and both rows of a turn are routinely
342+ // written inside one millisecond of the thread's own creation.
343+ assert!(stamped > opened, "{stamped} !> {opened}");
344+
345+ let id = thread.get_id().clone();
346+ delete(&db, thread).await.expect("delete");
347+ let orphan = chatbot_message::append_user(&db, &id, &user, say()).await;
348+ assert!(
349+ matches!(orphan, Err(AppError::NotFound)),
350+ "a turn on a deleted thread must be refused: {orphan:?}"
351+ );
352+ assert_eq!(
353+ chatbot_message::list_for_thread(&db, &id, None, 0)
354+ .await
355+ .expect("list")
356+ .1,
357+ 0,
358+ "the refused turn wrote nothing"
359+ );
360+ }
361+
362+ /// The stamp moves **strictly upwards**, never to the clock — the property
363+ /// the whole shape rests on, since an `UPDATE` that leaves the row
364+ /// unchanged is elided, never reaches the store's write set, and so
365+ /// collides with the racing delete not at all.
366+ ///
367+ /// The test above cannot see it: it compares one append against
368+ /// `create_capped`, which costs a millisecond or so on its own, and a plain
369+ /// `$now` clears that. Nor can a burst of appends — each is a transaction
370+ /// of its own and takes about as long, so the clock has moved on by the
371+ /// time the next one reads it. Timing cannot reach the window on demand.
372+ ///
373+ /// So the *state* the window produces is set up directly instead: a stamp
374+ /// **ahead of the clock**, which is precisely what `math::max` leaves
375+ /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a
376+ /// contrived one. From there the two rules are told apart with no race at
377+ /// all — upwards keeps climbing off the stored value, the clock drags the
378+ /// stamp back down to itself. The lead is a second, far more than two
379+ /// writes can burn, and the guard below fails loudly rather than vacuously
380+ /// on a machine that manages to burn it.
381+ #[tokio::test]
382+ async fn a_stamp_ahead_of_the_clock_still_climbs() {
383+ const LEAD: i64 = 1_000;
384+
385+ let db = a_user_capped_at(1).await;
386+ let user = UserId::from_key("u");
387+ let thread = create_capped(&db, &user, None).await.expect("thread");
388+
389+ let parked = Timestamp::now().as_millis() + LEAD;
390+ db.query("UPDATE $id SET updated_at = $parked")
391+ .bind(("id", thread.get_id().record()))
392+ .bind(("parked", parked))
393+ .await
394+ .unwrap()
395+ .check()
396+ .unwrap();
397+
398+ for _ in 0..2 {
399+ chatbot_message::append_user(
400+ &db,
401+ thread.get_id(),
402+ &user,
403+ ChatContent::try_new("selam").unwrap(),
404+ )
405+ .await
406+ .expect("append");
407+ }
408+ let stamped = read_for(&db, thread.get_id(), &user)
409+ .await
410+ .expect("re-read")
411+ .expect("still there")
412+ .get_updated_at()
413+ .as_millis();
414+
415+ assert!(
416+ Timestamp::now().as_millis() < parked,
417+ "the clock caught the {LEAD}ms lead up during two appends, so this \
418+ probe proves nothing"
419+ );
420+ assert_eq!(
421+ stamped,
422+ parked + 2,
423+ "two appends off a stamp of {parked} must leave {}: a stamp that \
424+ follows the clock instead is one an unchanged-row UPDATE elides",
425+ parked + 2
426+ );
427+ }
428+
429+ /// No turn may survive the delete that swept its thread. An orphan is not
430+ /// litter: nothing sweeps `chatbot_message` afterwards, and both
431+ /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered
432+ /// `200` with the text of a thread the user had deleted.
433+ ///
434+ /// The window is between [`delete`]'s sweep and its commit:
435+ /// a create landing in there reads a thread that is still present
436+ /// (uncommitted) while the sweep ran on a snapshot predating the new row,
437+ /// so both commit. It is closed by making the create **write** the thread
438+ /// row ([`touch_and_write`]) instead of reading it — the two transactions
439+ /// then touch one key and the store refuses to commit both.
440+ ///
441+ /// The window is opened by the database itself rather than by a lucky
442+ /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the
443+ /// delete's own transaction, the instant the row goes, so the `SLEEP` lands
444+ /// after the message sweep and before the commit every single time.
445+ ///
446+ /// Real server, and `#[ignore]`d for it: the subject is the store's
447+ /// conflict detection, which `init_mem`'s embedded engine does not have —
448+ /// it commits both writes and answers `Ok` to each, which would fail this
449+ /// test on correct code (see [`crate::database::init_test_server`]).
450+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
451+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
452+ async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {
453+ let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await;
454+ db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
455+ .await
456+ .unwrap()
457+ .check()
458+ .unwrap();
459+ // Hold the delete open for a full second after the thread row is gone,
460+ // while its transaction still has to commit.
461+ db.query(
462+ "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \
463+ THEN { SLEEP 1s; };",
464+ )
465+ .await
466+ .unwrap()
467+ .check()
468+ .unwrap();
469+
470+ let user = UserId::from_key("u");
471+ let (mut orphans, mut swept) = (0, 0);
472+ for round in 0..4 {
473+ let thread = create_capped(&db, &user, None).await.expect("thread");
474+ let id = thread.get_id().clone();
475+
476+ let drop_it = {
477+ let db = db.clone();
478+ tokio::spawn(async move { delete(&db, thread).await })
479+ };
480+ // The turn starts inside the held window — the thread row is gone
481+ // but uncommitted, which is exactly what a read believes.
482+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
483+ let turn = {
484+ let (id, db, user) = (id.clone(), db.clone(), user.clone());
485+ tokio::spawn(async move {
486+ chatbot_message::append_user(
487+ &db,
488+ &id,
489+ &user,
490+ ChatContent::try_new("selam").unwrap(),
491+ )
492+ .await
493+ .map(|_| ())
494+ })
495+ };
496+ let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap());
497+ // A 404 for the turn, or a NotFound for the delete, is a correct
498+ // answer — the only defect is stored state.
499+ assert!(
500+ !matches!(turn, Err(AppError::Db(_))),
501+ "round {round}: a raced turn must be answered, not 500: {turn:?}"
502+ );
503+
504+ // Stored state is the whole verdict; a return value is not evidence.
505+ if read_for(&db, &id, &user).await.unwrap().is_none() {
506+ swept += 1;
507+ orphans += chatbot_message::list_for_thread(&db, &id, None, 0)
508+ .await
509+ .unwrap()
510+ .1;
511+ } else if drop_it.is_ok() {
512+ panic!("round {round}: the delete reported success but the thread is still there");
513+ }
514+ }
515+ eprintln!("chatbot_thread::delete raced by a turn: {swept}/4 rounds deleted the thread");
516+ assert!(
517+ swept > 0,
518+ "no round ever deleted the thread, so the window was never reached"
519+ );
520+ assert_eq!(orphans, 0, "a turn outlived its thread");
521+ }
522+}
src/db/mod.rsmodified+3 -0
@@ -5,6 +5,8 @@ pub mod appointment_slot;
5 pub mod badge;5 pub mod badge;
6 pub mod builder;6 pub mod builder;
7 pub mod cap;7 pub mod cap;
8+pub mod chatbot_message;
9+pub mod chatbot_thread;
8 pub mod class_blueprint;10 pub mod class_blueprint;
9 pub mod course;11 pub mod course;
10 pub mod course_session;12 pub mod course_session;
@@ -22,6 +24,7 @@ pub mod parent_link;
22 pub mod payment_ledger;24 pub mod payment_ledger;
23 pub mod pomodoro;25 pub mod pomodoro;
24 pub mod profile;26 pub mod profile;
27+pub mod rag_output;
25 pub mod registration;28 pub mod registration;
26 pub mod session;29 pub mod session;
27 pub mod settings;30 pub mod settings;
src/db/rag_output.rsadded+242 -0
@@ -0,0 +1,242 @@
1+//! The `rag_output` table: what an AI service produced for a course note —
2+//! an index, a summary, an embedding manifest — stored as this side's own
3+//! copy of the answer. The AI service never writes here (it answers a
4+//! request over the bridge, and this side stores the answer), which is what
5+//! keeps the api-read bridge GET-only. Derived, disposable data: the row is
6+//! dropped and regenerated whenever its input changes, so the cascades
7+//! below — [`delete_for_note`] when the note goes, [`delete_with_source`]
8+//! when one of the attachments it was built from goes — keep a stale output
9+//! from outliving its input, even in a deployment with no AI service
10+//! connected. The row shape lives in [`crate::domain::rag_output`].
11+
12+use crate::database::Database;
13+use crate::db::page::PagedList;
14+use crate::domain::course::CourseId;
15+use crate::domain::course_note::CourseNoteId;
16+use crate::domain::course_note_file::CourseNoteFileId;
17+use crate::domain::rag_output::{RagOutput, RagOutputId};
18+use crate::domain::timestamp::Timestamp;
19+use crate::error::AppError;
20+use serde_json::Value;
21+
22+/// Store one service output against `note`.
23+pub async fn create(
24+ db: &Database,
25+ note: &CourseNoteId,
26+ course: &CourseId,
27+ sources: Vec<CourseNoteFileId>,
28+ payload: Value,
29+) -> Result<RagOutput, AppError> {
30+ let row = RagOutput {
31+ id: RagOutputId::generate(),
32+ course_note: note.clone(),
33+ course: course.clone(),
34+ sources,
35+ payload,
36+ generated_at: Timestamp::now(),
37+ };
38+ // whole-row-save-ok: create of a fresh ULID row built in place — there is no prior row to clobber
39+ let created: Option<RagOutput> = db.create(row.id.record()).content(row).await?;
40+ created.ok_or_else(|| AppError::Internal("failed to create rag output".into()))
41+}
42+
43+pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> {
44+ Ok(db.select(id.record()).await?)
45+}
46+
47+/// A note's outputs, newest first.
48+pub async fn list_for(
49+ db: &Database,
50+ note: &CourseNoteId,
51+ limit: Option<i64>,
52+ offset: i64,
53+) -> Result<(Vec<RagOutput>, i64), AppError> {
54+ PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC")
55+ .bind("note", note.record())
56+ .run(limit, offset, db)
57+ .await
58+}
59+
60+pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> {
61+ let deleted: Option<RagOutput> = db.delete(id.record()).await?;
62+ deleted.ok_or(AppError::NotFound)
63+}
64+
65+/// Cascade: every output of `note`. Deleting none is a success — a note
66+/// no service ever indexed has nothing to drop.
67+pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> {
68+ db.query("DELETE rag_output WHERE course_note = $note")
69+ .bind(("note", note.record()))
70+ .await?
71+ .check()?;
72+ Ok(())
73+}
74+
75+/// Newest-wins replace, without a lock: store `payload` first, then drop
76+/// this note's older rows. Two concurrent index tasks can interleave in any
77+/// order and still leave exactly one row — the newest — because ids come
78+/// from the process-wide monotonic generator, so "older" is `id <` the row
79+/// just written and the loser's row is always below the winner's.
80+pub async fn replace_for_note(
81+ db: &Database,
82+ note: &CourseNoteId,
83+ course: &CourseId,
84+ sources: Vec<CourseNoteFileId>,
85+ payload: Value,
86+) -> Result<RagOutput, AppError> {
87+ let created = create(db, note, course, sources, payload).await?;
88+ db.query("DELETE rag_output WHERE course_note = $note AND id < $new")
89+ .bind(("note", note.record()))
90+ .bind(("new", created.id.record()))
91+ .await?
92+ .check()?;
93+ Ok(created)
94+}
95+
96+/// Cascade: every output built from `file`. Runs on a file delete even
97+/// with no AI service connected, so a stale output cannot survive its
98+/// source.
99+pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {
100+ db.query("DELETE rag_output WHERE sources CONTAINS $file")
101+ .bind(("file", file.record()))
102+ .await?
103+ .check()?;
104+ Ok(())
105+}
106+
107+#[cfg(test)]
108+mod tests {
109+ use super::*;
110+ use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
111+ use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle};
112+ use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName};
113+ use serde_json::json;
114+
115+ async fn note_of(db: &Database, title: &str) -> CourseNote {
116+ let creator = crate::domain::user::UserId::generate();
117+ let course = crate::db::course::create(
118+ db,
119+ &creator,
120+ CourseTitle::try_new("c").unwrap(),
121+ CourseDescription::try_new("").unwrap(),
122+ CourseKind::try_new("course").unwrap(),
123+ None,
124+ None,
125+ )
126+ .await
127+ .unwrap();
128+ CourseNote::create(
129+ course.get_id(),
130+ &creator,
131+ CourseNoteTitle::try_new(title).unwrap(),
132+ CourseNoteContent::try_new("body").unwrap(),
133+ db,
134+ )
135+ .await
136+ .unwrap()
137+ }
138+
139+ async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId {
140+ CourseNoteFile::new(
141+ note,
142+ FileName::try_new("plan.pdf").unwrap(),
143+ FileContentType::try_new("application/pdf").unwrap(),
144+ 3,
145+ )
146+ .insert(db)
147+ .await
148+ .unwrap()
149+ .get_id()
150+ .clone()
151+ }
152+
153+ /// Replace converges on one row — the newest — even when an earlier
154+ /// interleaving already left two rows behind for the note.
155+ #[tokio::test]
156+ async fn replace_keeps_only_the_newest_output() {
157+ let db = crate::database::init_mem().await.unwrap();
158+ let note = note_of(&db, "a").await;
159+ let stale = create(
160+ &db,
161+ note.get_id(),
162+ note.get_course(),
163+ Vec::new(),
164+ json!({ "n": 1 }),
165+ )
166+ .await
167+ .unwrap();
168+ // The race this fixes: a second row for the same note.
169+ create(
170+ &db,
171+ note.get_id(),
172+ note.get_course(),
173+ Vec::new(),
174+ json!({ "n": 2 }),
175+ )
176+ .await
177+ .unwrap();
178+
179+ let fresh = replace_for_note(
180+ &db,
181+ note.get_id(),
182+ note.get_course(),
183+ Vec::new(),
184+ json!({ "n": 3 }),
185+ )
186+ .await
187+ .unwrap();
188+
189+ let rows = list_for(&db, note.get_id(), None, 0).await.unwrap().0;
190+ assert_eq!(rows.len(), 1);
191+ assert_eq!(rows[0].get_id(), fresh.get_id());
192+ assert!(fresh.get_id().key() > stale.get_id().key());
193+ }
194+
195+ /// The payload survives the round trip unread, and both cascades take only
196+ /// what they are aimed at.
197+ #[tokio::test]
198+ async fn outputs_round_trip_and_cascade() {
199+ let db = crate::database::init_mem().await.unwrap();
200+ let note = note_of(&db, "a").await;
201+ let other = note_of(&db, "b").await;
202+ let file = file_on(&db, note.get_id()).await;
203+
204+ let stored = create(
205+ &db,
206+ note.get_id(),
207+ note.get_course(),
208+ vec![file.clone()],
209+ json!({ "summary": "x", "chunks": [{ "text": "y" }] }),
210+ )
211+ .await
212+ .unwrap();
213+ let roundtrip = read(&db, stored.get_id()).await.unwrap().unwrap();
214+ assert_eq!(roundtrip.get_payload()["summary"], "x");
215+ assert_eq!(roundtrip.get_payload()["chunks"][0]["text"], "y");
216+ assert_eq!(roundtrip.get_sources(), std::slice::from_ref(&file));
217+ assert_eq!(roundtrip.get_course(), note.get_course());
218+ let untouched = create(
219+ &db,
220+ other.get_id(),
221+ other.get_course(),
222+ Vec::new(),
223+ json!({ "summary": "z" }),
224+ )
225+ .await
226+ .unwrap();
227+
228+ let listed =
229+ async |note: &CourseNoteId| list_for(&db, note, None, 0).await.unwrap().0.len();
230+ assert_eq!(listed(note.get_id()).await, 1);
231+
232+ // Losing a source drops the output that cited it, and nothing else.
233+ delete_with_source(&db, &file).await.unwrap();
234+ assert_eq!(listed(note.get_id()).await, 0);
235+ assert_eq!(listed(other.get_id()).await, 1);
236+
237+ // Cascading a note with no outputs left is still a success.
238+ delete_for_note(&db, note.get_id()).await.unwrap();
239+ delete_for_note(&db, other.get_id()).await.unwrap();
240+ assert!(read(&db, untouched.get_id()).await.unwrap().is_none());
241+ }
242+}
src/domain/chatbot_message.rsmodified+41 -315
@@ -1,12 +1,13 @@
1-//! One turn of a chatbot thread. Both sides are persisted: the user's prompt1+//! One turn of a chatbot thread — the row shape and its read-time
2-//! lands `complete`, and the assistant's row is written `pending` *before* the2+//! presentation. `user_id` is duplicated from the thread onto every message
3-//! AI call so a reload never loses an answer in flight. The task that owns the3+//! so an ownership check is one read, with no join.
4-//! bridge round trip then flips it to `complete` (with the text) or `failed`
5-//! (with a code), and the boot sweep in `database.rs` fails whatever a process
6-//! death left behind past the staleness window.
7 //!4 //!
8-//! `user_id` is duplicated from the thread onto every message so an5+//! Persistence lives in [`crate::db::chatbot_message`]: the assistant's row
9-//! ownership check is one read, with no join.6+//! is written `pending` *before* the AI call and flipped to `complete` or
7+//! `failed` by the task that owns the bridge round trip, and a read
8+//! projects a long-stale `pending` as failed without writing
9+//! ([`ChatbotMessage::projected`]) — the durable repair for a dead process
10+//! happens once, at boot, in `database.rs`.
10 11
11 use std::sync::{LazyLock, Mutex};12 use std::sync::{LazyLock, Mutex};
12 13
@@ -14,21 +15,19 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14 use ulid::{Generator, Ulid};15 use ulid::{Generator, Ulid};
15 16
16 use crate::constant::{17 use crate::constant::{
17- CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, MAX_ERROR_CODE_LEN,18+ CHAT_MESSAGE_TABLE, CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE,
18- STALE_ERROR_CODE,
19 };19 };
20-use crate::database::Database;20+use crate::domain::chatbot_thread::ChatbotThreadId;
21-use crate::domain::chatbot_thread::{ChatbotThreadId, touch_and_write};
22-use crate::db::page::PagedList;
23 use crate::domain::timestamp::Timestamp;21 use crate::domain::timestamp::Timestamp;
24 use crate::domain::user::UserId;22 use crate::domain::user::UserId;
25-use crate::error::{AppError, ValidationError};23+use crate::error::ValidationError;
26 use crate::validate::validate_required;24 use crate::validate::validate_required;
27 25
28 /// Mints message ids in write order. Unlike `Ulid::new()`, whose 80 random26 /// Mints message ids in write order. Unlike `Ulid::new()`, whose 80 random
29 /// low bits sort arbitrarily among ids minted in the same millisecond, this27 /// low bits sort arbitrarily among ids minted in the same millisecond, this
30 /// increments the previous id — so the `id` tie-break in the `ORDER BY` of28 /// increments the previous id — so the `id` tie-break in the `ORDER BY` of
31-/// [`ChatbotMessage::list_for_thread`] / [`ChatbotMessage::list_tail`] is the29+/// [`list_for_thread`](crate::db::chatbot_message::list_for_thread) /
30+/// [`list_tail`](crate::db::chatbot_message::list_tail) is the
32 /// order the rows were written. The user prompt and the assistant row one POST31 /// order the rows were written. The user prompt and the assistant row one POST
33 /// writes back-to-back routinely share a millisecond, and a random tie-break32 /// writes back-to-back routinely share a millisecond, and a random tie-break
34 /// there renders the answer *above* its own question — and hands the AI33 /// there renders the answer *above* its own question — and hands the AI
@@ -112,7 +111,7 @@ impl MessageStatus {
112 /// One turn's text. The hard ceiling only — the school-adjustable111 /// One turn's text. The hard ceiling only — the school-adjustable
113 /// `max_chatbot_message_len` is the web layer's to enforce, below this.112 /// `max_chatbot_message_len` is the web layer's to enforce, below this.
114 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]113 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
115-pub struct ChatContent(String);114+pub struct ChatContent(pub(crate) String);
116 115
117 impl ChatContent {116 impl ChatContent {
118 pub fn try_new(value: &str) -> Result<Self, ValidationError> {117 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
@@ -121,8 +120,9 @@ impl ChatContent {
121 }120 }
122 121
123 /// The placeholder a `pending` assistant row carries until its answer122 /// The placeholder a `pending` assistant row carries until its answer
124- /// lands. Private: every content that comes from outside is non-empty.123+ /// lands. Crate-visible: only the persistence layer writes it, for the
125- fn empty() -> Self {124+ /// reserved row before the answer exists.
125+ pub(crate) fn empty() -> Self {
126 Self(String::new())126 Self(String::new())
127 }127 }
128 128
@@ -133,19 +133,19 @@ impl ChatContent {
133 133
134 #[derive(Debug, Clone, SurrealValue)]134 #[derive(Debug, Clone, SurrealValue)]
135 pub struct ChatbotMessage {135 pub struct ChatbotMessage {
136- id: ChatbotMessageId,136+ pub(crate) id: ChatbotMessageId,
137- thread_id: ChatbotThreadId,137+ pub(crate) thread_id: ChatbotThreadId,
138- user_id: UserId,138+ pub(crate) user_id: UserId,
139- role: MessageRole,139+ pub(crate) role: MessageRole,
140- content: ChatContent,140+ pub(crate) content: ChatContent,
141- status: MessageStatus,141+ pub(crate) status: MessageStatus,
142 /// Whether the stored `content` is a clipped version of what the AI142 /// Whether the stored `content` is a clipped version of what the AI
143 /// service actually answered. Only an assistant turn can ever set it: a143 /// service actually answered. Only an assistant turn can ever set it: a
144 /// user prompt over the cap is refused (400), never trimmed.144 /// user prompt over the cap is refused (400), never trimmed.
145- truncated: bool,145+ pub(crate) truncated: bool,
146- error_code: Option<String>,146+ pub(crate) error_code: Option<String>,
147- created_at: Timestamp,147+ pub(crate) created_at: Timestamp,
148- completed_at: Option<Timestamp>,148+ pub(crate) completed_at: Option<Timestamp>,
149 }149 }
150 150
151 impl ChatbotMessage {151 impl ChatbotMessage {
@@ -198,7 +198,7 @@ impl ChatbotMessage {
198 /// reply that is still coming — and the durable repair for the real cause198 /// reply that is still coming — and the durable repair for the real cause
199 /// (a dead process) already happens once, at boot. The stored row stays199 /// (a dead process) already happens once, at boot. The stored row stays
200 /// truthful; only the answer handed to the caller is projected.200 /// truthful; only the answer handed to the caller is projected.
201- fn projected(mut self) -> Self {201+ pub(crate) fn projected(mut self) -> Self {
202 let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000;202 let stale_at = self.created_at.as_millis() + CHATBOT_PENDING_STALE_SECS * 1_000;
203 if self.status == MessageStatus::Pending && Timestamp::now().as_millis() > stale_at {203 if self.status == MessageStatus::Pending && Timestamp::now().as_millis() > stale_at {
204 self.status = MessageStatus::Failed;204 self.status = MessageStatus::Failed;
@@ -206,249 +206,11 @@ impl ChatbotMessage {
206 }206 }
207 self207 self
208 }208 }
209-
210- /// Write one turn *through its thread's own row* ([`touch_and_write`]),
211- /// which is what makes the thread's existence something this write writes
212- /// rather than something the caller read and then trusted: a
213- /// [`ChatbotThread::delete`](crate::domain::chatbot_thread::ChatbotThread::delete)
214- /// racing it touches the very key this transaction moves, so the two cannot
215- /// both commit and no turn is left under a thread that is gone. It also
216- /// carries the thread's activity stamp, so a turn and its `updated_at` land
217- /// together.
218- ///
219- /// [`AppError::NotFound`] = the thread is gone, and nothing was written.
220- async fn insert(message: ChatbotMessage, db: &Database) -> Result<ChatbotMessage, AppError> {
221- let thread = message.thread_id.clone();
222- let id = message.id.record();
223- touch_and_write(
224- &thread,
225- "CREATE $id CONTENT $row RETURN AFTER",
226- vec![
227- ("id".into(), id.into_value()),
228- ("row".into(), message.into_value()),
229- ],
230- db,
231- )
232- .await?
233- .ok_or_else(|| AppError::Internal("failed to create chat message".into()))
234- }
235-
236- /// Append the user's prompt. Nothing is awaited for it, so it is born
237- /// complete.
238- pub async fn append_user(
239- thread: &ChatbotThreadId,
240- user: &UserId,
241- content: ChatContent,
242- db: &Database,
243- ) -> Result<ChatbotMessage, AppError> {
244- let now = Timestamp::now();
245- Self::insert(
246- ChatbotMessage {
247- id: ChatbotMessageId::generate(),
248- thread_id: thread.clone(),
249- user_id: user.clone(),
250- role: MessageRole::User,
251- content,
252- status: MessageStatus::Complete,
253- truncated: false,
254- error_code: None,
255- created_at: now,
256- completed_at: Some(now),
257- },
258- db,
259- )
260- .await
261- }
262-
263- /// Reserve the assistant's answer *before* the AI call: the row exists,
264- /// empty and `pending`, so a reload finds the turn and can wait on it.
265- pub async fn append_pending_assistant(
266- thread: &ChatbotThreadId,
267- user: &UserId,
268- db: &Database,
269- ) -> Result<ChatbotMessage, AppError> {
270- Self::insert(
271- ChatbotMessage {
272- id: ChatbotMessageId::generate(),
273- thread_id: thread.clone(),
274- user_id: user.clone(),
275- role: MessageRole::Assistant,
276- content: ChatContent::empty(),
277- status: MessageStatus::Pending,
278- truncated: false,
279- error_code: None,
280- created_at: Timestamp::now(),
281- completed_at: None,
282- },
283- db,
284- )
285- .await
286- }
287-
288- /// The whole thread, oldest first — the order both the UI and the AI
289- /// history payload read in.
290- pub async fn list_for_thread(
291- thread: &ChatbotThreadId,
292- limit: Option<i64>,
293- offset: i64,
294- db: &Database,
295- ) -> Result<(Vec<ChatbotMessage>, i64), AppError> {
296- let (rows, total) = PagedList::new(
297- "chatbot_message WHERE thread_id = $conv",
298- "ORDER BY created_at ASC, id ASC",
299- )
300- .bind("conv", thread.record())
301- .run::<ChatbotMessage>(limit, offset, db)
302- .await?;
303- Ok((
304- rows.into_iter().map(ChatbotMessage::projected).collect(),
305- total,
306- ))
307- }
308-
309- /// The last `limit` turns, still oldest-first — the tail replayed to the
310- /// AI service as context. Taken newest-first in the database (so the
311- /// `LIMIT` keeps the *recent* end) and flipped back here.
312- pub async fn list_tail(
313- thread: &ChatbotThreadId,
314- limit: usize,
315- db: &Database,
316- ) -> Result<Vec<ChatbotMessage>, AppError> {
317- let mut result = db
318- .query(
319- "SELECT * FROM chatbot_message WHERE thread_id = $conv \
320- ORDER BY created_at DESC, id DESC LIMIT $limit",
321- )
322- .bind(("conv", thread.record()))
323- .bind(("limit", limit as i64))
324- .await?
325- .check()?;
326- let mut messages: Vec<ChatbotMessage> = result
327- .take::<Vec<ChatbotMessage>>(0)?
328- .into_iter()
329- .map(ChatbotMessage::projected)
330- .collect();
331- messages.reverse();
332- Ok(messages)
333- }
334-
335- /// The last `limit` *settled* turns that carry text, still oldest-first —
336- /// the tail replayed to the AI service as context. The filter runs in the
337- /// query, not after it: a `LIMIT` over the raw tail hands back fewer usable
338- /// rows the moment a run of answers fails, silently shrinking the context
339- /// instead of reaching further back. No projection is applied — it only
340- /// ever rewrites a `pending` row, and none is selected here.
341- pub async fn list_settled_tail(
342- thread: &ChatbotThreadId,
343- limit: usize,
344- db: &Database,
345- ) -> Result<Vec<ChatbotMessage>, AppError> {
346- let mut result = db
347- .query(
348- "SELECT * FROM chatbot_message WHERE thread_id = $conv \
349- AND status = 'complete' AND content != '' \
350- ORDER BY created_at DESC, id DESC LIMIT $limit",
351- )
352- .bind(("conv", thread.record()))
353- .bind(("limit", limit as i64))
354- .await?
355- .check()?;
356- let mut messages: Vec<ChatbotMessage> = result.take(0)?;
357- messages.reverse();
358- Ok(messages)
359- }
360-
361- /// The user turn a reserved answer belongs to, by *identity*: the prompt
362- /// row of the very POST that reserved it, whose id the answering task
363- /// carries.
364- ///
365- /// Never derived from write order. Two POSTs on one thread interleave
366- /// across the two creates — the rows land `userA, userB, asstA, asstB` —
367- /// so "the newest user row written before this answer" resolves *both*
368- /// answers to prompt B, and prompt A is never answered.
369- pub async fn prompt_of(
370- id: &ChatbotMessageId,
371- db: &Database,
372- ) -> Result<Option<ChatbotMessage>, AppError> {
373- Ok(db.select(id.record()).await?)
374- }
375-
376- /// Read one turn only if `user` owns it — the poll loop's read.
377- pub async fn read_for(
378- id: &ChatbotMessageId,
379- user: &UserId,
380- db: &Database,
381- ) -> Result<Option<ChatbotMessage>, AppError> {
382- let message: Option<ChatbotMessage> = db.select(id.record()).await?;
383- Ok(message
384- .filter(|message| &message.user_id == user)
385- .map(ChatbotMessage::projected))
386- }
387-
388- /// Land the answer, recording whether it had to be clipped to fit the
389- /// school's cap. Field-scoped and gated on `status = 'pending'` in the
390- /// `WHERE`, so a late reply can't overwrite a row the boot sweep (or a
391- /// timeout) already failed, and two answers can't both apply.
392- pub async fn complete(
393- id: &ChatbotMessageId,
394- text: ChatContent,
395- truncated: bool,
396- db: &Database,
397- ) -> Result<ChatbotMessage, AppError> {
398- Self::settle(id, Some(text), truncated, None, db).await
399- }
400-
401- /// Mark the answer failed with a short code (`unavailable`, the service's
402- /// own error code, …). Same pending gate as [`ChatbotMessage::complete`].
403- pub async fn fail(
404- id: &ChatbotMessageId,
405- error_code: &str,
406- db: &Database,
407- ) -> Result<ChatbotMessage, AppError> {
408- // A failed turn has no text, so there is nothing that could be clipped.
409- Self::settle(id, None, false, Some(error_code), db).await
410- }
411-
412- async fn settle(
413- id: &ChatbotMessageId,
414- text: Option<ChatContent>,
415- truncated: bool,
416- error_code: Option<&str>,
417- db: &Database,
418- ) -> Result<ChatbotMessage, AppError> {
419- let status = if text.is_some() {
420- MessageStatus::Complete
421- } else {
422- MessageStatus::Failed
423- };
424- let mut result = db
425- .query(
426- "UPDATE $id SET content = $content, status = $status, truncated = $truncated, \
427- error_code = $code, completed_at = $now WHERE status = 'pending' RETURN AFTER",
428- )
429- .bind(("id", id.record()))
430- .bind(("content", text.map(|t| t.0).unwrap_or_default()))
431- .bind(("status", status.as_str().to_string()))
432- .bind(("truncated", truncated))
433- .bind((
434- "code",
435- error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::<String>()),
436- ))
437- .bind(("now", Timestamp::now().as_millis()))
438- .await?
439- .check()?;
440- result
441- .take::<Vec<ChatbotMessage>>(0)?
442- .into_iter()
443- .next()
444- .ok_or(AppError::NotFound)
445- }
446 }209 }
447 210
448 #[cfg(test)]211 #[cfg(test)]
449 mod tests {212 mod tests {
450 use super::*;213 use super::*;
451- use surrealdb::types::Value;
452 214
453 #[tokio::test]215 #[tokio::test]
454 async fn content_is_required_and_capped() {216 async fn content_is_required_and_capped() {
@@ -463,7 +225,10 @@ mod tests {
463 // write, and a junk string must read back as an error, not a panic.225 // write, and a junk string must read back as an error, not a panic.
464 for role in [MessageRole::User, MessageRole::Assistant] {226 for role in [MessageRole::User, MessageRole::Assistant] {
465 let value = role.into_value();227 let value = role.into_value();
466- assert_eq!(value, Value::String(role.as_str().to_string()));228+ assert_eq!(
229+ value,
230+ surrealdb::types::Value::String(role.as_str().to_string())
231+ );
467 assert_eq!(MessageRole::from_value(value).unwrap(), role);232 assert_eq!(MessageRole::from_value(value).unwrap(), role);
468 }233 }
469 for status in [234 for status in [
@@ -472,55 +237,16 @@ mod tests {
472 MessageStatus::Failed,237 MessageStatus::Failed,
473 ] {238 ] {
474 let value = status.into_value();239 let value = status.into_value();
475- assert_eq!(value, Value::String(status.as_str().to_string()));240+ assert_eq!(
241+ value,
242+ surrealdb::types::Value::String(status.as_str().to_string())
243+ );
476 assert_eq!(MessageStatus::from_value(value).unwrap(), status);244 assert_eq!(MessageStatus::from_value(value).unwrap(), status);
477 }245 }
478- assert!(MessageRole::from_value(Value::String("system".into())).is_err());246+ assert!(MessageRole::from_value(surrealdb::types::Value::String("system".into())).is_err());
479- assert!(MessageStatus::from_value(Value::String("queued".into())).is_err());247+ assert!(
480- }248+ MessageStatus::from_value(surrealdb::types::Value::String("queued".into())).is_err()
481-249+ );
482- #[tokio::test]
483- async fn a_turns_two_rows_never_sort_inverted() {
484- // Both rows of a turn land in the same millisecond routinely, so the
485- // `id` tie-break decides the thread's order. With a random ULID this
486- // inverted a fifth of the pairs; here every pair must read back
487- // question-then-answer, from both read paths.
488- let db = crate::database::init_mem().await.unwrap();
489- // A real thread row: every turn is written through it, so a turn with
490- // no thread is refused (see [`ChatbotMessage::insert`]).
491- db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0")
492- .await
493- .unwrap()
494- .check()
495- .unwrap();
496- let thread = ChatbotThreadId::from_key("c");
497- let user = UserId::from_key("u");
498- const TURNS: usize = 200;
499-
500- for turn in 0..TURNS {
501- let content = ChatContent::try_new(&format!("soru {turn}")).unwrap();
502- ChatbotMessage::append_user(&thread, &user, content, &db)
503- .await
504- .unwrap();
505- ChatbotMessage::append_pending_assistant(&thread, &user, &db)
506- .await
507- .unwrap();
508- }
509-
510- let (whole, _) = ChatbotMessage::list_for_thread(&thread, None, 0, &db)
511- .await
512- .unwrap();
513- let tail = ChatbotMessage::list_tail(&thread, TURNS * 2, &db)
514- .await
515- .unwrap();
516- for messages in [&whole, &tail] {
517- assert_eq!(messages.len(), TURNS * 2);
518- for (turn, pair) in messages.chunks(2).enumerate() {
519- assert_eq!(pair[0].get_role(), MessageRole::User, "turn {turn}");
520- assert_eq!(pair[0].get_content().as_str(), format!("soru {turn}"));
521- assert_eq!(pair[1].get_role(), MessageRole::Assistant, "turn {turn}");
522- }
523- }
524 }250 }
525 251
526 #[tokio::test]252 #[tokio::test]
src/domain/chatbot_thread.rsmodified+11 -531
@@ -1,21 +1,16 @@
1 //! A chatbot thread. It only groups turns and carries the ordering key the1 //! A chatbot thread. It only groups turns and carries the ordering key the
2 //! list view sorts on: `updated_at` moves on every new turn, so a user's2 //! list view sorts on: `updated_at` moves on every new turn, so a user's
3 //! threads list newest-activity-first. The turns themselves live in3 //! threads list newest-activity-first. The turns themselves live in
4-//! [`crate::domain::chatbot_message`], and deleting a thread cascades them.4+//! [`crate::db::chatbot_message`], and deleting a thread cascades them; the
5+//! threads' own persistence lives in [`crate::db::chatbot_thread`].
5 6
6-use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};7+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
7 8
8-use crate::constant::{9+use crate::constant::{CHATBOT_THREAD_TABLE, MAX_CHATBOT_THREAD_TITLE_LEN};
9- CHATBOT_THREAD_COUNT_FIELD, CHATBOT_THREAD_TABLE, DEFAULT_MAX_CHATBOT_THREADS,
10- MAX_CHATBOT_THREAD_TITLE_LEN, SETTINGS_KEY, SETTINGS_TABLE,
11-};
12-use crate::database::{Database, transaction_with_retry};
13-use crate::db::cap;
14-use crate::db::page::PagedList;
15 use crate::domain::monotonic_id::next_ulid;10 use crate::domain::monotonic_id::next_ulid;
16 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
17 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
18-use crate::error::{AppError, ValidationError};13+use crate::error::ValidationError;
19 use crate::validate::validate_required;14 use crate::validate::validate_required;
20 15
21 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]16 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -45,82 +40,10 @@ impl ChatbotThreadId {
45 }40 }
46 }41 }
47 }42 }
48-
49-/// Move the thread's `updated_at` **and** run `statement` — a write to a turn
50-/// hanging off that thread — in one transaction, handing back the row it
51-/// returned. [`AppError::NotFound`] means the thread is gone and `statement`
52-/// wrote nothing.
53-///
54-/// The bump is what ties a turn's fate to its thread, and reading the thread
55-/// first does not: [`ChatbotThread::delete`] sweeps `chatbot_message` and drops
56-/// the thread in one transaction, so a create landing after that sweep but
57-/// before its commit reads a thread that is still there (uncommitted) while the
58-/// sweep ran on a snapshot predating the new row — both commit, and the turn
59-/// outlives the thread it was deleted with, readable and deletable by nothing.
60-/// Reads do not conflict; only a write that *moves* a value on a key the delete
61-/// also writes does. That is the shape
62-/// [`bump_menu_and_write`](crate::domain::menu::bump_menu_and_write) and
63-/// [`ExamAnswer::save`](crate::domain::exam_answer::ExamAnswer::save) already
64-/// use, and the sweep's ordering inside the delete stops mattering once it is
65-/// in place.
66-///
67-/// `updated_at` is the value moved, and it doubles as the stamp the thread list
68-/// sorts on — this *is* the activity touch the send path used to issue
69-/// afterwards as a separate, best-effort query whose failure was only logged.
70-/// It is written strictly upwards rather than to `$now`: an `UPDATE` that
71-/// leaves the document unchanged is elided and never reaches the store's write
72-/// set, a turn's two rows are routinely written inside one millisecond, and a
73-/// write that does not happen collides with nothing. The stamp can therefore
74-/// sit a few milliseconds ahead of the clock, which an ordering key does not
75-/// care about.
76-///
77-/// Admissible for [`transaction_with_retry`] as long as `statement` is: the
78-/// `UPDATE`, the `IF`/`THROW` and the `RETURN` can never answer "already
79-/// exists", and neither can a `CREATE` on a freshly minted ULID on a table with
80-/// no `UNIQUE` index — no rival can have aimed at it, and a lost round wrote
81-/// nothing, so re-sending it is the recovery.
82-pub(crate) async fn touch_and_write<T: SurrealValue>(
83- thread: &ChatbotThreadId,
84- statement: &str,
85- mut bindings: Vec<(String, Value)>,
86- db: &Database,
87-) -> Result<Option<T>, AppError> {
88- bindings.push(("conv".into(), thread.record().into_value()));
89- bindings.push(("now".into(), Timestamp::now().as_millis().into_value()));
90- let (mut result, mut errors) = transaction_with_retry(
91- db,
92- &format!(
93- "BEGIN TRANSACTION;
94- LET $touched = (UPDATE $conv SET updated_at = \
95- math::max([$now, updated_at + 1]) RETURN VALUE id);
96- IF array::len($touched) = 0 {{ THROW 'no_thread' }};
97- LET $row = ({statement});
98- RETURN $row;
99- COMMIT TRANSACTION;"
100- ),
101- &bindings,
102- &["no_thread"],
103- )
104- .await?;
105- // An aborted transaction errors *every* slot, most with a generic "not
106- // executed" — only the THROW's own slot names the reason.
107- if errors
108- .values()
109- .any(|error| error.to_string().contains("no_thread"))
110- {
111- return Err(AppError::NotFound);
112- }
113- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
114- return Err(error.into());
115- }
116- // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4.
117- Ok(result.take::<Vec<T>>(4)?.into_iter().next())
118-}
119-
120 /// A user-chosen thread name. Required-and-bounded here; "untitled" is43 /// A user-chosen thread name. Required-and-bounded here; "untitled" is
121 /// `Option<ChatbotThreadTitle>` on the row.44 /// `Option<ChatbotThreadTitle>` on the row.
122 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]45 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
123-pub struct ChatbotThreadTitle(String);46+pub struct ChatbotThreadTitle(pub(crate) String);
124 47
125 impl ChatbotThreadTitle {48 impl ChatbotThreadTitle {
126 pub fn try_new(value: &str) -> Result<Self, ValidationError> {49 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
@@ -135,11 +58,11 @@ impl ChatbotThreadTitle {
135 58
136 #[derive(Debug, Clone, SurrealValue)]59 #[derive(Debug, Clone, SurrealValue)]
137 pub struct ChatbotThread {60 pub struct ChatbotThread {
138- id: ChatbotThreadId,61+ pub(crate) id: ChatbotThreadId,
139- user_id: UserId,62+ pub(crate) user_id: UserId,
140- title: Option<ChatbotThreadTitle>,63+ pub(crate) title: Option<ChatbotThreadTitle>,
141- created_at: Timestamp,64+ pub(crate) created_at: Timestamp,
142- updated_at: Timestamp,65+ pub(crate) updated_at: Timestamp,
143 }66 }
144 67
145 impl ChatbotThread {68 impl ChatbotThread {
@@ -162,454 +85,11 @@ impl ChatbotThread {
162 pub fn get_updated_at(&self) -> Timestamp {85 pub fn get_updated_at(&self) -> Timestamp {
163 self.updated_at86 self.updated_at
164 }87 }
165-
166- /// Start a thread unless `user` is already at the school's
167- /// `max_chatbot_threads`. The slot is taken on the user row in the same
168- /// transaction as the thread ([`cap::claim_live_and_create`]) — an atomic
169- /// single-record write, so two requests racing the same user's last slot
170- /// cannot both win and the counter can never count a row that did not
171- /// commit.
172- ///
173- /// The cap is the one *live* on the settings singleton, sub-queried inside
174- /// that same conditional write rather than bound as a number: this cap does
175- /// not live on the parent row (the seat is on the user, the limit is the
176- /// school's), and a snapshot of it admits every request already in flight
177- /// when a `PATCH /settings` lowers it. The subquery costs one extra record
178- /// read per claim on a path that already reads the row it writes.
179- /// `DEFAULT_MAX_CHATBOT_THREADS` is the fallback the settings row's own
180- /// absent column means — no row, or a school that never set the knob.
181- pub async fn create_capped(
182- user: &UserId,
183- title: Option<ChatbotThreadTitle>,
184- db: &Database,
185- ) -> Result<ChatbotThread, AppError> {
186- let now = Timestamp::now();
187- let thread = ChatbotThread {
188- id: ChatbotThreadId::generate(),
189- user_id: user.clone(),
190- title,
191- created_at: now,
192- updated_at: now,
193- };
194- match cap::claim_live_and_create(
195- &user.record(),
196- CHATBOT_THREAD_COUNT_FIELD,
197- &format!(
198- "(SELECT VALUE max_chatbot_threads FROM ONLY {SETTINGS_TABLE}:{SETTINGS_KEY}) ?? $num"
199- ),
200- DEFAULT_MAX_CHATBOT_THREADS,
201- // No holder claim: the parent row *is* the user's, so this write
202- // already lands on the key a role change writes.
203- None,
204- (&thread.id.record(), &thread),
205- db,
206- )
207- .await?
208- {
209- cap::Claimed::Made(saved) => Ok(saved),
210- // Full, or the user's row is gone — the conditional write matches
211- // nothing either way.
212- cap::Claimed::Full => Err(AppError::Conflict(
213- "you have reached the school's limit on saved threads — delete one first",
214- )),
215- // The id is a freshly minted ULID on a table with no UNIQUE index,
216- // so no rival can have aimed at it.
217- cap::Claimed::Duplicate => Err(AppError::Internal("thread id collided".into())),
218- }
219- }
220-
221- /// A user's threads, most recently active first — the sort the
222- /// `chatbot_thread_user_updated` index exists for.
223- pub async fn list_for_user(
224- user: &UserId,
225- limit: Option<i64>,
226- offset: i64,
227- db: &Database,
228- ) -> Result<(Vec<ChatbotThread>, i64), AppError> {
229- PagedList::new(
230- "chatbot_thread WHERE user_id = $usr",
231- "ORDER BY updated_at DESC, id DESC",
232- )
233- .bind("usr", user.record())
234- .run(limit, offset, db)
235- .await
236- }
237-
238- /// How many threads `user` keeps — the `max_chatbot_threads` cap check.
239- pub async fn count_for_user(user: &UserId, db: &Database) -> Result<usize, AppError> {
240- let mut result = db
241- .query("SELECT VALUE count() FROM chatbot_thread WHERE user_id = $usr GROUP ALL")
242- .bind(("usr", user.record()))
243- .await?
244- .check()?;
245- Ok(result
246- .take::<Vec<i64>>(0)?
247- .first()
248- .copied()
249- .unwrap_or_default()
250- .max(0) as usize)
251- }
252-
253- /// Read a thread only if `user` owns it — a foreign id reads as absent, so
254- /// the web layer answers 404 rather than leaking that it exists.
255- pub async fn read_for(
256- id: &ChatbotThreadId,
257- user: &UserId,
258- db: &Database,
259- ) -> Result<Option<ChatbotThread>, AppError> {
260- let thread: Option<ChatbotThread> = db.select(id.record()).await?;
261- Ok(thread.filter(|thread| &thread.user_id == user))
262- }
263-
264- // Stamping new activity is not a call of its own: it is the bump inside
265- // [`touch_and_write`], which every turn already rides, so a stamp can no
266- // longer be lost (it used to be a best-effort query after the two creates,
267- // whose failure was a `warn!`) and no turn can be written without it.
268-
269- /// Rename the thread (`None` clears the name back to untitled), stamping
270- /// the edit as activity. Field-scoped for the same reason as
271- /// [`ChatbotThread::touch`]: a turn may be landing concurrently.
272- pub async fn rename(
273- &self,
274- title: Option<ChatbotThreadTitle>,
275- db: &Database,
276- ) -> Result<ChatbotThread, AppError> {
277- let mut result = db
278- .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER")
279- .bind(("id", self.id.record()))
280- .bind(("title", title.map(|title| title.0)))
281- .bind(("now", Timestamp::now().as_millis()))
282- .await?
283- .check()?;
284- result
285- .take::<Vec<ChatbotThread>>(0)?
286- .into_iter()
287- .next()
288- .ok_or(AppError::NotFound)
289- }
290-
291- /// Delete the thread and every turn in it — one transaction, so a crash
292- /// can't orphan messages under a vanished thread. The owner's slot comes
293- /// back in that same transaction, or the cap would ratchet shut.
294- ///
295- /// A turn, a rename and this delete all write the thread row (see
296- /// [`touch_and_write`]), so the store aborting one of them is ordinary
297- /// here — that collision is exactly what keeps a turn from outliving the
298- /// thread — and a lost round is re-sent rather than reported as the `500`
299- /// it used to be. Re-sending is sound: every statement is a `DELETE` or a
300- /// field-scoped `UPDATE`, none of which can ever answer "already exists"
301- /// (see [`transaction_with_retry`]). On the re-sent round the thread is
302- /// already gone, so the `RETURN` is empty and the caller gets the `404`
303- /// that is the truth.
304- pub async fn delete(self, db: &Database) -> Result<ChatbotThread, AppError> {
305- let (mut result, mut errors) = transaction_with_retry(
306- db,
307- "BEGIN TRANSACTION;
308- DELETE chatbot_message WHERE thread_id = $conv;
309- LET $gone = (DELETE $conv RETURN BEFORE);
310- UPDATE $usr SET chatbot_thread_count = math::max([(chatbot_thread_count ?? 0) - array::len($gone), 0]);
311- RETURN $gone;
312- COMMIT TRANSACTION;",
313- &[
314- ("conv".into(), self.id.record().into_value()),
315- ("usr".into(), self.user_id.record().into_value()),
316- ],
317- &[],
318- )
319- .await?;
320- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
321- return Err(error.into());
322- }
323- // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN
324- // is slot 4.
325- let deleted: Option<ChatbotThread> =
326- result.take::<Vec<ChatbotThread>>(4)?.into_iter().next();
327- deleted.ok_or(AppError::NotFound)
328- }
329 }88 }
330 89
331 #[cfg(test)]90 #[cfg(test)]
332 mod tests {91 mod tests {
333 use super::*;92 use super::*;
334- use crate::domain::settings::{Settings, SettingsParams};
335-
336- /// The owner's counter and the threads it counts, both re-read out of the
337- /// store — never off a return value, which the in-memory engine forges
338- /// wins on (see [`cap`]).
339- async fn stored(db: &Database) -> (i64, usize) {
340- let mut result = db
341- .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u")
342- .query("SELECT VALUE id FROM chatbot_thread")
343- .await
344- .unwrap()
345- .check()
346- .unwrap();
347- let counter = result.take::<Vec<i64>>(0).unwrap();
348- let rows = result.take::<Vec<RecordId>>(1).unwrap();
349- (counter[0], rows.len())
350- }
351-
352- async fn a_user_capped_at(threads: i64) -> Database {
353- let db = crate::database::init_mem().await.unwrap();
354- db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
355- .await
356- .unwrap()
357- .check()
358- .unwrap();
359- crate::db::settings::save(
360- &db,
361- Settings::try_new(SettingsParams {
362- max_chatbot_threads: threads,
363- ..Settings::defaults().params()
364- })
365- .unwrap(),
366- )
367- .await
368- .unwrap();
369- db
370- }
371-
372- /// The seat and the row commit together, so the counter the cap reads can
373- /// never disagree with the threads it counts — and a create refused at the
374- /// cap advances neither.
375- #[tokio::test]
376- async fn a_capped_create_moves_the_counter_with_the_row() {
377- let db = a_user_capped_at(1).await;
378- let user = UserId::from_key("u");
379-
380- ChatbotThread::create_capped(&user, None, &db)
381- .await
382- .expect("first thread");
383- assert_eq!(stored(&db).await, (1, 1));
384-
385- let refused = ChatbotThread::create_capped(&user, None, &db).await;
386- assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap");
387- assert_eq!(
388- stored(&db).await,
389- (1, 1),
390- "a refused create advances neither"
391- );
392- }
393-
394- /// A turn is written *through* its thread's row, so a thread that is gone
395- /// takes the write with it — and one that is there is stamped by it.
396- /// The race this shape exists to close is the `#[ignore]`d test below;
397- /// this one pins the logic, which the in-memory engine can answer.
398- #[tokio::test]
399- async fn a_turn_writes_its_thread_and_dies_with_it() {
400- use crate::domain::chatbot_message::{ChatContent, ChatbotMessage};
401-
402- let db = a_user_capped_at(2).await;
403- let user = UserId::from_key("u");
404- let thread = ChatbotThread::create_capped(&user, None, &db)
405- .await
406- .expect("thread");
407- let opened = thread.get_updated_at().as_millis();
408-
409- let say = || ChatContent::try_new("selam").unwrap();
410- ChatbotMessage::append_user(thread.get_id(), &user, say(), &db)
411- .await
412- .expect("append");
413- let stamped = ChatbotThread::read_for(thread.get_id(), &user, &db)
414- .await
415- .expect("re-read")
416- .expect("still there")
417- .get_updated_at()
418- .as_millis();
419- // Strictly upwards, never merely re-stamped: an `UPDATE` that leaves
420- // the row unchanged is elided, and both rows of a turn are routinely
421- // written inside one millisecond of the thread's own creation.
422- assert!(stamped > opened, "{stamped} !> {opened}");
423-
424- let id = thread.get_id().clone();
425- thread.delete(&db).await.expect("delete");
426- let orphan = ChatbotMessage::append_user(&id, &user, say(), &db).await;
427- assert!(
428- matches!(orphan, Err(AppError::NotFound)),
429- "a turn on a deleted thread must be refused: {orphan:?}"
430- );
431- assert_eq!(
432- ChatbotMessage::list_for_thread(&id, None, 0, &db)
433- .await
434- .expect("list")
435- .1,
436- 0,
437- "the refused turn wrote nothing"
438- );
439- }
440-
441- /// The stamp moves **strictly upwards**, never to the clock — the property
442- /// the whole shape rests on, since an `UPDATE` that leaves the row
443- /// unchanged is elided, never reaches the store's write set, and so
444- /// collides with the racing delete not at all.
445- ///
446- /// The test above cannot see it: it compares one append against
447- /// `create_capped`, which costs a millisecond or so on its own, and a plain
448- /// `$now` clears that. Nor can a burst of appends — each is a transaction
449- /// of its own and takes about as long, so the clock has moved on by the
450- /// time the next one reads it. Timing cannot reach the window on demand.
451- ///
452- /// So the *state* the window produces is set up directly instead: a stamp
453- /// **ahead of the clock**, which is precisely what `math::max` leaves
454- /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a
455- /// contrived one. From there the two rules are told apart with no race at
456- /// all — upwards keeps climbing off the stored value, the clock drags the
457- /// stamp back down to itself. The lead is a second, far more than two
458- /// writes can burn, and the guard below fails loudly rather than vacuously
459- /// on a machine that manages to burn it.
460- #[tokio::test]
461- async fn a_stamp_ahead_of_the_clock_still_climbs() {
462- use crate::domain::chatbot_message::{ChatContent, ChatbotMessage};
463-
464- const LEAD: i64 = 1_000;
465-
466- let db = a_user_capped_at(1).await;
467- let user = UserId::from_key("u");
468- let thread = ChatbotThread::create_capped(&user, None, &db)
469- .await
470- .expect("thread");
471-
472- let parked = Timestamp::now().as_millis() + LEAD;
473- db.query("UPDATE $id SET updated_at = $parked")
474- .bind(("id", thread.get_id().record()))
475- .bind(("parked", parked))
476- .await
477- .unwrap()
478- .check()
479- .unwrap();
480-
481- for _ in 0..2 {
482- ChatbotMessage::append_user(
483- thread.get_id(),
484- &user,
485- ChatContent::try_new("selam").unwrap(),
486- &db,
487- )
488- .await
489- .expect("append");
490- }
491- let stamped = ChatbotThread::read_for(thread.get_id(), &user, &db)
492- .await
493- .expect("re-read")
494- .expect("still there")
495- .get_updated_at()
496- .as_millis();
497-
498- assert!(
499- Timestamp::now().as_millis() < parked,
500- "the clock caught the {LEAD}ms lead up during two appends, so this \
501- probe proves nothing"
502- );
503- assert_eq!(
504- stamped,
505- parked + 2,
506- "two appends off a stamp of {parked} must leave {}: a stamp that \
507- follows the clock instead is one an unchanged-row UPDATE elides",
508- parked + 2
509- );
510- }
511-
512- /// No turn may survive the delete that swept its thread. An orphan is not
513- /// litter: nothing sweeps `chatbot_message` afterwards, and both
514- /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered
515- /// `200` with the text of a thread the user had deleted.
516- ///
517- /// The window is between [`ChatbotThread::delete`]'s sweep and its commit:
518- /// a create landing in there reads a thread that is still present
519- /// (uncommitted) while the sweep ran on a snapshot predating the new row,
520- /// so both commit. It is closed by making the create **write** the thread
521- /// row ([`touch_and_write`]) instead of reading it — the two transactions
522- /// then touch one key and the store refuses to commit both.
523- ///
524- /// The window is opened by the database itself rather than by a lucky
525- /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the
526- /// delete's own transaction, the instant the row goes, so the `SLEEP` lands
527- /// after the message sweep and before the commit every single time.
528- ///
529- /// Real server, and `#[ignore]`d for it: the subject is the store's
530- /// conflict detection, which `init_mem`'s embedded engine does not have —
531- /// it commits both writes and answers `Ok` to each, which would fail this
532- /// test on correct code (see [`crate::database::init_test_server`]).
533- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
534- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
535- async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {
536- use crate::domain::chatbot_message::{ChatContent, ChatbotMessage};
537-
538- let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await;
539- db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
540- .await
541- .unwrap()
542- .check()
543- .unwrap();
544- // Hold the delete open for a full second after the thread row is gone,
545- // while its transaction still has to commit.
546- db.query(
547- "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \
548- THEN { SLEEP 1s; };",
549- )
550- .await
551- .unwrap()
552- .check()
553- .unwrap();
554-
555- let user = UserId::from_key("u");
556- let (mut orphans, mut swept) = (0, 0);
557- for round in 0..4 {
558- let thread = ChatbotThread::create_capped(&user, None, &db)
559- .await
560- .expect("thread");
561- let id = thread.get_id().clone();
562-
563- let drop_it = {
564- let db = db.clone();
565- tokio::spawn(async move { thread.delete(&db).await })
566- };
567- // The turn starts inside the held window — the thread row is gone
568- // but uncommitted, which is exactly what a read believes.
569- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
570- let turn = {
571- let (id, db, user) = (id.clone(), db.clone(), user.clone());
572- tokio::spawn(async move {
573- ChatbotMessage::append_user(
574- &id,
575- &user,
576- ChatContent::try_new("selam").unwrap(),
577- &db,
578- )
579- .await
580- .map(|_| ())
581- })
582- };
583- let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap());
584- // A 404 for the turn, or a NotFound for the delete, is a correct
585- // answer — the only defect is stored state.
586- assert!(
587- !matches!(turn, Err(AppError::Db(_))),
588- "round {round}: a raced turn must be answered, not 500: {turn:?}"
589- );
590-
591- // Stored state is the whole verdict; a return value is not evidence.
592- if ChatbotThread::read_for(&id, &user, &db)
593- .await
594- .unwrap()
595- .is_none()
596- {
597- swept += 1;
598- orphans += ChatbotMessage::list_for_thread(&id, None, 0, &db)
599- .await
600- .unwrap()
601- .1;
602- } else if drop_it.is_ok() {
603- panic!("round {round}: the delete reported success but the thread is still there");
604- }
605- }
606- eprintln!("ChatbotThread::delete raced by a turn: {swept}/4 rounds deleted the thread");
607- assert!(
608- swept > 0,
609- "no round ever deleted the thread, so the window was never reached"
610- );
611- assert_eq!(orphans, 0, "a turn outlived its thread");
612- }
613 93
614 #[tokio::test]94 #[tokio::test]
615 async fn title_is_required_and_bounded() {95 async fn title_is_required_and_bounded() {
src/domain/rag_output.rsmodified+16 -262
@@ -6,30 +6,30 @@
6 //!6 //!
7 //! Derived data, so it is disposable: the note is the source of truth and a7 //! Derived data, so it is disposable: the note is the source of truth and a
8 //! row here can be dropped and regenerated at any time. It therefore cascades8 //! row here can be dropped and regenerated at any time. It therefore cascades
9-//! from both sides of what it was built from — [`Self::delete_for_note`] when9+//! from both sides of what it was built from —
10-//! the note goes, [`Self::delete_with_source`] when one of the attachments it10+//! [`delete_for_note`](crate::db::rag_output::delete_for_note) when the note
11-//! was built from goes — so a stale output never outlives its input, even in a11+//! goes, [`delete_with_source`](crate::db::rag_output::delete_with_source)
12-//! deployment with no AI service connected.12+//! when one of the attachments it was built from goes — so a stale output
13+//! never outlives its input, even in a deployment with no AI service
14+//! connected. Persistence lives in [`crate::db::rag_output`].
13 15
14 use serde_json::Value;16 use serde_json::Value;
15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};17 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16 18
17 use crate::constant::RAG_OUTPUT_TABLE;19 use crate::constant::RAG_OUTPUT_TABLE;
18-use crate::database::Database;
19 use crate::domain::course::CourseId;20 use crate::domain::course::CourseId;
20 use crate::domain::course_note::CourseNoteId;21 use crate::domain::course_note::CourseNoteId;
21 use crate::domain::course_note_file::CourseNoteFileId;22 use crate::domain::course_note_file::CourseNoteFileId;
22 use crate::domain::monotonic_id::next_ulid;23 use crate::domain::monotonic_id::next_ulid;
23-use crate::db::page::PagedList;
24 use crate::domain::timestamp::Timestamp;24 use crate::domain::timestamp::Timestamp;
25-use crate::error::AppError;
26 25
27 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]26 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
28 pub struct RagOutputId(RecordId);27 pub struct RagOutputId(RecordId);
29 28
30 impl RagOutputId {29 impl RagOutputId {
31 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:30 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:
32- /// a note's outputs list `id DESC` (newest first, [`RagOutput::list_for`]).31+ /// a note's outputs list `id DESC` (newest first,
32+ /// [`list_for`](crate::db::rag_output::list_for)).
33 pub fn generate() -> Self {33 pub fn generate() -> Self {
34 Self(RecordId::new(RAG_OUTPUT_TABLE, next_ulid().to_string()))34 Self(RecordId::new(RAG_OUTPUT_TABLE, next_ulid().to_string()))
35 }35 }
@@ -52,20 +52,20 @@ impl RagOutputId {
52 52
53 #[derive(Debug, Clone, SurrealValue)]53 #[derive(Debug, Clone, SurrealValue)]
54 pub struct RagOutput {54 pub struct RagOutput {
55- id: RagOutputId,55+ pub(crate) id: RagOutputId,
56- course_note: CourseNoteId,56+ pub(crate) course_note: CourseNoteId,
57 /// The note's course, denormalised so a course-wide read needs no join.57 /// The note's course, denormalised so a course-wide read needs no join.
58- course: CourseId,58+ pub(crate) course: CourseId,
59 /// The attachments the output was built from, as they stood at generation59 /// The attachments the output was built from, as they stood at generation
60 /// time. Deleting any one of them drops this row60 /// time. Deleting any one of them drops this row
61- /// ([`Self::delete_with_source`]) rather than leaving an output citing a61+ /// ([`delete_with_source`](crate::db::rag_output::delete_with_source))
62- /// file that no longer exists.62+ /// rather than leaving an output citing a file that no longer exists.
63- sources: Vec<CourseNoteFileId>,63+ pub(crate) sources: Vec<CourseNoteFileId>,
64 /// The service's answer, stored verbatim. Opaque to the backend — it is a64 /// The service's answer, stored verbatim. Opaque to the backend — it is a
65 /// service-owned shape, so this side neither validates nor interprets it,65 /// service-owned shape, so this side neither validates nor interprets it,
66 /// beyond it having to be a JSON **object** (the stored column is one).66 /// beyond it having to be a JSON **object** (the stored column is one).
67- payload: Value,67+ pub(crate) payload: Value,
68- generated_at: Timestamp,68+ pub(crate) generated_at: Timestamp,
69 }69 }
70 70
71 impl RagOutput {71 impl RagOutput {
@@ -92,250 +92,4 @@ impl RagOutput {
92 pub fn get_generated_at(&self) -> Timestamp {92 pub fn get_generated_at(&self) -> Timestamp {
93 self.generated_at93 self.generated_at
94 }94 }
95-
96- /// Store one service output against `note`.
97- pub async fn create(
98- note: &CourseNoteId,
99- course: &CourseId,
100- sources: Vec<CourseNoteFileId>,
101- payload: Value,
102- db: &Database,
103- ) -> Result<RagOutput, AppError> {
104- let row = RagOutput {
105- id: RagOutputId::generate(),
106- course_note: note.clone(),
107- course: course.clone(),
108- sources,
109- payload,
110- generated_at: Timestamp::now(),
111- };
112- // whole-row-save-ok: create of a fresh ULID row built in place — there is no prior row to clobber
113- let created: Option<RagOutput> = db.create(row.id.record()).content(row).await?;
114- created.ok_or_else(|| AppError::Internal("failed to create rag output".into()))
115- }
116-
117- pub async fn read(id: &RagOutputId, db: &Database) -> Result<Option<RagOutput>, AppError> {
118- Ok(db.select(id.record()).await?)
119- }
120-
121- /// A note's outputs, newest first.
122- pub async fn list_for(
123- note: &CourseNoteId,
124- limit: Option<i64>,
125- offset: i64,
126- db: &Database,
127- ) -> Result<(Vec<RagOutput>, i64), AppError> {
128- PagedList::new("rag_output WHERE course_note = $note", "ORDER BY id DESC")
129- .bind("note", note.record())
130- .run(limit, offset, db)
131- .await
132- }
133-
134- pub async fn delete(id: &RagOutputId, db: &Database) -> Result<RagOutput, AppError> {
135- let deleted: Option<RagOutput> = db.delete(id.record()).await?;
136- deleted.ok_or(AppError::NotFound)
137- }
138-
139- /// Cascade: every output of `note`. Deleting none is a success — a note
140- /// no service ever indexed has nothing to drop.
141- pub async fn delete_for_note(note: &CourseNoteId, db: &Database) -> Result<(), AppError> {
142- db.query("DELETE rag_output WHERE course_note = $note")
143- .bind(("note", note.record()))
144- .await?
145- .check()?;
146- Ok(())
147- }
148-
149- /// Newest-wins replace, without a lock: store `payload` first, then drop
150- /// this note's older rows. Two concurrent index tasks can interleave in any
151- /// order and still leave exactly one row — the newest — because ids come
152- /// from the process-wide monotonic generator, so "older" is `id <` the row
153- /// just written and the loser's row is always below the winner's.
154- pub async fn replace_for_note(
155- note: &CourseNoteId,
156- course: &CourseId,
157- sources: Vec<CourseNoteFileId>,
158- payload: Value,
159- db: &Database,
160- ) -> Result<RagOutput, AppError> {
161- let created = Self::create(note, course, sources, payload, db).await?;
162- db.query("DELETE rag_output WHERE course_note = $note AND id < $new")
163- .bind(("note", note.record()))
164- .bind(("new", created.id.record()))
165- .await?
166- .check()?;
167- Ok(created)
168- }
169-
170- /// Cascade: every output built from `file`. Runs on a file delete even
171- /// with no AI service connected, so a stale output cannot survive its
172- /// source.
173- pub async fn delete_with_source(
174- file: &CourseNoteFileId,
175- db: &Database,
176- ) -> Result<(), AppError> {
177- db.query("DELETE rag_output WHERE sources CONTAINS $file")
178- .bind(("file", file.record()))
179- .await?
180- .check()?;
181- Ok(())
182- }
183-}
184-
185-#[cfg(test)]
186-mod tests {
187- use super::*;
188- use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
189- use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle};
190- use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName};
191- use serde_json::json;
192-
193- async fn note_of(db: &Database, title: &str) -> CourseNote {
194- let creator = crate::domain::user::UserId::generate();
195- let course = crate::db::course::create(
196- db,
197- &creator,
198- CourseTitle::try_new("c").unwrap(),
199- CourseDescription::try_new("").unwrap(),
200- CourseKind::try_new("course").unwrap(),
201- None,
202- None,
203- )
204- .await
205- .unwrap();
206- CourseNote::create(
207- course.get_id(),
208- &creator,
209- CourseNoteTitle::try_new(title).unwrap(),
210- CourseNoteContent::try_new("body").unwrap(),
211- db,
212- )
213- .await
214- .unwrap()
215- }
216-
217- async fn file_on(db: &Database, note: &CourseNoteId) -> CourseNoteFileId {
218- CourseNoteFile::new(
219- note,
220- FileName::try_new("plan.pdf").unwrap(),
221- FileContentType::try_new("application/pdf").unwrap(),
222- 3,
223- )
224- .insert(db)
225- .await
226- .unwrap()
227- .get_id()
228- .clone()
229- }
230-
231- /// Replace converges on one row — the newest — even when an earlier
232- /// interleaving already left two rows behind for the note.
233- #[tokio::test]
234- async fn replace_keeps_only_the_newest_output() {
235- let db = crate::database::init_mem().await.unwrap();
236- let note = note_of(&db, "a").await;
237- let stale = RagOutput::create(
238- note.get_id(),
239- note.get_course(),
240- Vec::new(),
241- json!({ "n": 1 }),
242- &db,
243- )
244- .await
245- .unwrap();
246- // The race this fixes: a second row for the same note.
247- RagOutput::create(
248- note.get_id(),
249- note.get_course(),
250- Vec::new(),
251- json!({ "n": 2 }),
252- &db,
253- )
254- .await
255- .unwrap();
256-
257- let fresh = RagOutput::replace_for_note(
258- note.get_id(),
259- note.get_course(),
260- Vec::new(),
261- json!({ "n": 3 }),
262- &db,
263- )
264- .await
265- .unwrap();
266-
267- let rows = RagOutput::list_for(note.get_id(), None, 0, &db)
268- .await
269- .unwrap()
270- .0;
271- assert_eq!(rows.len(), 1);
272- assert_eq!(rows[0].get_id(), fresh.get_id());
273- assert!(fresh.get_id().key() > stale.get_id().key());
274- }
275-
276- /// The payload survives the round trip unread, and both cascades take only
277- /// what they are aimed at.
278- #[tokio::test]
279- async fn outputs_round_trip_and_cascade() {
280- let db = crate::database::init_mem().await.unwrap();
281- let note = note_of(&db, "a").await;
282- let other = note_of(&db, "b").await;
283- let file = file_on(&db, note.get_id()).await;
284-
285- let stored = RagOutput::create(
286- note.get_id(),
287- note.get_course(),
288- vec![file.clone()],
289- json!({ "summary": "x", "chunks": [{ "text": "y" }] }),
290- &db,
291- )
292- .await
293- .unwrap();
294- let read = RagOutput::read(stored.get_id(), &db)
295- .await
296- .unwrap()
297- .unwrap();
298- assert_eq!(read.get_payload()["summary"], "x");
299- assert_eq!(read.get_payload()["chunks"][0]["text"], "y");
300- assert_eq!(read.get_sources(), std::slice::from_ref(&file));
301- assert_eq!(read.get_course(), note.get_course());
302-
303- let untouched = RagOutput::create(
304- other.get_id(),
305- other.get_course(),
306- Vec::new(),
307- json!({ "summary": "z" }),
308- &db,
309- )
310- .await
311- .unwrap();
312-
313- let listed = async |note: &CourseNoteId| {
314- RagOutput::list_for(note, None, 0, &db)
315- .await
316- .unwrap()
317- .0
318- .len()
319- };
320- assert_eq!(listed(note.get_id()).await, 1);
321-
322- // Losing a source drops the output that cited it, and nothing else.
323- RagOutput::delete_with_source(&file, &db).await.unwrap();
324- assert_eq!(listed(note.get_id()).await, 0);
325- assert_eq!(listed(other.get_id()).await, 1);
326-
327- // Cascading a note with no outputs left is still a success.
328- RagOutput::delete_for_note(note.get_id(), &db)
329- .await
330- .unwrap();
331- RagOutput::delete_for_note(other.get_id(), &db)
332- .await
333- .unwrap();
334- assert!(
335- RagOutput::read(untouched.get_id(), &db)
336- .await
337- .unwrap()
338- .is_none()
339- );
340- }
341 }95 }
src/service/chatbot_message.rsadded+97 -0
@@ -0,0 +1,97 @@
1+//! Chatbot message workflows: the turns of a thread. Sending is
2+//! asynchronous by design — the send path writes the user's prompt plus a
3+//! `pending` assistant row and answers at once; the answering task settles
4+//! that row later with [`complete`] or [`fail`], and the read paths present
5+//! a long-stale `pending` as failed via the domain's read-time projection
6+//! (see [`ChatbotMessage::projected`]). The queries live in
7+//! [`crate::db::chatbot_message`].
8+
9+use crate::database::Database;
10+use crate::db::chatbot_message;
11+use crate::domain::chatbot_message::{ChatContent, ChatbotMessage, ChatbotMessageId};
12+use crate::domain::chatbot_thread::ChatbotThreadId;
13+use crate::domain::user::UserId;
14+use crate::error::AppError;
15+
16+/// Append the user's prompt. Nothing is awaited for it, so it is born
17+/// complete.
18+pub async fn append_user(
19+ db: &Database,
20+ thread: &ChatbotThreadId,
21+ user: &UserId,
22+ content: ChatContent,
23+) -> Result<ChatbotMessage, AppError> {
24+ chatbot_message::append_user(db, thread, user, content).await
25+}
26+
27+/// Reserve the assistant's answer *before* the AI call: the row exists,
28+/// empty and `pending`, so a reload finds the turn and can wait on it.
29+pub async fn append_pending_assistant(
30+ db: &Database,
31+ thread: &ChatbotThreadId,
32+ user: &UserId,
33+) -> Result<ChatbotMessage, AppError> {
34+ chatbot_message::append_pending_assistant(db, thread, user).await
35+}
36+
37+/// The whole thread, oldest first — the order both the UI and the AI
38+/// history payload read in.
39+pub async fn list_for_thread(
40+ db: &Database,
41+ thread: &ChatbotThreadId,
42+ limit: Option<i64>,
43+ offset: i64,
44+) -> Result<(Vec<ChatbotMessage>, i64), AppError> {
45+ chatbot_message::list_for_thread(db, thread, limit, offset).await
46+}
47+
48+/// The last `limit` *settled* turns that carry text, still oldest-first —
49+/// the tail replayed to the AI service as context.
50+pub async fn list_settled_tail(
51+ db: &Database,
52+ thread: &ChatbotThreadId,
53+ limit: usize,
54+) -> Result<Vec<ChatbotMessage>, AppError> {
55+ chatbot_message::list_settled_tail(db, thread, limit).await
56+}
57+
58+/// The user turn a reserved answer belongs to, by *identity*: the prompt
59+/// row of the very POST that reserved it, whose id the answering task
60+/// carries.
61+pub async fn prompt_of(
62+ db: &Database,
63+ id: &ChatbotMessageId,
64+) -> Result<Option<ChatbotMessage>, AppError> {
65+ chatbot_message::prompt_of(db, id).await
66+}
67+
68+/// Read one turn only if `user` owns it — the poll loop's read.
69+pub async fn read_for(
70+ db: &Database,
71+ id: &ChatbotMessageId,
72+ user: &UserId,
73+) -> Result<Option<ChatbotMessage>, AppError> {
74+ chatbot_message::read_for(db, id, user).await
75+}
76+
77+/// Land the answer, recording whether it had to be clipped to fit the
78+/// school's cap. Gated on `status = 'pending'`, so a late reply can't
79+/// overwrite a row that was already failed.
80+pub async fn complete(
81+ db: &Database,
82+ id: &ChatbotMessageId,
83+ text: ChatContent,
84+ truncated: bool,
85+) -> Result<ChatbotMessage, AppError> {
86+ chatbot_message::complete(db, id, text, truncated).await
87+}
88+
89+/// Mark the answer failed with a short code (`unavailable`, the service's
90+/// own error code, …). Same pending gate as [`complete`].
91+pub async fn fail(
92+ db: &Database,
93+ id: &ChatbotMessageId,
94+ error_code: &str,
95+) -> Result<ChatbotMessage, AppError> {
96+ chatbot_message::fail(db, id, error_code).await
97+}
src/service/chatbot_thread.rsadded+59 -0
@@ -0,0 +1,59 @@
1+//! Chatbot thread workflows: the create, rename and delete paths the
2+//! chatbot surface drives, all scoped to the owning user — a foreign id
3+//! reads as absent. The queries live in [`crate::db::chatbot_thread`].
4+
5+use crate::database::Database;
6+use crate::db::chatbot_thread;
7+use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
8+use crate::domain::user::UserId;
9+use crate::error::AppError;
10+
11+/// Start a thread unless `user` is already at the school's
12+/// `max_chatbot_threads` (409 at the cap — the cap is storage protection,
13+/// not a usage quota). The cap check and the row write are one atomic
14+/// conditional write, so two requests racing the same user's last slot
15+/// cannot both win.
16+pub async fn create_capped(
17+ db: &Database,
18+ user: &UserId,
19+ title: Option<ChatbotThreadTitle>,
20+) -> Result<ChatbotThread, AppError> {
21+ chatbot_thread::create_capped(db, user, title).await
22+}
23+
24+/// The caller's own threads, most recently active first.
25+pub async fn list_for_user(
26+ db: &Database,
27+ user: &UserId,
28+ limit: Option<i64>,
29+ offset: i64,
30+) -> Result<(Vec<ChatbotThread>, i64), AppError> {
31+ chatbot_thread::list_for_user(db, user, limit, offset).await
32+}
33+
34+/// Read a thread only if `user` owns it — a foreign id reads as absent, so
35+/// the web layer answers 404 rather than leaking that it exists.
36+pub async fn read_for(
37+ db: &Database,
38+ id: &ChatbotThreadId,
39+ user: &UserId,
40+) -> Result<Option<ChatbotThread>, AppError> {
41+ chatbot_thread::read_for(db, id, user).await
42+}
43+
44+/// Rename the thread (`None` clears the name back to untitled), stamping
45+/// the edit as activity so the thread moves to the top of the list.
46+pub async fn rename(
47+ db: &Database,
48+ thread: &ChatbotThread,
49+ title: Option<ChatbotThreadTitle>,
50+) -> Result<ChatbotThread, AppError> {
51+ chatbot_thread::rename(db, thread, title).await
52+}
53+
54+/// Delete the thread and every turn in it — one transaction, so a crash
55+/// can't orphan messages under a vanished thread — and give the owner's
56+/// cap slot back in the same transaction.
57+pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThread, AppError> {
58+ chatbot_thread::delete(db, thread).await
59+}
src/service/mod.rsmodified+3 -0
@@ -5,6 +5,8 @@ pub mod appointment;
5 pub mod appointment_slot;5 pub mod appointment_slot;
6 pub mod badge;6 pub mod badge;
7 pub mod builder;7 pub mod builder;
8+pub mod chatbot_message;
9+pub mod chatbot_thread;
8 pub mod class_blueprint;10 pub mod class_blueprint;
9 pub mod course;11 pub mod course;
10 pub mod course_session;12 pub mod course_session;
@@ -20,6 +22,7 @@ pub mod parent_link;
20 pub mod payment_ledger;22 pub mod payment_ledger;
21 pub mod pomodoro;23 pub mod pomodoro;
22 pub mod profile;24 pub mod profile;
25+pub mod rag_output;
23 pub mod registration;26 pub mod registration;
24 pub mod session;27 pub mod session;
25 pub mod settings;28 pub mod settings;
src/service/rag_output.rsadded+43 -0
@@ -0,0 +1,43 @@
1+//! RAG-output workflows on the course-notes surface: list a note's outputs,
2+//! read and delete one, and cascade-drop every output of a note or of one
3+//! of its source files. The rows are derived data (the note is the source
4+//! of truth), so every path here is disposable by design. The queries live
5+//! in [`crate::db::rag_output`].
6+
7+use crate::database::Database;
8+use crate::db::rag_output;
9+use crate::domain::course_note::CourseNoteId;
10+use crate::domain::course_note_file::CourseNoteFileId;
11+use crate::domain::rag_output::{RagOutput, RagOutputId};
12+use crate::error::AppError;
13+
14+pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> {
15+ rag_output::read(db, id).await
16+}
17+
18+/// A note's outputs, newest first.
19+pub async fn list_for(
20+ db: &Database,
21+ note: &CourseNoteId,
22+ limit: Option<i64>,
23+ offset: i64,
24+) -> Result<(Vec<RagOutput>, i64), AppError> {
25+ rag_output::list_for(db, note, limit, offset).await
26+}
27+
28+pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> {
29+ rag_output::delete(db, id).await
30+}
31+
32+/// Cascade: every output of `note`. Deleting none is a success — a note
33+/// no service ever indexed has nothing to drop.
34+pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> {
35+ rag_output::delete_for_note(db, note).await
36+}
37+
38+/// Cascade: every output built from `file`. Runs on a file delete even
39+/// with no AI service connected, so a stale output cannot survive its
40+/// source.
41+pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {
42+ rag_output::delete_with_source(db, file).await
43+}
src/web/chatbot.rsmodified+44 -28
@@ -131,7 +131,7 @@ async fn create_thread(
131 // The cap is checked and the row written as one critical section in the131 // The cap is checked and the row written as one critical section in the
132 // domain: counting here and creating after would over-admit under132 // domain: counting here and creating after would over-admit under
133 // concurrency (the database does not serialize a count against inserts).133 // concurrency (the database does not serialize a count against inserts).
134- let thread = ChatbotThread::create_capped(user.get_id(), title, &st.db).await?;134+ let thread = service::chatbot_thread::create_capped(&st.db, user.get_id(), title).await?;
135 Ok((135 Ok((
136 StatusCode::CREATED,136 StatusCode::CREATED,
137 Json(ChatbotThreadResponse::new(&thread)),137 Json(ChatbotThreadResponse::new(&thread)),
@@ -159,7 +159,7 @@ async fn list_threads(
159 ) -> Result<Json<Page<ChatbotThreadResponse>>, AppError> {159 ) -> Result<Json<Page<ChatbotThreadResponse>>, AppError> {
160 let (limit, offset) = page.resolve()?;160 let (limit, offset) = page.resolve()?;
161 let (threads, total) =161 let (threads, total) =
162- ChatbotThread::list_for_user(user.get_id(), limit, offset, &st.db).await?;162+ service::chatbot_thread::list_for_user(&st.db, user.get_id(), limit, offset).await?;
163 let items = threads.iter().map(ChatbotThreadResponse::new).collect();163 let items = threads.iter().map(ChatbotThreadResponse::new).collect();
164 Ok(Json(Page::new(items, total, limit, offset)))164 Ok(Json(Page::new(items, total, limit, offset)))
165 }165 }
@@ -205,7 +205,7 @@ async fn rename_thread(
205 value => Some(ChatbotThreadTitle::try_new(value)?),205 value => Some(ChatbotThreadTitle::try_new(value)?),
206 };206 };
207 let thread = own_thread(&id, user.get_id(), &st.db).await?;207 let thread = own_thread(&id, user.get_id(), &st.db).await?;
208- let renamed = thread.rename(title, &st.db).await?;208+ let renamed = service::chatbot_thread::rename(&st.db, &thread, title).await?;
209 Ok(Json(ChatbotThreadResponse::new(&renamed)))209 Ok(Json(ChatbotThreadResponse::new(&renamed)))
210 }210 }
211 211
@@ -229,14 +229,14 @@ async fn delete_thread(
229 Path(id): Path<String>,229 Path(id): Path<String>,
230 ) -> Result<StatusCode, AppError> {230 ) -> Result<StatusCode, AppError> {
231 let thread = own_thread(&id, user.get_id(), &st.db).await?;231 let thread = own_thread(&id, user.get_id(), &st.db).await?;
232- thread.delete(&st.db).await?;232+ service::chatbot_thread::delete(&st.db, thread).await?;
233 Ok(StatusCode::NO_CONTENT)233 Ok(StatusCode::NO_CONTENT)
234 }234 }
235 235
236 /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable236 /// Read a thread the caller owns, or `404`. A foreign id is indistinguishable
237 /// from a missing one.237 /// from a missing one.
238 async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result<ChatbotThread, AppError> {238 async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result<ChatbotThread, AppError> {
239- ChatbotThread::read_for(&ChatbotThreadId::from_key(id), user, db)239+ service::chatbot_thread::read_for(db, &ChatbotThreadId::from_key(id), user)
240 .await?240 .await?
241 .ok_or(AppError::NotFound)241 .ok_or(AppError::NotFound)
242 }242 }
@@ -341,7 +341,7 @@ async fn list_messages(
341 let (limit, offset) = page.resolve()?;341 let (limit, offset) = page.resolve()?;
342 let thread = own_thread(&id, user.get_id(), &st.db).await?;342 let thread = own_thread(&id, user.get_id(), &st.db).await?;
343 let (messages, total) =343 let (messages, total) =
344- ChatbotMessage::list_for_thread(thread.get_id(), limit, offset, &st.db).await?;344+ service::chatbot_message::list_for_thread(&st.db, thread.get_id(), limit, offset).await?;
345 let items = messages.iter().map(ChatbotMessageResponse::new).collect();345 let items = messages.iter().map(ChatbotMessageResponse::new).collect();
346 Ok(Json(Page::new(items, total, limit, offset)))346 Ok(Json(Page::new(items, total, limit, offset)))
347 }347 }
@@ -422,9 +422,11 @@ async fn send_message(
422 // creates therefore refuses the second one with a 404 — and the first is422 // creates therefore refuses the second one with a 404 — and the first is
423 // swept by that same delete, so the turn leaves no half of itself behind.423 // swept by that same delete, so the turn leaves no half of itself behind.
424 let prompt =424 let prompt =
425- ChatbotMessage::append_user(thread.get_id(), user.get_id(), content, &st.db).await?;425+ service::chatbot_message::append_user(&st.db, thread.get_id(), user.get_id(), content)
426+ .await?;
426 let answer =427 let answer =
427- ChatbotMessage::append_pending_assistant(thread.get_id(), user.get_id(), &st.db).await?;428+ service::chatbot_message::append_pending_assistant(&st.db, thread.get_id(), user.get_id())
429+ .await?;
428 430
429 let message_id = answer.get_id().key().to_string();431 let message_id = answer.get_id().key().to_string();
430 // Never awaited inline: the bridge round trip can outlast the request432 // Never awaited inline: the bridge round trip can outlast the request
@@ -502,13 +504,13 @@ async fn answer_turn(
502 // This request's own question, read back by id — the text is already504 // This request's own question, read back by id — the text is already
503 // stored, so carrying the id rather than the string keeps the prompt and505 // stored, so carrying the id rather than the string keeps the prompt and
504 // its answer paired however two POSTs on one thread interleave.506 // its answer paired however two POSTs on one thread interleave.
505- let prompt = match ChatbotMessage::prompt_of(&prompt_id, &db).await {507+ let prompt = match service::chatbot_message::prompt_of(&db, &prompt_id).await {
506 Ok(Some(prompt)) => prompt,508 Ok(Some(prompt)) => prompt,
507 Ok(None) => {509 Ok(None) => {
508 // The prompt row is gone — only reachable if the thread was deleted510 // The prompt row is gone — only reachable if the thread was deleted
509 // out from under this task. There is nothing to ask, so settle.511 // out from under this task. There is nothing to ask, so settle.
510 tracing::warn!("chat answer {} has no prompt to send", answer_id.key());512 tracing::warn!("chat answer {} has no prompt to send", answer_id.key());
511- let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await;513+ let _ = service::chatbot_message::fail(&db, &answer_id, "internal").await;
512 return;514 return;
513 }515 }
514 Err(err) => {516 Err(err) => {
@@ -516,7 +518,7 @@ async fn answer_turn(
516 // used to reclaim an unsettled row is gone, so leaving it `pending`518 // used to reclaim an unsettled row is gone, so leaving it `pending`
517 // means a spinner until the 300s stale horizon. Settle it here.519 // means a spinner until the 300s stale horizon. Settle it here.
518 tracing::warn!("could not read the prompt for {}: {err}", answer_id.key());520 tracing::warn!("could not read the prompt for {}: {err}", answer_id.key());
519- let _ = ChatbotMessage::fail(&answer_id, "internal", &db).await;521+ let _ = service::chatbot_message::fail(&db, &answer_id, "internal").await;
520 return;522 return;
521 }523 }
522 };524 };
@@ -532,10 +534,12 @@ async fn answer_turn(
532 )534 )
533 .await535 .await
534 {536 {
535- Ok((text, truncated)) => ChatbotMessage::complete(&answer_id, text, truncated, &db).await,537+ Ok((text, truncated)) => {
538+ service::chatbot_message::complete(&db, &answer_id, text, truncated).await
539+ }
536 Err(code) => {540 Err(code) => {
537 tracing::warn!("chat answer {} failed: {code}", answer_id.key());541 tracing::warn!("chat answer {} failed: {code}", answer_id.key());
538- ChatbotMessage::fail(&answer_id, &code, &db).await542+ service::chatbot_message::fail(&db, &answer_id, &code).await
539 }543 }
540 };544 };
541 match settled {545 match settled {
@@ -624,7 +628,8 @@ async fn history_for(
624 // what "the last `chatbot_history_turns` settled turns" means. +2 so dropping628 // what "the last `chatbot_history_turns` settled turns" means. +2 so dropping
625 // this turn's own two rows cannot shorten it either (only the user one can629 // this turn's own two rows cannot shorten it either (only the user one can
626 // match: the assistant row is still `pending`).630 // match: the assistant row is still `pending`).
627- let tail = ChatbotMessage::list_settled_tail(thread, turns.saturating_add(2), db).await?;631+ let tail =
632+ service::chatbot_message::list_settled_tail(db, thread, turns.saturating_add(2)).await?;
628 let mut history: Vec<ChatTurn> = tail633 let mut history: Vec<ChatTurn> = tail
629 .iter()634 .iter()
630 .filter(|message| !fresh.contains(message.get_id()))635 .filter(|message| !fresh.contains(message.get_id()))
@@ -709,7 +714,7 @@ async fn own_message(
709 db: &Database,714 db: &Database,
710 ) -> Result<ChatbotMessage, AppError> {715 ) -> Result<ChatbotMessage, AppError> {
711 own_thread(thread, user, db).await?;716 own_thread(thread, user, db).await?;
712- ChatbotMessage::read_for(&ChatbotMessageId::from_key(message), user, db)717+ service::chatbot_message::read_for(db, &ChatbotMessageId::from_key(message), user)
713 .await?718 .await?
714 .filter(|message| message.get_thread_id().key() == thread)719 .filter(|message| message.get_thread_id().key() == thread)
715 .ok_or(AppError::NotFound)720 .ok_or(AppError::NotFound)
@@ -769,7 +774,8 @@ async fn stream_message(
769 _ = ticker.tick() => {}774 _ = ticker.tick() => {}
770 _ = tx.closed() => return,775 _ = tx.closed() => return,
771 }776 }
772- let message = match ChatbotMessage::read_for(&message_id, &user_id, &db).await {777+ let message = match service::chatbot_message::read_for(&db, &message_id, &user_id).await
778+ {
773 Ok(Some(message)) => message,779 Ok(Some(message)) => message,
774 // Deleted mid-stream (the thread went away) — say so and stop.780 // Deleted mid-stream (the thread went away) — say so and stop.
775 Ok(None) => {781 Ok(None) => {
@@ -907,33 +913,43 @@ mod tests {
907 let say = |text: String| ChatContent::try_new(&text).unwrap();913 let say = |text: String| ChatContent::try_new(&text).unwrap();
908 914
909 for turn in 0..10 {915 for turn in 0..10 {
910- ChatbotMessage::append_user(&thread, &user, say(format!("soru {turn}")), &db)916+ service::chatbot_message::append_user(&db, &thread, &user, say(format!("soru {turn}")))
911- .await
912- .unwrap();
913- let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db)
914 .await917 .await
915 .unwrap();918 .unwrap();
916- ChatbotMessage::complete(answer.get_id(), say(format!("cevap {turn}")), false, &db)919+ let answer = service::chatbot_message::append_pending_assistant(&db, &thread, &user)
917 .await920 .await
918 .unwrap();921 .unwrap();
922+ service::chatbot_message::complete(
923+ &db,
924+ answer.get_id(),
925+ say(format!("cevap {turn}")),
926+ false,
927+ )
928+ .await
929+ .unwrap();
919 }930 }
920 // Five turns in a row whose answer never landed.931 // Five turns in a row whose answer never landed.
921 for turn in 0..5 {932 for turn in 0..5 {
922- ChatbotMessage::append_user(&thread, &user, say(format!("kayıp {turn}")), &db)933+ service::chatbot_message::append_user(
923- .await934+ &db,
924- .unwrap();935+ &thread,
925- let answer = ChatbotMessage::append_pending_assistant(&thread, &user, &db)936+ &user,
937+ say(format!("kayıp {turn}")),
938+ )
939+ .await
940+ .unwrap();
941+ let answer = service::chatbot_message::append_pending_assistant(&db, &thread, &user)
926 .await942 .await
927 .unwrap();943 .unwrap();
928- ChatbotMessage::fail(answer.get_id(), "timed_out", &db)944+ service::chatbot_message::fail(&db, answer.get_id(), "timed_out")
929 .await945 .await
930 .unwrap();946 .unwrap();
931 }947 }
932 // And this turn's own two rows, which never belong in the history.948 // And this turn's own two rows, which never belong in the history.
933- let prompt = ChatbotMessage::append_user(&thread, &user, say("yeni".into()), &db)949+ let prompt = service::chatbot_message::append_user(&db, &thread, &user, say("yeni".into()))
934 .await950 .await
935 .unwrap();951 .unwrap();
936- let pending = ChatbotMessage::append_pending_assistant(&thread, &user, &db)952+ let pending = service::chatbot_message::append_pending_assistant(&db, &thread, &user)
937 .await953 .await
938 .unwrap();954 .unwrap();
939 let fresh = [prompt.get_id().clone(), pending.get_id().clone()];955 let fresh = [prompt.get_id().clone(), pending.get_id().clone()];
src/web/course_notes.rsmodified+6 -5
@@ -305,7 +305,7 @@ async fn delete_one(
305 // disposable, so failing here leaves the note intact and the 500 truthful,305 // disposable, so failing here leaves the note intact and the 500 truthful,
306 // whereas dropping them after the note would strand every blob on an error306 // whereas dropping them after the note would strand every blob on an error
307 // — and if the note delete then fails, the next change regenerates them.307 // — and if the note delete then fails, the next change regenerates them.
308- RagOutput::delete_for_note(note.get_id(), &st.db).await?;308+ service::rag_output::delete_for_note(&st.db, note.get_id()).await?;
309 // Rows go first (the note delete cascades them), blobs after: a crash in309 // Rows go first (the note delete cascades them), blobs after: a crash in
310 // between strands at worst an unreachable blob, never a row whose blob is310 // between strands at worst an unreachable blob, never a row whose blob is
311 // already gone. The files to unlink come from the delete itself, not a311 // already gone. The files to unlink come from the delete itself, not a
@@ -542,7 +542,7 @@ async fn delete_file(
542 // stale index cannot outlive its source in a deployment with no AI service542 // stale index cannot outlive its source in a deployment with no AI service
543 // at all, and a failure here leaves the file whole instead of stranding its543 // at all, and a failure here leaves the file whole instead of stranding its
544 // blob; the re-index rebuilds from what is left, if a service is connected.544 // blob; the re-index rebuilds from what is left, if a service is connected.
545- RagOutput::delete_with_source(file.get_id(), &st.db).await?;545+ service::rag_output::delete_with_source(&st.db, file.get_id()).await?;
546 let file = file.delete(&st.db).await?;546 let file = file.delete(&st.db).await?;
547 remove_blob(&st.files_path, file.get_id().key()).await;547 remove_blob(&st.files_path, file.get_id().key()).await;
548 spawn_index(&st, &tenant, note);548 spawn_index(&st, &tenant, note);
@@ -612,7 +612,8 @@ async fn list_rag(
612 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's AI outputs",612 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's AI outputs",
613 ));613 ));
614 }614 }
615- let (outputs, total) = RagOutput::list_for(note.get_id(), limit, offset, &st.db).await?;615+ let (outputs, total) =
616+ service::rag_output::list_for(&st.db, note.get_id(), limit, offset).await?;
616 let items = outputs.iter().map(RagOutputResponse::new).collect();617 let items = outputs.iter().map(RagOutputResponse::new).collect();
617 Ok(Json(Page::new(items, total, limit, offset)))618 Ok(Json(Page::new(items, total, limit, offset)))
618 }619 }
@@ -651,10 +652,10 @@ async fn delete_rag(
651 crate::service::course::require_open(&st.db, &course).await?;652 crate::service::course::require_open(&st.db, &course).await?;
652 // Scoped to the note in the path, like `CourseNoteFile::read_for`: an653 // Scoped to the note in the path, like `CourseNoteFile::read_for`: an
653 // output of another note is a 404 here, never a cross-note delete.654 // output of another note is a 404 here, never a cross-note delete.
654- let output = RagOutput::read(&RagOutputId::from_key(&output_id), &st.db)655+ let output = service::rag_output::read(&st.db, &RagOutputId::from_key(&output_id))
655 .await?656 .await?
656 .filter(|output| output.get_course_note() == note.get_id())657 .filter(|output| output.get_course_note() == note.get_id())
657 .ok_or(AppError::NotFound)?;658 .ok_or(AppError::NotFound)?;
658- RagOutput::delete(output.get_id(), &st.db).await?;659+ service::rag_output::delete(&st.db, output.get_id()).await?;
659 Ok(StatusCode::NO_CONTENT)660 Ok(StatusCode::NO_CONTENT)
660 }661 }
tests/ai_bridge.rsmodified+1 -1
@@ -1722,7 +1722,7 @@ use hezarfen_backend::domain::rag_output::RagOutput;
1722 1722
1723 /// Every stored output of `note`, newest first.1723 /// Every stored output of `note`, newest first.
1724 async fn outputs(db: &Database, note: &str) -> Vec<RagOutput> {1724 async fn outputs(db: &Database, note: &str) -> Vec<RagOutput> {
1725- RagOutput::list_for(&CourseNoteId::from_key(note), None, 0, db)1725+ hezarfen_backend::db::rag_output::list_for(&db, &CourseNoteId::from_key(note), None, 0)
1726 .await1726 .await
1727 .expect("list rag outputs")1727 .expect("list rag outputs")
1728 .01728 .0
tests/integration.rsmodified+12 -12
@@ -19,13 +19,11 @@ use hezarfen_backend::db::exam_attempt::any_for_exam;
19 use hezarfen_backend::db::session;19 use hezarfen_backend::db::session;
20 use hezarfen_backend::domain::board::{Board, BoardId};20 use hezarfen_backend::domain::board::{Board, BoardId};
21 use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId};21 use hezarfen_backend::domain::board_stroke::{BoardStroke, BoardStrokeId};
22-use hezarfen_backend::domain::chatbot_message::ChatbotMessage;
23 use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId;22 use hezarfen_backend::domain::chatbot_thread::ChatbotThreadId;
24 use hezarfen_backend::domain::course::CourseId;23 use hezarfen_backend::domain::course::CourseId;
25 use hezarfen_backend::domain::course_note::CourseNoteId;24 use hezarfen_backend::domain::course_note::CourseNoteId;
26 use hezarfen_backend::domain::course_note_file::CourseNoteFileId;25 use hezarfen_backend::domain::course_note_file::CourseNoteFileId;
27 use hezarfen_backend::domain::exam::ExamId;26 use hezarfen_backend::domain::exam::ExamId;
28-use hezarfen_backend::domain::rag_output::RagOutput;
29 use hezarfen_backend::domain::timestamp::Timestamp;27 use hezarfen_backend::domain::timestamp::Timestamp;
30 use hezarfen_backend::domain::user::{Password, User, UserId, Username};28 use hezarfen_backend::domain::user::{Password, User, UserId, Username};
31 use hezarfen_backend::module::ModuleSet;29 use hezarfen_backend::module::ModuleSet;
@@ -16976,12 +16974,14 @@ async fn chat_stream_stops_polling_when_the_client_hangs_up() {
16976 let thread = new_thread(&app, &ali).await;16974 let thread = new_thread(&app, &ali).await;
16977 let me = send(&app, "GET", "/auth/me", Some(&ali), None).await;16975 let me = send(&app, "GET", "/auth/me", Some(&ali), None).await;
16978 let user = UserId::from_key(me.body["id"].as_str().unwrap());16976 let user = UserId::from_key(me.body["id"].as_str().unwrap());
16979- let pending =16977+ let pending = hezarfen_backend::db::chatbot_message::append_pending_assistant(
16980- ChatbotMessage::append_pending_assistant(&ChatbotThreadId::from_key(&thread), &user, &db)16978+ &db,
16981- .await16979+ &ChatbotThreadId::from_key(&thread),
16982- .expect("reserve an assistant row");16980+ &user,
16981+ )
16982+ .await
16983+ .expect("reserve an assistant row");
16983 let mid = pending.get_id().key().to_string();16984 let mid = pending.get_id().key().to_string();
16984-
16985 // The witness is the runtime's task count, so it is read only once the16985 // The witness is the runtime's task count, so it is read only once the
16986 // setup's short-lived database tasks have drained — otherwise one of those16986 // setup's short-lived database tasks have drained — otherwise one of those
16987 // finishing mid-measurement looks like the stream's own task.16987 // finishing mid-measurement looks like the stream's own task.
@@ -27280,22 +27280,22 @@ async fn course_note_rag_outputs_read_and_delete() {
27280 assert_eq!(up.status, StatusCode::CREATED, "{}", up.body);27280 assert_eq!(up.status, StatusCode::CREATED, "{}", up.body);
27281 let file_id = id_of(&up.body);27281 let file_id = id_of(&up.body);
27282 27282
27283- let output = RagOutput::create(27283+ let output = hezarfen_backend::db::rag_output::create(
27284+ &db,
27284 &CourseNoteId::from_key(&note),27285 &CourseNoteId::from_key(&note),
27285 &CourseId::from_key(&course),27286 &CourseId::from_key(&course),
27286 vec![CourseNoteFileId::from_key(&file_id)],27287 vec![CourseNoteFileId::from_key(&file_id)],
27287 json!({ "summary": "acids and bases" }),27288 json!({ "summary": "acids and bases" }),
27288- &db,
27289 )27289 )
27290 .await27290 .await
27291 .unwrap();27291 .unwrap();
27292 let output_id = output.get_id().key().to_string();27292 let output_id = output.get_id().key().to_string();
27293- let sibling_output = RagOutput::create(27293+ let sibling_output = hezarfen_backend::db::rag_output::create(
27294+ &db,
27294 &CourseNoteId::from_key(&sibling),27295 &CourseNoteId::from_key(&sibling),
27295 &CourseId::from_key(&course),27296 &CourseId::from_key(&course),
27296 Vec::new(),27297 Vec::new(),
27297 json!({ "summary": "other" }),27298 json!({ "summary": "other" }),
27298- &db,
27299 )27299 )
27300 .await27300 .await
27301 .unwrap();27301 .unwrap();
@@ -27363,7 +27363,7 @@ async fn course_note_rag_outputs_read_and_delete() {
27363 .await;27363 .await;
27364 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);27364 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
27365 assert!(27365 assert!(
27366- RagOutput::read(sibling_output.get_id(), &db)27366+ hezarfen_backend::db::rag_output::read(&db, sibling_output.get_id())
27367 .await27367 .await
27368 .unwrap()27368 .unwrap()
27369 .is_some()27369 .is_some()
tests/persistence.rsmodified+24 -24
@@ -1065,8 +1065,8 @@ async fn attempt_history_survives_remigration() {
1065 /// second user reads neither the thread nor its messages.1065 /// second user reads neither the thread nor its messages.
1066 #[tokio::test]1066 #[tokio::test]
1067 async fn chat_thread_delete_cascades_and_stays_owner_scoped() {1067 async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
1068- use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage, MessageStatus};1068+ use hezarfen_backend::db::{chatbot_message, chatbot_thread};
1069- use hezarfen_backend::domain::chatbot_thread::ChatbotThread;1069+ use hezarfen_backend::domain::chatbot_message::{ChatContent, MessageStatus};
1070 use hezarfen_backend::domain::user::UserId;1070 use hezarfen_backend::domain::user::UserId;
1071 1071
1072 let (app, db) = common::app_and_db().await;1072 let (app, db) = common::app_and_db().await;
@@ -1075,28 +1075,28 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
1075 let owner = UserId::from_key(&me_id(&app, &owner_cookie).await);1075 let owner = UserId::from_key(&me_id(&app, &owner_cookie).await);
1076 let other = UserId::from_key(&me_id(&app, &other_cookie).await);1076 let other = UserId::from_key(&me_id(&app, &other_cookie).await);
1077 1077
1078- let thread = ChatbotThread::create_capped(&owner, None, &db)1078+ let thread = chatbot_thread::create_capped(&db, &owner, None)
1079 .await1079 .await
1080 .expect("create");1080 .expect("create");
1081 let id = thread.get_id().clone();1081 let id = thread.get_id().clone();
1082- let prompt = ChatbotMessage::append_user(1082+ let prompt = chatbot_message::append_user(
1083+ &db,
1083 &id,1084 &id,
1084 &owner,1085 &owner,
1085 ChatContent::try_new("selam").expect("content"),1086 ChatContent::try_new("selam").expect("content"),
1086- &db,
1087 )1087 )
1088 .await1088 .await
1089 .expect("append user");1089 .expect("append user");
1090- let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db)1090+ let reply = chatbot_message::append_pending_assistant(&db, &id, &owner)
1091 .await1091 .await
1092 .expect("append assistant");1092 .expect("append assistant");
1093 assert_eq!(reply.get_status(), MessageStatus::Pending);1093 assert_eq!(reply.get_status(), MessageStatus::Pending);
1094 1094
1095- let reply = ChatbotMessage::complete(1095+ let reply = chatbot_message::complete(
1096+ &db,
1096 reply.get_id(),1097 reply.get_id(),
1097 ChatContent::try_new("aleykum selam").expect("content"),1098 ChatContent::try_new("aleykum selam").expect("content"),
1098 false,1099 false,
1099- &db,
1100 )1100 )
1101 .await1101 .await
1102 .expect("complete");1102 .expect("complete");
@@ -1104,7 +1104,7 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
1104 assert_eq!(reply.get_content().as_str(), "aleykum selam");1104 assert_eq!(reply.get_content().as_str(), "aleykum selam");
1105 assert!(reply.get_completed_at().is_some());1105 assert!(reply.get_completed_at().is_some());
1106 assert_eq!(1106 assert_eq!(
1107- ChatbotMessage::list_for_thread(&id, None, 0, &db)1107+ chatbot_message::list_for_thread(&db, &id, None, 0)
1108 .await1108 .await
1109 .expect("thread")1109 .expect("thread")
1110 .01110 .0
@@ -1114,39 +1114,39 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
1114 1114
1115 // The other user sees nothing of it, by thread or by message.1115 // The other user sees nothing of it, by thread or by message.
1116 assert!(1116 assert!(
1117- ChatbotThread::read_for(&id, &other, &db)1117+ chatbot_thread::read_for(&db, &id, &other)
1118 .await1118 .await
1119 .expect("cross-user thread")1119 .expect("cross-user thread")
1120 .is_none()1120 .is_none()
1121 );1121 );
1122 assert!(1122 assert!(
1123- ChatbotMessage::read_for(prompt.get_id(), &other, &db)1123+ chatbot_message::read_for(&db, prompt.get_id(), &other)
1124 .await1124 .await
1125 .expect("cross-user message")1125 .expect("cross-user message")
1126 .is_none()1126 .is_none()
1127 );1127 );
1128 assert_eq!(1128 assert_eq!(
1129- ChatbotThread::count_for_user(&other, &db)1129+ chatbot_thread::count_for_user(&db, &other)
1130 .await1130 .await
1131 .expect("count"),1131 .expect("count"),
1132 01132 0
1133 );1133 );
1134 assert_eq!(1134 assert_eq!(
1135- ChatbotThread::count_for_user(&owner, &db)1135+ chatbot_thread::count_for_user(&db, &owner)
1136 .await1136 .await
1137 .expect("count"),1137 .expect("count"),
1138 11138 1
1139 );1139 );
1140 1140
1141- thread.delete(&db).await.expect("delete");1141+ chatbot_thread::delete(&db, thread).await.expect("delete");
1142 assert!(1142 assert!(
1143- ChatbotThread::read_for(&id, &owner, &db)1143+ chatbot_thread::read_for(&db, &id, &owner)
1144 .await1144 .await
1145 .expect("deleted thread")1145 .expect("deleted thread")
1146 .is_none()1146 .is_none()
1147 );1147 );
1148 assert_eq!(1148 assert_eq!(
1149- ChatbotThread::list_for_user(&owner, None, 0, &db)1149+ chatbot_thread::list_for_user(&db, &owner, None, 0)
1150 .await1150 .await
1151 .unwrap()1151 .unwrap()
1152 .01152 .0
@@ -1172,8 +1172,8 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
1172 /// read back as whole, which is exactly how they were shown at the time.1172 /// read back as whole, which is exactly how they were shown at the time.
1173 #[tokio::test]1173 #[tokio::test]
1174 async fn legacy_chat_turns_backfill_to_untruncated() {1174 async fn legacy_chat_turns_backfill_to_untruncated() {
1175- use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage};1175+ use hezarfen_backend::db::{chatbot_message, chatbot_thread};
1176- use hezarfen_backend::domain::chatbot_thread::ChatbotThread;1176+ use hezarfen_backend::domain::chatbot_message::ChatContent;
1177 use hezarfen_backend::domain::user::UserId;1177 use hezarfen_backend::domain::user::UserId;
1178 1178
1179 let (app, db) = common::app_and_db().await;1179 let (app, db) = common::app_and_db().await;
@@ -1190,26 +1190,26 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
1190 .unwrap();1190 .unwrap();
1191 let owner = UserId::from_key(&me_id(&app, &cookie).await);1191 let owner = UserId::from_key(&me_id(&app, &cookie).await);
1192 1192
1193- let thread = ChatbotThread::create_capped(&owner, None, &db)1193+ let thread = chatbot_thread::create_capped(&db, &owner, None)
1194 .await1194 .await
1195 .expect("create");1195 .expect("create");
1196 let id = thread.get_id().clone();1196 let id = thread.get_id().clone();
1197- ChatbotMessage::append_user(1197+ chatbot_message::append_user(
1198+ &db,
1198 &id,1199 &id,
1199 &owner,1200 &owner,
1200 ChatContent::try_new("selam").expect("content"),1201 ChatContent::try_new("selam").expect("content"),
1201- &db,
1202 )1202 )
1203 .await1203 .await
1204 .expect("append user");1204 .expect("append user");
1205- let reply = ChatbotMessage::append_pending_assistant(&id, &owner, &db)1205+ let reply = chatbot_message::append_pending_assistant(&db, &id, &owner)
1206 .await1206 .await
1207 .expect("append assistant");1207 .expect("append assistant");
1208- ChatbotMessage::complete(1208+ chatbot_message::complete(
1209+ &db,
1209 reply.get_id(),1210 reply.get_id(),
1210 ChatContent::try_new("aleykum selam").expect("content"),1211 ChatContent::try_new("aleykum selam").expect("content"),
1211 false,1212 false,
1212- &db,
1213 )1213 )
1214 .await1214 .await
1215 .expect("complete");1215 .expect("complete");
tests/regress_appointments.rsmodified+13 -13
@@ -15,9 +15,9 @@ mod common;
15 15
16 use axum::http::StatusCode;16 use axum::http::StatusCode;
17 use common::{app_and_db, id_of, login, login_as, me_id, send};17 use common::{app_and_db, id_of, login, login_as, me_id, send};
18+use hezarfen_backend::db::{chatbot_message, chatbot_thread};
18 use hezarfen_backend::domain::appointment::AppointmentId;19 use hezarfen_backend::domain::appointment::AppointmentId;
19-use hezarfen_backend::domain::chatbot_message::{ChatContent, ChatbotMessage};20+use hezarfen_backend::domain::chatbot_message::ChatContent;
20-use hezarfen_backend::domain::chatbot_thread::ChatbotThread;
21 use hezarfen_backend::domain::timestamp::Timestamp;21 use hezarfen_backend::domain::timestamp::Timestamp;
22 use hezarfen_backend::domain::user::UserId;22 use hezarfen_backend::domain::user::UserId;
23 use serde_json::json;23 use serde_json::json;
@@ -271,29 +271,29 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() {
271 let (app, db) = app_and_db().await;271 let (app, db) = app_and_db().await;
272 let cookie = login(&app, "veli").await;272 let cookie = login(&app, "veli").await;
273 let owner = UserId::from_key(&me_id(&app, &cookie).await);273 let owner = UserId::from_key(&me_id(&app, &cookie).await);
274- let thread = ChatbotThread::create_capped(&owner, None, &db)274+ let thread = chatbot_thread::create_capped(&db, &owner, None)
275 .await275 .await
276 .expect("create thread");276 .expect("create thread");
277 let id = thread.get_id().clone();277 let id = thread.get_id().clone();
278 let say = |text: &str| ChatContent::try_new(text).expect("content");278 let say = |text: &str| ChatContent::try_new(text).expect("content");
279 279
280 // Exactly the order the interleave produces.280 // Exactly the order the interleave produces.
281- let prompt_a = ChatbotMessage::append_user(&id, &owner, say("soru A"), &db)281+ let prompt_a = chatbot_message::append_user(&db, &id, &owner, say("soru A"))
282 .await282 .await
283 .expect("prompt A");283 .expect("prompt A");
284- let prompt_b = ChatbotMessage::append_user(&id, &owner, say("soru B"), &db)284+ let prompt_b = chatbot_message::append_user(&db, &id, &owner, say("soru B"))
285 .await285 .await
286 .expect("prompt B");286 .expect("prompt B");
287- let answer_a = ChatbotMessage::append_pending_assistant(&id, &owner, &db)287+ let answer_a = chatbot_message::append_pending_assistant(&db, &id, &owner)
288 .await288 .await
289 .expect("answer A");289 .expect("answer A");
290- let answer_b = ChatbotMessage::append_pending_assistant(&id, &owner, &db)290+ let answer_b = chatbot_message::append_pending_assistant(&db, &id, &owner)
291 .await291 .await
292 .expect("answer B");292 .expect("answer B");
293 293
294 // The interleave is real: by write order the newest user row before *both*294 // The interleave is real: by write order the newest user row before *both*
295 // answers is B, which is what used to be handed to both of them.295 // answers is B, which is what used to be handed to both of them.
296- let (stored, _) = ChatbotMessage::list_for_thread(&id, None, 0, &db)296+ let (stored, _) = chatbot_message::list_for_thread(&db, &id, None, 0)
297 .await297 .await
298 .expect("thread");298 .expect("thread");
299 let texts: Vec<&str> = stored299 let texts: Vec<&str> = stored
@@ -304,11 +304,11 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() {
304 304
305 // Identity decides instead, so each answer keeps its own question — the id305 // Identity decides instead, so each answer keeps its own question — the id
306 // the answering task carries is the prompt of its own POST.306 // the answering task carries is the prompt of its own POST.
307- let carried_a = ChatbotMessage::prompt_of(prompt_a.get_id(), &db)307+ let carried_a = chatbot_message::prompt_of(&db, prompt_a.get_id())
308 .await308 .await
309 .expect("read A")309 .expect("read A")
310 .expect("prompt A exists");310 .expect("prompt A exists");
311- let carried_b = ChatbotMessage::prompt_of(prompt_b.get_id(), &db)311+ let carried_b = chatbot_message::prompt_of(&db, prompt_b.get_id())
312 .await312 .await
313 .expect("read B")313 .expect("read B")
314 .expect("prompt B exists");314 .expect("prompt B exists");
@@ -317,13 +317,13 @@ async fn an_answer_resolves_its_own_prompt_across_an_interleave() {
317 317
318 // And the answers each settle with the reply to their own question — the318 // And the answers each settle with the reply to their own question — the
319 // stored state, not just what a lookup returned.319 // stored state, not just what a lookup returned.
320- ChatbotMessage::complete(answer_a.get_id(), say("cevap A"), false, &db)320+ chatbot_message::complete(&db, answer_a.get_id(), say("cevap A"), false)
321 .await321 .await
322 .expect("settle A");322 .expect("settle A");
323- ChatbotMessage::complete(answer_b.get_id(), say("cevap B"), false, &db)323+ chatbot_message::complete(&db, answer_b.get_id(), say("cevap B"), false)
324 .await324 .await
325 .expect("settle B");325 .expect("settle B");
326- let (stored, _) = ChatbotMessage::list_for_thread(&id, None, 0, &db)326+ let (stored, _) = chatbot_message::list_for_thread(&db, &id, None, 0)
327 .await327 .await
328 .expect("thread");328 .expect("thread");
329 let texts: Vec<&str> = stored329 let texts: Vec<&str> = stored