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_scope.rs449 lines, 19.8 KiBHistoryRawDownload
1//! The `(class, course)` scope a RAG question is answered from.
2//!
3//! The RAG corpus is routed by the **pair** — a grade and a subject list sent
4//! separately would cross-product into combinations the asker never named
5//! ([`crate::constant::MAX_RAG_SCOPE_PAIRS`]) — so every question needs the set
6//! of pairs its asker is allowed to retrieve from, and that set is derived
7//! *here*, never from the request body: a scope a client could name is a
8//! scope a client could widen.
9//!
10//! The derivation is the school's own visibility rules, not a second copy of
11//! them. A student's or a teacher's pairs are the courses their
12//! [`super::instance::visible_instances`] teach them — the very set
13//! `GET /instances/me` serves — and a club/supervised-study membership
14//! ([`crate::db::course_membership`]) adds its subject with no grade, since a
15//! school-scoped course belongs to no section. A parent has no sections of
16//! their own, so their scope is their linked children's, read child by child
17//! through the same reader: what a parent may ask about is exactly what their
18//! children could be taught. A manager or an admin is none of those people:
19//! their scope is every class-course instance in the school
20//! ([`crate::db::class_group::list_all`] plus
21//! [`crate::db::class_course::list_for_class_ids`]), not the rows their own
22//! account happens to hold. An empty personal membership is not an empty
23//! school, and it is not a legal empty scope.
24//!
25//! Two consequences are deliberate. An empty scope is legal and returned as an
26//! empty list when the asker really has nothing to retrieve from — a student
27//! in no section, a teacher with no assignment, a parent with no linked child,
28//! a manager of a school that has no class-course instance. The service
29//! answers an unscopable question by abstaining, and a `400` here would refuse
30//! questions the asker is entitled to ask. And a union over the cap is
31//! **refused**, never narrowed: dropping pairs would answer a question scoped
32//! to corpora the asker did not name, which is worse than no answer at all.
33
34use std::collections::{HashMap, HashSet};
35
36use crate::ai::rag_chat::RagScopePair;
37use crate::constant::MAX_RAG_SCOPE_PAIRS;
38use crate::database::Database;
39use crate::domain::class_course::ClassCourse;
40use crate::domain::class_group::ClassGroupId;
41use crate::domain::course::CourseId;
42use crate::domain::role::Role;
43use crate::domain::user::User;
44use crate::error::{AppError, ValidationError};
45
46/// The `(class, course)` pairs `user`'s questions may be scoped to, in
47/// first-seen order and deduped — one entry per distinct pair.
48///
49/// `role` is the caller's **live** session role, the same value the
50/// `rag.chat` payload carries. A manager or an admin reads every class-course
51/// instance in the school. Everyone else reads their own rows: a section
52/// membership, a homeroom column and a teaching assignment are all keyed on
53/// the live role, and the parent arm is chosen by role because a parent's own
54/// sections do not exist.
55///
56/// The non-manager instance arm reads its rows through
57/// [`super::instance::visible_instances`], and both arms finish with the same
58/// two lookup tables (the class sections the pairs sit in and the titles of
59/// every course named) in one batch read each — never one query per instance.
60/// A teacher can be assigned to dozens of sections, and a per-row lookup would
61/// spend the request's whole budget before the AI service is even called.
62pub async fn for_user(
63 db: &Database,
64 user: &User,
65 role: Role,
66) -> Result<Vec<RagScopePair>, AppError> {
67 let mut instances: Vec<ClassCourse> = Vec::new();
68 if role.at_least(Role::Manager) {
69 // A manager or an admin asks about the school, not about the rows
70 // their own account holds. A system admin is in no section, no
71 // homeroom and no teaching assignment, so the personal read is empty
72 // — and an empty personal read is not an empty school.
73 let (classes, _) = crate::db::class_group::list_all(db, None, None, 0).await?;
74 let class_ids: Vec<ClassGroupId> =
75 classes.iter().map(|class| class.get_id().clone()).collect();
76 instances = crate::db::class_course::list_for_class_ids(db, &class_ids).await?;
77 } else if role == Role::Parent {
78 // A parent's scope is what their children are taught — read through
79 // the same visibility rule, one child at a time because the rule
80 // keys on the person asking. A link whose student side changed role
81 // is inert by construction: the demotion sweep takes their
82 // memberships and enrollments with it, so the child simply has
83 // nothing left to widen the parent into.
84 for link in crate::db::parent_link::list_for_parent(db, user.get_id()).await? {
85 let Some(child) = super::user::read(db, link.get_student()).await? else {
86 continue;
87 };
88 instances.extend(
89 super::instance::visible_instances(&child, db)
90 .await?
91 .into_iter()
92 .map(|(instance, _)| instance),
93 );
94 }
95 } else {
96 instances.extend(
97 super::instance::visible_instances(user, db)
98 .await?
99 .into_iter()
100 .map(|(instance, _)| instance),
101 );
102 }
103 // The school-scoped courses the asker joined directly (club, supervised
104 // study). Every role may hold one — the table's own gate is the student
105 // role, so for staff this read is simply empty. A manager's scope is the
106 // school's instances, not this personal list, so the read is skipped.
107 let memberships = if role.at_least(Role::Manager) {
108 Vec::new()
109 } else {
110 crate::db::course_membership::list_for_user(db, user.get_id(), None, 0)
111 .await?
112 .0
113 };
114
115 // One batch read per lookup, over every id the two arms named: the class
116 // sections decide each instance's grade, and the courses carry the titles
117 // every pair is scoped by. Ids repeat freely — a class usually carries
118 // several instances — and `list_by_ids` answers each row once.
119 let class_ids: Vec<ClassGroupId> = instances
120 .iter()
121 .map(|instance| instance.get_class().clone())
122 .collect();
123 let mut course_ids: Vec<CourseId> = instances
124 .iter()
125 .map(|instance| instance.get_course().clone())
126 .collect();
127 course_ids.extend(
128 memberships
129 .iter()
130 .map(|membership| membership.get_course().clone()),
131 );
132 let classes = crate::db::class_group::list_by_ids(db, &class_ids).await?;
133 let courses = crate::db::course::list_by_ids(db, &course_ids).await?;
134
135 // Display labels, keyed by class section. Every section carries a ladder
136 // rung now, so every class-keyed instance pairs with one; only the
137 // school-wide club/study memberships ride in with no grade at all (the
138 // documented meaning of an absent `sinif`).
139 let grades: HashMap<String, String> = classes
140 .iter()
141 .map(|class| (class.get_id().key(), class.get_grade_level().label().to_owned()))
142 .collect();
143 // The instances' **resolved** titles (override → offering → catalog): the
144 // section's own grade content is what a scope pair names. Batched — one
145 // offering read + one catalog read for the whole scope. The club/study
146 // memberships below keep the catalog title: a school-wide course has no
147 // offering, so the catalog row is the only label there is.
148 let instance_refs: Vec<&ClassCourse> = instances.iter().collect();
149 let resolved = crate::service::instance_resolve::resolved_content(db, &instance_refs).await?;
150 let ders_by_instance: HashMap<String, String> = resolved
151 .into_iter()
152 .map(|(key, content)| (key, content.title))
153 .collect();
154 let titles: HashMap<String, String> = courses
155 .iter()
156 .map(|course| (course.get_id().key(), course.get_title().as_str().to_owned()))
157 .collect();
158
159 let mut pairs: Vec<RagScopePair> = Vec::new();
160 let mut seen: HashSet<(Option<String>, String)> = HashSet::new();
161 for instance in &instances {
162 // A title the batch read did not answer is unreachable — the
163 // instance's key is a foreign key — so the skip is a guard against a
164 // dangling read, not a rule: a title-less pair could not be routed.
165 let Some(ders) = ders_by_instance.get(instance.get_id().key().as_str()) else {
166 continue;
167 };
168 push_pair(
169 &mut pairs,
170 &mut seen,
171 grades.get(&instance.get_class().key()).cloned(),
172 ders.clone(),
173 );
174 }
175 for membership in &memberships {
176 let Some(ders) = titles.get(&membership.get_course().key()) else {
177 continue;
178 };
179 push_pair(&mut pairs, &mut seen, None, ders.clone());
180 }
181 // The cap is checked on the *union*: the dedup is what one frame would
182 // carry, and it is exactly the number this refusal is about. Refused,
183 // never truncated — see the module doc.
184 if pairs.len() > MAX_RAG_SCOPE_PAIRS {
185 return Err(AppError::Validation(ValidationError::TooLong {
186 field: "scope",
187 max: MAX_RAG_SCOPE_PAIRS,
188 got: pairs.len(),
189 }));
190 }
191 Ok(pairs)
192}
193
194/// Append `pair` unless the very same pair is already in the list — a scope is
195/// a set. Two class sections at one grade teaching one course are one scope,
196/// and a course attached to a section while also joined as a club contributes
197/// both of its pairs; a duplicate would spend one of the cap's slots twice and
198/// hand the service the same corpus under two entries.
199fn push_pair(
200 pairs: &mut Vec<RagScopePair>,
201 seen: &mut HashSet<(Option<String>, String)>,
202 sinif: Option<String>,
203 ders: String,
204) {
205 if seen.insert((sinif.clone(), ders.clone())) {
206 pairs.push(RagScopePair { sinif, ders });
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use crate::domain::class_group::{ClassGroupId, ClassName};
214 use crate::domain::grade::GradeLevel;
215 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
216 use crate::domain::user::Username;
217
218 /// One scope pair, spelled the way the service reads the wire type.
219 fn pair(sinif: Option<&str>, ders: &str) -> RagScopePair {
220 RagScopePair {
221 sinif: sinif.map(str::to_owned),
222 ders: ders.to_owned(),
223 }
224 }
225
226 /// A real account at a role: every arm of the derivation judges the live
227 /// row (and the membership and parent-link gates judge the exact role), so
228 /// a fabricated id or the `fixture_user` default would not do.
229 async fn person(db: &Database, username: &str, role: Role) -> User {
230 crate::db::user::create_with_role(
231 db,
232 Username::try_new(username).unwrap(),
233 None,
234 role,
235 None,
236 )
237 .await
238 .unwrap()
239 }
240
241 /// A class section at a chosen rung — the half of every instance pair
242 /// that scopes by grade.
243 async fn graded_class(db: &Database, name: &str, grade: &str) -> ClassGroupId {
244 let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await;
245 crate::service::class_group::create(
246 db,
247 &office,
248 ClassName::try_new(name).unwrap(),
249 GradeLevel::new(grade.parse().unwrap()).unwrap(),
250 None,
251 None,
252 )
253 .await
254 .unwrap()
255 .get_id()
256 .clone()
257 }
258
259 /// Attach a catalog course to a class section, answering the instance.
260 async fn attach(
261 db: &Database,
262 class: &ClassGroupId,
263 title: &str,
264 ) -> crate::domain::class_course::ClassCourse {
265 let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await;
266 let course = crate::db::class_member::tests::a_course(title, db).await;
267 crate::service::class_course::attach(db, class, &course, &office)
268 .await
269 .unwrap()
270 }
271
272 /// A student at a section's roster — the membership the instance half of
273 /// the scope is read through.
274 async fn enrolment(db: &Database, class: &ClassGroupId, student: &User) {
275 let office = crate::db::class_member::tests::fixture_user(db, "ragscope-office").await;
276 crate::service::class_member::add(db, class, student.get_id(), &office)
277 .await
278 .unwrap();
279 }
280
281 /// A student's pair is the section's grade plus the course attached to
282 /// it — the same set `GET /instances/me` hands them.
283 #[tokio::test]
284 async fn a_students_sections_scope_their_subjects() {
285 let (db, _leases) = crate::database::init_test_db().await;
286 let student = person(&db, "ragscope-student", Role::Student).await;
287 let class = graded_class(&db, "5-A", "5").await;
288 attach(&db, &class, "Matematik").await;
289 enrolment(&db, &class, &student).await;
290
291 let scope = for_user(&db, &student, Role::Student).await.unwrap();
292 assert_eq!(scope, vec![pair(Some("5"), "Matematik")]);
293 }
294
295 /// A teacher reaches a section through the teaching assignment, not
296 /// through a roster: the course they run is in scope exactly as it is for
297 /// the students they teach.
298 #[tokio::test]
299 async fn an_assigned_teachers_subject_is_in_scope() {
300 let (db, _leases) = crate::database::init_test_db().await;
301 let teacher = person(&db, "ragscope-teacher", Role::Teacher).await;
302 let class = graded_class(&db, "9-A", "9").await;
303 let instance = attach(&db, &class, "Fizik").await;
304 // The office staffing call minus its role gate: what this test reads
305 // is the scope, not who may write the assignment row.
306 crate::db::class_course_teacher::assign(&db, instance.get_id(), teacher.get_id())
307 .await
308 .unwrap();
309
310 let scope = for_user(&db, &teacher, Role::Teacher).await.unwrap();
311 assert_eq!(scope, vec![pair(Some("9"), "Fizik")]);
312 }
313
314 /// A parent has no sections of their own: their scope is the linked
315 /// child's, and nobody else's — an unrelated student's section, graded the
316 /// same or not, never widens it.
317 #[tokio::test]
318 async fn a_parents_scope_is_their_linked_childs() {
319 let (db, _leases) = crate::database::init_test_db().await;
320 let parent = person(&db, "ragscope-parent", Role::Parent).await;
321 let child = person(&db, "ragscope-child", Role::Student).await;
322 let stranger = person(&db, "ragscope-stranger", Role::Student).await;
323 let child_class = graded_class(&db, "7-A", "7").await;
324 attach(&db, &child_class, "Türkçe").await;
325 enrolment(&db, &child_class, &child).await;
326 let stranger_class = graded_class(&db, "7-B", "7").await;
327 attach(&db, &stranger_class, "Türkçe").await;
328 enrolment(&db, &stranger_class, &stranger).await;
329 let office = crate::db::class_member::tests::fixture_user(&db, "ragscope-office").await;
330 crate::service::parent_link::link(&db, parent.get_id(), child.get_id(), &office)
331 .await
332 .unwrap();
333
334 let scope = for_user(&db, &parent, Role::Parent).await.unwrap();
335 assert_eq!(
336 scope,
337 vec![pair(Some("7"), "Türkçe")],
338 "the linked child's section, and only that one"
339 );
340 }
341
342 /// A club or supervised study is school-scoped: it belongs to no class
343 /// section, so its subject is scoped with no grade at all.
344 #[tokio::test]
345 async fn a_club_membership_scopes_a_subject_with_no_grade() {
346 let (db, _leases) = crate::database::init_test_db().await;
347 let student = person(&db, "ragscope-club", Role::Student).await;
348 let office = crate::db::class_member::tests::fixture_user(&db, "ragscope-office").await;
349 let club = crate::db::course::create(
350 &db,
351 &office,
352 CourseTitle::try_new("Satranç").unwrap(),
353 CourseDescription::try_new("").unwrap(),
354 CourseKind::try_new("club").unwrap(),
355 )
356 .await
357 .unwrap();
358 crate::db::course_membership::add(&db, club.get_id(), student.get_id(), &office)
359 .await
360 .unwrap();
361
362 let scope = for_user(&db, &student, Role::Student).await.unwrap();
363 assert_eq!(scope, vec![pair(None, "Satranç")]);
364 }
365
366 /// The same pair reached twice is one scope: two class sections at one
367 /// grade teaching one course are two instances and a single
368 /// `(class, course)`, which is what the corpus is routed by.
369 #[tokio::test]
370 async fn a_pair_reached_twice_rides_once() {
371 let (db, _leases) = crate::database::init_test_db().await;
372 let student = person(&db, "ragscope-twice", Role::Student).await;
373 let a = graded_class(&db, "6-A", "6").await;
374 let b = graded_class(&db, "6-B", "6").await;
375 attach(&db, &a, "Matematik").await;
376 attach(&db, &b, "Matematik").await;
377 enrolment(&db, &a, &student).await;
378 enrolment(&db, &b, &student).await;
379
380 // Both sections really are the student's — the pair was reached twice.
381 assert_eq!(
382 crate::service::instance::visible_instances(&student, &db)
383 .await
384 .unwrap()
385 .len(),
386 2
387 );
388 let scope = for_user(&db, &student, Role::Student).await.unwrap();
389 assert_eq!(scope, vec![pair(Some("6"), "Matematik")]);
390 }
391
392 /// A manager or an admin with no personal class row still scopes every
393 /// class-course pair in the school. A student or a teacher with none does
394 /// not: their empty membership stays an empty scope. Two sections at one
395 /// grade teaching one subject are still one pair — the cap refuses a
396 /// union, it does not get a duplicate slot.
397 #[tokio::test]
398 async fn a_manager_with_no_membership_scopes_the_whole_school() {
399 let (db, _leases) = crate::database::init_test_db().await;
400 let manager = person(&db, "ragscope-manager", Role::Manager).await;
401 let admin = person(&db, "ragscope-admin", Role::Admin).await;
402 let student = person(&db, "ragscope-empty-student", Role::Student).await;
403 let teacher = person(&db, "ragscope-empty-teacher", Role::Teacher).await;
404 let grade_eight_a = graded_class(&db, "8-A", "8").await;
405 let grade_eight_b = graded_class(&db, "8-B", "8").await;
406 let grade_nine = graded_class(&db, "9-A", "9").await;
407 attach(&db, &grade_eight_a, "Biology").await;
408 attach(&db, &grade_eight_b, "Biology").await;
409 attach(&db, &grade_nine, "Chemistry").await;
410
411 let expected = vec![
412 (Some("8".to_owned()), "Biology".to_owned()),
413 (Some("9".to_owned()), "Chemistry".to_owned()),
414 ];
415 let manager_scope = for_user(&db, &manager, Role::Manager).await.unwrap();
416 let admin_scope = for_user(&db, &admin, Role::Admin).await.unwrap();
417 assert_eq!(pair_keys(&manager_scope), expected);
418 assert_eq!(pair_keys(&admin_scope), expected);
419 assert_eq!(
420 manager_scope.len(),
421 2,
422 "the repeated grade-8 subject is one pair"
423 );
424 assert!(
425 for_user(&db, &student, Role::Student)
426 .await
427 .unwrap()
428 .is_empty(),
429 "a student with no membership still has an empty scope"
430 );
431 assert!(
432 for_user(&db, &teacher, Role::Teacher)
433 .await
434 .unwrap()
435 .is_empty(),
436 "a teacher with no assignment still has an empty scope"
437 );
438 }
439
440 /// First-seen order is the wire order; the assertion compares the set.
441 fn pair_keys(pairs: &[RagScopePair]) -> Vec<(Option<String>, String)> {
442 let mut keys: Vec<_> = pairs
443 .iter()
444 .map(|pair| (pair.sinif.clone(), pair.ders.clone()))
445 .collect();
446 keys.sort();
447 keys
448 }
449}