forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

chatbot_thread.rs525 lines, 21.7 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 sqlx::Row as _;
197
198 use crate::db::chatbot_message;
199 use crate::domain::chatbot_message::ChatContent;
200 use crate::domain::settings::{Settings, SettingsParams};
201
202 /// The fixed fixture person, by a valid id every helper can name.
203 const U: &str = "019732e3-7b00-7000-8000-00000000aaaa";
204
205 /// The owner's counter and the threads it counts, both re-read out of the
206 /// store — never off a return value.
207 async fn stored(db: &Database) -> (i64, usize) {
208 let counter = sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1")
209 .bind(UserId::from_key(U).uuid())
210 .fetch_one(db)
211 .await
212 .unwrap()
213 .try_get::<i64, _>(0)
214 .unwrap();
215 let rows = sqlx::query("SELECT count(*) FROM chatbot_thread")
216 .fetch_one(db)
217 .await
218 .unwrap()
219 .try_get::<i64, _>(0)
220 .unwrap();
221 (counter, rows as usize)
222 }
223
224 async fn a_user_capped_at(threads: i64) -> (Database, crate::database::TestDatabases) {
225 let (db, leases) = crate::database::init_test_db().await;
226 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'u', 0)")
227 .bind(UserId::from_key(U).uuid())
228 .execute(&db)
229 .await
230 .unwrap();
231 crate::db::settings::save(
232 &db,
233 Settings::try_new(SettingsParams {
234 max_chatbot_threads: threads,
235 ..Settings::defaults().params()
236 })
237 .unwrap(),
238 )
239 .await
240 .unwrap();
241 (db, leases)
242 }
243
244 /// The seat and the row commit together, so the counter the cap reads can
245 /// never disagree with the threads it counts — and a create refused at the
246 /// cap advances neither.
247 #[tokio::test]
248 async fn a_capped_create_moves_the_counter_with_the_row() {
249 let (db, _leases) = a_user_capped_at(1).await;
250 let user = UserId::from_key(U);
251
252 create_capped(&db, &user, None).await.expect("first thread");
253 assert_eq!(stored(&db).await, (1, 1));
254
255 let refused = create_capped(&db, &user, None).await;
256 assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap");
257 assert_eq!(
258 stored(&db).await,
259 (1, 1),
260 "a refused create advances neither"
261 );
262 }
263
264 /// A turn is written *through* its thread's row, so a thread that is gone
265 /// takes the write with it — and one that is there is stamped by it.
266 /// The race this shape exists to close is the `#[ignore]`d test below;
267 /// this one pins the logic, which the in-memory engine can answer.
268 #[tokio::test]
269 async fn a_turn_writes_its_thread_and_dies_with_it() {
270 let (db, _leases) = a_user_capped_at(2).await;
271 let user = UserId::from_key(U);
272 let thread = create_capped(&db, &user, None).await.expect("thread");
273 let opened = thread.get_updated_at().as_millis();
274
275 let say = || ChatContent::try_new("selam").unwrap();
276 chatbot_message::append_user(&db, thread.get_id(), &user, say())
277 .await
278 .expect("append");
279 let stamped = read_for(&db, thread.get_id(), &user)
280 .await
281 .expect("re-read")
282 .expect("still there")
283 .get_updated_at()
284 .as_millis();
285 // Strictly upwards, never merely re-stamped: an `UPDATE` that leaves
286 // the row unchanged is elided, and both rows of a turn are routinely
287 // written inside one millisecond of the thread's own creation.
288 assert!(stamped > opened, "{stamped} !> {opened}");
289
290 let id = thread.get_id().clone();
291 delete(&db, thread).await.expect("delete");
292 let orphan = chatbot_message::append_user(&db, &id, &user, say()).await;
293 assert!(
294 matches!(orphan, Err(AppError::NotFound)),
295 "a turn on a deleted thread must be refused: {orphan:?}"
296 );
297 assert_eq!(
298 chatbot_message::list_for_thread(&db, &id, None, 0)
299 .await
300 .expect("list")
301 .1,
302 0,
303 "the refused turn wrote nothing"
304 );
305 }
306
307 /// The stamp moves **strictly upwards**, never to the clock — the property
308 /// the whole shape rests on, since an `UPDATE` that leaves the row
309 /// unchanged is elided, never reaches the store's write set, and so
310 /// collides with the racing delete not at all.
311 ///
312 /// The test above cannot see it: it compares one append against
313 /// `create_capped`, which costs a millisecond or so on its own, and a plain
314 /// `$now` clears that. Nor can a burst of appends — each is a transaction
315 /// of its own and takes about as long, so the clock has moved on by the
316 /// time the next one reads it. Timing cannot reach the window on demand.
317 ///
318 /// So the *state* the window produces is set up directly instead: a stamp
319 /// **ahead of the clock**, which is precisely what `math::max` leaves
320 /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a
321 /// contrived one. From there the two rules are told apart with no race at
322 /// all — upwards keeps climbing off the stored value, the clock drags the
323 /// stamp back down to itself. The lead is a second, far more than two
324 /// writes can burn, and the guard below fails loudly rather than vacuously
325 /// on a machine that manages to burn it.
326 #[tokio::test]
327 async fn a_stamp_ahead_of_the_clock_still_climbs() {
328 const LEAD: i64 = 1_000;
329
330 let (db, _leases) = a_user_capped_at(1).await;
331 let user = UserId::from_key(U);
332 let thread = create_capped(&db, &user, None).await.expect("thread");
333
334 let parked = Timestamp::now().as_millis() + LEAD;
335 sqlx::query("UPDATE chatbot_thread SET updated_at = $1 WHERE id = $2")
336 .bind(parked)
337 .bind(thread.get_id().uuid())
338 .execute(&db)
339 .await
340 .unwrap();
341
342 for _ in 0..2 {
343 chatbot_message::append_user(
344 &db,
345 thread.get_id(),
346 &user,
347 ChatContent::try_new("selam").unwrap(),
348 )
349 .await
350 .expect("append");
351 }
352 let stamped = read_for(&db, thread.get_id(), &user)
353 .await
354 .expect("re-read")
355 .expect("still there")
356 .get_updated_at()
357 .as_millis();
358
359 assert!(
360 Timestamp::now().as_millis() < parked,
361 "the clock caught the {LEAD}ms lead up during two appends, so this \
362 probe proves nothing"
363 );
364 assert_eq!(
365 stamped,
366 parked + 2,
367 "two appends off a stamp of {parked} must leave {}: a stamp that \
368 follows the clock instead is one an unchanged-row UPDATE elides",
369 parked + 2
370 );
371 }
372
373 /// No turn may survive the delete that swept its thread. An orphan is not
374 /// litter: nothing sweeps `chatbot_message` afterwards, and both
375 /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered
376 /// `200` with the text of a thread the user had deleted.
377 ///
378 /// The window is between [`delete`]'s sweep and its commit:
379 /// a create landing in there reads a thread that is still present
380 /// (uncommitted) while the sweep ran on a snapshot predating the new row,
381 /// so both commit. It is closed by making the create **write** the thread
382 /// row ([`touch_and_write`]) instead of reading it — the two transactions
383 /// then touch one key and the store refuses to commit both.
384 ///
385 /// The window the schema event used to force open is the thread row's own
386 /// lock now: a turn is written *through* the row ([`touch_and_write`]),
387 /// so a turn racing the delete serializes on that row instead of
388 /// committing past the sweep. Both orders are forced by awaiting one side
389 /// to completion before the other starts — a barrier is a coin toss under
390 /// load, and a run where the delete loses every overlapped round has still
391 /// proved the invariant. A few rounds still start together; those may all
392 /// lose the delete, and that is not a failure.
393 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
394 async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {
395 // Forced rounds free their seat. Concurrent rounds may keep theirs, so
396 // the cap covers every thread this test can leave standing.
397 let (db, _leases) = a_user_capped_at(6).await;
398 let user = UserId::from_key(U);
399
400 async fn append(
401 db: &Database,
402 id: &ChatbotThreadId,
403 user: &UserId,
404 ) -> Result<(), AppError> {
405 chatbot_message::append_user(db, id, user, ChatContent::try_new("selam").unwrap())
406 .await
407 .map(|_| ())
408 }
409
410 // Delete-first: the thread is gone before the turn starts.
411 {
412 let thread = create_capped(&db, &user, None).await.expect("thread");
413 let id = thread.get_id().clone();
414 let dropped = delete(&db, thread).await;
415 assert!(
416 !matches!(dropped, Err(AppError::Db(_))),
417 "delete-first: a delete must be answered, not 500: {dropped:?}"
418 );
419 assert!(
420 read_for(&db, &id, &user).await.unwrap().is_none(),
421 "delete-first: the thread is still there after delete: {dropped:?}"
422 );
423 let turn = append(&db, &id, &user).await;
424 assert!(
425 !matches!(turn, Err(AppError::Db(_))),
426 "delete-first: a turn must be answered, not 500: {turn:?}"
427 );
428 assert_eq!(
429 chatbot_message::list_for_thread(&db, &id, None, 0)
430 .await
431 .unwrap()
432 .1,
433 0,
434 "a turn outlived its thread"
435 );
436 }
437
438 // Write-first: the turn lands, then the delete sweeps it.
439 {
440 let thread = create_capped(&db, &user, None).await.expect("thread");
441 let id = thread.get_id().clone();
442 let turn = append(&db, &id, &user).await;
443 assert!(
444 turn.is_ok(),
445 "write-first: the turn must land before the delete: {turn:?}"
446 );
447 let dropped = delete(&db, thread).await;
448 assert!(
449 !matches!(dropped, Err(AppError::Db(_))),
450 "write-first: a delete must be answered, not 500: {dropped:?}"
451 );
452 assert!(
453 read_for(&db, &id, &user).await.unwrap().is_none(),
454 "write-first: the thread is still there"
455 );
456 assert_eq!(
457 chatbot_message::list_for_thread(&db, &id, None, 0)
458 .await
459 .unwrap()
460 .1,
461 0,
462 "a turn outlived its thread"
463 );
464 }
465
466 // Overlapped rounds. Delete may lose every one of them.
467 let mut swept = 0;
468 for round in 0..4 {
469 let thread = create_capped(&db, &user, None).await.expect("thread");
470 let id = thread.get_id().clone();
471
472 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
473 let drop_it = {
474 let (db, thread, gate) = (db.clone(), thread, gate.clone());
475 tokio::spawn(async move {
476 gate.wait().await;
477 delete(&db, thread).await
478 })
479 };
480 let turn = {
481 let (id, db, user, gate) = (id.clone(), db.clone(), user, gate);
482 tokio::spawn(async move {
483 gate.wait().await;
484 append(&db, &id, &user).await
485 })
486 };
487 let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap());
488 assert!(
489 !matches!(turn, Err(AppError::Db(_))),
490 "round {round}: a raced turn must be answered, not 500: {turn:?}"
491 );
492 // A lost round here is a 23503, not a missed sweep. The turn's
493 // insert and this delete's `DELETE chatbot_message` do not share a
494 // row lock, `chatbot_message.thread_id` is `ON DELETE NO ACTION`,
495 // and [`delete`] does not retry that (`cascade = false`). The
496 // thread is still there; nothing outlived a gone parent. Any other
497 // database error is a 500. The forced rounds above are the ones
498 // that require the delete itself to answer without one.
499 let parent_gone = read_for(&db, &id, &user).await.unwrap().is_none();
500 if let Err(AppError::Db(err)) = &drop_it {
501 let lost_the_gap = crate::database::foreign_key_violation(err) && !parent_gone;
502 assert!(
503 lost_the_gap,
504 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
505 );
506 }
507 if parent_gone {
508 swept += 1;
509 assert_eq!(
510 chatbot_message::list_for_thread(&db, &id, None, 0)
511 .await
512 .unwrap()
513 .1,
514 0,
515 "round {round}: a turn outlived its thread"
516 );
517 } else if drop_it.is_ok() {
518 panic!("round {round}: the delete reported success but the thread is still there");
519 }
520 }
521 eprintln!(
522 "chatbot_thread::delete raced by a turn: {swept}/4 concurrent rounds deleted the thread"
523 );
524 }
525}