forge
Explore
Log in

Don't you dare go Hollow

Add a manual course-note RAG reindex door

Browse files at this commit

f5403d14959aeaec5644a65c214600839c4f309fAhmet Kaan GümüşParent: d0dce85
  • feat
    • add a manual course-note RAG reindex door
Show full message
✨ feat: add a manual course-note RAG reindex door
src/web/chatbot.rsmodified+3 -15
@@ -53,7 +53,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
53 use crate::service;53 use crate::service;
54 use crate::state::{AppState, scoped_key};54 use crate::state::{AppState, scoped_key};
55 55
56-use super::{CurrentUser, Page, PageParams};56+use super::{CurrentUser, Page, PageParams, ai_unavailable};
57 57
58 pub fn routes() -> OpenApiRouter<AppState> {58 pub fn routes() -> OpenApiRouter<AppState> {
59 OpenApiRouter::new()59 OpenApiRouter::new()
@@ -406,12 +406,12 @@ async fn send_message(
406 // documented racy — that is fine here: it never guards a write, it only406 // documented racy — that is fine here: it never guards a write, it only
407 // spares the user a thread full of rows nothing could ever answer.407 // spares the user a thread full of rows nothing could ever answer.
408 let Some(bridge) = st.ai.clone() else {408 let Some(bridge) = st.ai.clone() else {
409- return Ok(unavailable(409+ return Ok(ai_unavailable(
410 "the AI service is not enabled on this deployment",410 "the AI service is not enabled on this deployment",
411 ));411 ));
412 };412 };
413 if !bridge.has_capability(AI_CHAT_CAPABILITY) {413 if !bridge.has_capability(AI_CHAT_CAPABILITY) {
414- return Ok(unavailable("no AI service is connected right now"));414+ return Ok(ai_unavailable("no AI service is connected right now"));
415 }415 }
416 416
417 // Each create rides the thread's own row — it moves `updated_at` (the417 // Each create rides the thread's own row — it moves `updated_at` (the
@@ -475,18 +475,6 @@ fn content_cap(settings: &Settings) -> usize {
475 (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN)475 (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN)
476 }476 }
477 477
478-/// The AI-unavailable `503`. Built here rather than as an `AppError` variant:
479-/// this is the only route that can produce it, and `AppError`'s 503s all mean
480-/// "the database is reconnecting", which this is not. No `Retry-After` — when
481-/// a service will dial back in is unknowable.
482-fn unavailable(message: &str) -> Response {
483- (
484- StatusCode::SERVICE_UNAVAILABLE,
485- Json(json!({ "error": message })),
486- )
487- .into_response()
488-}
489-
490 /// Fetch one turn's answer and settle its row. Runs detached from the request.478 /// Fetch one turn's answer and settle its row. Runs detached from the request.
491 ///479 ///
492 /// Every path settles: a row left `pending` would show as a spinner forever.480 /// Every path settles: a row left `pending` would show as a spinner forever.
src/web/course_notes.rsmodified+63 -3
@@ -19,7 +19,7 @@ use utoipa_axum::router::OpenApiRouter;
19 use utoipa_axum::routes;19 use utoipa_axum::routes;
20 20
21 use crate::ai::rag::spawn_index;21 use crate::ai::rag::spawn_index;
22-use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};22+use crate::constant::{AI_RAG_INDEX_CAPABILITY, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
23 use crate::database::Database;23 use crate::database::Database;
24 use crate::domain::course::{Course, CourseId};24 use crate::domain::course::{Course, CourseId};
25 use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle};25 use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteId, CourseNoteTitle};
@@ -28,14 +28,15 @@ use crate::domain::course_note_file::{
28 };28 };
29 use crate::domain::rag_output::{RagOutput, RagOutputId};29 use crate::domain::rag_output::{RagOutput, RagOutputId};
30 use crate::error::{AppError, ErrorResponse};30 use crate::error::{AppError, ErrorResponse};
31+use crate::module::Module;
31 use crate::service;32 use crate::service;
32 use crate::state::AppState;33 use crate::state::AppState;
33 34
34 use super::courses::{can_manage_course, can_view_course};35 use super::courses::{can_manage_course, can_view_course};
35 use super::notes::content_disposition;36 use super::notes::content_disposition;
36 use super::{37 use super::{
37- CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, read_upload,38+ CurrentUser, Page, PageParams, RequireTeacher, UploadFileForm, ai_unavailable, blob_path,
38- remove_blob,39+ read_upload, remove_blob,
39 };40 };
40 41
41 pub fn routes() -> OpenApiRouter<AppState> {42 pub fn routes() -> OpenApiRouter<AppState> {
@@ -52,6 +53,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
52 .routes(routes!(create, list))53 .routes(routes!(create, list))
53 .routes(routes!(get_one, update, delete_one))54 .routes(routes!(get_one, update, delete_one))
54 .routes(routes!(list_rag))55 .routes(routes!(list_rag))
56+ .routes(routes!(reindex_rag))
55 .routes(routes!(delete_rag))57 .routes(routes!(delete_rag))
56 .merge(files)58 .merge(files)
57 }59 }
@@ -660,3 +662,61 @@ async fn delete_rag(
660 service::rag_output::delete(&st.db, output.get_id()).await?;662 service::rag_output::delete(&st.db, output.get_id()).await?;
661 Ok(StatusCode::NO_CONTENT)663 Ok(StatusCode::NO_CONTENT)
662 }664 }
665+
666+/// Re-index a course note now, without waiting for its next write.
667+///
668+/// Indexing otherwise fires only on a note or file write, so a note saved
669+/// while no AI service was connected stays unindexed until something touches
670+/// it again — this door re-runs the same dispatch on demand. The `202` says
671+/// the re-index was *dispatched*, not that it finished: the bridge round trip
672+/// runs off the request path ([`spawn_index`]), and an unreachable service
673+/// leaves the stored index as it was. Poll `GET /course-notes/{id}/rag` for
674+/// the output once it lands.
675+#[utoipa::path(
676+ post,
677+ path = "/{id}/rag/reindex",
678+ tag = "course-notes",
679+ security(("session_cookie" = [])),
680+ params(("id" = String, Path, description = "Course note id")),
681+ responses(
682+ (status = 202, description = "Re-index dispatched; poll `GET /course-notes/{id}/rag` for the stored output"),
683+ (status = 401, description = "Not authenticated", body = ErrorResponse),
684+ (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
685+ (status = 404, description = "Not found", body = ErrorResponse),
686+ (status = 503, description = "No AI service is available — nothing was written, retry later", body = ErrorResponse),
687+ ),
688+)]
689+async fn reindex_rag(
690+ State(st): State<AppState>,
691+ tenant: ResolvedTenant,
692+ RequireTeacher(user): RequireTeacher,
693+ Path(id): Path<String>,
694+) -> Result<Response, AppError> {
695+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
696+ if !can_manage_course(&course, &user) {
697+ return Err(AppError::Forbidden(
698+ "only the course creator or a manager/admin can re-index this course note",
699+ ));
700+ }
701+ // The same 503 gate `ai::rag::index_course_note` applies internally, lifted
702+ // here so the caller learns why nothing will happen instead of getting a
703+ // `202` for a dispatch that would silently no-op. `has_capability` is racy
704+ // by design and guards no write — the note is untouched either way.
705+ if !tenant.modules.contains(Module::Chatbot) {
706+ return Ok(ai_unavailable(
707+ "the AI service is not enabled on this deployment",
708+ ));
709+ }
710+ let Some(bridge) = st.ai.as_ref() else {
711+ return Ok(ai_unavailable(
712+ "the AI service is not enabled on this deployment",
713+ ));
714+ };
715+ if !bridge.has_capability(AI_RAG_INDEX_CAPABILITY) {
716+ return Ok(ai_unavailable("no AI service is connected right now"));
717+ }
718+ // `note` was just read through the shared path, so the dispatched payload
719+ // is the note as it stands now.
720+ spawn_index(&st, &tenant, note);
721+ Ok(StatusCode::ACCEPTED.into_response())
722+}
src/web/mod.rsmodified+14 -0
@@ -62,12 +62,14 @@ pub use page::{Page, PageParams, Scheduled, WindowParams, paginate};
62 62
63 use std::path::{Path as FsPath, PathBuf};63 use std::path::{Path as FsPath, PathBuf};
64 64
65+use axum::Json;
65 use axum::extract::Multipart;66 use axum::extract::Multipart;
66 use axum::extract::multipart::MultipartError;67 use axum::extract::multipart::MultipartError;
67 use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};68 use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, X_CONTENT_TYPE_OPTIONS};
68 use axum::http::{HeaderValue, StatusCode};69 use axum::http::{HeaderValue, StatusCode};
69 use axum::response::{IntoResponse, Response};70 use axum::response::{IntoResponse, Response};
70 use serde::{Deserialize, Deserializer};71 use serde::{Deserialize, Deserializer};
72+use serde_json::json;
71 use utoipa::ToSchema;73 use utoipa::ToSchema;
72 74
73 use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS};75 use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS};
@@ -363,6 +365,18 @@ where
363 Option::<T>::deserialize(de).map(Some)365 Option::<T>::deserialize(de).map(Some)
364 }366 }
365 367
368+/// The AI-unavailable `503`. Shared by every route that can refuse because no
369+/// AI service is reachable: built here rather than as an `AppError` variant —
370+/// `AppError`'s 503s all mean "the database is reconnecting", which this is
371+/// not. No `Retry-After` — when a service will dial back in is unknowable.
372+pub(crate) fn ai_unavailable(message: &str) -> Response {
373+ (
374+ StatusCode::SERVICE_UNAVAILABLE,
375+ Json(json!({ "error": message })),
376+ )
377+ .into_response()
378+}
379+
366 #[cfg(test)]380 #[cfg(test)]
367 mod tests {381 mod tests {
368 use super::*;382 use super::*;
tests/integration.rsmodified+77 -1
@@ -433,7 +433,7 @@ async fn protected_routes_require_session() {
433 /// Floor on the number of protected operations swept. It only ever goes433 /// Floor on the number of protected operations swept. It only ever goes
434 /// up: raise it when routes are added. Without it, deleting a route family434 /// up: raise it when routes are added. Without it, deleting a route family
435 /// would delete its own coverage and still pass.435 /// would delete its own coverage and still pass.
436- const MIN_PROTECTED: usize = 268;436+ const MIN_PROTECTED: usize = 269;
437 437
438 let app = mem_app().await;438 let app = mem_app().await;
439 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)439 let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
@@ -27847,6 +27847,82 @@ async fn course_note_rag_outputs_read_and_delete() {
27847 assert_eq!(common::total(&list.body), 0, "{}", list.body);27847 assert_eq!(common::total(&list.body), 0, "{}", list.body);
27848 }27848 }
27849 27849
27850+/// The manual reindex door is a note write like any other: teacher+, and
27851+/// management rights over the parent course. A foreign teacher, a student, and
27852+/// an unknown note are all refused — and none of them writes a row.
27853+#[tokio::test]
27854+async fn course_note_rag_reindex_denies_foreign_teacher_student_and_unknown_note() {
27855+ let (app, db) = app_and_db().await;
27856+ let creator = login_as(&app, &db, "reindex_teacher", "teacher").await;
27857+ let outsider = login_as(&app, &db, "reindex_other_teacher", "teacher").await;
27858+ let student = login_as(&app, &db, "reindex_student", "student").await;
27859+
27860+ let course = create_course(&app, &creator, "reindex").await;
27861+ let note = create_course_note(&app, &creator, &course, "to reindex").await;
27862+ let uri = format!("/course-notes/{note}/rag/reindex");
27863+
27864+ // A teacher who does not manage the course: 403, like every other write.
27865+ let res = send(&app, "POST", &uri, Some(&outsider), None).await;
27866+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
27867+
27868+ // A student fails the teacher+ wall before any rights check.
27869+ let res = send(&app, "POST", &uri, Some(&student), None).await;
27870+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
27871+
27872+ // An unknown note is a 404, never a silent 202.
27873+ let res = send(
27874+ &app,
27875+ "POST",
27876+ "/course-notes/01NOTANOTE/rag/reindex",
27877+ Some(&creator),
27878+ None,
27879+ )
27880+ .await;
27881+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
27882+
27883+ let (rows, total) =
27884+ hezarfen_backend::db::rag_output::list_for(&db, &CourseNoteId::from_key(&note), None, 0)
27885+ .await
27886+ .unwrap();
27887+ assert!(rows.is_empty() && total == 0, "a refusal wrote a row");
27888+}
27889+
27890+/// With no AI service connected the door answers `503` and dispatches nothing:
27891+/// a `202` here would promise a reindex nothing could ever run.
27892+#[tokio::test]
27893+async fn course_note_rag_reindex_reports_503_and_writes_nothing_without_a_service() {
27894+ // `app_and_db` wires no AI bridge in — the same "no service connected"
27895+ // state a school is in before its AI features are provisioned.
27896+ let (app, db) = app_and_db().await;
27897+ let creator = login_as(&app, &db, "reindex_off_teacher", "teacher").await;
27898+ let course = create_course(&app, &creator, "reindex_off").await;
27899+ let note = create_course_note(&app, &creator, &course, "unindexed").await;
27900+
27901+ let res = send(
27902+ &app,
27903+ "POST",
27904+ &format!("/course-notes/{note}/rag/reindex"),
27905+ Some(&creator),
27906+ None,
27907+ )
27908+ .await;
27909+ assert_eq!(res.status, StatusCode::SERVICE_UNAVAILABLE, "{}", res.body);
27910+ assert!(
27911+ res.body["error"].as_str().is_some_and(|e| !e.is_empty()),
27912+ "{}",
27913+ res.body
27914+ );
27915+
27916+ let (rows, total) =
27917+ hezarfen_backend::db::rag_output::list_for(&db, &CourseNoteId::from_key(&note), None, 0)
27918+ .await
27919+ .unwrap();
27920+ assert!(
27921+ rows.is_empty() && total == 0,
27922+ "reindex dispatched while no service was connected"
27923+ );
27924+}
27925+
27850 // =========================================================================27926 // =========================================================================
27851 // Multi-school isolation probes (REFUTE lane B). Two schools, same usernames.27927 // Multi-school isolation probes (REFUTE lane B). Two schools, same usernames.
27852 // =========================================================================27928 // =========================================================================