forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

chatbot_thread.rs522 lines, 21.6 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 surrealdb::types::{SurrealValue, Value};
8
9use crate::constant::{
10 CHATBOT_THREAD_COUNT_FIELD, DEFAULT_MAX_CHATBOT_THREADS, SETTINGS_KEY, SETTINGS_TABLE,
11};
12use crate::database::{Database, transaction_with_retry};
13use crate::db::cap;
14use crate::db::page::PagedList;
15use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
16use crate::domain::timestamp::Timestamp;
17use crate::domain::user::UserId;
18use 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.
53pub(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.
106pub 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.
148pub 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.
164pub 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.
180pub 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.
197pub 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.
229pub 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)]
255mod 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}