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_message.rs465 lines, 18.2 KiBHistoryRawDownload
1//! The `rag_message` table: the turns of a thread, both sides persisted.
2//! The user's question lands `complete`, and the assistant's row is written
3//! `pending` *before* the AI call so a reload never loses an answer in
4//! flight. The task that owns the bridge round trip then flips it to
5//! `complete` (with the text and the service's reply) or `failed` (with a
6//! code), and the boot sweep in `database.rs` fails whatever a process death
7//! left behind past the staleness window. Every turn is written *through* its
8//! thread's own row — its guarded statement bumps `updated_at`, so a turn can
9//! never outlive the thread it belongs to. The row shape lives in
10//! [`crate::domain::rag_message`].
11
12use crate::constant::MAX_ERROR_CODE_LEN;
13use crate::database::Database;
14use crate::db::page::PagedList;
15use crate::domain::rag_message::{
16 RagContent, RagMessage, RagMessageId, RagMessageRole, RagMessageStatus, RagReply,
17};
18use crate::domain::rag_thread::RagThreadId;
19use crate::domain::timestamp::Timestamp;
20use crate::domain::user::UserId;
21use crate::error::AppError;
22use sqlx::query_as;
23use sqlx::types::Json;
24
25/// Write one turn *through its thread's own row*: the thread's activity
26/// bump and the turn's insert are a single guarded statement, which is what
27/// makes the thread's existence something this write writes rather than
28/// something the caller read and then trusted — a
29/// [`delete`](crate::db::rag_thread::delete) racing it touches the very
30/// row this statement's gate updates, so under Postgres's row locking the
31/// two serialize and no turn is left under a thread that is gone. It also
32/// carries the thread's activity stamp, so a turn and its `updated_at` land
33/// together. The stamp is written strictly upwards —
34/// `GREATEST($now, updated_at + 1)` — because a turn's two rows routinely
35/// land inside one millisecond and `updated_at` is the thread list's
36/// ordering key.
37///
38/// [`AppError::NotFound`] = the thread is gone, and nothing was written.
39async fn insert(db: &Database, message: RagMessage) -> Result<RagMessage, AppError> {
40 let inserted = query_as!(
41 RagMessage,
42 "WITH touch AS (
43 UPDATE rag_thread SET updated_at = GREATEST($2, updated_at + 1)
44 WHERE id = $1
45 RETURNING 1)
46 INSERT INTO rag_message (id, thread, user_id, role, content, status, \
47 reply, error_code, created_at, completed_at)
48 SELECT $3, $1, $4, $5, $6, $7, $8, $9, $10, $11
49 WHERE EXISTS (SELECT 1 FROM touch)
50 RETURNING id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \
51 user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \
52 status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \
53 error_code AS \"error_code: String\", \
54 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"",
55 message.get_thread_id().uuid(),
56 Timestamp::now().as_millis(),
57 message.get_id().uuid(),
58 message.user_id.uuid(),
59 message.role.as_str(),
60 message.content.as_str(),
61 message.status.as_str(),
62 message.reply as _,
63 message.error_code,
64 message.created_at.as_millis(),
65 message.completed_at.map(|t| t.as_millis()),
66 )
67 .fetch_optional(db)
68 .await?;
69 // No row out of the conditional insert means the thread's touch matched
70 // nothing: the thread is gone, and nothing was written.
71 inserted.ok_or(AppError::NotFound)
72}
73
74/// Append the user's question. Nothing is awaited for it, so it is born
75/// complete — and it carries no reply: there is nothing but the text.
76pub async fn append_user(
77 db: &Database,
78 thread: &RagThreadId,
79 user: &UserId,
80 content: RagContent,
81) -> Result<RagMessage, AppError> {
82 let now = Timestamp::now();
83 insert(
84 db,
85 RagMessage {
86 id: RagMessageId::generate(),
87 thread: thread.clone(),
88 user_id: *user,
89 role: RagMessageRole::User,
90 content,
91 status: RagMessageStatus::Complete,
92 reply: None,
93 error_code: None,
94 created_at: now,
95 completed_at: Some(now),
96 },
97 )
98 .await
99}
100
101/// Reserve the assistant's answer *before* the AI call: the row exists,
102/// empty and `pending`, so a reload finds the turn and can wait on it. The
103/// reply column stays NULL until the answer lands — the service's JSON is not
104/// known yet.
105pub async fn append_pending_assistant(
106 db: &Database,
107 thread: &RagThreadId,
108 user: &UserId,
109) -> Result<RagMessage, AppError> {
110 insert(
111 db,
112 RagMessage {
113 id: RagMessageId::generate(),
114 thread: thread.clone(),
115 user_id: *user,
116 role: RagMessageRole::Assistant,
117 content: RagContent::empty(),
118 status: RagMessageStatus::Pending,
119 reply: None,
120 error_code: None,
121 created_at: Timestamp::now(),
122 completed_at: None,
123 },
124 )
125 .await
126}
127
128/// The whole thread, oldest first — the order both the UI and the AI
129/// history payload read in.
130pub async fn list_for_thread(
131 db: &Database,
132 thread: &RagThreadId,
133 limit: Option<i64>,
134 offset: i64,
135) -> Result<(Vec<RagMessage>, i64), AppError> {
136 let (rows, total) = PagedList::new(
137 "rag_message WHERE thread = $1",
138 "ORDER BY created_at ASC, id ASC",
139 )
140 .bind(thread.uuid())
141 .run::<RagMessage>(limit, offset, db)
142 .await?;
143 Ok((rows.into_iter().map(RagMessage::projected).collect(), total))
144}
145
146/// The last `limit` turns, still oldest-first — the tail replayed to the
147/// AI service as context. Taken newest-first in the database (so the
148/// `LIMIT` keeps the *recent* end) and flipped back here.
149pub async fn list_tail(
150 db: &Database,
151 thread: &RagThreadId,
152 limit: usize,
153) -> Result<Vec<RagMessage>, AppError> {
154 let mut messages: Vec<RagMessage> = query_as!(
155 RagMessage,
156 "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \
157 user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \
158 status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \
159 error_code AS \"error_code: String\", \
160 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
161 FROM rag_message WHERE thread = $1 \
162 ORDER BY created_at DESC, id DESC LIMIT $2",
163 thread.uuid(),
164 limit as i64
165 )
166 .fetch_all(db)
167 .await?;
168 messages.reverse();
169 Ok(messages)
170}
171
172/// The last `limit` *settled* turns that carry text, still oldest-first —
173/// the tail replayed to the AI service as context. The filter runs in the
174/// query, not after it: a `LIMIT` over the raw tail hands back fewer usable
175/// rows the moment a run of answers fails, silently shrinking the context
176/// instead of reaching further back. No projection is applied — it only
177/// ever rewrites a `pending` row, and none is selected here.
178pub async fn list_settled_tail(
179 db: &Database,
180 thread: &RagThreadId,
181 limit: usize,
182) -> Result<Vec<RagMessage>, AppError> {
183 let mut messages: Vec<RagMessage> = query_as!(
184 RagMessage,
185 "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \
186 user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \
187 status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \
188 error_code AS \"error_code: String\", \
189 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
190 FROM rag_message WHERE thread = $1 \
191 AND status = 'complete' AND content <> '' \
192 ORDER BY created_at DESC, id DESC LIMIT $2",
193 thread.uuid(),
194 limit as i64
195 )
196 .fetch_all(db)
197 .await?;
198 messages.reverse();
199 Ok(messages)
200}
201
202/// The user turn a reserved answer belongs to, by *identity*: the question
203/// row of the very POST that reserved it, whose id the answering task
204/// carries.
205///
206/// Never derived from write order. Two POSTs on one thread interleave
207/// across the two creates — the rows land `userA, userB, asstA, asstB` —
208/// so "the newest user row written before this answer" resolves *both*
209/// answers to question B, and question A is never answered.
210pub async fn prompt_of(
211 db: &Database,
212 id: &RagMessageId,
213) -> Result<Option<RagMessage>, AppError> {
214 let message = query_as!(
215 RagMessage,
216 "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \
217 user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \
218 status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \
219 error_code AS \"error_code: String\", \
220 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
221 FROM rag_message WHERE id = $1",
222 id.uuid()
223 )
224 .fetch_optional(db)
225 .await?;
226 Ok(message)
227}
228
229/// Read one turn only if `user` owns it — the poll loop's read.
230pub async fn read_for(
231 db: &Database,
232 id: &RagMessageId,
233 user: &UserId,
234) -> Result<Option<RagMessage>, AppError> {
235 let message = query_as!(
236 RagMessage,
237 "SELECT id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \
238 user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \
239 status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \
240 error_code AS \"error_code: String\", \
241 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
242 FROM rag_message WHERE id = $1",
243 id.uuid()
244 )
245 .fetch_optional(db)
246 .await?;
247 Ok(message
248 .filter(|message| &message.user_id == user)
249 .map(RagMessage::projected))
250}
251
252/// Land the answer: the text and the service's reply (abstention, reason,
253/// citations), the pair every settled answer is judged by. Gated on
254/// `status = 'pending'` in the `WHERE`, so a late answer can't overwrite a row
255/// the boot sweep (or a timeout) already failed, and two answers can't both
256/// apply.
257pub async fn complete(
258 db: &Database,
259 id: &RagMessageId,
260 text: RagContent,
261 reply: Json<RagReply>,
262) -> Result<RagMessage, AppError> {
263 settle(db, id, Some(text), Some(reply), None).await
264}
265
266/// Mark the answer failed with a short code (`unavailable`, the service's
267/// own error code, …). Same pending gate as [`complete`]; a failed turn
268/// stores no reply — the service never produced one worth keeping.
269pub async fn fail(
270 db: &Database,
271 id: &RagMessageId,
272 error_code: &str,
273) -> Result<RagMessage, AppError> {
274 settle(db, id, None, None, Some(error_code)).await
275}
276
277async fn settle(
278 db: &Database,
279 id: &RagMessageId,
280 text: Option<RagContent>,
281 reply: Option<Json<RagReply>>,
282 error_code: Option<&str>,
283) -> Result<RagMessage, AppError> {
284 let status = if text.is_some() {
285 RagMessageStatus::Complete
286 } else {
287 RagMessageStatus::Failed
288 };
289 let settled = query_as!(
290 RagMessage,
291 "UPDATE rag_message SET content = $2, status = $3, reply = $4, \
292 error_code = $5, completed_at = $6 \
293 WHERE id = $1 AND status = 'pending' \
294 RETURNING id AS \"id: RagMessageId\", thread AS \"thread: RagThreadId\", \
295 user_id AS \"user_id: UserId\", role AS \"role: RagMessageRole\", content AS \"content: RagContent\", \
296 status AS \"status: RagMessageStatus\", reply AS \"reply: Json<RagReply>\", \
297 error_code AS \"error_code: String\", \
298 created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"",
299 id.uuid(),
300 text.map(|t| t.as_str().to_string()).unwrap_or_default(),
301 status.as_str(),
302 reply as _,
303 error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::<String>()),
304 Timestamp::now().as_millis(),
305 )
306 .fetch_optional(db)
307 .await?;
308 settled.ok_or(AppError::NotFound)
309}
310#[cfg(test)]
311mod tests {
312 use super::*;
313 use crate::domain::rag_message::RagCitedFile;
314
315 /// A real owner and a real thread row: every turn is written through its
316 /// thread, so a turn with no thread is refused (see [`insert`]), and the
317 /// owner is a foreign key. Fixed keys, one per test.
318 async fn a_thread(
319 user: &str,
320 thread: &str,
321 ) -> (Database, crate::database::TestDatabases, UserId, RagThreadId) {
322 let (db, leases) = crate::database::init_test_db().await;
323 let user = UserId::from_key(user);
324 let thread = RagThreadId::from_key(thread);
325 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, 'rag-fixture', 0)")
326 .bind(user.uuid())
327 .execute(&db)
328 .await
329 .unwrap();
330 sqlx::query(
331 "INSERT INTO rag_thread (id, owner, created_at, updated_at) \
332 VALUES ($1, $2, 0, 0)",
333 )
334 .bind(thread.uuid())
335 .bind(user.uuid())
336 .execute(&db)
337 .await
338 .unwrap();
339 (db, leases, user, thread)
340 }
341
342 fn a_reply() -> Json<RagReply> {
343 Json(RagReply {
344 abstained: false,
345 reason: String::new(),
346 citations: vec![RagCitedFile {
347 n: 1,
348 file: None,
349 pages: vec![12],
350 span_ids: vec!["s1".to_string()],
351 ders: Some("Fizik".to_string()),
352 }],
353 })
354 }
355
356 #[tokio::test]
357 async fn a_turns_two_rows_never_sort_inverted() {
358 // Both rows of a turn land in the same millisecond routinely, so the
359 // `id` tie-break decides the thread's order. With a random ULID this
360 // inverted a fifth of the pairs; here every pair must read back
361 // question-then-answer, from both read paths.
362 let (db, _leases, user, thread) = a_thread(
363 "019732e3-7b00-7000-8000-00000000cafe",
364 "019732e3-7b00-7000-8000-00000000beef",
365 )
366 .await;
367 const TURNS: usize = 200;
368
369 for turn in 0..TURNS {
370 let content = RagContent::try_new(&format!("soru {turn}")).unwrap();
371 append_user(&db, &thread, &user, content).await.unwrap();
372 append_pending_assistant(&db, &thread, &user)
373 .await
374 .unwrap();
375 }
376
377 let (whole, _) = list_for_thread(&db, &thread, None, 0).await.unwrap();
378 let tail = list_tail(&db, &thread, TURNS * 2).await.unwrap();
379 for messages in [&whole, &tail] {
380 assert_eq!(messages.len(), TURNS * 2);
381 for (turn, pair) in messages.chunks(2).enumerate() {
382 assert_eq!(pair[0].get_role(), RagMessageRole::User, "turn {turn}");
383 assert_eq!(pair[0].get_content().as_str(), format!("soru {turn}"));
384 assert_eq!(
385 pair[1].get_role(),
386 RagMessageRole::Assistant,
387 "turn {turn}"
388 );
389 }
390 }
391 }
392
393 /// A settled answer carries the service's reply, and the reserved row it
394 /// replaced carried none — the column is written once, by the flip that
395 /// settles the turn.
396 #[tokio::test]
397 async fn a_completed_answer_carries_its_reply() {
398 let (db, _leases, user, thread) = a_thread(
399 "019732e3-7b00-7000-8000-00000000cafe",
400 "019732e3-7b00-7000-8000-00000000beef",
401 )
402 .await;
403 let pending = append_pending_assistant(&db, &thread, &user).await.unwrap();
404 assert!(pending.get_reply().is_none(), "nothing is known yet");
405 assert_eq!(pending.get_status(), RagMessageStatus::Pending);
406
407 let reply = a_reply();
408 let settled = complete(&db, pending.get_id(), RagContent::try_new("F = m·a").unwrap(), reply)
409 .await
410 .expect("land the answer");
411 assert_eq!(settled.get_status(), RagMessageStatus::Complete);
412 assert!(settled.get_completed_at().is_some());
413 assert_eq!(settled.get_reply(), Some(&a_reply().0));
414
415 // Re-read out of the store: the JSONB round trip is the contract a
416 // reader receives, and a return value is not evidence.
417 let stored = read_for(&db, pending.get_id(), &user)
418 .await
419 .unwrap()
420 .expect("settled row");
421 assert_eq!(stored.get_reply(), Some(&a_reply().0));
422 }
423
424 /// The boot sweep (or a timeout) fails a `pending` row; a reply that
425 /// arrives afterwards must be refused, not written over it — the
426 /// `status = 'pending'` gate in [`settle`] is the whole of that rule, and
427 /// the stored row is the verdict.
428 #[tokio::test]
429 async fn a_late_answer_cannot_overwrite_a_swept_row() {
430 let (db, _leases, user, thread) = a_thread(
431 "019732e3-7b00-7000-8000-00000000cafe",
432 "019732e3-7b00-7000-8000-00000000beef",
433 )
434 .await;
435 let pending = append_pending_assistant(&db, &thread, &user).await.unwrap();
436 sqlx::query(
437 "UPDATE rag_message SET status = 'failed', error_code = 'interrupted', \
438 completed_at = $1 WHERE id = $2",
439 )
440 .bind(Timestamp::now().as_millis())
441 .bind(pending.get_id().uuid())
442 .execute(&db)
443 .await
444 .unwrap();
445
446 let late = complete(
447 &db,
448 pending.get_id(),
449 RagContent::try_new("F = m·a").unwrap(),
450 a_reply(),
451 )
452 .await;
453 assert!(
454 matches!(late, Err(AppError::NotFound)),
455 "a settled row takes no second answer: {late:?}"
456 );
457 let stored = read_for(&db, pending.get_id(), &user)
458 .await
459 .unwrap()
460 .expect("swept row");
461 assert_eq!(stored.get_status(), RagMessageStatus::Failed);
462 assert_eq!(stored.get_error_code(), Some("interrupted"));
463 assert!(stored.get_reply().is_none(), "the late reply was not stored");
464 }
465}