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.rs384 lines, 15.0 KiBHistoryRawDownload
1//! Payload contract for the `rag.index` capability, and the dispatch behind
2//! it.
3//!
4//! Unlike [`chat`](crate::ai::chat) — a user waiting on an answer — this one
5//! is a background refresh: a course note changed, so whatever a service had
6//! indexed for it is stale. [`spawn_index`] therefore returns immediately and
7//! the round trip runs in its own task, because no course-note handler may
8//! slow down, fail, or 503 on account of an AI service.
9//!
10//! Failure is silence by design: no worker, a timeout, a transport error or an
11//! unreadable answer all leave the previously stored
12//! [`RagOutput`](crate::domain::rag_output::RagOutput) rows exactly as they
13//! are. A slightly stale index beats no index.
14//!
15//! A service restart wipes an in-memory index and does not replay it.
16//! [`spawn_index_replay`] runs when a worker that offers `rag.index`
17//! registers, and calls [`index_course_note`] for every course note that has
18//! files, in every active school. The spawn returns immediately: the QUIC
19//! handshake must not wait on it. A chatbot, zeka, or podcast registration
20//! does not offer `rag.index`, so it does not replay.
21
22use serde::{Deserialize, Serialize};
23
24use crate::constant::AI_RAG_INDEX_TIMEOUT_SECS;
25use crate::database::Database;
26use crate::domain::course_note::CourseNote;
27use crate::domain::course_note_file::CourseNoteFile;
28use crate::module::Module;
29use crate::state::AppState;
30use crate::tenant::ResolvedTenant;
31
32/// The capability string routed to an indexing service. Defined once, in
33/// [`crate::constant`]; re-exported here so a reader of the payload contract
34/// finds it next to the payloads.
35pub use crate::constant::AI_RAG_INDEX_CAPABILITY;
36
37/// One attachment of the note, metadata only.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct RagFile {
40 /// The file's record key — the same id `GET /course-notes/{id}/files`
41 /// publishes, so a service that wants the bytes fetches them itself.
42 pub id: String,
43 pub name: String,
44 pub content_type: String,
45 pub size: i64,
46}
47
48/// What the backend asks an indexing service to index.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub struct RagIndexPayload {
51 /// The course note's record key. The service echoes nothing back about it
52 /// — the backend keys the stored answer itself.
53 pub course_note: String,
54 pub course: String,
55 /// The note author's user id — who a service reads the file bytes
56 /// `on_behalf_of` on the blob stream, since the note's own teacher can
57 /// always view its course and the `ai` principal never can.
58 pub author: String,
59 pub title: String,
60 pub content: String,
61 /// Attachment **metadata only** — the bytes ride their own QUIC stream
62 /// (one `BlobRequest` per `files[].id`), never a JSON frame.
63 #[serde(default)]
64 pub files: Vec<RagFile>,
65}
66
67impl RagIndexPayload {
68 fn new(note: &CourseNote, files: &[CourseNoteFile]) -> Self {
69 Self {
70 course_note: note.get_id().key().to_string(),
71 course: note.get_course().key().to_string(),
72 author: note.get_author().key().to_string(),
73 title: note.get_title().as_str().to_string(),
74 content: note.get_content().as_str().to_string(),
75 files: files
76 .iter()
77 .map(|file| RagFile {
78 id: file.get_id().key().to_string(),
79 name: file.get_name().as_str().to_string(),
80 content_type: file.get_content_type().as_str().to_string(),
81 size: file.get_size(),
82 })
83 .collect(),
84 }
85 }
86}
87
88/// Re-index `note` and replace its stored outputs with what the service
89/// answered. Silent no-op when the bridge is off or no worker offers
90/// `rag.index`.
91///
92/// `tenant` is the caller's own school: its uuid rides the `hab/2` frame, and
93/// `state.db` — the same school's database, since the caller reached this
94/// through the shadow `State` — is where the answer is stored.
95///
96/// A school that did not buy the `ai` package sends **nothing** to an AI
97/// service: no dispatch, no `rag_output` row. That is `Module::Chatbot`, the
98/// package's only module, so it gates every outbound dispatch and not just the
99/// `/chatbot` nest.
100///
101/// The answer may also name the doc id the service minted per file — `files`
102/// as `[{id, doc_id}]` — which is stamped onto the matching attachment rows,
103/// and only onto this note's own files. Best-effort: a failed stamp is logged
104/// and the output still lands, because the map is optional on the wire and a
105/// service that omits it is simply not heard from on that front.
106pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note: &CourseNote) {
107 if !tenant.modules.contains(Module::Chatbot) {
108 tracing::debug!(
109 "skipping rag.index for course note {}: the `{}` school has no `chatbot` module",
110 note.get_id().key(),
111 tenant.id
112 );
113 return;
114 }
115 let school = &tenant.id;
116 let Some(bridge) = state.ai.as_ref() else {
117 return;
118 };
119 if !bridge.has_capability(AI_RAG_INDEX_CAPABILITY) {
120 return;
121 }
122 // Read the attachments here rather than taking a caller's list: the
123 // dispatch runs after the handler answered, so this is the freshest view
124 // of what the note holds, and the ids it sends are the ids it stores.
125 let files = match crate::db::course_note_file::list_for(&state.db, note.get_id(), None, 0).await
126 {
127 Ok((files, _)) => files,
128 Err(err) => {
129 tracing::warn!("could not load course note files for rag.index: {err}");
130 return;
131 }
132 };
133 let payload = match serde_json::to_value(RagIndexPayload::new(note, &files)) {
134 Ok(payload) => payload,
135 Err(err) => {
136 tracing::error!("could not encode a rag.index request: {err}");
137 return;
138 }
139 };
140
141 let answer = match bridge
142 .dispatch_with_timeout(
143 school,
144 AI_RAG_INDEX_CAPABILITY,
145 payload,
146 std::time::Duration::from_secs(AI_RAG_INDEX_TIMEOUT_SECS),
147 )
148 .await
149 {
150 Ok(answer) => answer,
151 Err(err) => {
152 tracing::warn!(
153 "rag.index failed for course note {}: {err}",
154 note.get_id().key()
155 );
156 return;
157 }
158 };
159 // The service is a trust boundary and the column is an object: anything
160 // else is a service bug, and storing it would only fail at the write.
161 if !answer.is_object() {
162 tracing::warn!("rag.index answered with a non-object payload — keeping the stored rows");
163 return;
164 }
165
166 // A service may name the doc id it minted for each file — `files` as
167 // `[{id, doc_id}]` — so a row remembers what its bytes were indexed as.
168 // Only ids of *this* note's attachments are honoured: a service bug
169 // naming another note's file must not stamp that row. Best-effort — a
170 // failed write is logged and the stored answer still lands.
171 if let Some(claims) = answer.get("files").and_then(serde_json::Value::as_array) {
172 for claim in claims {
173 let (Some(id), Some(doc_id)) = (
174 claim.get("id").and_then(serde_json::Value::as_str),
175 claim.get("doc_id").and_then(serde_json::Value::as_str),
176 ) else {
177 continue;
178 };
179 let Some(file) = files.iter().find(|file| file.get_id().key() == id) else {
180 continue;
181 };
182 if let Err(err) =
183 crate::db::course_note_file::set_rag_doc_id(&state.db, file.get_id(), doc_id).await
184 {
185 tracing::warn!(
186 "could not stamp doc id on course note file {}: {err}",
187 file.get_id().key()
188 );
189 }
190 }
191 } else {
192 tracing::debug!(
193 "the rag.index answer for course note {} names no doc ids",
194 note.get_id().key()
195 );
196 }
197
198 let sources = files.iter().map(|file| file.get_id().clone()).collect();
199 if let Err(err) = replace(&state.db, note, sources, answer).await {
200 tracing::warn!("could not store the rag.index output: {err}");
201 }
202}
203
204/// Swap the note's outputs for the fresh one. Create-then-drop-older, not an
205/// update: the previous output belongs to a previous version of the note, and
206/// this order is what makes two concurrent index tasks converge on one row
207/// ([`replace_for_note`](crate::db::rag_output::replace_for_note)).
208async fn replace(
209 db: &Database,
210 note: &CourseNote,
211 sources: Vec<crate::domain::course_note_file::CourseNoteFileId>,
212 payload: serde_json::Value,
213) -> Result<(), crate::error::AppError> {
214 crate::db::rag_output::replace_for_note(db, note.get_id(), note.get_course(), sources, payload)
215 .await?;
216 Ok(())
217}
218
219/// [`index_course_note`] off the request path: the handler has already
220/// answered by the time the service is asked.
221pub fn spawn_index(state: &AppState, tenant: &ResolvedTenant, note: CourseNote) {
222 // Cheap when AI is off — the spawned task returns on the first `let else`.
223 let state = state.clone();
224 let tenant = tenant.clone();
225 tokio::spawn(async move { index_course_note(&state, &tenant, &note).await });
226}
227
228/// Whether a worker that just registered should have the course-note index
229/// replayed. Only `rag.index` does. `rag.chat`, the chatbot, zeka, and the
230/// podcast worker do not — their registration must not walk every school.
231pub(crate) fn should_replay_index(capabilities: &[String]) -> bool {
232 capabilities
233 .iter()
234 .any(|capability| capability == AI_RAG_INDEX_CAPABILITY)
235}
236
237/// [`replay_indexed_notes`] off the handshake path. Returns as soon as the
238/// task is spawned. `state.ai` must already be the bridge that just
239/// registered the worker; `state.db` may still be the control database —
240/// each school is swapped in before [`index_course_note`].
241pub(crate) fn spawn_index_replay(state: AppState) {
242 tokio::spawn(async move {
243 replay_indexed_notes(state).await;
244 });
245}
246
247/// Re-dispatch [`index_course_note`] for every course note that has files, in
248/// every active school. One note at a time: a replay is a catch-up, not a
249/// stampede, and the worker's own concurrency cap is what bounds a single
250/// dispatch.
251async fn replay_indexed_notes(state: AppState) {
252 let directory = match crate::db::insight::active_schools(state.tenants.control()).await {
253 Ok(directory) => directory,
254 Err(err) => {
255 tracing::warn!("rag.index replay could not list active schools: {err}");
256 return;
257 }
258 };
259 for school in directory.schools {
260 replay_school(&state, &school).await;
261 }
262}
263
264async fn replay_school(state: &AppState, school: &str) {
265 let id = match crate::tenant::SchoolId::try_parse(school) {
266 Ok(id) => id,
267 Err(err) => {
268 tracing::warn!("rag.index replay skipped an unreadable school id: {err}");
269 return;
270 }
271 };
272 let tenant = match state.tenants.resolve(&id).await {
273 Ok(tenant) => tenant,
274 Err(err) => {
275 tracing::warn!("rag.index replay skipped `{id}`: {err}");
276 return;
277 }
278 };
279 if !tenant.modules.contains(Module::Chatbot) {
280 tracing::debug!("rag.index replay skipped `{id}`: the school has no chatbot module");
281 return;
282 }
283 let notes = match crate::db::course_note::list_with_files(&tenant.db).await {
284 Ok(notes) => notes,
285 Err(err) => {
286 tracing::warn!("rag.index replay could not list course notes in `{id}`: {err}");
287 return;
288 }
289 };
290 if notes.is_empty() {
291 tracing::debug!("rag.index replay: `{id}` has no course notes with files");
292 return;
293 }
294 tracing::info!(
295 school = %id,
296 notes = notes.len(),
297 "replaying rag.index for course notes with files"
298 );
299 // `index_course_note` writes through `state.db`, which on the request
300 // path is the shadow school's database. The root handed in here is the
301 // control database, so the school handle has to be swapped in first.
302 let school_state = AppState {
303 db: tenant.db.clone(),
304 ..state.clone()
305 };
306 for note in &notes {
307 index_course_note(&school_state, &tenant, note).await;
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use crate::constant::{
315 AI_CHAT_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY,
316 AI_RAG_CHAT_CAPABILITY,
317 };
318 use serde_json::json;
319
320 #[test]
321 fn rag_payload_keys_are_the_documented_wire_names() {
322 // Services in other languages match on these literals — a rename here
323 // silently breaks every one of them, so pin the encoding.
324 let payload = serde_json::to_value(RagIndexPayload {
325 course_note: "01NOTE".into(),
326 course: "01COURSE".into(),
327 author: "01AUTHOR".into(),
328 title: "Chapter 3".into(),
329 content: "quadratics".into(),
330 files: vec![RagFile {
331 id: "01FILE".into(),
332 name: "recap.pdf".into(),
333 content_type: "application/pdf".into(),
334 size: 12,
335 }],
336 })
337 .unwrap();
338 assert_eq!(
339 payload,
340 json!({
341 "course_note": "01NOTE",
342 "course": "01COURSE",
343 "author": "01AUTHOR",
344 "title": "Chapter 3",
345 "content": "quadratics",
346 "files": [{
347 "id": "01FILE",
348 "name": "recap.pdf",
349 "content_type": "application/pdf",
350 "size": 12,
351 }],
352 })
353 );
354 assert_eq!(AI_RAG_INDEX_CAPABILITY, "rag.index");
355 // A note with no attachments is the common case — `files` is optional
356 // on the wire, so a minimal service need not send it back or expect it.
357 let bare: RagIndexPayload = serde_json::from_value(json!({
358 "course_note": "01NOTE", "course": "01COURSE", "author": "01AUTHOR",
359 "title": "t", "content": "c",
360 }))
361 .unwrap();
362 assert!(bare.files.is_empty());
363 }
364
365 /// Chatbot, zeka, podcast, and even `rag.chat` must not replay. A worker
366 /// that offers `rag.index` alongside something else still does.
367 #[test]
368 fn index_replay_runs_only_when_the_worker_offers_rag_index() {
369 assert!(should_replay_index(&[AI_RAG_INDEX_CAPABILITY.to_string()]));
370 assert!(should_replay_index(&[
371 AI_CHAT_CAPABILITY.to_string(),
372 AI_RAG_INDEX_CAPABILITY.to_string(),
373 ]));
374 assert!(!should_replay_index(&[AI_CHAT_CAPABILITY.to_string()]));
375 assert!(!should_replay_index(&[AI_RAG_CHAT_CAPABILITY.to_string()]));
376 assert!(!should_replay_index(&[
377 AI_INSIGHT_STUDENT_CAPABILITY.to_string()
378 ]));
379 assert!(!should_replay_index(&[
380 AI_PODCAST_SUBMIT_CAPABILITY.to_string()
381 ]));
382 assert!(!should_replay_index(&[]));
383 }
384}