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    connection.busy_timeout(BUSY_TIMEOUT)?;
248    connection.pragma_update(None, "journal_mode", "WAL")?;
249    Ok(())
250}
251
252fn rebuild(connection: &mut Connection, sessions_dir: &Path) -> Result<(), SearchIndexError> {
253    let entries = match std::fs::read_dir(sessions_dir) {
254        Ok(entries) => entries,
255        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
256        Err(error) => return Err(SearchIndexError::Io(error)),
257    };
258    let tx = connection.transaction()?;
259    tx.execute("DELETE FROM session_search", [])?;
260    for entry in entries {
261        let entry = entry?;
262        if !entry.file_type()?.is_dir() {
263            continue;
264        }
265        let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
266            continue;
267        };
268        let Ok(session_id) = SessionId::new(&name) else {
269            continue;
270        };
271        let directory = entry.path();
272        let journal_path = directory.join(JOURNAL_FILE_NAME);
273        if !journal_path.is_file() {
274            continue;
275        }
276        let bytes = match std::fs::read(&journal_path) {
277            Ok(bytes) => bytes,
278            Err(error) => {
279                tracing::warn!(
280                    path = %journal_path.display(),
281                    error = %error,
282                    "session search skipped a journal"
283                );
284                continue;
285            }
286        };
287        let snapshot = match crate::session::extract_search_snapshot(&bytes) {
288            Ok(snapshot) => snapshot,
289            Err(error) => {
290                tracing::warn!(
291                    path = %journal_path.display(),
292                    error = %error,
293                    "session search skipped a journal"
294                );
295                continue;
296            }
297        };
298        let topic = meta_topic(&directory.join("meta.json"))
299            .or(snapshot.topic)
300            .unwrap_or_default();
301        tx.execute(
302            "INSERT INTO session_search (session_id, topic, user_text)
303             VALUES (?1, ?2, ?3)",
304            params![
305                session_id.as_str(),
306                indexable_text(&topic),
307                indexable_text(&snapshot.user_text)
308            ],
309        )?;
310    }
311    tx.commit()?;
312    Ok(())
313}
314
315fn meta_topic(path: &Path) -> Option<String> {
316    let bytes = std::fs::read(path).ok()?;
317    serde_json::from_slice::<MetaLabels>(&bytes)
318        .ok()
319        .and_then(|labels| labels.topic)
320}
321
322fn remove_index_files(path: &Path) {
323    let _ = std::fs::remove_file(path);
324    for suffix in ["-wal", "-shm"] {
325        let mut name = path.as_os_str().to_os_string();
326        name.push(suffix);
327        let _ = std::fs::remove_file(PathBuf::from(name));
328    }
329}
330
331/// Inserts spaces around CJK characters so FTS5's `unicode61` tokenizer indexes
332/// each ideograph at its position while keeping Latin/ASCII runs intact.
333fn indexable_text(raw: &str) -> String {
334    let mut out = String::with_capacity(raw.len());
335    let mut prev_cjk = false;
336    for ch in raw.chars() {
337        let cjk = is_cjk(ch);
338        if (cjk || prev_cjk) && !out.is_empty() && !out.ends_with(' ') && !ch.is_whitespace() {
339            out.push(' ');
340        }
341        out.push(ch);
342        prev_cjk = cjk;
343    }
344    out
345}
346
347fn is_cjk(ch: char) -> bool {
348    matches!(
349        ch as u32,
350        0x3040..=0x30FF // Hiragana & Katakana
351        | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A
352        | 0x4E00..=0x9FFF // CJK Unified Ideographs
353        | 0xAC00..=0xD7AF // Hangul Syllables
354        | 0xF900..=0xFAFF // CJK Compatibility Ideographs
355        | 0x20000..=0x2A6DF // CJK Extension B
356    )
357}
358
359/// Builds an FTS5 query matching all non-punctuation runs in `raw`.
360///
361/// Adjacent CJK runs become exact FTS5 phrase matches (e.g. `落盘` -> `"落 盘"`),
362/// while Latin/numeric tokens stay single-token matches.
363fn fts_query(raw: &str) -> Option<String> {
364    let mut clauses = Vec::new();
365    for segment in raw.split(|ch: char| !ch.is_alphanumeric()) {
366        if segment.is_empty() {
367            continue;
368        }
369        let mut current_ascii = String::new();
370        let mut current_cjk = Vec::new();
371        for ch in segment.chars() {
372            if is_cjk(ch) {
373                if !current_ascii.is_empty() {
374                    clauses.push(format!("\"{}\"", current_ascii.replace('"', "")));
375                    current_ascii.clear();
376                }
377                current_cjk.push(ch.to_string());
378            } else {
379                if !current_cjk.is_empty() {
380                    clauses.push(format!("\"{}\"", current_cjk.join(" ")));
381                    current_cjk.clear();
382                }
383                if ch != '"' {
384                    current_ascii.push(ch);
385                }
386            }
387        }
388        if !current_ascii.is_empty() {
389            clauses.push(format!("\"{current_ascii}\""));
390        }
391        if !current_cjk.is_empty() {
392            clauses.push(format!("\"{}\"", current_cjk.join(" ")));
393        }
394    }
395    if clauses.is_empty() {
396        None
397    } else {
398        Some(clauses.join(" AND "))
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405    use crate::session::SessionState;
406
407    #[tokio::test]
408    async fn search_index_finds_english_and_cjk_and_rebuilds_topic_from_journal() {
409        let temp = tempfile::tempdir().expect("tempdir");
410        let store = FileSessionStore::new(temp.path());
411        let session_id = SessionId::new("search-session").expect("valid session id");
412        let mut session = SessionState::new(session_id.clone());
413        let turn_id = session.begin_model_turn().expect("turn begins");
414        session
415            .record_user_message_body(turn_id, "alpha unique-token 优化落盘策略")
416            .expect("user message records");
417        session
418            .close_model_response(turn_id, false)
419            .expect("turn closes");
420        session.set_generated_topic("topic-token 日志优化".to_owned());
421        session.save_to(&store).await.expect("session saves");
422        store
423            .update_session_search_labels(&session_id, Some("topic-token 日志优化"))
424            .await;
425
426        assert_eq!(
427            store.search_session_ids("unique-token").await,
428            vec![session_id.clone()]
429        );
430        assert_eq!(
431            store.search_session_ids("落盘").await,
432            vec![session_id.clone()]
433        );
434        assert_eq!(
435            store.search_session_ids("topic-token").await,
436            vec![session_id.clone()]
437        );
438        assert_eq!(
439            store.search_session_ids("日志优化").await,
440            vec![session_id.clone()]
441        );
442        assert!(store.search_session_ids("策略优化").await.is_empty());
443        assert!(store.search_session_ids("missing-token").await.is_empty());
444
445        for entry in std::fs::read_dir(temp.path()).expect("sessions dir reads") {
446            let path = entry.expect("entry").path();
447            let name = path.file_name().unwrap_or_default().to_string_lossy();
448            if name.starts_with(INDEX_FILE_NAME) {
449                std::fs::remove_file(path).expect("index file removes");
450            }
451        }
452
453        // Rebuilding without meta.json still recovers both user text and journal topic.
454        assert_eq!(
455            store.search_session_ids("unique-token").await,
456            vec![session_id.clone()]
457        );
458        assert_eq!(
459            store.search_session_ids("落盘").await,
460            vec![session_id.clone()]
461        );
462        assert_eq!(
463            store.search_session_ids("topic-token").await,
464            vec![session_id]
465        );
466    }
467
468    #[tokio::test]
469    async fn search_index_recovers_from_corrupt_sqlite_file() {
470        let temp = tempfile::tempdir().expect("tempdir");
471        let store = FileSessionStore::new(temp.path());
472        let session_id = SessionId::new("corrupt-search-session").expect("valid session id");
473        let mut session = SessionState::new(session_id.clone());
474        let turn_id = session.begin_model_turn().expect("turn begins");
475        session
476            .record_user_message_body(turn_id, "recover-me")
477            .expect("user message records");
478        session
479            .close_model_response(turn_id, false)
480            .expect("turn closes");
481        session.save_to(&store).await.expect("session saves");
482
483        std::fs::write(temp.path().join(INDEX_FILE_NAME), b"not a sqlite database")
484            .expect("corrupt index writes");
485
486        assert_eq!(
487            store.search_session_ids("recover-me").await,
488            vec![session_id]
489        );
490    }
491
492    #[test]
493    fn fts_query_quotes_latin_and_cjk_phrases() {
494        assert_eq!(
495            fts_query("  plans: alpha, beta! ").as_deref(),
496            Some("\"plans\" AND \"alpha\" AND \"beta\"")
497        );
498        assert_eq!(
499            fts_query("优化Rust落盘").as_deref(),
500            Some("\"优 化\" AND \"Rust\" AND \"落 盘\"")
501        );
502        assert_eq!(fts_query("..."), None);
503    }
504}