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

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