forge
Explore
Log in

Don't you dare go Hollow

🇹🇷 split the fold: search collapses letters, identity must not

Browse files at this commit

50966f8cc115f54c6d5a569a68e48a3d73751628Ahmet Kaan GümüşParent: ef7becd
  • fix
    • 🇹🇷 split the fold: search collapses letters, identity must not
Show full message
fix: 🇹🇷 split the fold: search collapses letters, identity must not

c19dcea deduped the settings lists by folded word, but the fold it used
is a destructive ASCII collapse — `ı`, `İ`, `I` and `i` all become `i`,
`ü` becomes `u`. Correct for search, wrong for identity: it made
genuinely distinct Turkish words collide, so a school could not have
both a "tur" and a "tür" exam kind. The second was rejected 400 with no
way to override.

- `text_fold::case_fold_tr` is the new identity fold: Turkish casing
  only (`i`↔`İ`, `ı`↔`I`, plus decomposed `İ`), conflating no letters
- `fold`/`fold_sql` become `search_fold`/`search_fold_sql`. They keep
  the destructive collapse, which is a feature there — typing "tur"
  should still find "tür", and an ASCII keyboard should match accented
  data. The vague old name is part of why this went wrong
- settings dedup switches to `case_fold_tr`; the two search call sites
  keep the collapse, unchanged in behaviour

Relaxation only: `case_fold_tr` equal implies `search_fold` equal, so no
stored row becomes invalid and nothing needs migrating — previously
rejected values simply become legal. `ExamKind`/`AttendanceStatus`
lookups match byte-exactly, so newly coexisting entries stay
individually resolvable.

Tests pin both directions: `TÜR`/`tür` and `KIR`/`kır` fold together
while `tur`/`tür` and `kir`/`kır` do not — and each of those is asserted
still equal under `search_fold`, so the collapse stays deliberate.
src/domain/bank_question.rsmodified+3 -3
@@ -18,7 +18,7 @@ use crate::domain::exam_question::{
18 };18 };
19 use crate::domain::monotonic_id::next_ulid;19 use crate::domain::monotonic_id::next_ulid;
20 use crate::domain::subject::SubjectId;20 use crate::domain::subject::SubjectId;
21-use crate::domain::text_fold::{fold, fold_sql};21+use crate::domain::text_fold::{search_fold, search_fold_sql};
22 use crate::domain::timestamp::Timestamp;22 use crate::domain::timestamp::Timestamp;
23 use crate::domain::user::UserId;23 use crate::domain::user::UserId;
24 use crate::error::{AppError, ValidationError};24 use crate::error::{AppError, ValidationError};
@@ -295,7 +295,7 @@ impl BankQuestion {
295 offset: i64,295 offset: i64,
296 db: &Database,296 db: &Database,
297 ) -> Result<(Vec<BankQuestion>, i64), AppError> {297 ) -> Result<(Vec<BankQuestion>, i64), AppError> {
298- let needle = q.map(|q| fold(q.trim())).filter(|q| !q.is_empty());298+ let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty());
299 let mut clauses = Vec::new();299 let mut clauses = Vec::new();
300 if visible_to.is_some() {300 if visible_to.is_some() {
301 clauses.push("(visibility = 'school' OR owner = $viewer)");301 clauses.push("(visibility = 'school' OR owner = $viewer)");
@@ -309,7 +309,7 @@ impl BankQuestion {
309 if subject.is_some() {309 if subject.is_some() {
310 clauses.push("subject = $subject");310 clauses.push("subject = $subject");
311 }311 }
312- let text_clause = format!("{} CONTAINS $q", fold_sql("text"));312+ let text_clause = format!("{} CONTAINS $q", search_fold_sql("text"));
313 if needle.is_some() {313 if needle.is_some() {
314 clauses.push(text_clause.as_str());314 clauses.push(text_clause.as_str());
315 }315 }
src/domain/settings.rsmodified+29 -2
@@ -439,8 +439,9 @@ fn validate_list(field: &'static str, values: Vec<String>) -> Result<Vec<String>
439 }439 }
440 // `to_lowercase` is locale-invariant — `İZİN` lowercases to `i̇zin` (with a440 // `to_lowercase` is locale-invariant — `İZİN` lowercases to `i̇zin` (with a
441 // leftover combining dot) and would slip past `izin` as a distinct entry.441 // leftover combining dot) and would slip past `izin` as a distinct entry.
442- // Same folding as search uses, so the whole app agrees on "the same word".442+ // The *identity* fold, not search's: search deliberately collapses `ü`→`u`,
443- let mut folded: Vec<String> = trimmed.iter().map(|v| text_fold::fold(v)).collect();443+ // which would make a school unable to have both `tur` and `tür`.
444+ let mut folded: Vec<String> = trimmed.iter().map(|v| text_fold::case_fold_tr(v)).collect();
444 folded.sort_unstable();445 folded.sort_unstable();
445 folded.dedup();446 folded.dedup();
446 if folded.len() != trimmed.len() {447 if folded.len() != trimmed.len() {
@@ -560,6 +561,32 @@ mod tests {
560 );561 );
561 }562 }
562 563
564+ /// Dedup folds *case*, not letters. The search fold collapses `ü`→`u`, so
565+ /// using it here made genuinely distinct Turkish words un-listable: a
566+ /// school could not have both a `tur` and a `tür`.
567+ #[tokio::test]
568+ async fn distinct_turkish_words_are_not_duplicates() {
569+ let with_kinds = |exam_kinds| {
570+ Settings::try_new(SettingsParams {
571+ exam_kinds,
572+ ..params()
573+ })
574+ };
575+ assert!(with_kinds(kinds(&["tur", "tür"])).is_ok());
576+ assert!(with_kinds(kinds(&["kir", "kır"])).is_ok());
577+ // A true case variant of one of them is still a duplicate.
578+ assert!(with_kinds(kinds(&["tür", "TÜR"])).is_err());
579+ assert!(with_kinds(kinds(&["kır", "KIR"])).is_err());
580+ // Same on the other guarded list.
581+ assert!(
582+ Settings::try_new(SettingsParams {
583+ attendance_statuses: statuses_with(&["tur", "tür"]),
584+ ..params()
585+ })
586+ .is_ok()
587+ );
588+ }
589+
563 #[tokio::test]590 #[tokio::test]
564 async fn kind_weights_resolve_by_exact_name() {591 async fn kind_weights_resolve_by_exact_name() {
565 let s = Settings::try_new(SettingsParams {592 let s = Settings::try_new(SettingsParams {
src/domain/text_fold.rsmodified+86 -17
@@ -1,5 +1,14 @@
1-//! Case- and diacritic-insensitive folding for search, shared by the needle1+//! Two different folds, for two different jobs — never swap them:
2-//! (Rust side) and the column (SurrealQL side) so the two can never disagree.2+//!
3+//! * [`search_fold`] / [`search_fold_sql`] are the **search** fold:
4+//! deliberately *destructive*, collapsing `ı ş ğ ç ö ü â î û` onto their
5+//! ASCII bases so a teacher on an ASCII keyboard still finds accented data.
6+//! * [`case_fold_tr`] is the **identity** fold: Turkish-correct case folding
7+//! only. It answers "are these two entries the same word?" and must never
8+//! conflate distinct letters (`tur` ≠ `tür`, `kir` ≠ `kır`).
9+//!
10+//! The search fold is shared by the needle (Rust side) and the column
11+//! (SurrealQL side) so the two can never disagree.
3 //!12 //!
4 //! Rust's `to_lowercase` and SurrealQL's `string::lowercase` are both13 //! Rust's `to_lowercase` and SurrealQL's `string::lowercase` are both
5 //! locale-invariant: Turkish `İ` (U+0130) lowercases to `i` + U+030714 //! locale-invariant: Turkish `İ` (U+0130) lowercases to `i` + U+0307
@@ -10,8 +19,9 @@
10 //! `ıgdır` ↔ `Iğdır`).19 //! `ıgdır` ↔ `Iğdır`).
11 20
12 /// Replacements applied *after* lowercasing, in order. One table, two21 /// Replacements applied *after* lowercasing, in order. One table, two
13-/// consumers ([`fold`] and [`fold_sql`]): the needle and the column are folded22+/// consumers ([`search_fold`] and [`search_fold_sql`]): the needle and the
14-/// by the same rules by construction, which is the whole point.23+/// column are folded by the same rules by construction, which is the whole
24+/// point.
15 const REPLACEMENTS: &[(&str, &str)] = &[25 const REPLACEMENTS: &[(&str, &str)] = &[
16 ("\u{307}", ""), // combining dot above, left behind by İ → i̇26 ("\u{307}", ""), // combining dot above, left behind by İ → i̇
17 ("ı", "i"),27 ("ı", "i"),
@@ -25,8 +35,10 @@ const REPLACEMENTS: &[(&str, &str)] = &[
25 ("û", "u"),35 ("û", "u"),
26 ];36 ];
27 37
28-/// Fold a search needle (or any Rust-side string) for comparison.38+/// Fold a search needle (or any Rust-side string) for comparison. **Search
29-pub fn fold(text: &str) -> String {39+/// only** — this is lossy, `tür` and `tur` both fold to `tur`. For "is this
40+/// the same word?" use [`case_fold_tr`].
41+pub fn search_fold(text: &str) -> String {
30 let mut folded = text.to_lowercase();42 let mut folded = text.to_lowercase();
31 for (from, to) in REPLACEMENTS {43 for (from, to) in REPLACEMENTS {
32 folded = folded.replace(from, to);44 folded = folded.replace(from, to);
@@ -37,7 +49,7 @@ pub fn fold(text: &str) -> String {
37 /// The same folding as a SurrealQL expression over `column`, for use inside a49 /// The same folding as a SurrealQL expression over `column`, for use inside a
38 /// `WHERE`. `column` is always a literal field name we wrote — never user50 /// `WHERE`. `column` is always a literal field name we wrote — never user
39 /// input.51 /// input.
40-pub fn fold_sql(column: &str) -> String {52+pub fn search_fold_sql(column: &str) -> String {
41 let mut expr = format!("string::lowercase({column})");53 let mut expr = format!("string::lowercase({column})");
42 for (from, to) in REPLACEMENTS {54 for (from, to) in REPLACEMENTS {
43 expr = format!("string::replace({expr}, '{from}', '{to}')");55 expr = format!("string::replace({expr}, '{from}', '{to}')");
@@ -45,20 +57,77 @@ pub fn fold_sql(column: &str) -> String {
45 expr57 expr
46 }58 }
47 59
60+/// Case-fold under the **Turkish** casing rule, for identity comparisons
61+/// (list dedup). Only the two dotted/dotless pairs are folded together —
62+/// `i` ↔ `İ` and `ı` ↔ `I` — so `TÜR` and `tür` are one word while `tur` and
63+/// `tür` stay two. Never use this for search: it will not match an ASCII
64+/// spelling of an accented word (that is [`search_fold`]'s job).
65+pub fn case_fold_tr(text: &str) -> String {
66+ let mut folded = String::with_capacity(text.len());
67+ for ch in text.chars() {
68+ match ch {
69+ // Rust would lowercase these locale-invariantly: `İ` → `i` plus a
70+ // combining dot, and `I` → `i` (the *dotted* i, wrong letter).
71+ 'İ' => folded.push('i'),
72+ 'I' => folded.push('ı'),
73+ _ => folded.extend(ch.to_lowercase()),
74+ }
75+ }
76+ // A decomposed `İ` (`i` + combining dot above) is the same letter as `i`.
77+ folded.replace("i\u{307}", "i")
78+}
79+
48 #[cfg(test)]80 #[cfg(test)]
49 mod tests {81 mod tests {
50 use super::*;82 use super::*;
51 83
52 #[test]84 #[test]
53 fn folds_turkish_casing_both_ways() {85 fn folds_turkish_casing_both_ways() {
54- assert_eq!(fold("İSTANBUL"), "istanbul");86+ assert_eq!(search_fold("İSTANBUL"), "istanbul");
55- assert_eq!(fold("istanbul"), "istanbul");87+ assert_eq!(search_fold("istanbul"), "istanbul");
56- assert_eq!(fold("İstanbul"), "istanbul");88+ assert_eq!(search_fold("İstanbul"), "istanbul");
57- assert_eq!(fold("ISTANBUL"), "istanbul");89+ assert_eq!(search_fold("ISTANBUL"), "istanbul");
58- assert_eq!(fold("ıstanbul"), "istanbul");90+ assert_eq!(search_fold("ıstanbul"), "istanbul");
59- assert_eq!(fold("Iğdır"), "igdir");91+ assert_eq!(search_fold("Iğdır"), "igdir");
60- assert_eq!(fold("ÇÖZÜM"), "cozum");92+ assert_eq!(search_fold("ÇÖZÜM"), "cozum");
61- assert_eq!(fold("Şekil"), "sekil");93+ assert_eq!(search_fold("Şekil"), "sekil");
94+ }
95+
96+ /// The identity fold folds case (Turkish rules) and *nothing else* — the
97+ /// truth table the settings dedup depends on.
98+ #[test]
99+ fn case_fold_tr_folds_case_but_not_letters() {
100+ // Same word, different case.
101+ for (upper, lower) in [
102+ ("TÜR", "tür"),
103+ ("KIR", "kır"),
104+ ("İSTANBUL", "istanbul"),
105+ ("ISPARTA", "ısparta"),
106+ ("İZİN", "izin"),
107+ ("SINAV", "sınav"),
108+ ("LAB", "lab"),
109+ ] {
110+ assert_eq!(
111+ case_fold_tr(upper),
112+ case_fold_tr(lower),
113+ "{upper} and {lower} are the same word"
114+ );
115+ }
116+ // Distinct words the destructive search fold wrongly collapsed.
117+ for (a, b) in [("tur", "tür"), ("kir", "kır"), ("sıra", "sira")] {
118+ assert_ne!(
119+ case_fold_tr(a),
120+ case_fold_tr(b),
121+ "{a} and {b} are different words"
122+ );
123+ assert_eq!(
124+ search_fold(a),
125+ search_fold(b),
126+ "search fold still collapses {a}/{b}"
127+ );
128+ }
129+ // Decomposed `İ` (i + combining dot) is still plain `i`.
130+ assert_eq!(case_fold_tr("i\u{307}zin"), "izin");
62 }131 }
63 132
64 /// The SQL side must fold a literal exactly like the Rust side does, or the133 /// The SQL side must fold a literal exactly like the Rust side does, or the
@@ -68,14 +137,14 @@ mod tests {
68 let db = crate::database::init_mem().await.unwrap();137 let db = crate::database::init_mem().await.unwrap();
69 for sample in ["İSTANBUL", "Iğdır", "ÇÖZÜM", "istanbul"] {138 for sample in ["İSTANBUL", "Iğdır", "ÇÖZÜM", "istanbul"] {
70 let mut result = db139 let mut result = db
71- .query(format!("RETURN {};", fold_sql("$text")))140+ .query(format!("RETURN {};", search_fold_sql("$text")))
72 .bind(("text", sample.to_string()))141 .bind(("text", sample.to_string()))
73 .await142 .await
74 .unwrap()143 .unwrap()
75 .check()144 .check()
76 .unwrap();145 .unwrap();
77 let got = result.take::<Option<String>>(0).unwrap().unwrap();146 let got = result.take::<Option<String>>(0).unwrap().unwrap();
78- assert_eq!(got, fold(sample), "sql fold disagrees for {sample}");147+ assert_eq!(got, search_fold(sample), "sql fold disagrees for {sample}");
79 }148 }
80 }149 }
81 }150 }
src/domain/user.rsmodified+5 -5
@@ -9,7 +9,7 @@ use crate::database::{Database, USER_TABLE};
9 use crate::domain::preferences::{Language, Theme};9 use crate::domain::preferences::{Language, Theme};
10 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};10 use crate::domain::profile::{BirthDate, Email, PersonName, Phone};
11 use crate::domain::role::Role;11 use crate::domain::role::Role;
12-use crate::domain::text_fold::{fold, fold_sql};12+use crate::domain::text_fold::{search_fold, search_fold_sql};
13 use crate::error::{AppError, ValidationError};13 use crate::error::{AppError, ValidationError};
14 use crate::validate::{validate_password, validate_username};14 use crate::validate::{validate_password, validate_username};
15 15
@@ -341,12 +341,12 @@ impl User {
341 role: Option<Role>,341 role: Option<Role>,
342 db: &Database,342 db: &Database,
343 ) -> Result<Vec<User>, AppError> {343 ) -> Result<Vec<User>, AppError> {
344- let needle = fold(query.trim());344+ let needle = search_fold(query.trim());
345 let text_clause = format!(345 let text_clause = format!(
346 "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)",346 "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)",
347- fold_sql("username"),347+ search_fold_sql("username"),
348- fold_sql("name ?? ''"),348+ search_fold_sql("name ?? ''"),
349- fold_sql("surname ?? ''"),349+ search_fold_sql("surname ?? ''"),
350 );350 );
351 let mut clauses = Vec::new();351 let mut clauses = Vec::new();
352 if !needle.is_empty() {352 if !needle.is_empty() {