Rag_output cascade order, newest-wins replace, sources index
Browse files at this commitff36c8ce76f4a7eb1afd3b88aaec6fc39978b23dParent: 21a644f- fix
- rag_output cascade order, newest-wins replace, sources index
4 changed files +87 -15
- src/ai/rag.rs +5 -4
- src/domain/rag_output.rs +67 -1
- src/migration_sql.rs +5 -1
- src/web/course_notes.rs +10 -9
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 an | |
| 135 | -/// update: the previous output belongs to a previous version of the note. | |
| 134 | +/// 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, and | |
| 136 | +/// this order is what makes two concurrent index tasks converge on one row | |
| 137 | +/// ([`RagOutput::replace_for_note`]). | |
| 136 | 138 | async fn replace( |
| 137 | 139 | db: &Database, |
| 138 | 140 | note: &CourseNote, |
| 139 | 141 | sources: Vec<crate::domain::course_note_file::CourseNoteFileId>, |
| 140 | 142 | payload: serde_json::Value, |
| 141 | 143 | ) -> Result<(), crate::error::AppError> { |
| 142 | - RagOutput::delete_for_note(note.get_id(), db).await?; | |
| 143 | - RagOutput::create(note.get_id(), note.get_course(), sources, payload, db).await?; | |
| 144 | + RagOutput::replace_for_note(note.get_id(), note.get_course(), sources, payload, db).await?; | |
| 144 | 145 | Ok(()) |
| 145 | 146 | } |
| 146 | 147 |
src/domain/rag_output.rsmodified+67 -1
| @@ -146,6 +146,27 @@ impl RagOutput { | ||
| 146 | 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 | 170 | /// Cascade: every output built from `file`. Runs on a file delete even |
| 150 | 171 | /// with no AI service connected, so a stale output cannot survive its |
| 151 | 172 | /// source. |
| @@ -153,7 +174,7 @@ impl RagOutput { | ||
| 153 | 174 | file: &CourseNoteFileId, |
| 154 | 175 | db: &Database, |
| 155 | 176 | ) -> Result<(), AppError> { |
| 156 | - db.query("DELETE rag_output WHERE $file IN sources") | |
| 177 | + db.query("DELETE rag_output WHERE sources CONTAINS $file") | |
| 157 | 178 | .bind(("file", file.record())) |
| 158 | 179 | .await? |
| 159 | 180 | .check()?; |
| @@ -207,6 +228,51 @@ mod tests { | ||
| 207 | 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 | 276 | /// The payload survives the round trip unread, and both cascades take only |
| 211 | 277 | /// what they are aimed at. |
| 212 | 278 | #[tokio::test] |
src/migration_sql.rsmodified+5 -1
| @@ -210,7 +210,11 @@ pub const MIGRATION: &str = " | ||
| 210 | 210 | DEFINE FIELD IF NOT EXISTS payload ON rag_output TYPE object FLEXIBLE; |
| 211 | 211 | DEFINE FIELD IF NOT EXISTS generated_at ON rag_output TYPE int; |
| 212 | 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 | 219 | -- Chatbot relay (2026-07-23): a `thread` groups the turns, one |
| 216 | 220 | -- `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 | 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 = ¬e.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 | 300 | // Rows go first (the note delete cascades them), blobs after: a crash in |
| 297 | 301 | // between strands at worst an unreachable blob, never a row whose blob is |
| 298 | 302 | // already gone. The files to unlink come from the delete itself, not a |
| 299 | 303 | // pre-read list — an upload that landed in between is in the cascade too. |
| 300 | 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 | 305 | for file in &files { |
| 306 | 306 | remove_blob(&st.files_path, file.get_id().key()).await; |
| 307 | 307 | } |
| @@ -523,12 +523,13 @@ async fn delete_file( | ||
| 523 | 523 | CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) |
| 524 | 524 | .await? |
| 525 | 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 | 531 | let file = file.delete(&st.db).await?; |
| 527 | 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 | 533 | spawn_index(&st, note); |
| 533 | 534 | Ok(StatusCode::NO_CONTENT) |
| 534 | 535 | } |