forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB914d095Ahmet Kaan Gümüş2 months ago454 commits

chatbot_thread.rs449 lines, 18.4 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 =
209 sqlx::query("SELECT chatbot_thread_count FROM app_user WHERE id = $1")
210 .bind(UserId::from_key(U).uuid())
211 .fetch_one(db)
212 .await
213 .unwrap()
214 .try_get::<i64, _>(0)
215 .unwrap();
216 let rows = sqlx::query("SELECT count(*) FROM chatbot_thread")
217 .fetch_one(db)
218 .await
219 .unwrap()
220 .try_get::<i64, _>(0)
221 .unwrap();
222 (counter, rows as usize)
223 }
224
225 async fn a_user_capped_at(threads: i64) -> Database {
226 let (db, _leases) = crate::database::init_test_db().await;
227 sqlx::query("INSERT INTO app_user (id, username, password_hash) VALUES ($1, 'u', 'x')")
228 .bind(UserId::from_key(U).uuid())
229 .execute(&db)
230 .await
231 .unwrap();
232 crate::db::settings::save(
233 &db,
234 Settings::try_new(SettingsParams {
235 max_chatbot_threads: threads,
236 ..Settings::defaults().params()
237 })
238 .unwrap(),
239 )
240 .await
241 .unwrap();
242 db
243 }
244
245 /// The seat and the row commit together, so the counter the cap reads can
246 /// never disagree with the threads it counts — and a create refused at the
247 /// cap advances neither.
248 #[tokio::test]
249 async fn a_capped_create_moves_the_counter_with_the_row() {
250 let db = a_user_capped_at(1).await;
251 let user = UserId::from_key(U);
252
253 create_capped(&db, &user, None).await.expect("first thread");
254 assert_eq!(stored(&db).await, (1, 1));
255
256 let refused = create_capped(&db, &user, None).await;
257 assert!(matches!(refused, Err(AppError::Conflict(_))), "at the cap");
258 assert_eq!(
259 stored(&db).await,
260 (1, 1),
261 "a refused create advances neither"
262 );
263 }
264
265 /// A turn is written *through* its thread's row, so a thread that is gone
266 /// takes the write with it — and one that is there is stamped by it.
267 /// The race this shape exists to close is the `#[ignore]`d test below;
268 /// this one pins the logic, which the in-memory engine can answer.
269 #[tokio::test]
270 async fn a_turn_writes_its_thread_and_dies_with_it() {
271 let db = a_user_capped_at(2).await;
272 let user = UserId::from_key(U);
273 let thread = create_capped(&db, &user, None).await.expect("thread");
274 let opened = thread.get_updated_at().as_millis();
275
276 let say = || ChatContent::try_new("selam").unwrap();
277 chatbot_message::append_user(&db, thread.get_id(), &user, say())
278 .await
279 .expect("append");
280 let stamped = read_for(&db, thread.get_id(), &user)
281 .await
282 .expect("re-read")
283 .expect("still there")
284 .get_updated_at()
285 .as_millis();
286 // Strictly upwards, never merely re-stamped: an `UPDATE` that leaves
287 // the row unchanged is elided, and both rows of a turn are routinely
288 // written inside one millisecond of the thread's own creation.
289 assert!(stamped > opened, "{stamped} !> {opened}");
290
291 let id = thread.get_id().clone();
292 delete(&db, thread).await.expect("delete");
293 let orphan = chatbot_message::append_user(&db, &id, &user, say()).await;
294 assert!(
295 matches!(orphan, Err(AppError::NotFound)),
296 "a turn on a deleted thread must be refused: {orphan:?}"
297 );
298 assert_eq!(
299 chatbot_message::list_for_thread(&db, &id, None, 0)
300 .await
301 .expect("list")
302 .1,
303 0,
304 "the refused turn wrote nothing"
305 );
306 }
307
308 /// The stamp moves **strictly upwards**, never to the clock — the property
309 /// the whole shape rests on, since an `UPDATE` that leaves the row
310 /// unchanged is elided, never reaches the store's write set, and so
311 /// collides with the racing delete not at all.
312 ///
313 /// The test above cannot see it: it compares one append against
314 /// `create_capped`, which costs a millisecond or so on its own, and a plain
315 /// `$now` clears that. Nor can a burst of appends — each is a transaction
316 /// of its own and takes about as long, so the clock has moved on by the
317 /// time the next one reads it. Timing cannot reach the window on demand.
318 ///
319 /// So the *state* the window produces is set up directly instead: a stamp
320 /// **ahead of the clock**, which is precisely what `math::max` leaves
321 /// behind (see [`touch_and_write`]) and therefore an ordinary row, not a
322 /// contrived one. From there the two rules are told apart with no race at
323 /// all — upwards keeps climbing off the stored value, the clock drags the
324 /// stamp back down to itself. The lead is a second, far more than two
325 /// writes can burn, and the guard below fails loudly rather than vacuously
326 /// on a machine that manages to burn it.
327 #[tokio::test]
328 async fn a_stamp_ahead_of_the_clock_still_climbs() {
329 const LEAD: i64 = 1_000;
330
331 let db = a_user_capped_at(1).await;
332 let user = UserId::from_key(U);
333 let thread = create_capped(&db, &user, None).await.expect("thread");
334
335 let parked = Timestamp::now().as_millis() + LEAD;
336 sqlx::query("UPDATE chatbot_thread SET updated_at = $1 WHERE id = $2")
337 .bind(parked)
338 .bind(thread.get_id().uuid())
339 .execute(&db)
340 .await
341 .unwrap();
342
343 for _ in 0..2 {
344 chatbot_message::append_user(
345 &db,
346 thread.get_id(),
347 &user,
348 ChatContent::try_new("selam").unwrap(),
349 )
350 .await
351 .expect("append");
352 }
353 let stamped = read_for(&db, thread.get_id(), &user)
354 .await
355 .expect("re-read")
356 .expect("still there")
357 .get_updated_at()
358 .as_millis();
359
360 assert!(
361 Timestamp::now().as_millis() < parked,
362 "the clock caught the {LEAD}ms lead up during two appends, so this \
363 probe proves nothing"
364 );
365 assert_eq!(
366 stamped,
367 parked + 2,
368 "two appends off a stamp of {parked} must leave {}: a stamp that \
369 follows the clock instead is one an unchanged-row UPDATE elides",
370 parked + 2
371 );
372 }
373
374 /// No turn may survive the delete that swept its thread. An orphan is not
375 /// litter: nothing sweeps `chatbot_message` afterwards, and both
376 /// `GET /chatbot/threads/{id}/messages/{mid}` and its `/stream` answered
377 /// `200` with the text of a thread the user had deleted.
378 ///
379 /// The window is between [`delete`]'s sweep and its commit:
380 /// a create landing in there reads a thread that is still present
381 /// (uncommitted) while the sweep ran on a snapshot predating the new row,
382 /// so both commit. It is closed by making the create **write** the thread
383 /// row ([`touch_and_write`]) instead of reading it — the two transactions
384 /// then touch one key and the store refuses to commit both.
385 ///
386 /// The window the schema event used to force open is the thread row's own
387 /// lock now: a turn is written *through* the row ([`touch_and_write`]),
388 /// so a turn racing the delete serializes on that row instead of
389 /// committing past the sweep. A barrier start lets both orders happen,
390 /// and the invariant must hold in each.
391 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
392 async fn a_turn_written_inside_a_delete_never_outlives_the_thread() {
393 let db = a_user_capped_at(4).await;
394
395 let user = UserId::from_key(U);
396 let (mut orphans, mut swept) = (0, 0);
397 for round in 0..8 {
398 let thread = create_capped(&db, &user, None).await.expect("thread");
399 let id = thread.get_id().clone();
400
401 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
402 let drop_it = {
403 let (db, thread, gate) = (db.clone(), thread, gate.clone());
404 tokio::spawn(async move {
405 gate.wait().await;
406 delete(&db, thread).await
407 })
408 };
409 let turn = {
410 let (id, db, user, gate) = (id.clone(), db.clone(), user.clone(), gate);
411 tokio::spawn(async move {
412 gate.wait().await;
413 chatbot_message::append_user(
414 &db,
415 &id,
416 &user,
417 ChatContent::try_new("selam").unwrap(),
418 )
419 .await
420 .map(|_| ())
421 })
422 };
423 let (drop_it, turn) = (drop_it.await.unwrap(), turn.await.unwrap());
424 // A 404 for the turn, or a NotFound for the delete, is a correct
425 // answer — the only defect is stored state.
426 assert!(
427 !matches!(turn, Err(AppError::Db(_))),
428 "round {round}: a raced turn must be answered, not 500: {turn:?}"
429 );
430
431 // Stored state is the whole verdict; a return value is not evidence.
432 if read_for(&db, &id, &user).await.unwrap().is_none() {
433 swept += 1;
434 orphans += chatbot_message::list_for_thread(&db, &id, None, 0)
435 .await
436 .unwrap()
437 .1;
438 } else if drop_it.is_ok() {
439 panic!("round {round}: the delete reported success but the thread is still there");
440 }
441 }
442 eprintln!("chatbot_thread::delete raced by a turn: {swept}/8 rounds deleted the thread");
443 assert!(
444 swept > 0,
445 "no round ever deleted the thread, so the race never actually ran"
446 );
447 assert_eq!(orphans, 0, "a turn outlived its thread");
448 }
449}