Skip to main content

index/fulltext_index/create/
tantivy.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::HashMap;
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18use std::sync::atomic::{AtomicBool, Ordering};
19
20use async_trait::async_trait;
21use common_error::ext::BoxedError;
22use common_telemetry::warn;
23use puffin::puffin_manager::{PuffinWriter, PutOptions};
24use snafu::{OptionExt, ResultExt};
25use tantivy::indexer::NoMergePolicy;
26use tantivy::schema::{STORED, Schema, TEXT};
27use tantivy::store::{Compressor, ZstdCompressor};
28use tantivy::{Index, IndexWriter, doc};
29
30use crate::fulltext_index::create::FulltextIndexCreator;
31use crate::fulltext_index::error::{
32    ExternalSnafu, FinishedSnafu, IoSnafu, JoinSnafu, Result, SerializeToJsonSnafu, TantivySnafu,
33};
34use crate::fulltext_index::{Config, KEY_FULLTEXT_CONFIG};
35
36pub const TEXT_FIELD_NAME: &str = "greptime_fulltext_text";
37pub const ROWID_FIELD_NAME: &str = "greptime_fulltext_rowid";
38
39/// `TantivyFulltextIndexCreator` is a fulltext index creator using tantivy.
40pub struct TantivyFulltextIndexCreator {
41    /// The tantivy index writer.
42    writer: Option<IndexWriter>,
43    /// Retained across awaits so abort can join a cancelled finish operation.
44    finishing: Option<common_runtime::JoinHandle<Result<()>>>,
45
46    /// The field for the text.
47    text_field: tantivy::schema::Field,
48
49    /// The field for the row id.
50    rowid_field: tantivy::schema::Field,
51
52    /// The current max row id.
53    max_rowid: u64,
54
55    /// Shared with blocking work so cancellation cannot unlink an active index.
56    directory: Arc<TempIndexDirectory>,
57
58    /// Pauses the real commit at its blocking boundary in lifecycle tests.
59    #[cfg(test)]
60    before_commit: Option<Arc<dyn Fn() + Send + Sync>>,
61
62    /// The configuration of the fulltext index.
63    config: Config,
64}
65
66/// Owns an empty temporary directory, never a pre-existing index.
67struct TempIndexDirectory {
68    path: PathBuf,
69    removed: AtomicBool,
70}
71
72impl TempIndexDirectory {
73    fn create(path: PathBuf) -> Result<Arc<Self>> {
74        std::fs::create_dir_all(&path).context(IoSnafu)?;
75        if std::fs::read_dir(&path)
76            .context(IoSnafu)?
77            .next()
78            .transpose()
79            .context(IoSnafu)?
80            .is_some()
81        {
82            return Err(std::io::Error::new(
83                std::io::ErrorKind::AlreadyExists,
84                "Tantivy temporary directory must be empty",
85            ))
86            .context(IoSnafu);
87        }
88        Ok(Arc::new(Self {
89            path,
90            removed: AtomicBool::new(false),
91        }))
92    }
93}
94
95impl Drop for TempIndexDirectory {
96    fn drop(&mut self) {
97        if self.removed.load(Ordering::Relaxed) {
98            return;
99        }
100        let path = self.path.clone();
101        common_runtime::spawn_blocking_global(move || {
102            if let Err(error) = std::fs::remove_dir_all(&path)
103                && error.kind() != std::io::ErrorKind::NotFound
104            {
105                warn!(error; "Failed to remove temporary Tantivy directory: {}", path.display());
106            }
107        });
108    }
109}
110
111impl Drop for TantivyFulltextIndexCreator {
112    fn drop(&mut self) {
113        if let Some(writer) = self.writer.take() {
114            let directory = self.directory.clone();
115            // IndexWriter::drop joins its threads; neither that nor directory
116            // removal may block the async task cancelling this creator.
117            common_runtime::spawn_blocking_global(move || {
118                drop(writer);
119                drop(directory);
120            });
121        }
122    }
123}
124
125impl TantivyFulltextIndexCreator {
126    /// Creates a new `TantivyFulltextIndexCreator`.
127    ///
128    /// `path` must be an empty temporary directory. It is removed after the
129    /// creator and any in-flight blocking work release it.
130    pub async fn new(path: impl AsRef<Path>, config: Config, memory_limit: usize) -> Result<Self> {
131        let path = path.as_ref().to_path_buf();
132        // Keep creation and its guard in the same task: dropping the awaiting
133        // future must not race mkdir against cleanup.
134        common_runtime::spawn_blocking_global(move || Self::create(path, config, memory_limit))
135            .await
136            .context(JoinSnafu)?
137    }
138
139    fn create(path: PathBuf, config: Config, memory_limit: usize) -> Result<Self> {
140        let directory = TempIndexDirectory::create(path)?;
141        let mut schema_builder = Schema::builder();
142        let text_field = schema_builder.add_text_field(TEXT_FIELD_NAME, TEXT);
143        let rowid_field = schema_builder.add_u64_field(ROWID_FIELD_NAME, STORED);
144        let schema = schema_builder.build();
145
146        let mut index = Index::create_in_dir(&directory.path, schema).context(TantivySnafu)?;
147        index.settings_mut().docstore_compression = Compressor::Zstd(ZstdCompressor::default());
148        index.set_tokenizers(config.build_tantivy_tokenizer());
149
150        let memory_limit = Self::sanitize_memory_limit(memory_limit);
151
152        // Use one thread to keep order of the row id.
153        let writer = index
154            .writer_with_num_threads(1, memory_limit)
155            .context(TantivySnafu)?;
156        writer.set_merge_policy(Box::new(NoMergePolicy));
157
158        Ok(Self {
159            writer: Some(writer),
160            finishing: None,
161            text_field,
162            rowid_field,
163            max_rowid: 0,
164            directory,
165            #[cfg(test)]
166            before_commit: None,
167            config,
168        })
169    }
170
171    async fn finish_writer(&mut self) -> Result<()> {
172        if self.finishing.is_none() {
173            let writer = self.writer.take().context(FinishedSnafu)?;
174            let directory = self.directory.clone();
175            #[cfg(test)]
176            let before_commit = self.before_commit.clone();
177            self.finishing = Some(common_runtime::spawn_blocking_global(move || {
178                let _directory = directory;
179                // Declare the writer after the lease so error unwinding also
180                // drops/joins it before releasing the directory.
181                let mut writer = writer;
182                #[cfg(test)]
183                if let Some(before_commit) = before_commit {
184                    before_commit();
185                }
186                writer.commit().context(TantivySnafu)?;
187                writer.wait_merging_threads().context(TantivySnafu)
188            }));
189        }
190        let completed = self.finishing.as_mut().context(FinishedSnafu)?.await;
191        self.finishing.take();
192        completed.context(JoinSnafu)?
193    }
194
195    /// Effective per-column allocation, also used by compaction admission.
196    pub fn sanitize_memory_limit(memory_limit: usize) -> usize {
197        // Port from tantivy::indexer::index_writer::{MEMORY_BUDGET_NUM_BYTES_MIN, MEMORY_BUDGET_NUM_BYTES_MAX}
198        const MARGIN_IN_BYTES: usize = 1_000_000;
199        const MEMORY_BUDGET_NUM_BYTES_MIN: usize = ((MARGIN_IN_BYTES as u32) * 15u32) as usize;
200        const MEMORY_BUDGET_NUM_BYTES_MAX: usize = u32::MAX as usize - MARGIN_IN_BYTES - 1;
201
202        memory_limit.clamp(MEMORY_BUDGET_NUM_BYTES_MIN, MEMORY_BUDGET_NUM_BYTES_MAX)
203    }
204}
205
206#[async_trait]
207impl FulltextIndexCreator for TantivyFulltextIndexCreator {
208    async fn push_text(&mut self, text: &str) -> Result<()> {
209        let writer = self.writer.as_mut().context(FinishedSnafu)?;
210        let doc = doc!(self.text_field => text, self.rowid_field => self.max_rowid);
211        self.max_rowid += 1;
212        writer.add_document(doc).context(TantivySnafu)?;
213        Ok(())
214    }
215
216    async fn finish(
217        &mut self,
218        puffin_writer: &mut (impl PuffinWriter + Send),
219        blob_key: &str,
220        put_options: PutOptions,
221    ) -> Result<u64> {
222        self.finish_writer().await?;
223
224        let property_key = KEY_FULLTEXT_CONFIG.to_string();
225        let property_value = serde_json::to_string(&self.config).context(SerializeToJsonSnafu)?;
226
227        puffin_writer
228            .put_dir(
229                blob_key,
230                self.directory.path.clone(),
231                put_options,
232                HashMap::from([(property_key, property_value)]),
233            )
234            .await
235            .map_err(BoxedError::new)
236            .context(ExternalSnafu)
237    }
238
239    async fn abort(&mut self) -> Result<()> {
240        if self.writer.is_some() || self.finishing.is_some() {
241            self.finish_writer().await?;
242        }
243        match tokio::fs::remove_dir_all(&self.directory.path).await {
244            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
245            removed => removed.context(IoSnafu)?,
246        }
247        self.directory.removed.store(true, Ordering::Relaxed);
248        Ok(())
249    }
250
251    fn memory_usage(&self) -> usize {
252        // Unable to get the memory usage of `IndexWriter`.
253        0
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use std::collections::HashMap;
260
261    use common_test_util::temp_dir::create_temp_dir;
262    use futures::AsyncRead;
263    use tantivy::TantivyDocument;
264    use tantivy::collector::DocSetCollector;
265    use tantivy::query::QueryParser;
266    use tantivy::schema::Value;
267
268    use super::*;
269    use crate::fulltext_index::Analyzer;
270
271    #[derive(Default)]
272    struct MockPuffinWriter {
273        blocked: Option<Arc<tokio::sync::Notify>>,
274    }
275
276    #[async_trait]
277    impl PuffinWriter for MockPuffinWriter {
278        async fn put_blob<R>(
279            &mut self,
280            _key: &str,
281            _raw_data: R,
282            _options: PutOptions,
283            _properties: HashMap<String, String>,
284        ) -> puffin::error::Result<u64>
285        where
286            R: AsyncRead + Send,
287        {
288            unreachable!()
289        }
290
291        async fn put_dir(
292            &mut self,
293            _key: &str,
294            dir: PathBuf,
295            _options: PutOptions,
296            _properties: HashMap<String, String>,
297        ) -> puffin::error::Result<u64> {
298            if let Some(blocked) = &self.blocked {
299                assert!(dir.join("meta.json").exists());
300                blocked.notify_one();
301                futures::future::pending::<()>().await;
302            }
303            Ok(0)
304        }
305        fn set_footer_lz4_compressed(&mut self, _lz4_compressed: bool) {
306            unreachable!()
307        }
308
309        async fn finish(self) -> puffin::error::Result<u64> {
310            Ok(0)
311        }
312    }
313
314    async fn assert_directory_removed(path: &Path) {
315        tokio::time::timeout(std::time::Duration::from_secs(10), async {
316            while tokio::fs::try_exists(path).await.unwrap() {
317                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
318            }
319        })
320        .await
321        .expect("temporary Tantivy directory leaked");
322    }
323
324    #[tokio::test]
325    async fn test_creator_drop_cleans_temporary_files() {
326        for stage in ["active", "finished", "aborted"] {
327            let root = create_temp_dir("tantivy-drop-");
328            let path = root.path().join("index");
329            let mut creator = creator_with_text(&path).await;
330            assert!(path.join("meta.json").exists());
331            match stage {
332                "finished" => {
333                    creator
334                        .finish(
335                            &mut MockPuffinWriter::default(),
336                            "index",
337                            PutOptions::default(),
338                        )
339                        .await
340                        .unwrap();
341                }
342                "aborted" => {
343                    creator.abort().await.unwrap();
344                }
345                _ => {}
346            }
347            drop(creator);
348            assert_directory_removed(&path).await;
349            assert!(root.path().exists());
350        }
351    }
352
353    #[tokio::test]
354    async fn test_abort_after_cancelled_finish_cleans_temporary_files() {
355        let root = create_temp_dir("tantivy-cancel-finish-");
356        let path = root.path().join("index");
357        let mut creator = creator_with_text(&path).await;
358        let blocked = Arc::new(tokio::sync::Notify::new());
359        let mut writer = MockPuffinWriter {
360            blocked: Some(blocked.clone()),
361        };
362        {
363            let finishing = creator.finish(&mut writer, "index", PutOptions::default());
364            tokio::pin!(finishing);
365            tokio::select! {
366                _ = blocked.notified() => {}
367                result = &mut finishing => panic!("finish did not reach the blocked upload: {result:?}"),
368                _ = tokio::time::sleep(std::time::Duration::from_secs(10)) => panic!("finish stalled"),
369            }
370        }
371        creator.abort().await.unwrap();
372        creator.abort().await.unwrap();
373        assert!(!path.exists());
374    }
375
376    async fn creator_with_text(path: &Path) -> TantivyFulltextIndexCreator {
377        let mut creator = TantivyFulltextIndexCreator::new(path, Config::default(), 1)
378            .await
379            .unwrap();
380        creator.push_text("indexed text").await.unwrap();
381        creator
382    }
383
384    /// Cancels the real `finish()` while its commit is blocked, leaving the
385    /// production retained handle and directory lease in flight.
386    async fn creator_with_blocked_commit(
387        path: &Path,
388    ) -> (TantivyFulltextIndexCreator, std::sync::mpsc::Sender<()>) {
389        let mut creator = creator_with_text(path).await;
390        let started = Arc::new(tokio::sync::Notify::new());
391        let commit_started = started.clone();
392        let (release, released) = std::sync::mpsc::channel();
393        let released = Arc::new(std::sync::Mutex::new(released));
394        creator.before_commit = Some(Arc::new(move || {
395            commit_started.notify_one();
396            released.lock().unwrap().recv().unwrap();
397        }));
398        let mut writer = MockPuffinWriter::default();
399        {
400            let finishing = creator.finish(&mut writer, "index", PutOptions::default());
401            tokio::pin!(finishing);
402            tokio::select! {
403                _ = started.notified() => {}
404                result = &mut finishing => panic!("finish did not reach commit: {result:?}"),
405                _ = tokio::time::sleep(std::time::Duration::from_secs(10)) => panic!("commit stalled"),
406            }
407        }
408        assert!(creator.finishing.is_some());
409        (creator, release)
410    }
411
412    #[tokio::test]
413    async fn test_abort_joins_retained_finalization() {
414        let root = create_temp_dir("tantivy-retained-finalize-");
415        let path = root.path().join("index");
416        let (mut creator, release) = creator_with_blocked_commit(&path).await;
417        let aborting = tokio::spawn(async move {
418            creator.abort().await.unwrap();
419            creator
420        });
421        assert!(path.exists());
422        release.send(()).unwrap();
423        let mut creator = tokio::time::timeout(std::time::Duration::from_secs(10), aborting)
424            .await
425            .unwrap()
426            .unwrap();
427        assert!(creator.finishing.is_none());
428        assert!(!path.exists());
429        // Repeating abort must stay idempotent.
430        creator.abort().await.unwrap();
431    }
432
433    #[tokio::test]
434    async fn test_drop_with_retained_finalization_cleans_temporary_files() {
435        let root = create_temp_dir("tantivy-drop-retained-");
436        let path = root.path().join("index");
437        let (creator, release) = creator_with_blocked_commit(&path).await;
438        drop(creator);
439        assert!(path.exists());
440        release.send(()).unwrap();
441        assert_directory_removed(&path).await;
442    }
443
444    #[tokio::test]
445    async fn test_detached_initialization_cleans_its_result() {
446        let root = create_temp_dir("tantivy-detached-init-");
447        let path = root.path().join("index");
448        let creating_path = path.clone();
449        let (ready, initialized) = tokio::sync::oneshot::channel();
450        let (release, released) = std::sync::mpsc::channel();
451        // The real constructor runs on the blocking pool. Detaching its handle
452        // must clean even if cancellation happens before the result is delivered.
453        let creating = common_runtime::spawn_blocking_global(move || {
454            let creator =
455                TantivyFulltextIndexCreator::create(creating_path, Config::default(), 1).unwrap();
456            ready.send(()).unwrap();
457            released.recv().unwrap();
458            creator
459        });
460        tokio::time::timeout(std::time::Duration::from_secs(10), initialized)
461            .await
462            .unwrap()
463            .unwrap();
464        assert!(path.join("meta.json").exists());
465        drop(creating);
466        release.send(()).unwrap();
467        assert_directory_removed(&path).await;
468    }
469
470    #[tokio::test]
471    async fn test_initialization_preserves_nonempty_directory() {
472        let root = create_temp_dir("tantivy-existing-");
473        let sentinel = root.path().join("existing");
474        tokio::fs::write(&sentinel, "must survive").await.unwrap();
475        assert!(
476            TantivyFulltextIndexCreator::new(root.path(), Config::default(), 1)
477                .await
478                .is_err()
479        );
480        assert_eq!(
481            "must survive",
482            tokio::fs::read_to_string(&sentinel).await.unwrap()
483        );
484    }
485
486    #[tokio::test]
487    async fn test_creator_basic() {
488        let memory_limits = [1, 64_000_000, usize::MAX];
489
490        for memory_limit in memory_limits {
491            let temp_dir = create_temp_dir("test_creator_basic_");
492
493            let texts = vec!["hello", "world", "hello, world", "foo!", "Bar"];
494            let config = Config::default();
495            let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
496
497            let cases = [
498                ("hello", vec![0u32, 2]),
499                ("world", vec![1, 2]),
500                ("foo", vec![3]),
501                ("bar", vec![4]),
502            ];
503            query_and_check(temp_dir.path(), config, &cases).await;
504        }
505    }
506
507    #[tokio::test]
508    async fn test_creator_case_sensitive() {
509        let memory_limits = [1, 64_000_000, usize::MAX];
510
511        for memory_limit in memory_limits {
512            let temp_dir = create_temp_dir("test_creator_case_sensitive_");
513
514            let texts = vec!["hello", "world", "hello, world", "foo!", "Bar"];
515            let config = Config {
516                case_sensitive: true,
517                ..Config::default()
518            };
519            let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
520
521            let cases = [
522                ("hello", vec![0u32, 2]),
523                ("world", vec![1, 2]),
524                ("foo", vec![3]),
525                ("Foo", vec![]),
526                ("FOO", vec![]),
527                ("bar", vec![]),
528                ("Bar", vec![4]),
529                ("BAR", vec![]),
530            ];
531            query_and_check(temp_dir.path(), config, &cases).await;
532        }
533    }
534
535    #[tokio::test]
536    async fn test_creator_chinese() {
537        let memory_limits = [1, 64_000_000, usize::MAX];
538
539        for memory_limit in memory_limits {
540            let temp_dir = create_temp_dir("test_creator_chinese_");
541
542            let texts = vec!["你好", "世界", "你好,世界", "你好世界", "foo!", "Bar"];
543            let config = Config {
544                analyzer: Analyzer::Chinese,
545                ..Config::default()
546            };
547            let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
548
549            let cases = [
550                ("你好", vec![0u32, 2, 3]),
551                ("世界", vec![1, 2, 3]),
552                ("foo", vec![4]),
553                ("bar", vec![5]),
554            ];
555            query_and_check(temp_dir.path(), config, &cases).await;
556        }
557    }
558
559    #[tokio::test]
560    async fn test_creator_chinese_case_sensitive() {
561        let memory_limits = [1, 64_000_000, usize::MAX];
562
563        for memory_limit in memory_limits {
564            let temp_dir = create_temp_dir("test_creator_chinese_case_sensitive_");
565
566            let texts = vec!["你好", "世界", "你好,世界", "你好世界", "foo!", "Bar"];
567            let config = Config {
568                case_sensitive: true,
569                analyzer: Analyzer::Chinese,
570            };
571            let _creator = build_index(&texts, temp_dir.path(), config, memory_limit).await;
572
573            let cases = [
574                ("你好", vec![0u32, 2, 3]),
575                ("世界", vec![1, 2, 3]),
576                ("foo", vec![4]),
577                ("bar", vec![]),
578                ("Foo", vec![]),
579                ("FOO", vec![]),
580                ("Bar", vec![5]),
581                ("BAR", vec![]),
582            ];
583            query_and_check(temp_dir.path(), config, &cases).await;
584        }
585    }
586
587    async fn build_index(
588        texts: &[&str],
589        path: &Path,
590        config: Config,
591        memory_limit: usize,
592    ) -> TantivyFulltextIndexCreator {
593        let mut creator = TantivyFulltextIndexCreator::new(path, config, memory_limit)
594            .await
595            .unwrap();
596        for text in texts {
597            creator.push_text(text).await.unwrap();
598        }
599        creator
600            .finish(&mut MockPuffinWriter::default(), "", PutOptions::default())
601            .await
602            .unwrap();
603        creator
604    }
605
606    async fn query_and_check(path: &Path, config: Config, cases: &[(&str, Vec<u32>)]) {
607        let mut index = Index::open_in_dir(path).unwrap();
608        index.set_tokenizers(config.build_tantivy_tokenizer());
609        let reader = index.reader().unwrap();
610        let searcher = reader.searcher();
611        for (query, expected) in cases {
612            let query_parser = QueryParser::for_index(
613                &index,
614                vec![index.schema().get_field(TEXT_FIELD_NAME).unwrap()],
615            );
616            let query = query_parser.parse_query(query).unwrap();
617            let docs = searcher.search(&query, &DocSetCollector).unwrap();
618
619            let mut res = vec![];
620            let rowid_field = searcher.schema().get_field(ROWID_FIELD_NAME).unwrap();
621            for doc_addr in &docs {
622                let doc: TantivyDocument = searcher.doc(*doc_addr).unwrap();
623                let rowid = doc.get_first(rowid_field).unwrap().as_u64().unwrap();
624                assert_eq!(rowid as u32, doc_addr.doc_id);
625                res.push(rowid as u32);
626            }
627
628            res.sort();
629            assert_eq!(res, *expected);
630        }
631    }
632}