forge
Explore
Log in

Don't you dare go Hollow

Rag_output cascade order, newest-wins replace, sources index

Browse files at this commit

ff36c8ce76f4a7eb1afd3b88aaec6fc39978b23dAhmet Kaan GümüşParent: 21a644f
  • fix
    • rag_output cascade order, newest-wins replace, sources index
Show full message
🐛 fix: rag_output cascade order, newest-wins replace, sources index

Index the `sources` array (per element) and query it with CONTAINS so the
file cascade is a lookup, not a scan; retire the unused `course` index.
Run the rag cascade BEFORE the primary delete in both course-note delete
handlers: derived rows are disposable, so a failure there leaves the note
or file intact instead of 500ing after the row is gone and stranding blobs.
Replace is now create-then-drop-older, so two concurrent rag.index tasks
converge on exactly one row (the newest monotonic id) with no lock.

Ref #27
src/ai/rag.rsmodified+5 -4
@@ -131,16 +131,17 @@ pub async fn index_course_note(state: &AppState, note: &CourseNote) {
131 }131 }
132 }132 }
133 133
134-/// Swap the note's outputs for the fresh one. Delete-then-create, not an134+/// Swap the note's outputs for the fresh one. Create-then-drop-older, not an
135-/// update: the previous output belongs to a previous version of the note.135+/// update: the previous output belongs to a previous version of the note, and
136+/// this order is what makes two concurrent index tasks converge on one row
137+/// ([`RagOutput::replace_for_note`]).
136 async fn replace(138 async fn replace(
137 db: &Database,139 db: &Database,
138 note: &CourseNote,140 note: &CourseNote,
139 sources: Vec<crate::domain::course_note_file::CourseNoteFileId>,141 sources: Vec<crate::domain::course_note_file::CourseNoteFileId>,
140 payload: serde_json::Value,142 payload: serde_json::Value,
141 ) -> Result<(), crate::error::AppError> {143 ) -> Result<(), crate::error::AppError> {
142- RagOutput::delete_for_note(note.get_id(), db).await?;144+ RagOutput::replace_for_note(note.get_id(), note.get_course(), sources, payload, db).await?;
143- RagOutput::create(note.get_id(), note.get_course(), sources, payload, db).await?;
144 Ok(())145 Ok(())
145 }146 }
146 147
src/domain/rag_output.rsmodified+67 -1
@@ -146,6 +146,27 @@ impl RagOutput {
146 Ok(())146 Ok(())
147 }147 }
148 148
149+ /// Newest-wins replace, without a lock: store `payload` first, then drop
150+ /// this note's older rows. Two concurrent index tasks can interleave in any
151+ /// order and still leave exactly one row — the newest — because ids come
152+ /// from the process-wide monotonic generator, so "older" is `id <` the row
153+ /// just written and the loser's row is always below the winner's.
154+ pub async fn replace_for_note(
155+ note: &CourseNoteId,
156+ course: &CourseId,
157+ sources: Vec<CourseNoteFileId>,
158+ payload: Value,
159+ db: &Database,
160+ ) -> Result<RagOutput, AppError> {
161+ let created = Self::create(note, course, sources, payload, db).await?;
162+ db.query("DELETE rag_output WHERE course_note = $note AND id < $new")
163+ .bind(("note", note.record()))
164+ .bind(("new", created.id.record()))
165+ .await?
166+ .check()?;
167+ Ok(created)
168+ }
169+
149 /// Cascade: every output built from `file`. Runs on a file delete even170 /// Cascade: every output built from `file`. Runs on a file delete even
150 /// with no AI service connected, so a stale output cannot survive its171 /// with no AI service connected, so a stale output cannot survive its
151 /// source.172 /// source.
@@ -153,7 +174,7 @@ impl RagOutput {
153 file: &CourseNoteFileId,174 file: &CourseNoteFileId,
154 db: &Database,175 db: &Database,
155 ) -> Result<(), AppError> {176 ) -> Result<(), AppError> {
156- db.query("DELETE rag_output WHERE $file IN sources")177+ db.query("DELETE rag_output WHERE sources CONTAINS $file")
157 .bind(("file", file.record()))178 .bind(("file", file.record()))
158 .await?179 .await?
159 .check()?;180 .check()?;
@@ -207,6 +228,51 @@ mod tests {
207 .clone()228 .clone()
208 }229 }
209 230
231+ /// Replace converges on one row — the newest — even when an earlier
232+ /// interleaving already left two rows behind for the note.
233+ #[tokio::test]
234+ async fn replace_keeps_only_the_newest_output() {
235+ let db = crate::database::init_mem().await.unwrap();
236+ let note = note_of(&db, "a").await;
237+ let stale = RagOutput::create(
238+ note.get_id(),
239+ note.get_course(),
240+ Vec::new(),
241+ json!({ "n": 1 }),
242+ &db,
243+ )
244+ .await
245+ .unwrap();
246+ // The race this fixes: a second row for the same note.
247+ RagOutput::create(
248+ note.get_id(),
249+ note.get_course(),
250+ Vec::new(),
251+ json!({ "n": 2 }),
252+ &db,
253+ )
254+ .await
255+ .unwrap();
256+
257+ let fresh = RagOutput::replace_for_note(
258+ note.get_id(),
259+ note.get_course(),
260+ Vec::new(),
261+ json!({ "n": 3 }),
262+ &db,
263+ )
264+ .await
265+ .unwrap();
266+
267+ let rows = RagOutput::list_for(note.get_id(), None, 0, &db)
268+ .await
269+ .unwrap()
270+ .0;
271+ assert_eq!(rows.len(), 1);
272+ assert_eq!(rows[0].get_id(), fresh.get_id());
273+ assert!(fresh.get_id().key() > stale.get_id().key());
274+ }
275+
210 /// The payload survives the round trip unread, and both cascades take only276 /// The payload survives the round trip unread, and both cascades take only
211 /// what they are aimed at.277 /// what they are aimed at.
212 #[tokio::test]278 #[tokio::test]
src/migration_sql.rsmodified+5 -1
@@ -210,7 +210,11 @@ pub const MIGRATION: &str = "
210 DEFINE FIELD IF NOT EXISTS payload ON rag_output TYPE object FLEXIBLE;210 DEFINE FIELD IF NOT EXISTS payload ON rag_output TYPE object FLEXIBLE;
211 DEFINE FIELD IF NOT EXISTS generated_at ON rag_output TYPE int;211 DEFINE FIELD IF NOT EXISTS generated_at ON rag_output TYPE int;
212 DEFINE INDEX IF NOT EXISTS rag_output_note ON rag_output FIELDS course_note;212 DEFINE INDEX IF NOT EXISTS rag_output_note ON rag_output FIELDS course_note;
213- DEFINE INDEX IF NOT EXISTS rag_output_course ON rag_output FIELDS course;213+ -- Retire the course index: nothing queries rag_output by course.
214+ REMOVE INDEX IF EXISTS rag_output_course ON rag_output;
215+ -- Indexed per element, so the source cascade's `sources CONTAINS $file`
216+ -- is a lookup rather than a table scan.
217+ DEFINE INDEX IF NOT EXISTS rag_output_source ON rag_output FIELDS sources;
214 218
215 -- Chatbot relay (2026-07-23): a `thread` groups the turns, one219 -- Chatbot relay (2026-07-23): a `thread` groups the turns, one
216 -- `chatbot_message` is one turn. `user_id` rides on the message too so an220 -- `chatbot_message` is one turn. `user_id` rides on the message too so an
src/web/course_notes.rsmodified+10 -9
@@ -292,16 +292,16 @@ async fn delete_one(
292 "only the course creator, an assigned teacher, or a manager/admin can delete this course note",292 "only the course creator, an assigned teacher, or a manager/admin can delete this course note",
293 ));293 ));
294 }294 }
295- let note_id = &note.get_id().clone();295+ // Derived rows first, outside the note's own cascade transaction: they are
296+ // disposable, so failing here leaves the note intact and the 500 truthful,
297+ // whereas dropping them after the note would strand every blob on an error
298+ // — and if the note delete then fails, the next change regenerates them.
299+ RagOutput::delete_for_note(note.get_id(), &st.db).await?;
296 // Rows go first (the note delete cascades them), blobs after: a crash in300 // Rows go first (the note delete cascades them), blobs after: a crash in
297 // between strands at worst an unreachable blob, never a row whose blob is301 // between strands at worst an unreachable blob, never a row whose blob is
298 // already gone. The files to unlink come from the delete itself, not a302 // already gone. The files to unlink come from the delete itself, not a
299 // pre-read list — an upload that landed in between is in the cascade too.303 // pre-read list — an upload that landed in between is in the cascade too.
300 let (_, files) = note.delete(&st.db).await?;304 let (_, files) = note.delete(&st.db).await?;
301- // Derived rows go with their note. Not part of the note's own cascade
302- // transaction on purpose: an index is disposable, and failing the delete
303- // over one would leave the caller unable to remove their note at all.
304- RagOutput::delete_for_note(note_id, &st.db).await?;
305 for file in &files {305 for file in &files {
306 remove_blob(&st.files_path, file.get_id().key()).await;306 remove_blob(&st.files_path, file.get_id().key()).await;
307 }307 }
@@ -523,12 +523,13 @@ async fn delete_file(
523 CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db)523 CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db)
524 .await?524 .await?
525 .ok_or(AppError::NotFound)?;525 .ok_or(AppError::NotFound)?;
526+ // Drop every output built from this file before the file itself, so a
527+ // stale index cannot outlive its source in a deployment with no AI service
528+ // at all, and a failure here leaves the file whole instead of stranding its
529+ // blob; the re-index rebuilds from what is left, if a service is connected.
530+ RagOutput::delete_with_source(file.get_id(), &st.db).await?;
526 let file = file.delete(&st.db).await?;531 let file = file.delete(&st.db).await?;
527 remove_blob(&st.files_path, file.get_id().key()).await;532 remove_blob(&st.files_path, file.get_id().key()).await;
528- // Drop every output built from this file first, so a stale index cannot
529- // outlive its source in a deployment with no AI service at all; the
530- // re-index then rebuilds from what is left, if a service is connected.
531- RagOutput::delete_with_source(file.get_id(), &st.db).await?;
532 spawn_index(&st, note);533 spawn_index(&st, note);
533 Ok(StatusCode::NO_CONTENT)534 Ok(StatusCode::NO_CONTENT)
534 }535 }