forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

chatbot_thread.rs461 lines, 19.1 KiBHistoryRawDownload
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
7use crate::constant::DEFAULT_MAX_CHATBOT_THREADS;
8use crate::database::{Database, tx_with_retry};
9use crate::db::page::PagedList;
10use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
11use crate::domain::timestamp::Timestamp;
12use crate::domain::user::UserId;
13use crate::error::AppError;
14use sqlx::query_as;
15
16/// Start a thread unless `user` is already at the school's
17/// `max_chatbot_threads`. The claim recipe of one: the slot bump on the
18/// user row, the live cap read, and the thread's insert are a single
19/// statement — two requests racing the same user's last slot cannot both
20/// win, and the counter can never count a row that did not commit.
21///
22/// The cap is the one *live* on the settings singleton, sub-queried inside
23/// that same conditional write rather than bound as a number: this cap does
24/// not live on the parent row (the seat is on the user, the limit is the
25/// school's), and a snapshot of it admits every request already in flight
26/// when a `PATCH /settings` lowers it. `DEFAULT_MAX_CHATBOT_THREADS` is the
27/// fallback the settings row's own NULL means — no row, or a school that
28/// never set the knob.
29///
30/// The seat is taken on the user's own row, which is also the key a role
31/// change writes, so this write already contends with a demotion — no
32/// separate holder claim is needed.
33pub async fn create_capped(
34 db: &Database,
35 user: &UserId,
36 title: Option<ChatbotThreadTitle>,
37) -> Result<ChatbotThread, AppError> {
38 let now = Timestamp::now();
39 match query_as!(
40 ChatbotThread,
41 "WITH seat AS (
42 UPDATE app_user SET chatbot_thread_count = chatbot_thread_count + 1
43 WHERE id = $1
44 AND chatbot_thread_count < COALESCE(
45 (SELECT max_chatbot_threads FROM settings WHERE id = 'school'),
46 $2)
47 RETURNING 1)
48 INSERT INTO chatbot_thread (id, user_id, title, created_at, updated_at)
49 SELECT $3, $1, $4, $5, $5
50 WHERE EXISTS (SELECT 1 FROM seat)
51 RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \
52 created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
53 user.uuid(),
54 DEFAULT_MAX_CHATBOT_THREADS,
55 ChatbotThreadId::generate().uuid(),
56 title.map(|t| t.as_str().to_string()),
57 now.as_millis(),
58 )
59 .fetch_optional(db)
60 .await?
61 {
62 Some(saved) => Ok(saved),
63 // Full, or the user's row is gone — the conditional write matches
64 // nothing either way, as before.
65 None => Err(AppError::Conflict(
66 "you have reached the school's limit on saved threads — delete one first",
67 )),
68 }
69}
70
71/// A user's threads, most recently active first — the sort the
72/// `chatbot_thread_user_updated` index exists for.
73pub async fn list_for_user(
74 db: &Database,
75 user: &UserId,
76 limit: Option<i64>,
77 offset: i64,
78) -> Result<(Vec<ChatbotThread>, i64), AppError> {
79 PagedList::new(
80 "chatbot_thread WHERE user_id = $1",
81 "ORDER BY updated_at DESC, id DESC",
82 )
83 .bind(user.uuid())
84 .run(limit, offset, db)
85 .await
86}
87
88/// How many threads `user` keeps — the `max_chatbot_threads` cap check.
89pub async fn count_for_user(db: &Database, user: &UserId) -> Result<usize, AppError> {
90 let row = sqlx::query!(
91 "SELECT count(*) AS threads FROM chatbot_thread WHERE user_id = $1",
92 user.uuid()
93 )
94 .fetch_one(db)
95 .await?;
96 Ok(row.threads.unwrap_or(0).max(0) as usize)
97}
98
99/// Read a thread only if `user` owns it — a foreign id reads as absent, so
100/// the web layer answers 404 rather than leaking that it exists.
101pub async fn read_for(
102 db: &Database,
103 id: &ChatbotThreadId,
104 user: &UserId,
105) -> Result<Option<ChatbotThread>, AppError> {
106 let thread = query_as!(
107 ChatbotThread,
108 "SELECT id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM chatbot_thread WHERE id = $1",
109 id.uuid()
110 )
111 .fetch_optional(db)
112 .await?;
113 Ok(thread.filter(|thread| &thread.user_id == user))
114}
115
116// Stamping new activity is not a call of its own: it is the monotonic bump
117// inside every write that touches the thread (a turn's insert, the rename,
118// the delete below), so a stamp can no longer be lost (it used to be a
119// best-effort query after the two creates, whose failure was a `warn!`) and
120// no turn can be written without it.
121
122/// Rename the thread (`None` clears the name back to untitled), stamping
123/// the edit as activity. Field-scoped: a turn may be landing concurrently.
124/// The stamp is written strictly upwards — `GREATEST($now, updated_at + 1)`
125/// — because a thread's writes routinely land inside one millisecond and
126/// `updated_at` is the list's ordering key; the stamp may sit a few
127/// milliseconds ahead of the clock, which an ordering key does not care
128/// about. Zero rows: the thread is gone, the same 404 the delete answers.
129pub async fn rename(
130 db: &Database,
131 thread: &ChatbotThread,
132 title: Option<ChatbotThreadTitle>,
133) -> Result<ChatbotThread, AppError> {
134 let updated = query_as!(
135 ChatbotThread,
136 "UPDATE chatbot_thread SET title = $2, updated_at = GREATEST($3, updated_at + 1) \
137 WHERE id = $1 \
138 RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \
139 created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
140 thread.get_id().uuid(),
141 title.map(|t| t.as_str().to_string()),
142 Timestamp::now().as_millis(),
143 )
144 .fetch_optional(db)
145 .await?;
146 updated.ok_or(AppError::NotFound)
147}
148
149/// Delete the thread and every turn in it — one transaction, so a crash
150/// can't orphan messages under a vanished thread. The owner's slot comes
151/// back in that same transaction, or the cap would ratchet shut.
152///
153/// A turn's insert (see [`crate::db::chatbot_message`]) writes *through*
154/// the thread's row — its guarded statement moves `updated_at`, the key
155/// this delete's final write removes — so under Postgres's row locking the
156/// two serialize: either the turn saw the thread and committed first (the
157/// delete then refuses nothing, the sweep takes the turn), or the thread
158/// was gone and the turn's gate matched nothing. No turn outlives its
159/// thread. On a re-sent round the thread is already gone, so the caller
160/// gets the `404` that is the truth.
161pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThread, AppError> {
162 tx_with_retry(db, false, async move |tx| {
163 // Children first: the foreign key would refuse the parent while a
164 // turn still names it.
165 sqlx::query!(
166 "DELETE FROM chatbot_message WHERE thread_id = $1",
167 thread.get_id().uuid()
168 )
169 .execute(&mut *tx)
170 .await?;
171 let gone = query_as!(
172 ChatbotThread,
173 "DELETE FROM chatbot_thread WHERE id = $1 \
174 RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \
175 created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
176 thread.get_id().uuid()
177 )
178 .fetch_optional(&mut *tx)
179 .await?;
180 if let Some(gone) = &gone {
181 sqlx::query!(
182 "UPDATE app_user SET chatbot_thread_count = GREATEST(chatbot_thread_count - 1, 0) \
183 WHERE id = $1",
184 gone.get_user_id().uuid()
185 )
186 .execute(&mut *tx)
187 .await?;
188 }
189 gone.ok_or(AppError::NotFound)
190 })
191 .await
192}
193#[cfg(test)]
194mod tests {
195 use super::*;
196 use surrealdb::types::RecordId;
197
198 use crate::db::chatbot_message;
199 use crate::domain::chatbot_message::ChatContent;
200 use crate::domain::settings::{Settings, SettingsParams};
201
202 /// The owner's counter and the threads it counts, both re-read out of the
203 /// store — never off a return value, which the in-memory engine forges
204 /// wins on (see [`cap`]).
205 async fn stored(db: &Database) -> (i64, usize) {
206 let mut result = db
207 .query("SELECT VALUE (chatbot_thread_count ?? 0) FROM user:u")
208 .query("SELECT VALUE id FROM chatbot_thread")
209 .await
210 .unwrap()
211 .check()
212 .unwrap();
213 let counter = result.take::<Vec<i64>>(0).unwrap();
214 let rows = result.take::<Vec<RecordId>>(1).unwrap();
215 (counter[0], rows.len())
216 }
217
218 async fn a_user_capped_at(threads: i64) -> Database {
219 let db = crate::database::init_mem().await.unwrap();
220 db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
221 .await
222 .unwrap()
223 .check()
224 .unwrap();
225 crate::db::settings::save(
226 &db,
227 Settings::try_new(SettingsParams {
228 max_chatbot_threads: threads,
229 ..Settings::defaults().params()
230 })
231 .unwrap(),
232 )
233 .await
234 .unwrap();
235 db
236 }
237
238 /// The seat and the row commit together, so the counter the cap reads can
239 /// never disagree with the threads it counts — and a create refused at the
240 /// cap advances neither.
241 #[tokio::test]
242 async fn a_capped_create_moves_the_counter_with_the_row() {
243 let db = a_user_capped_at(1).await;
244 let user = UserId::from_key("u");
245
246 create_capped(&db, &user, None).await.expect("first thread");
247 assert_eq!(stored(&db).await, (1, 1));
248
249 let refused = create_capped(&db, &user, None).await;
250 assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap");
251 assert_eq!(
252 stored(&db).await,
253 (1, 1),
254 "a refused create advances neither"
255 );
256 }
257
258 /// A turn is written *through* its thread's row, so a thread that is gone
259 /// takes the write with it — and one that is there is stamped by it.
260 /// The race this shape exists to close is the `#[ignore]`d test below;
261 /// this one pins the logic, which the in-memory engine can answer.
262 #[tokio::test]
263 async fn a_turn_writes_its_thread_and_dies_with_it() {
264 let db = a_user_capped_at(2).await;
265 let user = UserId::from_key("u");
266 let thread = create_capped(&db, &user, None).await.expect("thread");
267 let opened = thread.get_updated_at().as_millis();
268
269 let say = || ChatContent::try_new("selam").unwrap();
270 chatbot_message::append_user(&db, thread.get_id(), &user, say())
271 .await
272 .expect("append");
273 let stamped = read_for(&db, thread.get_id(), &user)
274 .await
275 .expect("re-read")
276 .expect("still there")
277 .get_updated_at()
278 .as_millis();
279 // Strictly upwards, never merely re-stamped: an `UPDATE` that leaves
280 // the row unchanged is elided, and both rows of a turn are routinely
281 // written inside one millisecond of the thread's own creation.
282 assert!(stamped > opened, "{stamped} !> {opened}");
283
284 let id = thread.get_id().clone();
285 delete(&db, thread).await.expect("delete");
286 let orphan = chatbot_message::append_user(&db, &id, &user, say()).await;
287 assert!(
288 matches!(orphan, Err(AppError::NotFound)),
289 "a turn on a deleted thread must be refused: {orphan:?}"
290 );
291 assert_eq!(
292 chatbot_message::list_for_thread(&db, &id, None, 0)
293 .await
294 .expect("list")
295 .1,
296 0,
297 "the refused turn wrote nothing"
298 );
299 }
300
301 /// The stamp moves **strictly upwards**, never to the clock — the property
302 /// the whole shape rests on, since an `UPDATE` that leaves the row
303 /// unchanged is elided, never reaches the store's write set, and so
304 /// collides with the racing delete not at all.
305 ///
306 /// The test above cannot see it: it compares one append against
307 /// `create_capped`, which costs a millisecond or so on its own, and a plain
308 /// `$now` clears that. Nor can a burst of appends — each is a transaction
309 /// of its own and takes about as long, so the clock has moved on by the
310 /// time the next one reads it. Timing cannot reach the window on demand.
311 ///
312 /// So the *state* the window produces is set up directly instead: a stamp
313 /// **ahead of the clock**, which is precisely what `math::max` leaves
314 /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a
315 /// contrived one. From there the two rules are told apart with no race at
316 /// all — upwards keeps climbing off the stored value, the clock drags the
317 /// stamp back down to itself. The lead is a second, far more than two
318 /// writes can burn, and the guard below fails loudly rather than vacuously
319 /// on a machine that manages to burn it.
320 #[tokio::test]
321 async fn a_stamp_ahead_of_the_clock_still_climbs() {
322 const LEAD: i64 = 1_000;
323
324 let db = a_user_capped_at(1).await;
325 let user = UserId::from_key("u");
326 let thread = create_capped(&db, &user, None).await.expect("thread");
327
328 let parked = Timestamp::now().as_millis() + LEAD;
329 db.query("UPDATE $id SET updated_at = $parked")
330 .bind(("id", thread.get_id().record()))
331 .bind(("parked", parked))
332 .await
333 .unwrap()
334 .check()
335 .unwrap();
336
337 for _ in 0..2 {
338 chatbot_message::append_user(
339 &db,
340 thread.get_id(),
341 &user,
342 ChatContent::try_new("selam").unwrap(),
343 )
344 .await
345 .expect("append");
346 }
347 let stamped = read_for(&db, thread.get_id(), &user)
348 .await
349 .expect("re-read")
350 .expect("still there")
351 .get_updated_at()
352 .as_millis();
353
354 assert!(
355 Timestamp::now().as_millis() < parked,
356 "the clock caught the {LEAD}ms lead up during two appends, so this \
357 probe proves nothing"
358 );
359 assert_eq!(
360 stamped,
361 parked + 2,
362 "two appends off a stamp of {parked} must leave {}: a stamp that \
363 follows the clock instead is one an unchanged-row UPDATE elides",
364 parked + 2
365 );
366 }
367
368 /// No turn may survive the delete that swept its thread. An orphan is not
369 /// litter: nothing sweeps `chatbot_message` afterwards, and both
370 /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered
371 /// `200` with the text of a thread the user had deleted.
372 ///
373 /// The window is between [`delete`]'s sweep and its commit:
374 /// a create landing in there reads a thread that is still present
375 /// (uncommitted) while the sweep ran on a snapshot predating the new row,
376 /// so both commit. It is closed by making the create **write** the thread
377 /// row ([`touch_and_write`]) instead of reading it — the two transactions
378 /// then touch one key and the store refuses to commit both.
379 ///
380 /// The window is opened by the database itself rather than by a lucky
381 /// interleaving: a `DEFINE EVENT` on `chatbot_thread` fires *inside* the
382 /// delete's own transaction, the instant the row goes, so the `SLEEP` lands
383 /// after the message sweep and before the commit every single time.
384 ///
385 /// Real server, and `#[ignore]`d for it: the subject is the store's
386 /// conflict detection, which `init_mem`'s embedded engine does not have —
387 /// it commits both writes and answers `Ok` to each, which would fail this
388 /// test on correct code (see [`crate::database::init_test_server`]).
389 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
390 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
391 async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {
392 let (db, _serialized) = crate::database::init_test_server("chat_delete_race").await;
393 db.query("CREATE user:u SET username = 'u', password_hash = 'x';")
394 .await
395 .unwrap()
396 .check()
397 .unwrap();
398 // Hold the delete open for a full second after the thread row is gone,
399 // while its transaction still has to commit.
400 db.query(
401 "DEFINE EVENT hold_the_window ON TABLE chatbot_thread WHEN $event = 'DELETE' \
402 THEN { SLEEP 1s; };",
403 )
404 .await
405 .unwrap()
406 .check()
407 .unwrap();
408
409 let user = UserId::from_key("u");
410 let (mut orphans, mut swept) = (0, 0);
411 for round in 0..4 {
412 let thread = create_capped(&db, &user, None).await.expect("thread");
413 let id = thread.get_id().clone();
414
415 let drop_it = {
416 let db = db.clone();
417 tokio::spawn(async move { delete(&db, thread).await })
418 };
419 // The turn starts inside the held window — the thread row is gone
420 // but uncommitted, which is exactly what a read believes.
421 tokio::time::sleep(std::time::Duration::from_millis(300)).await;
422 let turn = {
423 let (id, db, user) = (id.clone(), db.clone(), user.clone());
424 tokio::spawn(async move {
425 chatbot_message::append_user(
426 &db,
427 &id,
428 &user,
429 ChatContent::try_new("selam").unwrap(),
430 )
431 .await
432 .map(|_| ())
433 })
434 };
435 let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap());
436 // A 404 for the turn, or a NotFound for the delete, is a correct
437 // answer — the only defect is stored state.
438 assert!(
439 !matches!(turn, Err(AppError::Db(_))),
440 "round {round}: a raced turn must be answered, not 500: {turn:?}"
441 );
442
443 // Stored state is the whole verdict; a return value is not evidence.
444 if read_for(&db, &id, &user).await.unwrap().is_none() {
445 swept += 1;
446 orphans += chatbot_message::list_for_thread(&db, &id, None, 0)
447 .await
448 .unwrap()
449 .1;
450 } else if drop_it.is_ok() {
451 panic!("round {round}: the delete reported success but the thread is still there");
452 }
453 }
454 eprintln!("chatbot_thread::delete raced by a turn: {swept}/4 rounds deleted the thread");
455 assert!(
456 swept > 0,
457 "no round ever deleted the thread, so the window was never reached"
458 );
459 assert_eq!(orphans, 0, "a turn outlived its thread");
460 }
461}