Skip to main content

merry_runtime/session_store/
search.rs

1//! Rebuildable full-text index beside session directories.
2//!
3//! The index is not resume state. A corrupt or outdated database is deleted
4//! and rebuilt from `journal.jsonl` plus optional `meta.json` labels. Transient
5//! lock contention (`SQLITE_BUSY` / `SQLITE_LOCKED`) never deletes the database.
6
7use super::{FileSessionStore, JOURNAL_FILE_NAME};
8use merry_core::SessionId;
9use rusqlite::{Connection, ErrorCode, params};
10use serde::Deserialize;
11use std::{
12    path::{Path, PathBuf},
13    time::Duration,
14};
15use thiserror::Error;
16
17const INDEX_FILE_NAME: &str = "session_search.sqlite";
18const SCHEMA_VERSION: i64 = 3;
19const BUSY_TIMEOUT: Duration = Duration::from_secs(2);
20const SCHEMA: &str = "
21CREATE TABLE session_search (
22    session_id TEXT PRIMARY KEY,
23    topic TEXT NOT NULL DEFAULT '',
24    user_text TEXT NOT NULL DEFAULT ''
25);
26CREATE VIRTUAL TABLE session_fts USING fts5(
27    topic,
28    user_text,
29    content='session_search',
30    content_rowid='rowid'
31);
32CREATE TRIGGER session_search_ai AFTER INSERT ON session_search BEGIN
33    INSERT INTO session_fts(rowid, topic, user_text)
34    VALUES (new.rowid, new.topic, new.user_text);
35END;
36CREATE TRIGGER session_search_ad AFTER DELETE ON session_search BEGIN
37    INSERT INTO session_fts(session_fts, rowid, topic, user_text)
38    VALUES ('delete', old.rowid, old.topic, old.user_text);
39END;
40CREATE TRIGGER session_search_au AFTER UPDATE ON session_search BEGIN
41    INSERT INTO session_fts(session_fts, rowid, topic, user_text)
42    VALUES ('delete', old.rowid, old.topic, old.user_text);
43    INSERT INTO session_fts(rowid, topic, user_text)
44    VALUES (new.rowid, new.topic, new.user_text);
45END;
46";
47
48#[derive(Debug, Error)]
49enum SearchIndexError {
50    #[error("sqlite error: {0}")]
51    Sqlite(#[from] rusqlite::Error),
52    #[error("filesystem error: {0}")]
53    Io(#[from] std::io::Error),
54    #[error("blocking task join error: {0}")]
55    Join(#[from] tokio::task::JoinError),
56}
57
58impl SearchIndexError {
59    fn is_corruption(&self) -> bool {
60        matches!(
61            self,
62            Self::Sqlite(rusqlite::Error::SqliteFailure(err, _))
63                if matches!(err.code, ErrorCode::DatabaseCorrupt | ErrorCode::NotADatabase)
64        )
65    }
66}
67
68#[derive(Debug, Clone)]
69pub(super) struct SessionSearchUpdate {
70    pub(super) sessions_dir: PathBuf,
71    pub(super) session_id: SessionId,
72    pub(super) user_text: String,
73}
74
75#[derive(Debug, Deserialize)]
76struct MetaLabels {
77    #[serde(default)]
78    topic: Option<String>,
79}
80
81impl FileSessionStore {
82    fn search_index_path(&self) -> PathBuf {
83        self.sessions_dir.join(INDEX_FILE_NAME)
84    }
85
86    /// Returns session ids whose topic or user text matches `query`.
87    ///
88    /// An empty or unusable query returns no rows. Index failures are logged
89    /// and also return no rows; they do not affect resume.
90    pub async fn search_session_ids(&self, query: &str) -> Vec<SessionId> {
91        let Some(fts_query) = fts_query(query) else {
92            return Vec::new();
93        };
94        let path = self.search_index_path();
95        let sessions_dir = self.sessions_dir.clone();
96        let result = tokio::task::spawn_blocking(move || {
97            with_recoverable_index(&path, &sessions_dir, |connection| {
98                search_ids(connection, &fts_query)
99            })
100        })
101        .await;
102        match flatten_join(result) {
103            Ok(ids) => ids,
104            Err(error) => {
105                tracing::warn!(error = %error, "session search failed");
106                Vec::new()
107            }
108        }
109    }
110
111    /// Updates list labels without replacing indexed user text.
112    pub async fn update_session_search_labels(&self, session_id: &SessionId, topic: Option<&str>) {
113        let path = self.search_index_path();
114        let sessions_dir = self.sessions_dir.clone();
115        let session_id = session_id.as_str().to_owned();
116        let topic = indexable_text(topic.unwrap_or(""));
117        let result = tokio::task::spawn_blocking(move || {
118            with_recoverable_index(&path, &sessions_dir, |connection| {
119                connection.execute(
120                    "INSERT INTO session_search (session_id, topic, user_text)
121                     VALUES (?1, ?2, '')
122                     ON CONFLICT(session_id) DO UPDATE SET
123                        topic = excluded.topic",
124                    params![session_id, topic],
125                )?;
126                Ok(())
127            })
128        })
129        .await;
130        if let Err(error) = flatten_join(result) {
131            tracing::warn!(error = %error, "session search label update failed");
132        }
133    }
134}
135
136pub(super) async fn upsert_user_text(update: SessionSearchUpdate) {
137    let path = update.sessions_dir.join(INDEX_FILE_NAME);
138    let user_text = indexable_text(&update.user_text);
139    let result = tokio::task::spawn_blocking(move || {
140        with_recoverable_index(&path, &update.sessions_dir, |connection| {
141            connection.execute(
142                "INSERT INTO session_search (session_id, topic, user_text)
143                 VALUES (?1, '', ?2)
144                 ON CONFLICT(session_id) DO UPDATE SET user_text = excluded.user_text",
145                params![update.session_id.as_str(), user_text],
146            )?;
147            Ok(())
148        })
149    })
150    .await;
151    if let Err(error) = flatten_join(result) {
152        tracing::warn!(error = %error, "session search index update failed");
153    }
154}
155
156fn flatten_join<T>(
157    result: Result<Result<T, SearchIndexError>, tokio::task::JoinError>,
158) -> Result<T, SearchIndexError> {
159    match result {
160        Ok(inner) => inner,
161        Err(error) => Err(SearchIndexError::Join(error)),
162    }
163}
164
165/// Runs `op` against the search index, rebuilding once if SQLite reports
166/// genuine database corruption. Transient errors (such as `SQLITE_BUSY`) are
167/// returned directly without deleting the database.
168fn with_recoverable_index<T>(
169    path: &Path,
170    sessions_dir: &Path,
171    mut op: impl FnMut(&mut Connection) -> Result<T, SearchIndexError>,
172) -> Result<T, SearchIndexError> {
173    match open_or_create_index(path, sessions_dir).and_then(|mut connection| op(&mut connection)) {
174        Ok(value) => Ok(value),
175        Err(error) if error.is_corruption() => {
176            tracing::warn!(
177                path = %path.display(),
178                error = %error,
179                "rebuilding corrupt session search index"
180            );
181            let mut connection = reset_and_rebuild_index(path, sessions_dir)?;
182            op(&mut connection)
183        }
184        Err(error) => Err(error),
185    }
186}
187
188fn search_ids(
189    connection: &mut Connection,
190    fts_query: &str,
191) -> Result<Vec<SessionId>, SearchIndexError> {
192    let mut statement = connection.prepare(
193        "SELECT session_search.session_id
194         FROM session_fts
195         JOIN session_search ON session_search.rowid = session_fts.rowid
196         WHERE session_fts MATCH ?1
197         ORDER BY rank",
198    )?;
199    let rows = statement.query_map(params![fts_query], |row| row.get::<_, String>(0))?;
200    let mut ids = Vec::new();
201    for row in rows {
202        let session_id = row?;
203        if let Ok(session_id) = SessionId::new(&session_id) {
204            ids.push(session_id);
205        }
206    }
207    Ok(ids)
208}
209
210fn open_or_create_index(path: &Path, sessions_dir: &Path) -> Result<Connection, SearchIndexError> {
211    if !path.exists() {
212        return reset_and_rebuild_index(path, sessions_dir);
213    }
214    let connection = Connection::open(path)?;
215    configure(&connection)?;
216    let version = schema_version(&connection)?;
217    if version == SCHEMA_VERSION {
218        return Ok(connection);
219    }
220    drop(connection);
221    reset_and_rebuild_index(path, sessions_dir)
222}
223
224fn reset_and_rebuild_index(
225    path: &Path,
226    sessions_dir: &Path,
227) -> Result<Connection, SearchIndexError> {
228    if path.exists() {
229        remove_index_files(path);
230    }
231    if let Some(parent) = path.parent() {
232        std::fs::create_dir_all(parent)?;
233    }
234    let mut connection = Connection::open(path)?;
235    configure(&connection)?;
236    connection.execute_batch(SCHEMA)?;
237    rebuild(&mut connection, sessions_dir)?;
238    connection.pragma_update(None, "user_version", SCHEMA_VERSION)?;
239    Ok(connection)
240}
241
242fn schema_version(connection: &Connection) -> Result<i64, SearchIndexError> {
243    Ok(connection.query_row("PRAGMA user_version", [], |row| row.get(0))?)
244}
245
246fn configure(connection: &Connection) -> Result<(), SearchIndexError> {
247    // Use `PRAGMA busy_timeout` instead of `Connection::busy_timeout`:
248    // rusqlite 0.43 calls `sqlite3_set_clientdata` (SQLite 3.44+) inside
249    // `busy_timeout`, which is missing from Apple's system `libsqlite3` on
250    // macOS and iOS when `bundled-sqlite` is disabled.
251    let timeout_ms = i64::try_from(BUSY_TIMEOUT.as_millis()).unwrap_or(i64::MAX);
252    connection.pragma_update(None, "busy_timeout", timeout_ms)?;
253    connection.pragma_update(None, "journal_mode", "WAL")?;
254    Ok(())
255}
256
257fn rebuild(connection: &mut Connection, sessions_dir: &Path) -> Result<(), SearchIndexError> {
258    let entries = match std::fs::read_dir(sessions_dir) {
259        Ok(entries) => entries,
260        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
261        Err(error) => return Err(SearchIndexError::Io(error)),
262    };
263    let tx = connection.transaction()?;
264    tx.execute("DELETE FROM session_search", [])?;
265    for entry in entries {
266        let entry = entry?;
267        if !entry.file_type()?.is_dir() {
268            continue;
269        }
270        let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
271            continue;
272        };
273        let Ok(session_id) = SessionId::new(&name) else {
274            continue;
275        };
276        let directory = entry.path();
277        let journal_path = directory.join(JOURNAL_FILE_NAME);
278        if !journal_path.is_file() {
279            continue;
280        }
281        let bytes = match std::fs::read(&journal_path) {
282            Ok(bytes) => bytes,
283            Err(error) => {
284                tracing::warn!(
285                    path = %journal_path.display(),
286                    error = %error,
287                    "session search skipped a journal"
288                );
289                continue;
290            }
291        };
292        let snapshot = match crate::session::extract_search_snapshot(&bytes) {
293            Ok(snapshot) => snapshot,
294            Err(error) => {
295                tracing::warn!(
296                    path = %journal_path.display(),
297                    error = %error,
298                    "session search skipped a journal"
299                );
300                continue;
301            }
302        };
303        let topic = meta_topic(&directory.join("meta.json"))
304            .or(snapshot.topic)
305            .unwrap_or_default();
306        tx.execute(
307            "INSERT INTO session_search (session_id, topic, user_text)
308             VALUES (?1, ?2, ?3)",
309            params![
310                session_id.as_str(),
311                indexable_text(&topic),
312                indexable_text(&snapshot.user_text)
313            ],
314        )?;
315    }
316    tx.commit()?;
317    Ok(())
318}
319
320fn meta_topic(path: &Path) -> Option<String> {
321    let bytes = std::fs::read(path).ok()?;
322    serde_json::from_slice::<MetaLabels>(&bytes)
323        .ok()
324        .and_then(|labels| labels.topic)
325}
326
327fn remove_index_files(path: &Path) {
328    let _ = std::fs::remove_file(path);
329    for suffix in ["-wal", "-shm"] {
330        let mut name = path.as_os_str().to_os_string();
331        name.push(suffix);
332        let _ = std::fs::remove_file(PathBuf::from(name));
333    }
334}
335
336/// Inserts spaces around CJK characters so FTS5's `unicode61` tokenizer indexes
337/// each ideograph at its position while keeping Latin/ASCII runs intact.
338fn indexable_text(raw: &str) -> String {
339    let mut out = String::with_capacity(raw.len());
340    let mut prev_cjk = false;
341    for ch in raw.chars() {
342        let cjk = is_cjk(ch);
343        if (cjk || prev_cjk) && !out.is_empty() && !out.ends_with(' ') && !ch.is_whitespace() {
344            out.push(' ');
345        }
346        out.push(ch);
347        prev_cjk = cjk;
348    }
349    out
350}
351
352fn is_cjk(ch: char) -> bool {
353    matches!(
354        ch as u32,
355        0x3040..=0x30FF // Hiragana & Katakana
356        | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A
357        | 0x4E00..=0x9FFF // CJK Unified Ideographs
358        | 0xAC00..=0xD7AF // Hangul Syllables
359        | 0xF900..=0xFAFF // CJK Compatibility Ideographs
360        | 0x20000..=0x2A6DF // CJK Extension B
361    )
362}
363
364/// Builds an FTS5 query matching all non-punctuation runs in `raw`.
365///
366/// Adjacent CJK runs become exact FTS5 phrase matches (e.g. `落盘` -> `"落 盘"`),
367/// while Latin/numeric tokens stay single-token matches.
368fn fts_query(raw: &str) -> Option<String> {
369    let mut clauses = Vec::new();
370    for segment in raw.split(|ch: char| !ch.is_alphanumeric()) {
371        if segment.is_empty() {
372            continue;
373        }
374        let mut current_ascii = String::new();
375        let mut current_cjk = Vec::new();
376        for ch in segment.chars() {
377            if is_cjk(ch) {
378                if !current_ascii.is_empty() {
379                    clauses.push(format!("\"{}\"", current_ascii.replace('"', "")));
380                    current_ascii.clear();
381                }
382                current_cjk.push(ch.to_string());
383            } else {
384                if !current_cjk.is_empty() {
385                    clauses.push(format!("\"{}\"", current_cjk.join(" ")));
386                    current_cjk.clear();
387                }
388                if ch != '"' {
389                    current_ascii.push(ch);
390                }
391            }
392        }
393        if !current_ascii.is_empty() {
394            clauses.push(format!("\"{current_ascii}\""));
395        }
396        if !current_cjk.is_empty() {
397            clauses.push(format!("\"{}\"", current_cjk.join(" ")));
398        }
399    }
400    if clauses.is_empty() {
401        None
402    } else {
403        Some(clauses.join(" AND "))
404    }
405}
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410    use crate::session::SessionState;
411
412    #[tokio::test]
413    async fn search_index_finds_english_and_cjk_and_rebuilds_topic_from_journal() {
414        let temp = tempfile::tempdir().expect("tempdir");
415        let store = FileSessionStore::new(temp.path());
416        let session_id = SessionId::new("search-session").expect("valid session id");
417        let mut session = SessionState::new(session_id.clone());
418        let turn_id = session.begin_model_turn().expect("turn begins");
419        session
420            .record_user_message_body(turn_id, "alpha unique-token 优化落盘策略")
421            .expect("user message records");
422        session
423            .close_model_response(turn_id, false)
424            .expect("turn closes");
425        session.set_generated_topic("topic-token 日志优化".to_owned());
426        session.save_to(&store).await.expect("session saves");
427        store
428            .update_session_search_labels(&session_id, Some("topic-token 日志优化"))
429            .await;
430
431        assert_eq!(
432            store.search_session_ids("unique-token").await,
433            vec![session_id.clone()]
434        );
435        assert_eq!(
436            store.search_session_ids("落盘").await,
437            vec![session_id.clone()]
438        );
439        assert_eq!(
440            store.search_session_ids("topic-token").await,
441            vec![session_id.clone()]
442        );
443        assert_eq!(
444            store.search_session_ids("日志优化").await,
445            vec![session_id.clone()]
446        );
447        assert!(store.search_session_ids("策略优化").await.is_empty());
448        assert!(store.search_session_ids("missing-token").await.is_empty());
449
450        for entry in std::fs::read_dir(temp.path()).expect("sessions dir reads") {
451            let path = entry.expect("entry").path();
452            let name = path.file_name().unwrap_or_default().to_string_lossy();
453            if name.starts_with(INDEX_FILE_NAME) {
454                std::fs::remove_file(path).expect("index file removes");
455            }
456        }
457
458        // Rebuilding without meta.json still recovers both user text and journal topic.
459        assert_eq!(
460            store.search_session_ids("unique-token").await,
461            vec![session_id.clone()]
462        );
463        assert_eq!(
464            store.search_session_ids("落盘").await,
465            vec![session_id.clone()]
466        );
467        assert_eq!(
468            store.search_session_ids("topic-token").await,
469            vec![session_id]
470        );
471    }
472
473    #[tokio::test]
474    async fn search_index_recovers_from_corrupt_sqlite_file() {
475        let temp = tempfile::tempdir().expect("tempdir");
476        let store = FileSessionStore::new(temp.path());
477        let session_id = SessionId::new("corrupt-search-session").expect("valid session id");
478        let mut session = SessionState::new(session_id.clone());
479        let turn_id = session.begin_model_turn().expect("turn begins");
480        session
481            .record_user_message_body(turn_id, "recover-me")
482            .expect("user message records");
483        session
484            .close_model_response(turn_id, false)
485            .expect("turn closes");
486        session.save_to(&store).await.expect("session saves");
487
488        std::fs::write(temp.path().join(INDEX_FILE_NAME), b"not a sqlite database")
489            .expect("corrupt index writes");
490
491        assert_eq!(
492            store.search_session_ids("recover-me").await,
493            vec![session_id]
494        );
495    }
496
497    #[test]
498    fn fts_query_quotes_latin_and_cjk_phrases() {
499        assert_eq!(
500            fts_query("  plans: alpha, beta! ").as_deref(),
501            Some("\"plans\" AND \"alpha\" AND \"beta\"")
502        );
503        assert_eq!(
504            fts_query("优化Rust落盘").as_deref(),
505            Some("\"优 化\" AND \"Rust\" AND \"落 盘\"")
506        );
507        assert_eq!(fts_query("..."), None);
508    }
509}