forge
Explore
Log in

Don't you dare go Hollow

Resolve the study pair through the search fold

Browse files at this commit

1e8567dd5f08c120b308276f3760198b7e11919aAhmet Kaan GümüşParent: 64eabd4
  • fix
    • resolve the study pair through the search fold
Show full message
🐛 fix(rag): resolve the study pair through the search fold

Citations carry ders in the service's slug vocabulary (lowercase,
diacritic-stripped) while scope pairs carry course titles, and the
door compared them byte-exact — so Soru üret/Özetle on a study answer
403'd for every role. Exact match stays the fast path; the folded
fallback refuses with a 400 when two distinct titles fold equal,
never a first-wins guess.
Local-Gate: 3bdd611a53d3849b1f5d3473cf39d86c08fb3768 (1515 passed, 455s)
src/web/rag.rsmodified+118 -28
@@ -1032,12 +1032,18 @@ impl From<RagQuestionsReply> for RagQuestionsResponse {
10321032 /// The one `(sınıf, ders)` pair a study request may address, resolved against
10331033 /// the asker's own derived pairs — the body only *names* a target inside them.
10341034 ///
1035-/// A named grade must be a pair the asker holds **exactly**; anything else is a
1036-/// `403`, because a corpus the asker cannot study must not be summarized on
1037-/// their behalf. An absent or empty grade resolves the subject alone: exactly
1038-/// one pair for that `ders` is the target, none is a `403`, and more than one
1039-/// is a `400` — the caller must name the şube, since picking one for them would
1040-/// answer from a corpus they did not name.
1035+/// A named ders matches a pair **exactly** first — a picker's own spelling is
1036+/// never re-rolled — and only then through [`crate::domain::text_fold::search_fold`],
1037+/// the fold the RAG slug vocabulary rides: a citation names its course by slug
1038+/// (`biyoloji`), the pair carries the course title (`Biyoloji`), and the two
1039+/// spellings must resolve to one pair. A named grade must still be a pair the
1040+/// asker holds; anything else is a `403`, because a corpus the asker cannot
1041+/// study must not be summarized on their behalf. An absent or empty grade
1042+/// resolves the subject alone: exactly one pair for that `ders` is the target,
1043+/// none is a `403`, and more than one is a `400` — the caller must name the
1044+/// şube, since picking one for them would answer from a corpus they did not
1045+/// name. Two *distinct* courses folding to one key refuse the same way rather
1046+/// than routing on a guess.
10411047 fn resolve_study_pair(
10421048 pairs: &[RagScopePair],
10431049 ders: &str,
@@ -1046,30 +1052,41 @@ fn resolve_study_pair(
10461052 if ders.trim().is_empty() {
10471053 return Err(AppError::Validation(ValidationError::Empty("ders")));
10481054 }
1049- match sinif.filter(|grade| !grade.trim().is_empty()) {
1050- Some(grade) => pairs
1055+ let grade = sinif.filter(|grade| !grade.trim().is_empty());
1056+ let in_grade =
1057+ |pair: &&RagScopePair| grade.is_none() || pair.sinif.as_deref() == grade;
1058+ let mut matches: Vec<&RagScopePair> =
1059+ pairs.iter().filter(|pair| in_grade(pair) && pair.ders == ders).collect();
1060+ if matches.is_empty() {
1061+ let folded = crate::domain::text_fold::search_fold(ders);
1062+ matches = pairs
10511063 .iter()
1052- .find(|pair| pair.ders == ders && pair.sinif.as_deref() == Some(grade))
1053- .cloned()
1054- .ok_or(AppError::Forbidden(
1055- "the requested ders/sinif pair is not in your scope",
1056- )),
1057- None => {
1058- let mut candidates = pairs.iter().filter(|pair| pair.ders == ders);
1059- let Some(first) = candidates.next() else {
1060- return Err(AppError::Forbidden(
1061- "the requested ders is not in your scope",
1062- ));
1063- };
1064- if candidates.next().is_some() {
1065- return Err(AppError::Validation(ValidationError::Invalid {
1066- field: "sinif",
1067- reason: "name the grade: this ders is taught in more than one",
1068- }));
1069- }
1070- Ok(first.clone())
1071- }
1064+ .filter(|pair| {
1065+ in_grade(pair) && crate::domain::text_fold::search_fold(&pair.ders) == folded
1066+ })
1067+ .collect();
1068+ }
1069+ let Some(first) = matches.first() else {
1070+ return Err(AppError::Forbidden(match grade {
1071+ Some(_) => "the requested ders/sinif pair is not in your scope",
1072+ None => "the requested ders is not in your scope",
1073+ }));
1074+ };
1075+ if matches.len() > 1 {
1076+ // One title across several grades is the name-the-grade refusal;
1077+ // distinct titles folding equal cannot be settled by naming anything,
1078+ // so the ders itself is judged ambiguous — never a first-wins guess.
1079+ let one_title = matches.iter().all(|pair| pair.ders == first.ders);
1080+ return Err(AppError::Validation(ValidationError::Invalid {
1081+ field: if one_title { "sinif" } else { "ders" },
1082+ reason: if one_title {
1083+ "name the grade: this ders is taught in more than one"
1084+ } else {
1085+ "more than one course matches this name; name the course exactly"
1086+ },
1087+ }));
10721088 }
1089+ Ok((*first).clone())
10731090 }
10741091
10751092 /// Summarize one range of one corpus the caller may study.
@@ -1309,4 +1326,77 @@ mod tests {
13091326 ));
13101327 assert!(resolve_study_pair(&two, "Fizik", Some("10")).is_ok());
13111328 }
1329+ /// A citation names its course by the RAG slug vocabulary (lowercase,
1330+ /// diacritic-stripped) while the pair carries the course title: the body's
1331+ /// `biyoloji` must resolve the pair whose title is `Biyoloji`, with the
1332+ /// derived title — never the body's slug — being what travels.
1333+ #[test]
1334+ fn a_study_pair_matches_the_slug_spelling_through_the_search_fold() {
1335+ let pairs = vec![
1336+ pair(Some("10"), "Biyoloji"),
1337+ pair(Some("9"), "İngilizce"),
1338+ pair(Some("11"), "Coğrafya"),
1339+ ];
1340+
1341+ // The slug spelling resolves, with and without a named grade.
1342+ let resolved = resolve_study_pair(&pairs, "biyoloji", None).unwrap();
1343+ assert_eq!(resolved.ders, "Biyoloji");
1344+ assert_eq!(resolved.sinif.as_deref(), Some("10"));
1345+ assert_eq!(
1346+ resolve_study_pair(&pairs, "biyoloji", Some("10")).unwrap().ders,
1347+ "Biyoloji"
1348+ );
1349+
1350+ // The fold is Turkish-correct both ways: dotted İ folds, and the
1351+ // slug's stripped diacritics still reach the accented title.
1352+ assert_eq!(
1353+ resolve_study_pair(&pairs, "ingilizce", None).unwrap().ders,
1354+ "İngilizce"
1355+ );
1356+ assert_eq!(
1357+ resolve_study_pair(&pairs, "cografya", Some("11")).unwrap().ders,
1358+ "Coğrafya"
1359+ );
1360+
1361+ // A grade the asker holds no folded pair for, and a ders no course
1362+ // folds to, are still the same scope refusal — never widened access.
1363+ assert!(matches!(
1364+ resolve_study_pair(&pairs, "biyoloji", Some("11")),
1365+ Err(AppError::Forbidden(_))
1366+ ));
1367+ assert!(matches!(
1368+ resolve_study_pair(&pairs, "fizik", None),
1369+ Err(AppError::Forbidden(_))
1370+ ));
1371+ }
1372+
1373+ /// Two *distinct* courses folding to one key refuse rather than route on
1374+ /// a guess — the same multi-match verdict family as the multi-grade
1375+ /// refusal, judged on `ders` since naming a grade cannot settle it.
1376+ #[test]
1377+ fn folded_ambiguity_refuses_instead_of_guessing() {
1378+ // `Kâğıt` and `Kagit` fold to one key, and no exact spelling of the
1379+ // slug settles which one the caller meant.
1380+ let folded_twins = vec![pair(Some("9"), "Kâğıt"), pair(Some("9"), "Kagit")];
1381+ assert!(matches!(
1382+ resolve_study_pair(&folded_twins, "kagit", None),
1383+ Err(AppError::Validation(ValidationError::Invalid { field: "ders", .. }))
1384+ ));
1385+ assert!(matches!(
1386+ resolve_study_pair(&folded_twins, "kagit", Some("9")),
1387+ Err(AppError::Validation(ValidationError::Invalid { field: "ders", .. }))
1388+ ));
1389+
1390+ // One course taught in two grades, named by slug: the caller must
1391+ // still name the grade.
1392+ let two_grades = vec![pair(Some("9"), "Biyoloji"), pair(Some("10"), "Biyoloji")];
1393+ assert!(matches!(
1394+ resolve_study_pair(&two_grades, "biyoloji", None),
1395+ Err(AppError::Validation(ValidationError::Invalid { field: "sinif", .. }))
1396+ ));
1397+ assert_eq!(
1398+ resolve_study_pair(&two_grades, "biyoloji", Some("10")).unwrap().ders,
1399+ "Biyoloji"
1400+ );
1401+ }
13121402 }
tests/ai_bridge.rsmodified+38 -0
@@ -3499,6 +3499,44 @@ async fn the_summarize_request_carries_the_askers_scope_and_role() {
34993499 );
35003500 }
35013501
3502+/// A study request launched off an answer's citation names the course by the
3503+/// RAG slug vocabulary — lowercase, diacritic-stripped (`satranc kulubu` for
3504+/// `Satranç Kulübü`) — not by the course title a picker would send. The door
3505+/// folds both spellings through the same search fold, so the slug resolves;
3506+/// the pair that reaches the service is still the derived title.
3507+#[tokio::test]
3508+async fn a_slug_spelled_ders_resolves_to_the_derived_pair() {
3509+ let bridge = bridge().await;
3510+ let service = connect_service(
3511+ &bridge,
3512+ hello("rag", &[AI_RAG_SUMMARIZE_CAPABILITY, AI_RAG_QUESTIONS_CAPABILITY]),
3513+ Behaviour::Answer(json!({ "text": "özet", "items": [] })),
3514+ )
3515+ .await;
3516+ await_workers(&bridge, 1).await;
3517+ let (app, cookie, _student) = study_user(&bridge).await;
3518+
3519+ for path in ["/rag/summarize", "/rag/questions"] {
3520+ let res = common::send(
3521+ &app,
3522+ "POST",
3523+ path,
3524+ Some(&cookie),
3525+ Some(json!({ "ders": "satranc kulubu" })),
3526+ )
3527+ .await;
3528+ assert_eq!(res.status, StatusCode::OK, "{path}: {}", res.body);
3529+ }
3530+ let seen = service.seen();
3531+ assert_eq!(seen.len(), 2, "one dispatch per call, never a re-send");
3532+ for dispatch in &seen {
3533+ assert_eq!(
3534+ dispatch.payload["scope"]["ders"], "Satranç Kulübü",
3535+ "the derived pair travels, never the body's slug spelling"
3536+ );
3537+ }
3538+}
3539+
35023540 /// The questions wire contract: the same scope, plus the shape of the set, and
35033541 /// the service's own `soru`/`cevap`/`zorluk` rows mapped onto this API's
35043542 /// `question`/`answer`/`difficulty` (the wire keeps the service's vocabulary).