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_output.rs450 lines, 16.2 KiBHistoryRawDownload
1//! What an AI service produced for a course note, stored on this side: the
2//! write paths the api-read bridge serves (`create`/`replace_for_note` run
3//! when this backend answers a request over the bridge, and this side stores
4//! the answer), which is what keeps the api-read bridge GET-only. Derived,
5//! disposable data: the row is dropped and regenerated whenever its input
6//! changes, so the cascades below — [`delete_for_note`] when the note goes,
7//! [`delete_with_source`] dropping the citation links a file delete strands
8//! — keep the stored shape from outliving its input, even in a deployment
9//! with no AI service connected. The row shape lives in
10//! [`crate::domain::rag_output`].
11
12use std::collections::HashMap;
13
14use crate::database::{Database, tx_with_retry};
15use crate::db::page::PagedList;
16use crate::domain::course::CourseId;
17use crate::domain::course_note::CourseNoteId;
18use crate::domain::course_note_file::CourseNoteFileId;
19use crate::domain::rag_output::{RagOutput, RagOutputId};
20use crate::domain::timestamp::Timestamp;
21use crate::error::AppError;
22use serde_json::Value;
23use sqlx::types::Json;
24use uuid::Uuid;
25
26/// The plain `rag_output` columns. A citation list is not a column on the
27/// row — the links live in `rag_output_source`, and the `query!` macros
28/// cannot join an aggregate into a row — so every read decodes this shape
29/// and one batch junction statement supplies the links that
30/// [`RagOutputRow::into_rag_output`](RagOutputRow::into_rag_output) attaches.
31#[derive(Debug, sqlx::FromRow)]
32struct RagOutputRow {
33 id: RagOutputId,
34 course_note: CourseNoteId,
35 course: CourseId,
36 payload: Json<Value>,
37 generated_at: Timestamp,
38}
39
40impl RagOutputRow {
41 fn into_rag_output(self, sources: Vec<CourseNoteFileId>) -> RagOutput {
42 RagOutput {
43 id: self.id,
44 course_note: self.course_note,
45 course: self.course,
46 sources,
47 payload: self.payload,
48 generated_at: self.generated_at,
49 }
50 }
51}
52
53/// The citation links of many outputs in one statement, grouped by output
54/// uuid (the domain id newtype is not `Hash`), every list in `source` order —
55/// the one order all reads rebuild, so a create's answer and any later read
56/// hand back equal `Vec`s.
57async fn sources_for_many(
58 db: &Database,
59 outputs: &[RagOutputId],
60) -> Result<HashMap<Uuid, Vec<CourseNoteFileId>>, AppError> {
61 let keys: Vec<Uuid> = outputs.iter().map(|output| output.uuid()).collect();
62 let links = sqlx::query!(
63 r#"SELECT output, source AS "source: CourseNoteFileId"
64 FROM rag_output_source WHERE output = ANY($1) ORDER BY source"#,
65 &keys
66 )
67 .fetch_all(db)
68 .await?;
69 let mut grouped: HashMap<Uuid, Vec<CourseNoteFileId>> = HashMap::new();
70 for link in links {
71 grouped.entry(link.output).or_default().push(link.source);
72 }
73 Ok(grouped)
74}
75
76/// The citation links of one output, in `source` order.
77async fn sources_for(
78 db: &Database,
79 output: &RagOutputId,
80) -> Result<Vec<CourseNoteFileId>, AppError> {
81 let mut grouped = sources_for_many(db, std::slice::from_ref(output)).await?;
82 Ok(grouped.remove(&output.uuid()).unwrap_or_default())
83}
84
85pub async fn create(
86 db: &Database,
87 note: &CourseNoteId,
88 course: &CourseId,
89 mut sources: Vec<CourseNoteFileId>,
90 payload: Value,
91) -> Result<RagOutput, AppError> {
92 // Link rows carry no order of their own; the source id is the order.
93 // Sorting here makes `create`'s answer equal to any later read's.
94 sources.sort_by_key(|file| file.uuid());
95 let keys: Vec<Uuid> = sources.iter().map(|file| file.uuid()).collect();
96 let id = RagOutputId::generate();
97 let generated_at = Timestamp::now();
98 // Owned binds: capturing `&CourseNoteId` / `&CourseId` across the
99 // `tx_with_retry` await poisons Send at every caller (ai/rag, course_notes).
100 let id_u = id.uuid();
101 let note_u = note.uuid();
102 let course_u = course.uuid();
103 let at = generated_at.as_millis();
104 let row = tx_with_retry(db, false, async move |tx| {
105 let created = sqlx::query_as!(
106 RagOutputRow,
107 r#"INSERT INTO rag_output (id, course_note, course, payload, generated_at)
108 VALUES ($1, $2, $3, $4, $5)
109 RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",
110 course AS "course: CourseId",
111 payload AS "payload: Json<Value>",
112 generated_at AS "generated_at: Timestamp""#,
113 id_u,
114 note_u,
115 course_u,
116 &payload,
117 at
118 )
119 .fetch_one(&mut *tx)
120 .await?;
121 sqlx::query!(
122 "INSERT INTO rag_output_source (output, source)
123 SELECT $1, s FROM unnest($2::uuid[]) AS t(s)",
124 created.id.uuid(),
125 &keys
126 )
127 .execute(&mut *tx)
128 .await?;
129 Ok(created)
130 })
131 .await?;
132 Ok(row.into_rag_output(sources))
133}
134
135pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> {
136 let row = sqlx::query_as!(
137 RagOutputRow,
138 r#"SELECT id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",
139 course AS "course: CourseId",
140 payload AS "payload: Json<Value>",
141 generated_at AS "generated_at: Timestamp"
142 FROM rag_output WHERE id = $1"#,
143 id.uuid()
144 )
145 .fetch_optional(db)
146 .await?;
147 match row {
148 Some(row) => {
149 let sources = sources_for(db, &row.id).await?;
150 Ok(Some(row.into_rag_output(sources)))
151 }
152 None => Ok(None),
153 }
154}
155
156/// A note's outputs, newest first.
157pub async fn list_for(
158 db: &Database,
159 note: &CourseNoteId,
160 limit: Option<i64>,
161 offset: i64,
162) -> Result<(Vec<RagOutput>, i64), AppError> {
163 let (rows, total) = PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC")
164 .bind(note.uuid())
165 .run::<RagOutputRow>(limit, offset, db)
166 .await?;
167 let ids: Vec<RagOutputId> = rows.iter().map(|row| row.id).collect();
168 let grouped = sources_for_many(db, &ids).await?;
169 let items = rows
170 .into_iter()
171 .map(|row| {
172 let sources = grouped.get(&row.id.uuid()).cloned().unwrap_or_default();
173 row.into_rag_output(sources)
174 })
175 .collect();
176 Ok((items, total))
177}
178
179pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> {
180 let id_u = id.uuid();
181 let (row, sources) = tx_with_retry(db, false, async move |tx| {
182 let sources = sqlx::query!(
183 r#"SELECT source AS "source: CourseNoteFileId"
184 FROM rag_output_source WHERE output = $1 ORDER BY source"#,
185 id_u
186 )
187 .fetch_all(&mut *tx)
188 .await?
189 .into_iter()
190 .map(|link| link.source)
191 .collect::<Vec<_>>();
192 sqlx::query!("DELETE FROM rag_output_source WHERE output = $1", id_u)
193 .execute(&mut *tx)
194 .await?;
195 sqlx::query_as!(
196 RagOutputRow,
197 r#"DELETE FROM rag_output WHERE id = $1
198 RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",
199 course AS "course: CourseId",
200 payload AS "payload: Json<Value>",
201 generated_at AS "generated_at: Timestamp""#,
202 id_u
203 )
204 .fetch_optional(&mut *tx)
205 .await?
206 .map(|row| (row, sources))
207 .ok_or(AppError::NotFound)
208 })
209 .await?;
210 Ok(row.into_rag_output(sources))
211}
212
213/// Cascade: every output of `note`. Deleting none is a success — a note
214/// no service ever indexed has nothing to drop. The links go before the
215/// rows: they are the rows' children (`ON DELETE NO ACTION`).
216pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> {
217 sqlx::query!(
218 "DELETE FROM rag_output_source WHERE output IN
219 (SELECT id FROM rag_output WHERE course_note = $1)",
220 note.uuid()
221 )
222 .execute(db)
223 .await?;
224 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.uuid())
225 .execute(db)
226 .await?;
227 Ok(())
228}
229
230/// Newest-wins replace, without a lock: store `payload` first, then drop
231/// this note's older rows. Two concurrent index tasks can interleave in any
232/// order and still leave exactly one row — the newest — because ids come
233/// from the process-wide monotonic generator, so "older" is `id <` the row
234/// just written and the loser's row is always below the winner's. (The
235/// uuid column compares in byte order, which for UUIDv7 is mint order —
236/// the same property the old record ids got from the ULID.)
237pub async fn replace_for_note(
238 db: &Database,
239 note: &CourseNoteId,
240 course: &CourseId,
241 sources: Vec<CourseNoteFileId>,
242 payload: Value,
243) -> Result<RagOutput, AppError> {
244 let created = create(db, note, course, sources, payload).await?;
245 // The superseded rows' links go first (`ON DELETE NO ACTION`), then the
246 // rows themselves. Neither delete can touch the row just written: its id
247 // is above every id the generator has minted before it.
248 sqlx::query!(
249 "DELETE FROM rag_output_source WHERE output IN
250 (SELECT id FROM rag_output WHERE course_note = $1 AND id < $2)",
251 note.uuid(),
252 created.id.uuid()
253 )
254 .execute(db)
255 .await?;
256 sqlx::query!(
257 "DELETE FROM rag_output WHERE course_note = $1 AND id < $2",
258 note.uuid(),
259 created.id.uuid()
260 )
261 .execute(db)
262 .await?;
263 Ok(created)
264}
265
266/// Cascade: the citation links that point at `file`. Runs on a file delete
267/// even with no AI service connected — `ON DELETE NO ACTION` refuses the
268/// file row while any link still cites it. An output a link belonged to
269/// stops being true the moment its source is gone; the re-index a file
270/// delete triggers regenerates it from what is left, and until then it
271/// reads as a shorter — possibly empty — citation list.
272pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {
273 sqlx::query!(
274 "DELETE FROM rag_output_source WHERE source = $1",
275 file.uuid()
276 )
277 .execute(db)
278 .await?;
279 Ok(())
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
286 use crate::domain::course_note::CourseNote;
287 use crate::domain::course_note::CourseNoteContent;
288 use crate::domain::course_note::CourseNoteTitle;
289 use crate::domain::course_note_file::CourseNoteFile;
290 use crate::domain::course_note_file::FileContentType;
291 use crate::domain::course_note_file::FileName;
292 use serde_json::json;
293
294 /// A real `app_user` row: the course's creator is a foreign key now.
295 async fn a_person(db: &Database) -> crate::domain::user::UserId {
296 let user = crate::domain::user::UserId::generate();
297 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)")
298 .bind(user.uuid())
299 .bind(format!("rag-{}", &user.key()[30..]))
300 .execute(db)
301 .await
302 .unwrap();
303 user
304 }
305
306 async fn note_of(db: &Database, title: &str) -> CourseNote {
307 // The course's creator is a foreign key now: a real `app_user` row.
308 let creator = a_person(db).await;
309 let course = crate::db::course::create(
310 db,
311 &creator,
312 CourseTitle::try_new("c").unwrap(),
313 CourseDescription::try_new("").unwrap(),
314 CourseKind::try_new("course").unwrap(),
315 )
316 .await
317 .unwrap();
318 crate::db::course_note::create(
319 db,
320 course.get_id(),
321 &creator,
322 CourseNoteTitle::try_new(title).unwrap(),
323 CourseNoteContent::try_new("body").unwrap(),
324 )
325 .await
326 .unwrap()
327 }
328
329 async fn a_file(db: &Database, note: &CourseNote) -> CourseNoteFile {
330 crate::db::course_note_file::insert(
331 db,
332 CourseNoteFile::new(
333 note.get_id(),
334 FileName::try_new("f").unwrap(),
335 FileContentType::try_new("text/plain").unwrap(),
336 1,
337 ),
338 )
339 .await
340 .unwrap()
341 }
342
343 /// A stored round-trips through JSONB with its citations intact, the
344 /// file row refuses to go while a citation stands (23503), and the note
345 /// cascade sweeps the links with the rows so the file can go after.
346 #[tokio::test]
347 async fn create_reads_back_and_cascades_from_the_note() {
348 let (db, _leases) = crate::database::init_test_db().await;
349 let note = note_of(&db, "n").await;
350 let file = a_file(&db, &note).await;
351 let row = create(
352 &db,
353 note.get_id(),
354 note.get_course(),
355 vec![file.get_id().clone()],
356 json!({"answer": "x"}),
357 )
358 .await
359 .unwrap();
360 let read_back = read(&db, row.get_id()).await.unwrap().unwrap();
361 assert_eq!(read_back.get_payload(), &json!({"answer": "x"}));
362 assert_eq!(read_back.get_sources(), &[file.get_id().clone()]);
363
364 let refused = sqlx::query("DELETE FROM course_note_file WHERE id = $1")
365 .bind(file.get_id().uuid())
366 .execute(&db)
367 .await;
368 let err = refused.unwrap_err();
369 assert!(crate::database::foreign_key_violation(&err), "{err}");
370
371 delete_for_note(&db, note.get_id()).await.unwrap();
372 assert!(read(&db, row.get_id()).await.unwrap().is_none());
373 // The cascade swept the links with the outputs: the file row goes now.
374 sqlx::query("DELETE FROM course_note_file WHERE id = $1")
375 .bind(file.get_id().uuid())
376 .execute(&db)
377 .await
378 .unwrap();
379 }
380
381 /// Replace leaves exactly one row — the newest — and the source cascade
382 /// drops the link a file delete strands: the row survives reading as an
383 /// empty citation list until the re-index replaces it, and the file row
384 /// can go.
385 #[tokio::test]
386 async fn replace_is_newest_wins_and_source_cascade_empties_the_citations() {
387 let (db, _leases) = crate::database::init_test_db().await;
388 let note = note_of(&db, "n").await;
389 let file = a_file(&db, &note).await;
390 let first = create(
391 &db,
392 note.get_id(),
393 note.get_course(),
394 vec![file.get_id().clone()],
395 json!({"v": 1}),
396 )
397 .await
398 .unwrap();
399 let second = replace_for_note(
400 &db,
401 note.get_id(),
402 note.get_course(),
403 vec![file.get_id().clone()],
404 json!({"v": 2}),
405 )
406 .await
407 .unwrap();
408 let (rows, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
409 assert_eq!(total, 1);
410 assert_eq!(rows[0].get_id(), second.get_id());
411 assert!(first.get_id() != second.get_id());
412
413 delete_with_source(&db, file.get_id()).await.unwrap();
414 let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
415 assert_eq!(total, 1);
416 let survivor = read(&db, second.get_id()).await.unwrap().unwrap();
417 assert!(survivor.get_sources().is_empty());
418 // Links first, file after: with the link gone the file row deletes.
419 sqlx::query("DELETE FROM course_note_file WHERE id = $1")
420 .bind(file.get_id().uuid())
421 .execute(&db)
422 .await
423 .unwrap();
424 }
425
426 /// Deleting one row returns it, citations included; deleting it again is
427 /// a 404.
428 #[tokio::test]
429 async fn delete_returns_the_row_then_refuses() {
430 let (db, _leases) = crate::database::init_test_db().await;
431 let note = note_of(&db, "n").await;
432 let file = a_file(&db, &note).await;
433 let row = create(
434 &db,
435 note.get_id(),
436 note.get_course(),
437 vec![file.get_id().clone()],
438 json!({}),
439 )
440 .await
441 .unwrap();
442 let gone = delete(&db, row.get_id()).await.unwrap();
443 assert_eq!(gone.get_id(), row.get_id());
444 assert_eq!(gone.get_sources(), &[file.get_id().clone()]);
445 assert!(matches!(
446 delete(&db, row.get_id()).await,
447 Err(AppError::NotFound)
448 ));
449 }
450}