From ff36c8ce76f4a7eb1afd3b88aaec6fc39978b23d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 08:20:24 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20rag=5Foutput=20cascade=20?= =?UTF-8?q?order,=20newest-wins=20replace,=20sources=20index?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 9 +++--- src/domain/rag_output.rs | 68 +++++++++++++++++++++++++++++++++++++++- src/migration_sql.rs | 6 +++- src/web/course_notes.rs | 19 +++++------ 4 files changed, 87 insertions(+), 15 deletions(-) diff --git a/src/ai/rag.rs b/src/ai/rag.rs index 401dd28..7befdfc 100644 --- a/src/ai/rag.rs +++ b/src/ai/rag.rs @@ -131,16 +131,17 @@ pub async fn index_course_note(state: &AppState, note: &CourseNote) { } } -/// Swap the note's outputs for the fresh one. Delete-then-create, not an -/// update: the previous output belongs to a previous version of the note. +/// Swap the note's outputs for the fresh one. Create-then-drop-older, not an +/// update: the previous output belongs to a previous version of the note, and +/// this order is what makes two concurrent index tasks converge on one row +/// ([`RagOutput::replace_for_note`]). async fn replace( db: &Database, note: &CourseNote, sources: Vec, payload: serde_json::Value, ) -> Result<(), crate::error::AppError> { - RagOutput::delete_for_note(note.get_id(), db).await?; - RagOutput::create(note.get_id(), note.get_course(), sources, payload, db).await?; + RagOutput::replace_for_note(note.get_id(), note.get_course(), sources, payload, db).await?; Ok(()) } diff --git a/src/domain/rag_output.rs b/src/domain/rag_output.rs index 2fdbe29..338fbec 100644 --- a/src/domain/rag_output.rs +++ b/src/domain/rag_output.rs @@ -146,6 +146,27 @@ impl RagOutput { Ok(()) } + /// Newest-wins replace, without a lock: store `payload` first, then drop + /// this note's older rows. Two concurrent index tasks can interleave in any + /// order and still leave exactly one row — the newest — because ids come + /// from the process-wide monotonic generator, so "older" is `id <` the row + /// just written and the loser's row is always below the winner's. + pub async fn replace_for_note( + note: &CourseNoteId, + course: &CourseId, + sources: Vec, + payload: Value, + db: &Database, + ) -> Result { + let created = Self::create(note, course, sources, payload, db).await?; + db.query("DELETE rag_output WHERE course_note = $note AND id < $new") + .bind(("note", note.record())) + .bind(("new", created.id.record())) + .await? + .check()?; + Ok(created) + } + /// Cascade: every output built from `file`. Runs on a file delete even /// with no AI service connected, so a stale output cannot survive its /// source. @@ -153,7 +174,7 @@ impl RagOutput { file: &CourseNoteFileId, db: &Database, ) -> Result<(), AppError> { - db.query("DELETE rag_output WHERE $file IN sources") + db.query("DELETE rag_output WHERE sources CONTAINS $file") .bind(("file", file.record())) .await? .check()?; @@ -207,6 +228,51 @@ mod tests { .clone() } + /// Replace converges on one row — the newest — even when an earlier + /// interleaving already left two rows behind for the note. + #[tokio::test] + async fn replace_keeps_only_the_newest_output() { + let db = crate::database::init_mem().await.unwrap(); + let note = note_of(&db, "a").await; + let stale = RagOutput::create( + note.get_id(), + note.get_course(), + Vec::new(), + json!({ "n": 1 }), + &db, + ) + .await + .unwrap(); + // The race this fixes: a second row for the same note. + RagOutput::create( + note.get_id(), + note.get_course(), + Vec::new(), + json!({ "n": 2 }), + &db, + ) + .await + .unwrap(); + + let fresh = RagOutput::replace_for_note( + note.get_id(), + note.get_course(), + Vec::new(), + json!({ "n": 3 }), + &db, + ) + .await + .unwrap(); + + let rows = RagOutput::list_for(note.get_id(), None, 0, &db) + .await + .unwrap() + .0; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get_id(), fresh.get_id()); + assert!(fresh.get_id().key() > stale.get_id().key()); + } + /// The payload survives the round trip unread, and both cascades take only /// what they are aimed at. #[tokio::test] diff --git a/src/migration_sql.rs b/src/migration_sql.rs index c080fe5..4a35470 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -210,7 +210,11 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS payload ON rag_output TYPE object FLEXIBLE; DEFINE FIELD IF NOT EXISTS generated_at ON rag_output TYPE int; DEFINE INDEX IF NOT EXISTS rag_output_note ON rag_output FIELDS course_note; - DEFINE INDEX IF NOT EXISTS rag_output_course ON rag_output FIELDS course; + -- Retire the course index: nothing queries rag_output by course. + REMOVE INDEX IF EXISTS rag_output_course ON rag_output; + -- Indexed per element, so the source cascade's `sources CONTAINS $file` + -- is a lookup rather than a table scan. + DEFINE INDEX IF NOT EXISTS rag_output_source ON rag_output FIELDS sources; -- Chatbot relay (2026-07-23): a `thread` groups the turns, one -- `chatbot_message` is one turn. `user_id` rides on the message too so an diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index 905e6d2..8b2754f 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -292,16 +292,16 @@ async fn delete_one( "only the course creator, an assigned teacher, or a manager/admin can delete this course note", )); } - let note_id = ¬e.get_id().clone(); + // Derived rows first, outside the note's own cascade transaction: they are + // disposable, so failing here leaves the note intact and the 500 truthful, + // whereas dropping them after the note would strand every blob on an error + // — and if the note delete then fails, the next change regenerates them. + RagOutput::delete_for_note(note.get_id(), &st.db).await?; // Rows go first (the note delete cascades them), blobs after: a crash in // between strands at worst an unreachable blob, never a row whose blob is // already gone. The files to unlink come from the delete itself, not a // pre-read list — an upload that landed in between is in the cascade too. let (_, files) = note.delete(&st.db).await?; - // Derived rows go with their note. Not part of the note's own cascade - // transaction on purpose: an index is disposable, and failing the delete - // over one would leave the caller unable to remove their note at all. - RagOutput::delete_for_note(note_id, &st.db).await?; for file in &files { remove_blob(&st.files_path, file.get_id().key()).await; } @@ -523,12 +523,13 @@ async fn delete_file( CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) .await? .ok_or(AppError::NotFound)?; + // Drop every output built from this file before the file itself, so a + // stale index cannot outlive its source in a deployment with no AI service + // at all, and a failure here leaves the file whole instead of stranding its + // blob; the re-index rebuilds from what is left, if a service is connected. + RagOutput::delete_with_source(file.get_id(), &st.db).await?; let file = file.delete(&st.db).await?; remove_blob(&st.files_path, file.get_id().key()).await; - // Drop every output built from this file first, so a stale index cannot - // outlive its source in a deployment with no AI service at all; the - // re-index then rebuilds from what is left, if a service is connected. - RagOutput::delete_with_source(file.get_id(), &st.db).await?; spawn_index(&st, note); Ok(StatusCode::NO_CONTENT) }